xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 275efb9e5020d60178251611373d636da6def0ca)
1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This coordinates the per-module state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenModule.h"
15 #include "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGCall.h"
18 #include "CGDebugInfo.h"
19 #include "CGObjCRuntime.h"
20 #include "CGOpenCLRuntime.h"
21 #include "CGOpenMPRuntime.h"
22 #include "CodeGenFunction.h"
23 #include "CodeGenPGO.h"
24 #include "CodeGenTBAA.h"
25 #include "TargetInfo.h"
26 #include "clang/AST/ASTContext.h"
27 #include "clang/AST/CharUnits.h"
28 #include "clang/AST/DeclCXX.h"
29 #include "clang/AST/DeclObjC.h"
30 #include "clang/AST/DeclTemplate.h"
31 #include "clang/AST/Mangle.h"
32 #include "clang/AST/RecordLayout.h"
33 #include "clang/AST/RecursiveASTVisitor.h"
34 #include "clang/Basic/Builtins.h"
35 #include "clang/Basic/CharInfo.h"
36 #include "clang/Basic/Diagnostic.h"
37 #include "clang/Basic/Module.h"
38 #include "clang/Basic/SourceManager.h"
39 #include "clang/Basic/TargetInfo.h"
40 #include "clang/Basic/Version.h"
41 #include "clang/Frontend/CodeGenOptions.h"
42 #include "clang/Sema/SemaDiagnostic.h"
43 #include "llvm/ADT/APSInt.h"
44 #include "llvm/ADT/Triple.h"
45 #include "llvm/IR/CallSite.h"
46 #include "llvm/IR/CallingConv.h"
47 #include "llvm/IR/DataLayout.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/ProfileData/InstrProfReader.h"
52 #include "llvm/Support/ConvertUTF.h"
53 #include "llvm/Support/ErrorHandling.h"
54 
55 using namespace clang;
56 using namespace CodeGen;
57 
58 static const char AnnotationSection[] = "llvm.metadata";
59 
60 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
61   switch (CGM.getTarget().getCXXABI().getKind()) {
62   case TargetCXXABI::GenericAArch64:
63   case TargetCXXABI::GenericARM:
64   case TargetCXXABI::iOS:
65   case TargetCXXABI::iOS64:
66   case TargetCXXABI::GenericItanium:
67     return CreateItaniumCXXABI(CGM);
68   case TargetCXXABI::Microsoft:
69     return CreateMicrosoftCXXABI(CGM);
70   }
71 
72   llvm_unreachable("invalid C++ ABI kind");
73 }
74 
75 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
76                              llvm::Module &M, const llvm::DataLayout &TD,
77                              DiagnosticsEngine &diags)
78     : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
79       Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
80       ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
81       TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
82       ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
83       CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
84       NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
85       CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
86       NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
87       NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
88       BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
89       GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
90       LifetimeEndFn(nullptr),
91       SanitizerBlacklist(
92           llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
93       SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
94                                           : LangOpts.Sanitize) {
95 
96   // Initialize the type cache.
97   llvm::LLVMContext &LLVMContext = M.getContext();
98   VoidTy = llvm::Type::getVoidTy(LLVMContext);
99   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
100   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
101   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
102   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
103   FloatTy = llvm::Type::getFloatTy(LLVMContext);
104   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
105   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
106   PointerAlignInBytes =
107   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
108   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
109   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
110   Int8PtrTy = Int8Ty->getPointerTo(0);
111   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
112 
113   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
114 
115   if (LangOpts.ObjC1)
116     createObjCRuntime();
117   if (LangOpts.OpenCL)
118     createOpenCLRuntime();
119   if (LangOpts.OpenMP)
120     createOpenMPRuntime();
121   if (LangOpts.CUDA)
122     createCUDARuntime();
123 
124   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
125   if (SanOpts.Thread ||
126       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
127     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
128                            getCXXABI().getMangleContext());
129 
130   // If debug info or coverage generation is enabled, create the CGDebugInfo
131   // object.
132   if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
133       CodeGenOpts.EmitGcovArcs ||
134       CodeGenOpts.EmitGcovNotes)
135     DebugInfo = new CGDebugInfo(*this);
136 
137   Block.GlobalUniqueCount = 0;
138 
139   if (C.getLangOpts().ObjCAutoRefCount)
140     ARCData = new ARCEntrypoints();
141   RRData = new RREntrypoints();
142 
143   if (!CodeGenOpts.InstrProfileInput.empty()) {
144     if (llvm::error_code EC = llvm::IndexedInstrProfReader::create(
145             CodeGenOpts.InstrProfileInput, PGOReader)) {
146       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
147                                               "Could not read profile: %0");
148       getDiags().Report(DiagID) << EC.message();
149     }
150   }
151 }
152 
153 CodeGenModule::~CodeGenModule() {
154   delete ObjCRuntime;
155   delete OpenCLRuntime;
156   delete OpenMPRuntime;
157   delete CUDARuntime;
158   delete TheTargetCodeGenInfo;
159   delete TBAA;
160   delete DebugInfo;
161   delete ARCData;
162   delete RRData;
163 }
164 
165 void CodeGenModule::createObjCRuntime() {
166   // This is just isGNUFamily(), but we want to force implementors of
167   // new ABIs to decide how best to do this.
168   switch (LangOpts.ObjCRuntime.getKind()) {
169   case ObjCRuntime::GNUstep:
170   case ObjCRuntime::GCC:
171   case ObjCRuntime::ObjFW:
172     ObjCRuntime = CreateGNUObjCRuntime(*this);
173     return;
174 
175   case ObjCRuntime::FragileMacOSX:
176   case ObjCRuntime::MacOSX:
177   case ObjCRuntime::iOS:
178     ObjCRuntime = CreateMacObjCRuntime(*this);
179     return;
180   }
181   llvm_unreachable("bad runtime kind");
182 }
183 
184 void CodeGenModule::createOpenCLRuntime() {
185   OpenCLRuntime = new CGOpenCLRuntime(*this);
186 }
187 
188 void CodeGenModule::createOpenMPRuntime() {
189   OpenMPRuntime = new CGOpenMPRuntime(*this);
190 }
191 
192 void CodeGenModule::createCUDARuntime() {
193   CUDARuntime = CreateNVCUDARuntime(*this);
194 }
195 
196 void CodeGenModule::applyReplacements() {
197   for (ReplacementsTy::iterator I = Replacements.begin(),
198                                 E = Replacements.end();
199        I != E; ++I) {
200     StringRef MangledName = I->first();
201     llvm::Constant *Replacement = I->second;
202     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
203     if (!Entry)
204       continue;
205     auto *OldF = cast<llvm::Function>(Entry);
206     auto *NewF = dyn_cast<llvm::Function>(Replacement);
207     if (!NewF) {
208       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
209         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
210       } else {
211         auto *CE = cast<llvm::ConstantExpr>(Replacement);
212         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
213                CE->getOpcode() == llvm::Instruction::GetElementPtr);
214         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
215       }
216     }
217 
218     // Replace old with new, but keep the old order.
219     OldF->replaceAllUsesWith(Replacement);
220     if (NewF) {
221       NewF->removeFromParent();
222       OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
223     }
224     OldF->eraseFromParent();
225   }
226 }
227 
228 void CodeGenModule::checkAliases() {
229   // Check if the constructed aliases are well formed. It is really unfortunate
230   // that we have to do this in CodeGen, but we only construct mangled names
231   // and aliases during codegen.
232   bool Error = false;
233   DiagnosticsEngine &Diags = getDiags();
234   for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
235          E = Aliases.end(); I != E; ++I) {
236     const GlobalDecl &GD = *I;
237     const auto *D = cast<ValueDecl>(GD.getDecl());
238     const AliasAttr *AA = D->getAttr<AliasAttr>();
239     StringRef MangledName = getMangledName(GD);
240     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
241     auto *Alias = cast<llvm::GlobalAlias>(Entry);
242     llvm::GlobalValue *GV = Alias->getAliasee();
243     if (GV->isDeclaration()) {
244       Error = true;
245       Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
246     }
247 
248     llvm::GlobalObject *Aliasee = Alias->getAliasee();
249     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
250       StringRef AliasSection = SA->getName();
251       if (AliasSection != Aliasee->getSection())
252         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
253             << AliasSection;
254     }
255   }
256   if (!Error)
257     return;
258 
259   for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
260          E = Aliases.end(); I != E; ++I) {
261     const GlobalDecl &GD = *I;
262     StringRef MangledName = getMangledName(GD);
263     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
264     auto *Alias = cast<llvm::GlobalAlias>(Entry);
265     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
266     Alias->eraseFromParent();
267   }
268 }
269 
270 void CodeGenModule::clear() {
271   DeferredDeclsToEmit.clear();
272 }
273 
274 void CodeGenModule::Release() {
275   EmitDeferred();
276   applyReplacements();
277   checkAliases();
278   EmitCXXGlobalInitFunc();
279   EmitCXXGlobalDtorFunc();
280   EmitCXXThreadLocalInitFunc();
281   if (ObjCRuntime)
282     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
283       AddGlobalCtor(ObjCInitFunction);
284   if (getCodeGenOpts().ProfileInstrGenerate)
285     if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this))
286       AddGlobalCtor(PGOInit, 0);
287   if (PGOReader && PGOStats.isOutOfDate())
288     getDiags().Report(diag::warn_profile_data_out_of_date)
289         << PGOStats.Visited << PGOStats.Missing << PGOStats.Mismatched;
290   EmitCtorList(GlobalCtors, "llvm.global_ctors");
291   EmitCtorList(GlobalDtors, "llvm.global_dtors");
292   EmitGlobalAnnotations();
293   EmitStaticExternCAliases();
294   emitLLVMUsed();
295 
296   if (CodeGenOpts.Autolink &&
297       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
298     EmitModuleLinkOptions();
299   }
300   if (CodeGenOpts.DwarfVersion)
301     // We actually want the latest version when there are conflicts.
302     // We can change from Warning to Latest if such mode is supported.
303     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
304                               CodeGenOpts.DwarfVersion);
305   if (DebugInfo)
306     // We support a single version in the linked module. The LLVM
307     // parser will drop debug info with a different version number
308     // (and warn about it, too).
309     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
310                               llvm::DEBUG_METADATA_VERSION);
311 
312   SimplifyPersonality();
313 
314   if (getCodeGenOpts().EmitDeclMetadata)
315     EmitDeclMetadata();
316 
317   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
318     EmitCoverageFile();
319 
320   if (DebugInfo)
321     DebugInfo->finalize();
322 
323   EmitVersionIdentMetadata();
324 }
325 
326 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
327   // Make sure that this type is translated.
328   Types.UpdateCompletedType(TD);
329 }
330 
331 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
332   if (!TBAA)
333     return nullptr;
334   return TBAA->getTBAAInfo(QTy);
335 }
336 
337 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
338   if (!TBAA)
339     return nullptr;
340   return TBAA->getTBAAInfoForVTablePtr();
341 }
342 
343 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
344   if (!TBAA)
345     return nullptr;
346   return TBAA->getTBAAStructInfo(QTy);
347 }
348 
349 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
350   if (!TBAA)
351     return nullptr;
352   return TBAA->getTBAAStructTypeInfo(QTy);
353 }
354 
355 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
356                                                   llvm::MDNode *AccessN,
357                                                   uint64_t O) {
358   if (!TBAA)
359     return nullptr;
360   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
361 }
362 
363 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
364 /// and struct-path aware TBAA, the tag has the same format:
365 /// base type, access type and offset.
366 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
367 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
368                                         llvm::MDNode *TBAAInfo,
369                                         bool ConvertTypeToTag) {
370   if (ConvertTypeToTag && TBAA)
371     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
372                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
373   else
374     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
375 }
376 
377 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
378   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
379   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
380 }
381 
382 /// ErrorUnsupported - Print out an error that codegen doesn't support the
383 /// specified stmt yet.
384 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
385   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
386                                                "cannot compile this %0 yet");
387   std::string Msg = Type;
388   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
389     << Msg << S->getSourceRange();
390 }
391 
392 /// ErrorUnsupported - Print out an error that codegen doesn't support the
393 /// specified decl yet.
394 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
395   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
396                                                "cannot compile this %0 yet");
397   std::string Msg = Type;
398   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
399 }
400 
401 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
402   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
403 }
404 
405 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
406                                         const NamedDecl *D) const {
407   // Internal definitions always have default visibility.
408   if (GV->hasLocalLinkage()) {
409     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
410     return;
411   }
412 
413   // Set visibility for definitions.
414   LinkageInfo LV = D->getLinkageAndVisibility();
415   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
416     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
417 }
418 
419 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
420   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
421       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
422       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
423       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
424       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
425 }
426 
427 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
428     CodeGenOptions::TLSModel M) {
429   switch (M) {
430   case CodeGenOptions::GeneralDynamicTLSModel:
431     return llvm::GlobalVariable::GeneralDynamicTLSModel;
432   case CodeGenOptions::LocalDynamicTLSModel:
433     return llvm::GlobalVariable::LocalDynamicTLSModel;
434   case CodeGenOptions::InitialExecTLSModel:
435     return llvm::GlobalVariable::InitialExecTLSModel;
436   case CodeGenOptions::LocalExecTLSModel:
437     return llvm::GlobalVariable::LocalExecTLSModel;
438   }
439   llvm_unreachable("Invalid TLS model!");
440 }
441 
442 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
443                                const VarDecl &D) const {
444   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
445 
446   llvm::GlobalVariable::ThreadLocalMode TLM;
447   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
448 
449   // Override the TLS model if it is explicitly specified.
450   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
451     TLM = GetLLVMTLSModel(Attr->getModel());
452   }
453 
454   GV->setThreadLocalMode(TLM);
455 }
456 
457 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
458   const auto *ND = cast<NamedDecl>(GD.getDecl());
459 
460   StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
461   if (!Str.empty())
462     return Str;
463 
464   if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
465     IdentifierInfo *II = ND->getIdentifier();
466     assert(II && "Attempt to mangle unnamed decl.");
467 
468     Str = II->getName();
469     return Str;
470   }
471 
472   SmallString<256> Buffer;
473   llvm::raw_svector_ostream Out(Buffer);
474   if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
475     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
476   else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
477     getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
478   else
479     getCXXABI().getMangleContext().mangleName(ND, Out);
480 
481   // Allocate space for the mangled name.
482   Out.flush();
483   size_t Length = Buffer.size();
484   char *Name = MangledNamesAllocator.Allocate<char>(Length);
485   std::copy(Buffer.begin(), Buffer.end(), Name);
486 
487   Str = StringRef(Name, Length);
488 
489   return Str;
490 }
491 
492 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
493                                         const BlockDecl *BD) {
494   MangleContext &MangleCtx = getCXXABI().getMangleContext();
495   const Decl *D = GD.getDecl();
496   llvm::raw_svector_ostream Out(Buffer.getBuffer());
497   if (!D)
498     MangleCtx.mangleGlobalBlock(BD,
499       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
500   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
501     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
502   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
503     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
504   else
505     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
506 }
507 
508 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
509   return getModule().getNamedValue(Name);
510 }
511 
512 /// AddGlobalCtor - Add a function to the list that will be called before
513 /// main() runs.
514 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
515                                   llvm::Constant *AssociatedData) {
516   // FIXME: Type coercion of void()* types.
517   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
518 }
519 
520 /// AddGlobalDtor - Add a function to the list that will be called
521 /// when the module is unloaded.
522 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
523   // FIXME: Type coercion of void()* types.
524   GlobalDtors.push_back(Structor(Priority, Dtor, 0));
525 }
526 
527 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
528   // Ctor function type is void()*.
529   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
530   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
531 
532   // Get the type of a ctor entry, { i32, void ()*, i8* }.
533   llvm::StructType *CtorStructTy = llvm::StructType::get(
534       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, NULL);
535 
536   // Construct the constructor and destructor arrays.
537   SmallVector<llvm::Constant*, 8> Ctors;
538   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
539     llvm::Constant *S[] = {
540       llvm::ConstantInt::get(Int32Ty, I->Priority, false),
541       llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
542       (I->AssociatedData
543            ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
544            : llvm::Constant::getNullValue(VoidPtrTy))
545     };
546     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
547   }
548 
549   if (!Ctors.empty()) {
550     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
551     new llvm::GlobalVariable(TheModule, AT, false,
552                              llvm::GlobalValue::AppendingLinkage,
553                              llvm::ConstantArray::get(AT, Ctors),
554                              GlobalName);
555   }
556 }
557 
558 llvm::GlobalValue::LinkageTypes
559 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
560   const auto *D = cast<FunctionDecl>(GD.getDecl());
561 
562   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
563 
564   if (isa<CXXDestructorDecl>(D) &&
565       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
566                                          GD.getDtorType())) {
567     // Destructor variants in the Microsoft C++ ABI are always internal or
568     // linkonce_odr thunks emitted on an as-needed basis.
569     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
570                                    : llvm::GlobalValue::LinkOnceODRLinkage;
571   }
572 
573   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
574 }
575 
576 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
577                                                     llvm::Function *F) {
578   setNonAliasAttributes(D, F);
579 }
580 
581 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
582                                               const CGFunctionInfo &Info,
583                                               llvm::Function *F) {
584   unsigned CallingConv;
585   AttributeListType AttributeList;
586   ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
587   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
588   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
589 }
590 
591 /// Determines whether the language options require us to model
592 /// unwind exceptions.  We treat -fexceptions as mandating this
593 /// except under the fragile ObjC ABI with only ObjC exceptions
594 /// enabled.  This means, for example, that C with -fexceptions
595 /// enables this.
596 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
597   // If exceptions are completely disabled, obviously this is false.
598   if (!LangOpts.Exceptions) return false;
599 
600   // If C++ exceptions are enabled, this is true.
601   if (LangOpts.CXXExceptions) return true;
602 
603   // If ObjC exceptions are enabled, this depends on the ABI.
604   if (LangOpts.ObjCExceptions) {
605     return LangOpts.ObjCRuntime.hasUnwindExceptions();
606   }
607 
608   return true;
609 }
610 
611 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
612                                                            llvm::Function *F) {
613   llvm::AttrBuilder B;
614 
615   if (CodeGenOpts.UnwindTables)
616     B.addAttribute(llvm::Attribute::UWTable);
617 
618   if (!hasUnwindExceptions(LangOpts))
619     B.addAttribute(llvm::Attribute::NoUnwind);
620 
621   if (D->hasAttr<NakedAttr>()) {
622     // Naked implies noinline: we should not be inlining such functions.
623     B.addAttribute(llvm::Attribute::Naked);
624     B.addAttribute(llvm::Attribute::NoInline);
625   } else if (D->hasAttr<OptimizeNoneAttr>()) {
626     // OptimizeNone implies noinline; we should not be inlining such functions.
627     B.addAttribute(llvm::Attribute::OptimizeNone);
628     B.addAttribute(llvm::Attribute::NoInline);
629   } else if (D->hasAttr<NoDuplicateAttr>()) {
630     B.addAttribute(llvm::Attribute::NoDuplicate);
631   } else if (D->hasAttr<NoInlineAttr>()) {
632     B.addAttribute(llvm::Attribute::NoInline);
633   } else if (D->hasAttr<AlwaysInlineAttr>() &&
634              !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
635                                               llvm::Attribute::NoInline)) {
636     // (noinline wins over always_inline, and we can't specify both in IR)
637     B.addAttribute(llvm::Attribute::AlwaysInline);
638   }
639 
640   if (D->hasAttr<ColdAttr>()) {
641     B.addAttribute(llvm::Attribute::OptimizeForSize);
642     B.addAttribute(llvm::Attribute::Cold);
643   }
644 
645   if (D->hasAttr<MinSizeAttr>())
646     B.addAttribute(llvm::Attribute::MinSize);
647 
648   if (D->hasAttr<OptimizeNoneAttr>()) {
649     // OptimizeNone wins over OptimizeForSize and MinSize.
650     B.removeAttribute(llvm::Attribute::OptimizeForSize);
651     B.removeAttribute(llvm::Attribute::MinSize);
652   }
653 
654   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
655     B.addAttribute(llvm::Attribute::StackProtect);
656   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
657     B.addAttribute(llvm::Attribute::StackProtectStrong);
658   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
659     B.addAttribute(llvm::Attribute::StackProtectReq);
660 
661   // Add sanitizer attributes if function is not blacklisted.
662   if (!SanitizerBlacklist->isIn(*F)) {
663     // When AddressSanitizer is enabled, set SanitizeAddress attribute
664     // unless __attribute__((no_sanitize_address)) is used.
665     if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
666       B.addAttribute(llvm::Attribute::SanitizeAddress);
667     // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
668     if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
669       B.addAttribute(llvm::Attribute::SanitizeThread);
670     }
671     // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
672     if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
673       B.addAttribute(llvm::Attribute::SanitizeMemory);
674   }
675 
676   F->addAttributes(llvm::AttributeSet::FunctionIndex,
677                    llvm::AttributeSet::get(
678                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
679 
680   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
681     F->setUnnamedAddr(true);
682   else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
683     if (MD->isVirtual())
684       F->setUnnamedAddr(true);
685 
686   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
687   if (alignment)
688     F->setAlignment(alignment);
689 
690   // C++ ABI requires 2-byte alignment for member functions.
691   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
692     F->setAlignment(2);
693 }
694 
695 void CodeGenModule::SetCommonAttributes(const Decl *D,
696                                         llvm::GlobalValue *GV) {
697   if (const auto *ND = dyn_cast<NamedDecl>(D))
698     setGlobalVisibility(GV, ND);
699   else
700     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
701 
702   if (D->hasAttr<UsedAttr>())
703     addUsedGlobal(GV);
704 }
705 
706 void CodeGenModule::setNonAliasAttributes(const Decl *D,
707                                           llvm::GlobalObject *GO) {
708   SetCommonAttributes(D, GO);
709 
710   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
711     GO->setSection(SA->getName());
712 
713   getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this);
714 }
715 
716 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
717                                                   llvm::Function *F,
718                                                   const CGFunctionInfo &FI) {
719   SetLLVMFunctionAttributes(D, FI, F);
720   SetLLVMFunctionAttributesForDefinition(D, F);
721 
722   F->setLinkage(llvm::Function::InternalLinkage);
723 
724   setNonAliasAttributes(D, F);
725 }
726 
727 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
728                                          const NamedDecl *ND) {
729   // Set linkage and visibility in case we never see a definition.
730   LinkageInfo LV = ND->getLinkageAndVisibility();
731   if (LV.getLinkage() != ExternalLinkage) {
732     // Don't set internal linkage on declarations.
733   } else {
734     if (ND->hasAttr<DLLImportAttr>()) {
735       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
736       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
737     } else if (ND->hasAttr<DLLExportAttr>()) {
738       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
739       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
740     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
741       // "extern_weak" is overloaded in LLVM; we probably should have
742       // separate linkage types for this.
743       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
744     }
745 
746     // Set visibility on a declaration only if it's explicit.
747     if (LV.isVisibilityExplicit())
748       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
749   }
750 }
751 
752 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
753                                           llvm::Function *F,
754                                           bool IsIncompleteFunction) {
755   if (unsigned IID = F->getIntrinsicID()) {
756     // If this is an intrinsic function, set the function's attributes
757     // to the intrinsic's attributes.
758     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
759                                                     (llvm::Intrinsic::ID)IID));
760     return;
761   }
762 
763   const auto *FD = cast<FunctionDecl>(GD.getDecl());
764 
765   if (!IsIncompleteFunction)
766     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
767 
768   // Add the Returned attribute for "this", except for iOS 5 and earlier
769   // where substantial code, including the libstdc++ dylib, was compiled with
770   // GCC and does not actually return "this".
771   if (getCXXABI().HasThisReturn(GD) &&
772       !(getTarget().getTriple().isiOS() &&
773         getTarget().getTriple().isOSVersionLT(6))) {
774     assert(!F->arg_empty() &&
775            F->arg_begin()->getType()
776              ->canLosslesslyBitCastTo(F->getReturnType()) &&
777            "unexpected this return");
778     F->addAttribute(1, llvm::Attribute::Returned);
779   }
780 
781   // Only a few attributes are set on declarations; these may later be
782   // overridden by a definition.
783 
784   setLinkageAndVisibilityForGV(F, FD);
785 
786   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
787     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
788       // Don't dllexport/import destructor thunks.
789       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
790     }
791   }
792 
793   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
794     F->setSection(SA->getName());
795 
796   // A replaceable global allocation function does not act like a builtin by
797   // default, only if it is invoked by a new-expression or delete-expression.
798   if (FD->isReplaceableGlobalAllocationFunction())
799     F->addAttribute(llvm::AttributeSet::FunctionIndex,
800                     llvm::Attribute::NoBuiltin);
801 }
802 
803 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
804   assert(!GV->isDeclaration() &&
805          "Only globals with definition can force usage.");
806   LLVMUsed.push_back(GV);
807 }
808 
809 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
810   assert(!GV->isDeclaration() &&
811          "Only globals with definition can force usage.");
812   LLVMCompilerUsed.push_back(GV);
813 }
814 
815 static void emitUsed(CodeGenModule &CGM, StringRef Name,
816                      std::vector<llvm::WeakVH> &List) {
817   // Don't create llvm.used if there is no need.
818   if (List.empty())
819     return;
820 
821   // Convert List to what ConstantArray needs.
822   SmallVector<llvm::Constant*, 8> UsedArray;
823   UsedArray.resize(List.size());
824   for (unsigned i = 0, e = List.size(); i != e; ++i) {
825     UsedArray[i] =
826      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
827                                     CGM.Int8PtrTy);
828   }
829 
830   if (UsedArray.empty())
831     return;
832   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
833 
834   auto *GV = new llvm::GlobalVariable(
835       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
836       llvm::ConstantArray::get(ATy, UsedArray), Name);
837 
838   GV->setSection("llvm.metadata");
839 }
840 
841 void CodeGenModule::emitLLVMUsed() {
842   emitUsed(*this, "llvm.used", LLVMUsed);
843   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
844 }
845 
846 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
847   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
848   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
849 }
850 
851 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
852   llvm::SmallString<32> Opt;
853   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
854   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
855   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
856 }
857 
858 void CodeGenModule::AddDependentLib(StringRef Lib) {
859   llvm::SmallString<24> Opt;
860   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
861   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
862   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
863 }
864 
865 /// \brief Add link options implied by the given module, including modules
866 /// it depends on, using a postorder walk.
867 static void addLinkOptionsPostorder(CodeGenModule &CGM,
868                                     Module *Mod,
869                                     SmallVectorImpl<llvm::Value *> &Metadata,
870                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
871   // Import this module's parent.
872   if (Mod->Parent && Visited.insert(Mod->Parent)) {
873     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
874   }
875 
876   // Import this module's dependencies.
877   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
878     if (Visited.insert(Mod->Imports[I-1]))
879       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
880   }
881 
882   // Add linker options to link against the libraries/frameworks
883   // described by this module.
884   llvm::LLVMContext &Context = CGM.getLLVMContext();
885   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
886     // Link against a framework.  Frameworks are currently Darwin only, so we
887     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
888     if (Mod->LinkLibraries[I-1].IsFramework) {
889       llvm::Value *Args[2] = {
890         llvm::MDString::get(Context, "-framework"),
891         llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
892       };
893 
894       Metadata.push_back(llvm::MDNode::get(Context, Args));
895       continue;
896     }
897 
898     // Link against a library.
899     llvm::SmallString<24> Opt;
900     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
901       Mod->LinkLibraries[I-1].Library, Opt);
902     llvm::Value *OptString = llvm::MDString::get(Context, Opt);
903     Metadata.push_back(llvm::MDNode::get(Context, OptString));
904   }
905 }
906 
907 void CodeGenModule::EmitModuleLinkOptions() {
908   // Collect the set of all of the modules we want to visit to emit link
909   // options, which is essentially the imported modules and all of their
910   // non-explicit child modules.
911   llvm::SetVector<clang::Module *> LinkModules;
912   llvm::SmallPtrSet<clang::Module *, 16> Visited;
913   SmallVector<clang::Module *, 16> Stack;
914 
915   // Seed the stack with imported modules.
916   for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
917                                                MEnd = ImportedModules.end();
918        M != MEnd; ++M) {
919     if (Visited.insert(*M))
920       Stack.push_back(*M);
921   }
922 
923   // Find all of the modules to import, making a little effort to prune
924   // non-leaf modules.
925   while (!Stack.empty()) {
926     clang::Module *Mod = Stack.pop_back_val();
927 
928     bool AnyChildren = false;
929 
930     // Visit the submodules of this module.
931     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
932                                         SubEnd = Mod->submodule_end();
933          Sub != SubEnd; ++Sub) {
934       // Skip explicit children; they need to be explicitly imported to be
935       // linked against.
936       if ((*Sub)->IsExplicit)
937         continue;
938 
939       if (Visited.insert(*Sub)) {
940         Stack.push_back(*Sub);
941         AnyChildren = true;
942       }
943     }
944 
945     // We didn't find any children, so add this module to the list of
946     // modules to link against.
947     if (!AnyChildren) {
948       LinkModules.insert(Mod);
949     }
950   }
951 
952   // Add link options for all of the imported modules in reverse topological
953   // order.  We don't do anything to try to order import link flags with respect
954   // to linker options inserted by things like #pragma comment().
955   SmallVector<llvm::Value *, 16> MetadataArgs;
956   Visited.clear();
957   for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
958                                                MEnd = LinkModules.end();
959        M != MEnd; ++M) {
960     if (Visited.insert(*M))
961       addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
962   }
963   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
964   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
965 
966   // Add the linker options metadata flag.
967   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
968                             llvm::MDNode::get(getLLVMContext(),
969                                               LinkerOptionsMetadata));
970 }
971 
972 void CodeGenModule::EmitDeferred() {
973   // Emit code for any potentially referenced deferred decls.  Since a
974   // previously unused static decl may become used during the generation of code
975   // for a static function, iterate until no changes are made.
976 
977   while (true) {
978     if (!DeferredVTables.empty()) {
979       EmitDeferredVTables();
980 
981       // Emitting a v-table doesn't directly cause more v-tables to
982       // become deferred, although it can cause functions to be
983       // emitted that then need those v-tables.
984       assert(DeferredVTables.empty());
985     }
986 
987     // Stop if we're out of both deferred v-tables and deferred declarations.
988     if (DeferredDeclsToEmit.empty()) break;
989 
990     DeferredGlobal &G = DeferredDeclsToEmit.back();
991     GlobalDecl D = G.GD;
992     llvm::GlobalValue *GV = G.GV;
993     DeferredDeclsToEmit.pop_back();
994 
995     assert(GV == GetGlobalValue(getMangledName(D)));
996     // Check to see if we've already emitted this.  This is necessary
997     // for a couple of reasons: first, decls can end up in the
998     // deferred-decls queue multiple times, and second, decls can end
999     // up with definitions in unusual ways (e.g. by an extern inline
1000     // function acquiring a strong function redefinition).  Just
1001     // ignore these cases.
1002     if(!GV->isDeclaration())
1003       continue;
1004 
1005     // Otherwise, emit the definition and move on to the next one.
1006     EmitGlobalDefinition(D, GV);
1007   }
1008 }
1009 
1010 void CodeGenModule::EmitGlobalAnnotations() {
1011   if (Annotations.empty())
1012     return;
1013 
1014   // Create a new global variable for the ConstantStruct in the Module.
1015   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1016     Annotations[0]->getType(), Annotations.size()), Annotations);
1017   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1018                                       llvm::GlobalValue::AppendingLinkage,
1019                                       Array, "llvm.global.annotations");
1020   gv->setSection(AnnotationSection);
1021 }
1022 
1023 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1024   llvm::Constant *&AStr = AnnotationStrings[Str];
1025   if (AStr)
1026     return AStr;
1027 
1028   // Not found yet, create a new global.
1029   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1030   auto *gv =
1031       new llvm::GlobalVariable(getModule(), s->getType(), true,
1032                                llvm::GlobalValue::PrivateLinkage, s, ".str");
1033   gv->setSection(AnnotationSection);
1034   gv->setUnnamedAddr(true);
1035   AStr = gv;
1036   return gv;
1037 }
1038 
1039 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1040   SourceManager &SM = getContext().getSourceManager();
1041   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1042   if (PLoc.isValid())
1043     return EmitAnnotationString(PLoc.getFilename());
1044   return EmitAnnotationString(SM.getBufferName(Loc));
1045 }
1046 
1047 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1048   SourceManager &SM = getContext().getSourceManager();
1049   PresumedLoc PLoc = SM.getPresumedLoc(L);
1050   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1051     SM.getExpansionLineNumber(L);
1052   return llvm::ConstantInt::get(Int32Ty, LineNo);
1053 }
1054 
1055 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1056                                                 const AnnotateAttr *AA,
1057                                                 SourceLocation L) {
1058   // Get the globals for file name, annotation, and the line number.
1059   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1060                  *UnitGV = EmitAnnotationUnit(L),
1061                  *LineNoCst = EmitAnnotationLineNo(L);
1062 
1063   // Create the ConstantStruct for the global annotation.
1064   llvm::Constant *Fields[4] = {
1065     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1066     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1067     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1068     LineNoCst
1069   };
1070   return llvm::ConstantStruct::getAnon(Fields);
1071 }
1072 
1073 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1074                                          llvm::GlobalValue *GV) {
1075   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1076   // Get the struct elements for these annotations.
1077   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1078     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1079 }
1080 
1081 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
1082   // Never defer when EmitAllDecls is specified.
1083   if (LangOpts.EmitAllDecls)
1084     return false;
1085 
1086   return !getContext().DeclMustBeEmitted(Global);
1087 }
1088 
1089 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1090     const CXXUuidofExpr* E) {
1091   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1092   // well-formed.
1093   StringRef Uuid = E->getUuidAsStringRef(Context);
1094   std::string Name = "_GUID_" + Uuid.lower();
1095   std::replace(Name.begin(), Name.end(), '-', '_');
1096 
1097   // Look for an existing global.
1098   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1099     return GV;
1100 
1101   llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1102   assert(Init && "failed to initialize as constant");
1103 
1104   auto *GV = new llvm::GlobalVariable(
1105       getModule(), Init->getType(),
1106       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1107   return GV;
1108 }
1109 
1110 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1111   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1112   assert(AA && "No alias?");
1113 
1114   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1115 
1116   // See if there is already something with the target's name in the module.
1117   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1118   if (Entry) {
1119     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1120     return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1121   }
1122 
1123   llvm::Constant *Aliasee;
1124   if (isa<llvm::FunctionType>(DeclTy))
1125     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1126                                       GlobalDecl(cast<FunctionDecl>(VD)),
1127                                       /*ForVTable=*/false);
1128   else
1129     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1130                                     llvm::PointerType::getUnqual(DeclTy),
1131                                     nullptr);
1132 
1133   auto *F = cast<llvm::GlobalValue>(Aliasee);
1134   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1135   WeakRefReferences.insert(F);
1136 
1137   return Aliasee;
1138 }
1139 
1140 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1141   const auto *Global = cast<ValueDecl>(GD.getDecl());
1142 
1143   // Weak references don't produce any output by themselves.
1144   if (Global->hasAttr<WeakRefAttr>())
1145     return;
1146 
1147   // If this is an alias definition (which otherwise looks like a declaration)
1148   // emit it now.
1149   if (Global->hasAttr<AliasAttr>())
1150     return EmitAliasDefinition(GD);
1151 
1152   // If this is CUDA, be selective about which declarations we emit.
1153   if (LangOpts.CUDA) {
1154     if (CodeGenOpts.CUDAIsDevice) {
1155       if (!Global->hasAttr<CUDADeviceAttr>() &&
1156           !Global->hasAttr<CUDAGlobalAttr>() &&
1157           !Global->hasAttr<CUDAConstantAttr>() &&
1158           !Global->hasAttr<CUDASharedAttr>())
1159         return;
1160     } else {
1161       if (!Global->hasAttr<CUDAHostAttr>() && (
1162             Global->hasAttr<CUDADeviceAttr>() ||
1163             Global->hasAttr<CUDAConstantAttr>() ||
1164             Global->hasAttr<CUDASharedAttr>()))
1165         return;
1166     }
1167   }
1168 
1169   // Ignore declarations, they will be emitted on their first use.
1170   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1171     // Forward declarations are emitted lazily on first use.
1172     if (!FD->doesThisDeclarationHaveABody()) {
1173       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1174         return;
1175 
1176       StringRef MangledName = getMangledName(GD);
1177 
1178       // Compute the function info and LLVM type.
1179       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1180       llvm::Type *Ty = getTypes().GetFunctionType(FI);
1181 
1182       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1183                               /*DontDefer=*/false);
1184       return;
1185     }
1186   } else {
1187     const auto *VD = cast<VarDecl>(Global);
1188     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1189 
1190     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
1191       return;
1192   }
1193 
1194   // Defer code generation when possible if this is a static definition, inline
1195   // function etc.  These we only want to emit if they are used.
1196   if (!MayDeferGeneration(Global)) {
1197     // Emit the definition if it can't be deferred.
1198     EmitGlobalDefinition(GD);
1199     return;
1200   }
1201 
1202   // If we're deferring emission of a C++ variable with an
1203   // initializer, remember the order in which it appeared in the file.
1204   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1205       cast<VarDecl>(Global)->hasInit()) {
1206     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1207     CXXGlobalInits.push_back(nullptr);
1208   }
1209 
1210   // If the value has already been used, add it directly to the
1211   // DeferredDeclsToEmit list.
1212   StringRef MangledName = getMangledName(GD);
1213   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
1214     addDeferredDeclToEmit(GV, GD);
1215   else {
1216     // Otherwise, remember that we saw a deferred decl with this name.  The
1217     // first use of the mangled name will cause it to move into
1218     // DeferredDeclsToEmit.
1219     DeferredDecls[MangledName] = GD;
1220   }
1221 }
1222 
1223 namespace {
1224   struct FunctionIsDirectlyRecursive :
1225     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1226     const StringRef Name;
1227     const Builtin::Context &BI;
1228     bool Result;
1229     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1230       Name(N), BI(C), Result(false) {
1231     }
1232     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1233 
1234     bool TraverseCallExpr(CallExpr *E) {
1235       const FunctionDecl *FD = E->getDirectCallee();
1236       if (!FD)
1237         return true;
1238       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1239       if (Attr && Name == Attr->getLabel()) {
1240         Result = true;
1241         return false;
1242       }
1243       unsigned BuiltinID = FD->getBuiltinID();
1244       if (!BuiltinID)
1245         return true;
1246       StringRef BuiltinName = BI.GetName(BuiltinID);
1247       if (BuiltinName.startswith("__builtin_") &&
1248           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1249         Result = true;
1250         return false;
1251       }
1252       return true;
1253     }
1254   };
1255 }
1256 
1257 // isTriviallyRecursive - Check if this function calls another
1258 // decl that, because of the asm attribute or the other decl being a builtin,
1259 // ends up pointing to itself.
1260 bool
1261 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1262   StringRef Name;
1263   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1264     // asm labels are a special kind of mangling we have to support.
1265     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1266     if (!Attr)
1267       return false;
1268     Name = Attr->getLabel();
1269   } else {
1270     Name = FD->getName();
1271   }
1272 
1273   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1274   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1275   return Walker.Result;
1276 }
1277 
1278 bool
1279 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1280   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1281     return true;
1282   const auto *F = cast<FunctionDecl>(GD.getDecl());
1283   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1284     return false;
1285   // PR9614. Avoid cases where the source code is lying to us. An available
1286   // externally function should have an equivalent function somewhere else,
1287   // but a function that calls itself is clearly not equivalent to the real
1288   // implementation.
1289   // This happens in glibc's btowc and in some configure checks.
1290   return !isTriviallyRecursive(F);
1291 }
1292 
1293 /// If the type for the method's class was generated by
1294 /// CGDebugInfo::createContextChain(), the cache contains only a
1295 /// limited DIType without any declarations. Since EmitFunctionStart()
1296 /// needs to find the canonical declaration for each method, we need
1297 /// to construct the complete type prior to emitting the method.
1298 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1299   if (!D->isInstance())
1300     return;
1301 
1302   if (CGDebugInfo *DI = getModuleDebugInfo())
1303     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1304       const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1305       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1306     }
1307 }
1308 
1309 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1310   const auto *D = cast<ValueDecl>(GD.getDecl());
1311 
1312   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1313                                  Context.getSourceManager(),
1314                                  "Generating code for declaration");
1315 
1316   if (isa<FunctionDecl>(D)) {
1317     // At -O0, don't generate IR for functions with available_externally
1318     // linkage.
1319     if (!shouldEmitFunction(GD))
1320       return;
1321 
1322     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1323       CompleteDIClassType(Method);
1324       // Make sure to emit the definition(s) before we emit the thunks.
1325       // This is necessary for the generation of certain thunks.
1326       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1327         EmitCXXConstructor(CD, GD.getCtorType());
1328       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1329         EmitCXXDestructor(DD, GD.getDtorType());
1330       else
1331         EmitGlobalFunctionDefinition(GD, GV);
1332 
1333       if (Method->isVirtual())
1334         getVTables().EmitThunks(GD);
1335 
1336       return;
1337     }
1338 
1339     return EmitGlobalFunctionDefinition(GD, GV);
1340   }
1341 
1342   if (const auto *VD = dyn_cast<VarDecl>(D))
1343     return EmitGlobalVarDefinition(VD);
1344 
1345   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1346 }
1347 
1348 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1349 /// module, create and return an llvm Function with the specified type. If there
1350 /// is something in the module with the specified name, return it potentially
1351 /// bitcasted to the right type.
1352 ///
1353 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1354 /// to set the attributes on the function when it is first created.
1355 llvm::Constant *
1356 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1357                                        llvm::Type *Ty,
1358                                        GlobalDecl GD, bool ForVTable,
1359                                        bool DontDefer,
1360                                        llvm::AttributeSet ExtraAttrs) {
1361   const Decl *D = GD.getDecl();
1362 
1363   // Lookup the entry, lazily creating it if necessary.
1364   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1365   if (Entry) {
1366     if (WeakRefReferences.erase(Entry)) {
1367       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1368       if (FD && !FD->hasAttr<WeakAttr>())
1369         Entry->setLinkage(llvm::Function::ExternalLinkage);
1370     }
1371 
1372     if (Entry->getType()->getElementType() == Ty)
1373       return Entry;
1374 
1375     // Make sure the result is of the correct type.
1376     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1377   }
1378 
1379   // This function doesn't have a complete type (for example, the return
1380   // type is an incomplete struct). Use a fake type instead, and make
1381   // sure not to try to set attributes.
1382   bool IsIncompleteFunction = false;
1383 
1384   llvm::FunctionType *FTy;
1385   if (isa<llvm::FunctionType>(Ty)) {
1386     FTy = cast<llvm::FunctionType>(Ty);
1387   } else {
1388     FTy = llvm::FunctionType::get(VoidTy, false);
1389     IsIncompleteFunction = true;
1390   }
1391 
1392   llvm::Function *F = llvm::Function::Create(FTy,
1393                                              llvm::Function::ExternalLinkage,
1394                                              MangledName, &getModule());
1395   assert(F->getName() == MangledName && "name was uniqued!");
1396   if (D)
1397     SetFunctionAttributes(GD, F, IsIncompleteFunction);
1398   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1399     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1400     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1401                      llvm::AttributeSet::get(VMContext,
1402                                              llvm::AttributeSet::FunctionIndex,
1403                                              B));
1404   }
1405 
1406   if (!DontDefer) {
1407     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1408     // each other bottoming out with the base dtor.  Therefore we emit non-base
1409     // dtors on usage, even if there is no dtor definition in the TU.
1410     if (D && isa<CXXDestructorDecl>(D) &&
1411         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1412                                            GD.getDtorType()))
1413       addDeferredDeclToEmit(F, GD);
1414 
1415     // This is the first use or definition of a mangled name.  If there is a
1416     // deferred decl with this name, remember that we need to emit it at the end
1417     // of the file.
1418     llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1419     if (DDI != DeferredDecls.end()) {
1420       // Move the potentially referenced deferred decl to the
1421       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1422       // don't need it anymore).
1423       addDeferredDeclToEmit(F, DDI->second);
1424       DeferredDecls.erase(DDI);
1425 
1426       // Otherwise, if this is a sized deallocation function, emit a weak
1427       // definition
1428       // for it at the end of the translation unit.
1429     } else if (D && cast<FunctionDecl>(D)
1430                         ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
1431       addDeferredDeclToEmit(F, GD);
1432 
1433       // Otherwise, there are cases we have to worry about where we're
1434       // using a declaration for which we must emit a definition but where
1435       // we might not find a top-level definition:
1436       //   - member functions defined inline in their classes
1437       //   - friend functions defined inline in some class
1438       //   - special member functions with implicit definitions
1439       // If we ever change our AST traversal to walk into class methods,
1440       // this will be unnecessary.
1441       //
1442       // We also don't emit a definition for a function if it's going to be an
1443       // entry
1444       // in a vtable, unless it's already marked as used.
1445     } else if (getLangOpts().CPlusPlus && D) {
1446       // Look for a declaration that's lexically in a record.
1447       const auto *FD = cast<FunctionDecl>(D);
1448       FD = FD->getMostRecentDecl();
1449       do {
1450         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1451           if (FD->isImplicit() && !ForVTable) {
1452             assert(FD->isUsed() &&
1453                    "Sema didn't mark implicit function as used!");
1454             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1455             break;
1456           } else if (FD->doesThisDeclarationHaveABody()) {
1457             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1458             break;
1459           }
1460         }
1461         FD = FD->getPreviousDecl();
1462       } while (FD);
1463     }
1464   }
1465 
1466   getTargetCodeGenInfo().emitTargetMD(D, F, *this);
1467 
1468   // Make sure the result is of the requested type.
1469   if (!IsIncompleteFunction) {
1470     assert(F->getType()->getElementType() == Ty);
1471     return F;
1472   }
1473 
1474   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1475   return llvm::ConstantExpr::getBitCast(F, PTy);
1476 }
1477 
1478 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1479 /// non-null, then this function will use the specified type if it has to
1480 /// create it (this occurs when we see a definition of the function).
1481 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1482                                                  llvm::Type *Ty,
1483                                                  bool ForVTable,
1484                                                  bool DontDefer) {
1485   // If there was no specific requested type, just convert it now.
1486   if (!Ty)
1487     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1488 
1489   StringRef MangledName = getMangledName(GD);
1490   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
1491 }
1492 
1493 /// CreateRuntimeFunction - Create a new runtime function with the specified
1494 /// type and name.
1495 llvm::Constant *
1496 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1497                                      StringRef Name,
1498                                      llvm::AttributeSet ExtraAttrs) {
1499   llvm::Constant *C =
1500       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1501                               /*DontDefer=*/false, ExtraAttrs);
1502   if (auto *F = dyn_cast<llvm::Function>(C))
1503     if (F->empty())
1504       F->setCallingConv(getRuntimeCC());
1505   return C;
1506 }
1507 
1508 /// isTypeConstant - Determine whether an object of this type can be emitted
1509 /// as a constant.
1510 ///
1511 /// If ExcludeCtor is true, the duration when the object's constructor runs
1512 /// will not be considered. The caller will need to verify that the object is
1513 /// not written to during its construction.
1514 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1515   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1516     return false;
1517 
1518   if (Context.getLangOpts().CPlusPlus) {
1519     if (const CXXRecordDecl *Record
1520           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1521       return ExcludeCtor && !Record->hasMutableFields() &&
1522              Record->hasTrivialDestructor();
1523   }
1524 
1525   return true;
1526 }
1527 
1528 static bool isVarDeclInlineInitializedStaticDataMember(const VarDecl *VD) {
1529   if (!VD->isStaticDataMember())
1530     return false;
1531   const VarDecl *InitDecl;
1532   const Expr *InitExpr = VD->getAnyInitializer(InitDecl);
1533   if (!InitExpr)
1534     return false;
1535   if (InitDecl->isThisDeclarationADefinition())
1536     return false;
1537   return true;
1538 }
1539 
1540 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1541 /// create and return an llvm GlobalVariable with the specified type.  If there
1542 /// is something in the module with the specified name, return it potentially
1543 /// bitcasted to the right type.
1544 ///
1545 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1546 /// to set the attributes on the global when it is first created.
1547 llvm::Constant *
1548 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1549                                      llvm::PointerType *Ty,
1550                                      const VarDecl *D) {
1551   // Lookup the entry, lazily creating it if necessary.
1552   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1553   if (Entry) {
1554     if (WeakRefReferences.erase(Entry)) {
1555       if (D && !D->hasAttr<WeakAttr>())
1556         Entry->setLinkage(llvm::Function::ExternalLinkage);
1557     }
1558 
1559     if (Entry->getType() == Ty)
1560       return Entry;
1561 
1562     // Make sure the result is of the correct type.
1563     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1564       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1565 
1566     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1567   }
1568 
1569   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1570   auto *GV = new llvm::GlobalVariable(
1571       getModule(), Ty->getElementType(), false,
1572       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
1573       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1574 
1575   // This is the first use or definition of a mangled name.  If there is a
1576   // deferred decl with this name, remember that we need to emit it at the end
1577   // of the file.
1578   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1579   if (DDI != DeferredDecls.end()) {
1580     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1581     // list, and remove it from DeferredDecls (since we don't need it anymore).
1582     addDeferredDeclToEmit(GV, DDI->second);
1583     DeferredDecls.erase(DDI);
1584   }
1585 
1586   // Handle things which are present even on external declarations.
1587   if (D) {
1588     // FIXME: This code is overly simple and should be merged with other global
1589     // handling.
1590     GV->setConstant(isTypeConstant(D->getType(), false));
1591 
1592     setLinkageAndVisibilityForGV(GV, D);
1593 
1594     if (D->getTLSKind()) {
1595       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1596         CXXThreadLocals.push_back(std::make_pair(D, GV));
1597       setTLSMode(GV, *D);
1598     }
1599 
1600     // If required by the ABI, treat declarations of static data members with
1601     // inline initializers as definitions.
1602     if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1603         isVarDeclInlineInitializedStaticDataMember(D))
1604       EmitGlobalVarDefinition(D);
1605 
1606     // Handle XCore specific ABI requirements.
1607     if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1608         D->getLanguageLinkage() == CLanguageLinkage &&
1609         D->getType().isConstant(Context) &&
1610         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1611       GV->setSection(".cp.rodata");
1612   }
1613 
1614   if (AddrSpace != Ty->getAddressSpace())
1615     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1616 
1617   getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
1618 
1619   return GV;
1620 }
1621 
1622 
1623 llvm::GlobalVariable *
1624 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1625                                       llvm::Type *Ty,
1626                                       llvm::GlobalValue::LinkageTypes Linkage) {
1627   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1628   llvm::GlobalVariable *OldGV = nullptr;
1629 
1630   if (GV) {
1631     // Check if the variable has the right type.
1632     if (GV->getType()->getElementType() == Ty)
1633       return GV;
1634 
1635     // Because C++ name mangling, the only way we can end up with an already
1636     // existing global with the same name is if it has been declared extern "C".
1637     assert(GV->isDeclaration() && "Declaration has wrong type!");
1638     OldGV = GV;
1639   }
1640 
1641   // Create a new variable.
1642   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1643                                 Linkage, nullptr, Name);
1644 
1645   if (OldGV) {
1646     // Replace occurrences of the old variable if needed.
1647     GV->takeName(OldGV);
1648 
1649     if (!OldGV->use_empty()) {
1650       llvm::Constant *NewPtrForOldDecl =
1651       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1652       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1653     }
1654 
1655     OldGV->eraseFromParent();
1656   }
1657 
1658   return GV;
1659 }
1660 
1661 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1662 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1663 /// then it will be created with the specified type instead of whatever the
1664 /// normal requested type would be.
1665 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1666                                                   llvm::Type *Ty) {
1667   assert(D->hasGlobalStorage() && "Not a global variable");
1668   QualType ASTTy = D->getType();
1669   if (!Ty)
1670     Ty = getTypes().ConvertTypeForMem(ASTTy);
1671 
1672   llvm::PointerType *PTy =
1673     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1674 
1675   StringRef MangledName = getMangledName(D);
1676   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1677 }
1678 
1679 /// CreateRuntimeVariable - Create a new runtime global variable with the
1680 /// specified type and name.
1681 llvm::Constant *
1682 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1683                                      StringRef Name) {
1684   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
1685 }
1686 
1687 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1688   assert(!D->getInit() && "Cannot emit definite definitions here!");
1689 
1690   if (MayDeferGeneration(D)) {
1691     // If we have not seen a reference to this variable yet, place it
1692     // into the deferred declarations table to be emitted if needed
1693     // later.
1694     StringRef MangledName = getMangledName(D);
1695     if (!GetGlobalValue(MangledName)) {
1696       DeferredDecls[MangledName] = D;
1697       return;
1698     }
1699   }
1700 
1701   // The tentative definition is the only definition.
1702   EmitGlobalVarDefinition(D);
1703 }
1704 
1705 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1706     return Context.toCharUnitsFromBits(
1707       TheDataLayout.getTypeStoreSizeInBits(Ty));
1708 }
1709 
1710 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1711                                                  unsigned AddrSpace) {
1712   if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1713     if (D->hasAttr<CUDAConstantAttr>())
1714       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1715     else if (D->hasAttr<CUDASharedAttr>())
1716       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1717     else
1718       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1719   }
1720 
1721   return AddrSpace;
1722 }
1723 
1724 template<typename SomeDecl>
1725 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1726                                                llvm::GlobalValue *GV) {
1727   if (!getLangOpts().CPlusPlus)
1728     return;
1729 
1730   // Must have 'used' attribute, or else inline assembly can't rely on
1731   // the name existing.
1732   if (!D->template hasAttr<UsedAttr>())
1733     return;
1734 
1735   // Must have internal linkage and an ordinary name.
1736   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1737     return;
1738 
1739   // Must be in an extern "C" context. Entities declared directly within
1740   // a record are not extern "C" even if the record is in such a context.
1741   const SomeDecl *First = D->getFirstDecl();
1742   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1743     return;
1744 
1745   // OK, this is an internal linkage entity inside an extern "C" linkage
1746   // specification. Make a note of that so we can give it the "expected"
1747   // mangled name if nothing else is using that name.
1748   std::pair<StaticExternCMap::iterator, bool> R =
1749       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1750 
1751   // If we have multiple internal linkage entities with the same name
1752   // in extern "C" regions, none of them gets that name.
1753   if (!R.second)
1754     R.first->second = nullptr;
1755 }
1756 
1757 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1758   llvm::Constant *Init = nullptr;
1759   QualType ASTTy = D->getType();
1760   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1761   bool NeedsGlobalCtor = false;
1762   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1763 
1764   const VarDecl *InitDecl;
1765   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1766 
1767   if (!InitExpr) {
1768     // This is a tentative definition; tentative definitions are
1769     // implicitly initialized with { 0 }.
1770     //
1771     // Note that tentative definitions are only emitted at the end of
1772     // a translation unit, so they should never have incomplete
1773     // type. In addition, EmitTentativeDefinition makes sure that we
1774     // never attempt to emit a tentative definition if a real one
1775     // exists. A use may still exists, however, so we still may need
1776     // to do a RAUW.
1777     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1778     Init = EmitNullConstant(D->getType());
1779   } else {
1780     initializedGlobalDecl = GlobalDecl(D);
1781     Init = EmitConstantInit(*InitDecl);
1782 
1783     if (!Init) {
1784       QualType T = InitExpr->getType();
1785       if (D->getType()->isReferenceType())
1786         T = D->getType();
1787 
1788       if (getLangOpts().CPlusPlus) {
1789         Init = EmitNullConstant(T);
1790         NeedsGlobalCtor = true;
1791       } else {
1792         ErrorUnsupported(D, "static initializer");
1793         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1794       }
1795     } else {
1796       // We don't need an initializer, so remove the entry for the delayed
1797       // initializer position (just in case this entry was delayed) if we
1798       // also don't need to register a destructor.
1799       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1800         DelayedCXXInitPosition.erase(D);
1801     }
1802   }
1803 
1804   llvm::Type* InitType = Init->getType();
1805   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1806 
1807   // Strip off a bitcast if we got one back.
1808   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1809     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1810            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1811            // All zero index gep.
1812            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1813     Entry = CE->getOperand(0);
1814   }
1815 
1816   // Entry is now either a Function or GlobalVariable.
1817   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1818 
1819   // We have a definition after a declaration with the wrong type.
1820   // We must make a new GlobalVariable* and update everything that used OldGV
1821   // (a declaration or tentative definition) with the new GlobalVariable*
1822   // (which will be a definition).
1823   //
1824   // This happens if there is a prototype for a global (e.g.
1825   // "extern int x[];") and then a definition of a different type (e.g.
1826   // "int x[10];"). This also happens when an initializer has a different type
1827   // from the type of the global (this happens with unions).
1828   if (!GV ||
1829       GV->getType()->getElementType() != InitType ||
1830       GV->getType()->getAddressSpace() !=
1831        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1832 
1833     // Move the old entry aside so that we'll create a new one.
1834     Entry->setName(StringRef());
1835 
1836     // Make a new global with the correct type, this is now guaranteed to work.
1837     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1838 
1839     // Replace all uses of the old global with the new global
1840     llvm::Constant *NewPtrForOldDecl =
1841         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1842     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1843 
1844     // Erase the old global, since it is no longer used.
1845     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1846   }
1847 
1848   MaybeHandleStaticInExternC(D, GV);
1849 
1850   if (D->hasAttr<AnnotateAttr>())
1851     AddGlobalAnnotations(D, GV);
1852 
1853   GV->setInitializer(Init);
1854 
1855   // If it is safe to mark the global 'constant', do so now.
1856   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1857                   isTypeConstant(D->getType(), true));
1858 
1859   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1860 
1861   // Set the llvm linkage type as appropriate.
1862   llvm::GlobalValue::LinkageTypes Linkage =
1863       getLLVMLinkageVarDefinition(D, GV->isConstant());
1864   GV->setLinkage(Linkage);
1865   if (D->hasAttr<DLLImportAttr>())
1866     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1867   else if (D->hasAttr<DLLExportAttr>())
1868     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1869 
1870   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1871     // common vars aren't constant even if declared const.
1872     GV->setConstant(false);
1873 
1874   setNonAliasAttributes(D, GV);
1875 
1876   // Emit the initializer function if necessary.
1877   if (NeedsGlobalCtor || NeedsGlobalDtor)
1878     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1879 
1880   // If we are compiling with ASan, add metadata indicating dynamically
1881   // initialized globals.
1882   if (SanOpts.Address && NeedsGlobalCtor) {
1883     llvm::Module &M = getModule();
1884 
1885     llvm::NamedMDNode *DynamicInitializers =
1886         M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1887     llvm::Value *GlobalToAdd[] = { GV };
1888     llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1889     DynamicInitializers->addOperand(ThisGlobal);
1890   }
1891 
1892   // Emit global variable debug information.
1893   if (CGDebugInfo *DI = getModuleDebugInfo())
1894     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1895       DI->EmitGlobalVariable(GV, D);
1896 }
1897 
1898 static bool isVarDeclStrongDefinition(const VarDecl *D, bool NoCommon) {
1899   // Don't give variables common linkage if -fno-common was specified unless it
1900   // was overridden by a NoCommon attribute.
1901   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
1902     return true;
1903 
1904   // C11 6.9.2/2:
1905   //   A declaration of an identifier for an object that has file scope without
1906   //   an initializer, and without a storage-class specifier or with the
1907   //   storage-class specifier static, constitutes a tentative definition.
1908   if (D->getInit() || D->hasExternalStorage())
1909     return true;
1910 
1911   // A variable cannot be both common and exist in a section.
1912   if (D->hasAttr<SectionAttr>())
1913     return true;
1914 
1915   // Thread local vars aren't considered common linkage.
1916   if (D->getTLSKind())
1917     return true;
1918 
1919   // Tentative definitions marked with WeakImportAttr are true definitions.
1920   if (D->hasAttr<WeakImportAttr>())
1921     return true;
1922 
1923   return false;
1924 }
1925 
1926 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
1927     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
1928   if (Linkage == GVA_Internal)
1929     return llvm::Function::InternalLinkage;
1930 
1931   if (D->hasAttr<WeakAttr>()) {
1932     if (IsConstantVariable)
1933       return llvm::GlobalVariable::WeakODRLinkage;
1934     else
1935       return llvm::GlobalVariable::WeakAnyLinkage;
1936   }
1937 
1938   // We are guaranteed to have a strong definition somewhere else,
1939   // so we can use available_externally linkage.
1940   if (Linkage == GVA_AvailableExternally)
1941     return llvm::Function::AvailableExternallyLinkage;
1942 
1943   // Note that Apple's kernel linker doesn't support symbol
1944   // coalescing, so we need to avoid linkonce and weak linkages there.
1945   // Normally, this means we just map to internal, but for explicit
1946   // instantiations we'll map to external.
1947 
1948   // In C++, the compiler has to emit a definition in every translation unit
1949   // that references the function.  We should use linkonce_odr because
1950   // a) if all references in this translation unit are optimized away, we
1951   // don't need to codegen it.  b) if the function persists, it needs to be
1952   // merged with other definitions. c) C++ has the ODR, so we know the
1953   // definition is dependable.
1954   if (Linkage == GVA_DiscardableODR)
1955     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
1956                                             : llvm::Function::InternalLinkage;
1957 
1958   // An explicit instantiation of a template has weak linkage, since
1959   // explicit instantiations can occur in multiple translation units
1960   // and must all be equivalent. However, we are not allowed to
1961   // throw away these explicit instantiations.
1962   if (Linkage == GVA_StrongODR)
1963     return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
1964                                             : llvm::Function::ExternalLinkage;
1965 
1966   // If required by the ABI, give definitions of static data members with inline
1967   // initializers at least linkonce_odr linkage.
1968   if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1969       isa<VarDecl>(D) &&
1970       isVarDeclInlineInitializedStaticDataMember(cast<VarDecl>(D)))
1971     return llvm::GlobalValue::LinkOnceODRLinkage;
1972 
1973   // C++ doesn't have tentative definitions and thus cannot have common
1974   // linkage.
1975   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
1976       !isVarDeclStrongDefinition(cast<VarDecl>(D), CodeGenOpts.NoCommon))
1977     return llvm::GlobalVariable::CommonLinkage;
1978 
1979   // selectany symbols are externally visible, so use weak instead of
1980   // linkonce.  MSVC optimizes away references to const selectany globals, so
1981   // all definitions should be the same and ODR linkage should be used.
1982   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
1983   if (D->hasAttr<SelectAnyAttr>())
1984     return llvm::GlobalVariable::WeakODRLinkage;
1985 
1986   // Otherwise, we have strong external linkage.
1987   assert(Linkage == GVA_StrongExternal);
1988   return llvm::GlobalVariable::ExternalLinkage;
1989 }
1990 
1991 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
1992     const VarDecl *VD, bool IsConstant) {
1993   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
1994   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
1995 }
1996 
1997 /// Replace the uses of a function that was declared with a non-proto type.
1998 /// We want to silently drop extra arguments from call sites
1999 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2000                                           llvm::Function *newFn) {
2001   // Fast path.
2002   if (old->use_empty()) return;
2003 
2004   llvm::Type *newRetTy = newFn->getReturnType();
2005   SmallVector<llvm::Value*, 4> newArgs;
2006 
2007   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2008          ui != ue; ) {
2009     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2010     llvm::User *user = use->getUser();
2011 
2012     // Recognize and replace uses of bitcasts.  Most calls to
2013     // unprototyped functions will use bitcasts.
2014     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2015       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2016         replaceUsesOfNonProtoConstant(bitcast, newFn);
2017       continue;
2018     }
2019 
2020     // Recognize calls to the function.
2021     llvm::CallSite callSite(user);
2022     if (!callSite) continue;
2023     if (!callSite.isCallee(&*use)) continue;
2024 
2025     // If the return types don't match exactly, then we can't
2026     // transform this call unless it's dead.
2027     if (callSite->getType() != newRetTy && !callSite->use_empty())
2028       continue;
2029 
2030     // Get the call site's attribute list.
2031     SmallVector<llvm::AttributeSet, 8> newAttrs;
2032     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2033 
2034     // Collect any return attributes from the call.
2035     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2036       newAttrs.push_back(
2037         llvm::AttributeSet::get(newFn->getContext(),
2038                                 oldAttrs.getRetAttributes()));
2039 
2040     // If the function was passed too few arguments, don't transform.
2041     unsigned newNumArgs = newFn->arg_size();
2042     if (callSite.arg_size() < newNumArgs) continue;
2043 
2044     // If extra arguments were passed, we silently drop them.
2045     // If any of the types mismatch, we don't transform.
2046     unsigned argNo = 0;
2047     bool dontTransform = false;
2048     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2049            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2050       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2051         dontTransform = true;
2052         break;
2053       }
2054 
2055       // Add any parameter attributes.
2056       if (oldAttrs.hasAttributes(argNo + 1))
2057         newAttrs.
2058           push_back(llvm::
2059                     AttributeSet::get(newFn->getContext(),
2060                                       oldAttrs.getParamAttributes(argNo + 1)));
2061     }
2062     if (dontTransform)
2063       continue;
2064 
2065     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2066       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2067                                                  oldAttrs.getFnAttributes()));
2068 
2069     // Okay, we can transform this.  Create the new call instruction and copy
2070     // over the required information.
2071     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2072 
2073     llvm::CallSite newCall;
2074     if (callSite.isCall()) {
2075       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2076                                        callSite.getInstruction());
2077     } else {
2078       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2079       newCall = llvm::InvokeInst::Create(newFn,
2080                                          oldInvoke->getNormalDest(),
2081                                          oldInvoke->getUnwindDest(),
2082                                          newArgs, "",
2083                                          callSite.getInstruction());
2084     }
2085     newArgs.clear(); // for the next iteration
2086 
2087     if (!newCall->getType()->isVoidTy())
2088       newCall->takeName(callSite.getInstruction());
2089     newCall.setAttributes(
2090                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2091     newCall.setCallingConv(callSite.getCallingConv());
2092 
2093     // Finally, remove the old call, replacing any uses with the new one.
2094     if (!callSite->use_empty())
2095       callSite->replaceAllUsesWith(newCall.getInstruction());
2096 
2097     // Copy debug location attached to CI.
2098     if (!callSite->getDebugLoc().isUnknown())
2099       newCall->setDebugLoc(callSite->getDebugLoc());
2100     callSite->eraseFromParent();
2101   }
2102 }
2103 
2104 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2105 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2106 /// existing call uses of the old function in the module, this adjusts them to
2107 /// call the new function directly.
2108 ///
2109 /// This is not just a cleanup: the always_inline pass requires direct calls to
2110 /// functions to be able to inline them.  If there is a bitcast in the way, it
2111 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2112 /// run at -O0.
2113 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2114                                                       llvm::Function *NewFn) {
2115   // If we're redefining a global as a function, don't transform it.
2116   if (!isa<llvm::Function>(Old)) return;
2117 
2118   replaceUsesOfNonProtoConstant(Old, NewFn);
2119 }
2120 
2121 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2122   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2123   // If we have a definition, this might be a deferred decl. If the
2124   // instantiation is explicit, make sure we emit it at the end.
2125   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2126     GetAddrOfGlobalVar(VD);
2127 
2128   EmitTopLevelDecl(VD);
2129 }
2130 
2131 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2132                                                  llvm::GlobalValue *GV) {
2133   const auto *D = cast<FunctionDecl>(GD.getDecl());
2134 
2135   // Compute the function info and LLVM type.
2136   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2137   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2138 
2139   // Get or create the prototype for the function.
2140   if (!GV) {
2141     llvm::Constant *C =
2142         GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
2143 
2144     // Strip off a bitcast if we got one back.
2145     if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
2146       assert(CE->getOpcode() == llvm::Instruction::BitCast);
2147       GV = cast<llvm::GlobalValue>(CE->getOperand(0));
2148     } else {
2149       GV = cast<llvm::GlobalValue>(C);
2150     }
2151   }
2152 
2153   if (!GV->isDeclaration()) {
2154     getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2155     return;
2156   }
2157 
2158   if (GV->getType()->getElementType() != Ty) {
2159     // If the types mismatch then we have to rewrite the definition.
2160     assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
2161 
2162     // F is the Function* for the one with the wrong type, we must make a new
2163     // Function* and update everything that used F (a declaration) with the new
2164     // Function* (which will be a definition).
2165     //
2166     // This happens if there is a prototype for a function
2167     // (e.g. "int f()") and then a definition of a different type
2168     // (e.g. "int f(int x)").  Move the old function aside so that it
2169     // doesn't interfere with GetAddrOfFunction.
2170     GV->setName(StringRef());
2171     auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2172 
2173     // This might be an implementation of a function without a
2174     // prototype, in which case, try to do special replacement of
2175     // calls which match the new prototype.  The really key thing here
2176     // is that we also potentially drop arguments from the call site
2177     // so as to make a direct call, which makes the inliner happier
2178     // and suppresses a number of optimizer warnings (!) about
2179     // dropping arguments.
2180     if (!GV->use_empty()) {
2181       ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
2182       GV->removeDeadConstantUsers();
2183     }
2184 
2185     // Replace uses of F with the Function we will endow with a body.
2186     if (!GV->use_empty()) {
2187       llvm::Constant *NewPtrForOldDecl =
2188           llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
2189       GV->replaceAllUsesWith(NewPtrForOldDecl);
2190     }
2191 
2192     // Ok, delete the old function now, which is dead.
2193     GV->eraseFromParent();
2194 
2195     GV = NewFn;
2196   }
2197 
2198   // We need to set linkage and visibility on the function before
2199   // generating code for it because various parts of IR generation
2200   // want to propagate this information down (e.g. to local static
2201   // declarations).
2202   auto *Fn = cast<llvm::Function>(GV);
2203   setFunctionLinkage(GD, Fn);
2204 
2205   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
2206   setGlobalVisibility(Fn, D);
2207 
2208   MaybeHandleStaticInExternC(D, Fn);
2209 
2210   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2211 
2212   setFunctionDefinitionAttributes(D, Fn);
2213   SetLLVMFunctionAttributesForDefinition(D, Fn);
2214 
2215   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2216     AddGlobalCtor(Fn, CA->getPriority());
2217   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2218     AddGlobalDtor(Fn, DA->getPriority());
2219   if (D->hasAttr<AnnotateAttr>())
2220     AddGlobalAnnotations(D, Fn);
2221 }
2222 
2223 static llvm::GlobalObject &getGlobalObjectInExpr(DiagnosticsEngine &Diags,
2224                                                  const AliasAttr *AA,
2225                                                  llvm::Constant *C) {
2226   if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
2227     return *GO;
2228 
2229   auto *GA = dyn_cast<llvm::GlobalAlias>(C);
2230   if (GA) {
2231     if (GA->mayBeOverridden()) {
2232       Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
2233           << GA->getAliasee()->getName() << GA->getName();
2234     }
2235 
2236     return *GA->getAliasee();
2237   }
2238 
2239   auto *CE = cast<llvm::ConstantExpr>(C);
2240   assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2241          CE->getOpcode() == llvm::Instruction::GetElementPtr ||
2242          CE->getOpcode() == llvm::Instruction::AddrSpaceCast);
2243   return *cast<llvm::GlobalObject>(CE->getOperand(0));
2244 }
2245 
2246 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2247   const auto *D = cast<ValueDecl>(GD.getDecl());
2248   const AliasAttr *AA = D->getAttr<AliasAttr>();
2249   assert(AA && "Not an alias?");
2250 
2251   StringRef MangledName = getMangledName(GD);
2252 
2253   // If there is a definition in the module, then it wins over the alias.
2254   // This is dubious, but allow it to be safe.  Just ignore the alias.
2255   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2256   if (Entry && !Entry->isDeclaration())
2257     return;
2258 
2259   Aliases.push_back(GD);
2260 
2261   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2262 
2263   // Create a reference to the named value.  This ensures that it is emitted
2264   // if a deferred decl.
2265   llvm::Constant *Aliasee;
2266   if (isa<llvm::FunctionType>(DeclTy))
2267     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2268                                       /*ForVTable=*/false);
2269   else
2270     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2271                                     llvm::PointerType::getUnqual(DeclTy),
2272                                     nullptr);
2273 
2274   // Create the new alias itself, but don't set a name yet.
2275   auto *GA = llvm::GlobalAlias::create(
2276       cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0,
2277       llvm::Function::ExternalLinkage, "",
2278       &getGlobalObjectInExpr(Diags, AA, Aliasee));
2279 
2280   if (Entry) {
2281     if (GA->getAliasee() == Entry) {
2282       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2283       return;
2284     }
2285 
2286     assert(Entry->isDeclaration());
2287 
2288     // If there is a declaration in the module, then we had an extern followed
2289     // by the alias, as in:
2290     //   extern int test6();
2291     //   ...
2292     //   int test6() __attribute__((alias("test7")));
2293     //
2294     // Remove it and replace uses of it with the alias.
2295     GA->takeName(Entry);
2296 
2297     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2298                                                           Entry->getType()));
2299     Entry->eraseFromParent();
2300   } else {
2301     GA->setName(MangledName);
2302   }
2303 
2304   // Set attributes which are particular to an alias; this is a
2305   // specialization of the attributes which may be set on a global
2306   // variable/function.
2307   if (D->hasAttr<DLLExportAttr>()) {
2308     if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2309       // The dllexport attribute is ignored for undefined symbols.
2310       if (FD->hasBody())
2311         GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2312     } else {
2313       GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2314     }
2315   } else if (D->hasAttr<WeakAttr>() ||
2316              D->hasAttr<WeakRefAttr>() ||
2317              D->isWeakImported()) {
2318     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2319   }
2320 
2321   SetCommonAttributes(D, GA);
2322 }
2323 
2324 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2325                                             ArrayRef<llvm::Type*> Tys) {
2326   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2327                                          Tys);
2328 }
2329 
2330 static llvm::StringMapEntry<llvm::Constant*> &
2331 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2332                          const StringLiteral *Literal,
2333                          bool TargetIsLSB,
2334                          bool &IsUTF16,
2335                          unsigned &StringLength) {
2336   StringRef String = Literal->getString();
2337   unsigned NumBytes = String.size();
2338 
2339   // Check for simple case.
2340   if (!Literal->containsNonAsciiOrNull()) {
2341     StringLength = NumBytes;
2342     return Map.GetOrCreateValue(String);
2343   }
2344 
2345   // Otherwise, convert the UTF8 literals into a string of shorts.
2346   IsUTF16 = true;
2347 
2348   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2349   const UTF8 *FromPtr = (const UTF8 *)String.data();
2350   UTF16 *ToPtr = &ToBuf[0];
2351 
2352   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2353                            &ToPtr, ToPtr + NumBytes,
2354                            strictConversion);
2355 
2356   // ConvertUTF8toUTF16 returns the length in ToPtr.
2357   StringLength = ToPtr - &ToBuf[0];
2358 
2359   // Add an explicit null.
2360   *ToPtr = 0;
2361   return Map.
2362     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2363                                (StringLength + 1) * 2));
2364 }
2365 
2366 static llvm::StringMapEntry<llvm::Constant*> &
2367 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2368                        const StringLiteral *Literal,
2369                        unsigned &StringLength) {
2370   StringRef String = Literal->getString();
2371   StringLength = String.size();
2372   return Map.GetOrCreateValue(String);
2373 }
2374 
2375 llvm::Constant *
2376 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2377   unsigned StringLength = 0;
2378   bool isUTF16 = false;
2379   llvm::StringMapEntry<llvm::Constant*> &Entry =
2380     GetConstantCFStringEntry(CFConstantStringMap, Literal,
2381                              getDataLayout().isLittleEndian(),
2382                              isUTF16, StringLength);
2383 
2384   if (llvm::Constant *C = Entry.getValue())
2385     return C;
2386 
2387   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2388   llvm::Constant *Zeros[] = { Zero, Zero };
2389   llvm::Value *V;
2390 
2391   // If we don't already have it, get __CFConstantStringClassReference.
2392   if (!CFConstantStringClassRef) {
2393     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2394     Ty = llvm::ArrayType::get(Ty, 0);
2395     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2396                                            "__CFConstantStringClassReference");
2397     // Decay array -> ptr
2398     V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2399     CFConstantStringClassRef = V;
2400   }
2401   else
2402     V = CFConstantStringClassRef;
2403 
2404   QualType CFTy = getContext().getCFConstantStringType();
2405 
2406   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2407 
2408   llvm::Constant *Fields[4];
2409 
2410   // Class pointer.
2411   Fields[0] = cast<llvm::ConstantExpr>(V);
2412 
2413   // Flags.
2414   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2415   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2416     llvm::ConstantInt::get(Ty, 0x07C8);
2417 
2418   // String pointer.
2419   llvm::Constant *C = nullptr;
2420   if (isUTF16) {
2421     ArrayRef<uint16_t> Arr =
2422       llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2423                                      const_cast<char *>(Entry.getKey().data())),
2424                                    Entry.getKey().size() / 2);
2425     C = llvm::ConstantDataArray::get(VMContext, Arr);
2426   } else {
2427     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2428   }
2429 
2430   // Note: -fwritable-strings doesn't make the backing store strings of
2431   // CFStrings writable. (See <rdar://problem/10657500>)
2432   auto *GV =
2433       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2434                                llvm::GlobalValue::PrivateLinkage, C, ".str");
2435   GV->setUnnamedAddr(true);
2436   // Don't enforce the target's minimum global alignment, since the only use
2437   // of the string is via this class initializer.
2438   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2439   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2440   // that changes the section it ends in, which surprises ld64.
2441   if (isUTF16) {
2442     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2443     GV->setAlignment(Align.getQuantity());
2444     GV->setSection("__TEXT,__ustring");
2445   } else {
2446     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2447     GV->setAlignment(Align.getQuantity());
2448     GV->setSection("__TEXT,__cstring,cstring_literals");
2449   }
2450 
2451   // String.
2452   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2453 
2454   if (isUTF16)
2455     // Cast the UTF16 string to the correct type.
2456     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2457 
2458   // String length.
2459   Ty = getTypes().ConvertType(getContext().LongTy);
2460   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2461 
2462   // The struct.
2463   C = llvm::ConstantStruct::get(STy, Fields);
2464   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2465                                 llvm::GlobalVariable::PrivateLinkage, C,
2466                                 "_unnamed_cfstring_");
2467   GV->setSection("__DATA,__cfstring");
2468   Entry.setValue(GV);
2469 
2470   return GV;
2471 }
2472 
2473 llvm::Constant *
2474 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2475   unsigned StringLength = 0;
2476   llvm::StringMapEntry<llvm::Constant*> &Entry =
2477     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2478 
2479   if (llvm::Constant *C = Entry.getValue())
2480     return C;
2481 
2482   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2483   llvm::Constant *Zeros[] = { Zero, Zero };
2484   llvm::Value *V;
2485   // If we don't already have it, get _NSConstantStringClassReference.
2486   if (!ConstantStringClassRef) {
2487     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2488     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2489     llvm::Constant *GV;
2490     if (LangOpts.ObjCRuntime.isNonFragile()) {
2491       std::string str =
2492         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2493                             : "OBJC_CLASS_$_" + StringClass;
2494       GV = getObjCRuntime().GetClassGlobal(str);
2495       // Make sure the result is of the correct type.
2496       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2497       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2498       ConstantStringClassRef = V;
2499     } else {
2500       std::string str =
2501         StringClass.empty() ? "_NSConstantStringClassReference"
2502                             : "_" + StringClass + "ClassReference";
2503       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2504       GV = CreateRuntimeVariable(PTy, str);
2505       // Decay array -> ptr
2506       V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2507       ConstantStringClassRef = V;
2508     }
2509   }
2510   else
2511     V = ConstantStringClassRef;
2512 
2513   if (!NSConstantStringType) {
2514     // Construct the type for a constant NSString.
2515     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
2516     D->startDefinition();
2517 
2518     QualType FieldTypes[3];
2519 
2520     // const int *isa;
2521     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2522     // const char *str;
2523     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2524     // unsigned int length;
2525     FieldTypes[2] = Context.UnsignedIntTy;
2526 
2527     // Create fields
2528     for (unsigned i = 0; i < 3; ++i) {
2529       FieldDecl *Field = FieldDecl::Create(Context, D,
2530                                            SourceLocation(),
2531                                            SourceLocation(), nullptr,
2532                                            FieldTypes[i], /*TInfo=*/nullptr,
2533                                            /*BitWidth=*/nullptr,
2534                                            /*Mutable=*/false,
2535                                            ICIS_NoInit);
2536       Field->setAccess(AS_public);
2537       D->addDecl(Field);
2538     }
2539 
2540     D->completeDefinition();
2541     QualType NSTy = Context.getTagDeclType(D);
2542     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2543   }
2544 
2545   llvm::Constant *Fields[3];
2546 
2547   // Class pointer.
2548   Fields[0] = cast<llvm::ConstantExpr>(V);
2549 
2550   // String pointer.
2551   llvm::Constant *C =
2552     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2553 
2554   llvm::GlobalValue::LinkageTypes Linkage;
2555   bool isConstant;
2556   Linkage = llvm::GlobalValue::PrivateLinkage;
2557   isConstant = !LangOpts.WritableStrings;
2558 
2559   auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2560                                       Linkage, C, ".str");
2561   GV->setUnnamedAddr(true);
2562   // Don't enforce the target's minimum global alignment, since the only use
2563   // of the string is via this class initializer.
2564   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2565   GV->setAlignment(Align.getQuantity());
2566   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2567 
2568   // String length.
2569   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2570   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2571 
2572   // The struct.
2573   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2574   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2575                                 llvm::GlobalVariable::PrivateLinkage, C,
2576                                 "_unnamed_nsstring_");
2577   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2578   const char *NSStringNonFragileABISection =
2579       "__DATA,__objc_stringobj,regular,no_dead_strip";
2580   // FIXME. Fix section.
2581   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2582                      ? NSStringNonFragileABISection
2583                      : NSStringSection);
2584   Entry.setValue(GV);
2585 
2586   return GV;
2587 }
2588 
2589 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2590   if (ObjCFastEnumerationStateType.isNull()) {
2591     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
2592     D->startDefinition();
2593 
2594     QualType FieldTypes[] = {
2595       Context.UnsignedLongTy,
2596       Context.getPointerType(Context.getObjCIdType()),
2597       Context.getPointerType(Context.UnsignedLongTy),
2598       Context.getConstantArrayType(Context.UnsignedLongTy,
2599                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2600     };
2601 
2602     for (size_t i = 0; i < 4; ++i) {
2603       FieldDecl *Field = FieldDecl::Create(Context,
2604                                            D,
2605                                            SourceLocation(),
2606                                            SourceLocation(), nullptr,
2607                                            FieldTypes[i], /*TInfo=*/nullptr,
2608                                            /*BitWidth=*/nullptr,
2609                                            /*Mutable=*/false,
2610                                            ICIS_NoInit);
2611       Field->setAccess(AS_public);
2612       D->addDecl(Field);
2613     }
2614 
2615     D->completeDefinition();
2616     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2617   }
2618 
2619   return ObjCFastEnumerationStateType;
2620 }
2621 
2622 llvm::Constant *
2623 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2624   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2625 
2626   // Don't emit it as the address of the string, emit the string data itself
2627   // as an inline array.
2628   if (E->getCharByteWidth() == 1) {
2629     SmallString<64> Str(E->getString());
2630 
2631     // Resize the string to the right size, which is indicated by its type.
2632     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2633     Str.resize(CAT->getSize().getZExtValue());
2634     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2635   }
2636 
2637   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2638   llvm::Type *ElemTy = AType->getElementType();
2639   unsigned NumElements = AType->getNumElements();
2640 
2641   // Wide strings have either 2-byte or 4-byte elements.
2642   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2643     SmallVector<uint16_t, 32> Elements;
2644     Elements.reserve(NumElements);
2645 
2646     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2647       Elements.push_back(E->getCodeUnit(i));
2648     Elements.resize(NumElements);
2649     return llvm::ConstantDataArray::get(VMContext, Elements);
2650   }
2651 
2652   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2653   SmallVector<uint32_t, 32> Elements;
2654   Elements.reserve(NumElements);
2655 
2656   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2657     Elements.push_back(E->getCodeUnit(i));
2658   Elements.resize(NumElements);
2659   return llvm::ConstantDataArray::get(VMContext, Elements);
2660 }
2661 
2662 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2663 /// constant array for the given string literal.
2664 llvm::Constant *
2665 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2666   CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
2667 
2668   llvm::StringMapEntry<llvm::GlobalVariable *> *Entry = nullptr;
2669   llvm::GlobalVariable *GV = nullptr;
2670   if (!LangOpts.WritableStrings) {
2671     llvm::StringMap<llvm::GlobalVariable *> *ConstantStringMap = nullptr;
2672     switch (S->getCharByteWidth()) {
2673     case 1:
2674       ConstantStringMap = &Constant1ByteStringMap;
2675       break;
2676     case 2:
2677       ConstantStringMap = &Constant2ByteStringMap;
2678       break;
2679     case 4:
2680       ConstantStringMap = &Constant4ByteStringMap;
2681       break;
2682     default:
2683       llvm_unreachable("unhandled byte width!");
2684     }
2685     Entry = &ConstantStringMap->GetOrCreateValue(S->getBytes());
2686     GV = Entry->getValue();
2687   }
2688 
2689   if (!GV) {
2690     SmallString<256> MangledNameBuffer;
2691     StringRef GlobalVariableName;
2692     llvm::GlobalValue::LinkageTypes LT;
2693 
2694     // Mangle the string literal if the ABI allows for it.  However, we cannot
2695     // do this if  we are compiling with ASan or -fwritable-strings because they
2696     // rely on strings having normal linkage.
2697     if (!LangOpts.WritableStrings && !SanOpts.Address &&
2698         getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2699       llvm::raw_svector_ostream Out(MangledNameBuffer);
2700       getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2701       Out.flush();
2702 
2703       LT = llvm::GlobalValue::LinkOnceODRLinkage;
2704       GlobalVariableName = MangledNameBuffer;
2705     } else {
2706       LT = llvm::GlobalValue::PrivateLinkage;
2707       GlobalVariableName = ".str";
2708     }
2709 
2710     // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2711     unsigned AddrSpace = 0;
2712     if (getLangOpts().OpenCL)
2713       AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
2714 
2715     llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2716     GV = new llvm::GlobalVariable(
2717         getModule(), C->getType(), !LangOpts.WritableStrings, LT, C,
2718         GlobalVariableName, /*InsertBefore=*/nullptr,
2719         llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2720     GV->setUnnamedAddr(true);
2721     if (Entry)
2722       Entry->setValue(GV);
2723   }
2724 
2725   if (Align.getQuantity() > GV->getAlignment())
2726     GV->setAlignment(Align.getQuantity());
2727 
2728   return GV;
2729 }
2730 
2731 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2732 /// array for the given ObjCEncodeExpr node.
2733 llvm::Constant *
2734 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2735   std::string Str;
2736   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2737 
2738   return GetAddrOfConstantCString(Str);
2739 }
2740 
2741 
2742 /// GenerateWritableString -- Creates storage for a string literal.
2743 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2744                                              bool constant,
2745                                              CodeGenModule &CGM,
2746                                              const char *GlobalName,
2747                                              unsigned Alignment) {
2748   // Create Constant for this string literal. Don't add a '\0'.
2749   llvm::Constant *C =
2750       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2751 
2752   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2753   unsigned AddrSpace = 0;
2754   if (CGM.getLangOpts().OpenCL)
2755     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2756 
2757   // Create a global variable for this string
2758   auto *GV = new llvm::GlobalVariable(
2759       CGM.getModule(), C->getType(), constant,
2760       llvm::GlobalValue::PrivateLinkage, C, GlobalName, nullptr,
2761       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2762   GV->setAlignment(Alignment);
2763   GV->setUnnamedAddr(true);
2764   return GV;
2765 }
2766 
2767 /// GetAddrOfConstantString - Returns a pointer to a character array
2768 /// containing the literal. This contents are exactly that of the
2769 /// given string, i.e. it will not be null terminated automatically;
2770 /// see GetAddrOfConstantCString. Note that whether the result is
2771 /// actually a pointer to an LLVM constant depends on
2772 /// Feature.WriteableStrings.
2773 ///
2774 /// The result has pointer to array type.
2775 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2776                                                        const char *GlobalName,
2777                                                        unsigned Alignment) {
2778   // Get the default prefix if a name wasn't specified.
2779   if (!GlobalName)
2780     GlobalName = ".str";
2781 
2782   if (Alignment == 0)
2783     Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2784       .getQuantity();
2785 
2786   // Don't share any string literals if strings aren't constant.
2787   if (LangOpts.WritableStrings)
2788     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2789 
2790   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2791     Constant1ByteStringMap.GetOrCreateValue(Str);
2792 
2793   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2794     if (Alignment > GV->getAlignment()) {
2795       GV->setAlignment(Alignment);
2796     }
2797     return GV;
2798   }
2799 
2800   // Create a global variable for this.
2801   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2802                                                    Alignment);
2803   Entry.setValue(GV);
2804   return GV;
2805 }
2806 
2807 /// GetAddrOfConstantCString - Returns a pointer to a character
2808 /// array containing the literal and a terminating '\0'
2809 /// character. The result has pointer to array type.
2810 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2811                                                         const char *GlobalName,
2812                                                         unsigned Alignment) {
2813   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2814   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2815 }
2816 
2817 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
2818     const MaterializeTemporaryExpr *E, const Expr *Init) {
2819   assert((E->getStorageDuration() == SD_Static ||
2820           E->getStorageDuration() == SD_Thread) && "not a global temporary");
2821   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
2822 
2823   // If we're not materializing a subobject of the temporary, keep the
2824   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
2825   QualType MaterializedType = Init->getType();
2826   if (Init == E->GetTemporaryExpr())
2827     MaterializedType = E->getType();
2828 
2829   llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2830   if (Slot)
2831     return Slot;
2832 
2833   // FIXME: If an externally-visible declaration extends multiple temporaries,
2834   // we need to give each temporary the same name in every translation unit (and
2835   // we also need to make the temporaries externally-visible).
2836   SmallString<256> Name;
2837   llvm::raw_svector_ostream Out(Name);
2838   getCXXABI().getMangleContext().mangleReferenceTemporary(
2839       VD, E->getManglingNumber(), Out);
2840   Out.flush();
2841 
2842   APValue *Value = nullptr;
2843   if (E->getStorageDuration() == SD_Static) {
2844     // We might have a cached constant initializer for this temporary. Note
2845     // that this might have a different value from the value computed by
2846     // evaluating the initializer if the surrounding constant expression
2847     // modifies the temporary.
2848     Value = getContext().getMaterializedTemporaryValue(E, false);
2849     if (Value && Value->isUninit())
2850       Value = nullptr;
2851   }
2852 
2853   // Try evaluating it now, it might have a constant initializer.
2854   Expr::EvalResult EvalResult;
2855   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2856       !EvalResult.hasSideEffects())
2857     Value = &EvalResult.Val;
2858 
2859   llvm::Constant *InitialValue = nullptr;
2860   bool Constant = false;
2861   llvm::Type *Type;
2862   if (Value) {
2863     // The temporary has a constant initializer, use it.
2864     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
2865     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2866     Type = InitialValue->getType();
2867   } else {
2868     // No initializer, the initialization will be provided when we
2869     // initialize the declaration which performed lifetime extension.
2870     Type = getTypes().ConvertTypeForMem(MaterializedType);
2871   }
2872 
2873   // Create a global variable for this lifetime-extended temporary.
2874   llvm::GlobalValue::LinkageTypes Linkage =
2875       getLLVMLinkageVarDefinition(VD, Constant);
2876   // There is no need for this temporary to have global linkage if the global
2877   // variable has external linkage.
2878   if (Linkage == llvm::GlobalVariable::ExternalLinkage)
2879     Linkage = llvm::GlobalVariable::PrivateLinkage;
2880   unsigned AddrSpace = GetGlobalVarAddressSpace(
2881       VD, getContext().getTargetAddressSpace(MaterializedType));
2882   auto *GV = new llvm::GlobalVariable(
2883       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
2884       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2885       AddrSpace);
2886   setGlobalVisibility(GV, VD);
2887   GV->setAlignment(
2888       getContext().getTypeAlignInChars(MaterializedType).getQuantity());
2889   if (VD->getTLSKind())
2890     setTLSMode(GV, *VD);
2891   Slot = GV;
2892   return GV;
2893 }
2894 
2895 /// EmitObjCPropertyImplementations - Emit information for synthesized
2896 /// properties for an implementation.
2897 void CodeGenModule::EmitObjCPropertyImplementations(const
2898                                                     ObjCImplementationDecl *D) {
2899   for (const auto *PID : D->property_impls()) {
2900     // Dynamic is just for type-checking.
2901     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2902       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2903 
2904       // Determine which methods need to be implemented, some may have
2905       // been overridden. Note that ::isPropertyAccessor is not the method
2906       // we want, that just indicates if the decl came from a
2907       // property. What we want to know is if the method is defined in
2908       // this implementation.
2909       if (!D->getInstanceMethod(PD->getGetterName()))
2910         CodeGenFunction(*this).GenerateObjCGetter(
2911                                  const_cast<ObjCImplementationDecl *>(D), PID);
2912       if (!PD->isReadOnly() &&
2913           !D->getInstanceMethod(PD->getSetterName()))
2914         CodeGenFunction(*this).GenerateObjCSetter(
2915                                  const_cast<ObjCImplementationDecl *>(D), PID);
2916     }
2917   }
2918 }
2919 
2920 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2921   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2922   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2923        ivar; ivar = ivar->getNextIvar())
2924     if (ivar->getType().isDestructedType())
2925       return true;
2926 
2927   return false;
2928 }
2929 
2930 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2931 /// for an implementation.
2932 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2933   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2934   if (needsDestructMethod(D)) {
2935     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2936     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2937     ObjCMethodDecl *DTORMethod =
2938       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2939                              cxxSelector, getContext().VoidTy, nullptr, D,
2940                              /*isInstance=*/true, /*isVariadic=*/false,
2941                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2942                              /*isDefined=*/false, ObjCMethodDecl::Required);
2943     D->addInstanceMethod(DTORMethod);
2944     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2945     D->setHasDestructors(true);
2946   }
2947 
2948   // If the implementation doesn't have any ivar initializers, we don't need
2949   // a .cxx_construct.
2950   if (D->getNumIvarInitializers() == 0)
2951     return;
2952 
2953   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2954   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2955   // The constructor returns 'self'.
2956   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2957                                                 D->getLocation(),
2958                                                 D->getLocation(),
2959                                                 cxxSelector,
2960                                                 getContext().getObjCIdType(),
2961                                                 nullptr, D, /*isInstance=*/true,
2962                                                 /*isVariadic=*/false,
2963                                                 /*isPropertyAccessor=*/true,
2964                                                 /*isImplicitlyDeclared=*/true,
2965                                                 /*isDefined=*/false,
2966                                                 ObjCMethodDecl::Required);
2967   D->addInstanceMethod(CTORMethod);
2968   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2969   D->setHasNonZeroConstructors(true);
2970 }
2971 
2972 /// EmitNamespace - Emit all declarations in a namespace.
2973 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2974   for (auto *I : ND->decls()) {
2975     if (const auto *VD = dyn_cast<VarDecl>(I))
2976       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2977           VD->getTemplateSpecializationKind() != TSK_Undeclared)
2978         continue;
2979     EmitTopLevelDecl(I);
2980   }
2981 }
2982 
2983 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2984 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2985   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2986       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2987     ErrorUnsupported(LSD, "linkage spec");
2988     return;
2989   }
2990 
2991   for (auto *I : LSD->decls()) {
2992     // Meta-data for ObjC class includes references to implemented methods.
2993     // Generate class's method definitions first.
2994     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
2995       for (auto *M : OID->methods())
2996         EmitTopLevelDecl(M);
2997     }
2998     EmitTopLevelDecl(I);
2999   }
3000 }
3001 
3002 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3003 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3004   // Ignore dependent declarations.
3005   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3006     return;
3007 
3008   switch (D->getKind()) {
3009   case Decl::CXXConversion:
3010   case Decl::CXXMethod:
3011   case Decl::Function:
3012     // Skip function templates
3013     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3014         cast<FunctionDecl>(D)->isLateTemplateParsed())
3015       return;
3016 
3017     EmitGlobal(cast<FunctionDecl>(D));
3018     break;
3019 
3020   case Decl::Var:
3021     // Skip variable templates
3022     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3023       return;
3024   case Decl::VarTemplateSpecialization:
3025     EmitGlobal(cast<VarDecl>(D));
3026     break;
3027 
3028   // Indirect fields from global anonymous structs and unions can be
3029   // ignored; only the actual variable requires IR gen support.
3030   case Decl::IndirectField:
3031     break;
3032 
3033   // C++ Decls
3034   case Decl::Namespace:
3035     EmitNamespace(cast<NamespaceDecl>(D));
3036     break;
3037     // No code generation needed.
3038   case Decl::UsingShadow:
3039   case Decl::ClassTemplate:
3040   case Decl::VarTemplate:
3041   case Decl::VarTemplatePartialSpecialization:
3042   case Decl::FunctionTemplate:
3043   case Decl::TypeAliasTemplate:
3044   case Decl::Block:
3045   case Decl::Empty:
3046     break;
3047   case Decl::Using:          // using X; [C++]
3048     if (CGDebugInfo *DI = getModuleDebugInfo())
3049         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3050     return;
3051   case Decl::NamespaceAlias:
3052     if (CGDebugInfo *DI = getModuleDebugInfo())
3053         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3054     return;
3055   case Decl::UsingDirective: // using namespace X; [C++]
3056     if (CGDebugInfo *DI = getModuleDebugInfo())
3057       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3058     return;
3059   case Decl::CXXConstructor:
3060     // Skip function templates
3061     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3062         cast<FunctionDecl>(D)->isLateTemplateParsed())
3063       return;
3064 
3065     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3066     break;
3067   case Decl::CXXDestructor:
3068     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3069       return;
3070     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3071     break;
3072 
3073   case Decl::StaticAssert:
3074     // Nothing to do.
3075     break;
3076 
3077   // Objective-C Decls
3078 
3079   // Forward declarations, no (immediate) code generation.
3080   case Decl::ObjCInterface:
3081   case Decl::ObjCCategory:
3082     break;
3083 
3084   case Decl::ObjCProtocol: {
3085     auto *Proto = cast<ObjCProtocolDecl>(D);
3086     if (Proto->isThisDeclarationADefinition())
3087       ObjCRuntime->GenerateProtocol(Proto);
3088     break;
3089   }
3090 
3091   case Decl::ObjCCategoryImpl:
3092     // Categories have properties but don't support synthesize so we
3093     // can ignore them here.
3094     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3095     break;
3096 
3097   case Decl::ObjCImplementation: {
3098     auto *OMD = cast<ObjCImplementationDecl>(D);
3099     EmitObjCPropertyImplementations(OMD);
3100     EmitObjCIvarInitializations(OMD);
3101     ObjCRuntime->GenerateClass(OMD);
3102     // Emit global variable debug information.
3103     if (CGDebugInfo *DI = getModuleDebugInfo())
3104       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3105         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3106             OMD->getClassInterface()), OMD->getLocation());
3107     break;
3108   }
3109   case Decl::ObjCMethod: {
3110     auto *OMD = cast<ObjCMethodDecl>(D);
3111     // If this is not a prototype, emit the body.
3112     if (OMD->getBody())
3113       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3114     break;
3115   }
3116   case Decl::ObjCCompatibleAlias:
3117     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3118     break;
3119 
3120   case Decl::LinkageSpec:
3121     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3122     break;
3123 
3124   case Decl::FileScopeAsm: {
3125     auto *AD = cast<FileScopeAsmDecl>(D);
3126     StringRef AsmString = AD->getAsmString()->getString();
3127 
3128     const std::string &S = getModule().getModuleInlineAsm();
3129     if (S.empty())
3130       getModule().setModuleInlineAsm(AsmString);
3131     else if (S.end()[-1] == '\n')
3132       getModule().setModuleInlineAsm(S + AsmString.str());
3133     else
3134       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
3135     break;
3136   }
3137 
3138   case Decl::Import: {
3139     auto *Import = cast<ImportDecl>(D);
3140 
3141     // Ignore import declarations that come from imported modules.
3142     if (clang::Module *Owner = Import->getOwningModule()) {
3143       if (getLangOpts().CurrentModule.empty() ||
3144           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3145         break;
3146     }
3147 
3148     ImportedModules.insert(Import->getImportedModule());
3149     break;
3150   }
3151 
3152   case Decl::ClassTemplateSpecialization: {
3153     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3154     if (DebugInfo &&
3155         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
3156       DebugInfo->completeTemplateDefinition(*Spec);
3157   }
3158 
3159   default:
3160     // Make sure we handled everything we should, every other kind is a
3161     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3162     // function. Need to recode Decl::Kind to do that easily.
3163     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3164   }
3165 }
3166 
3167 /// Turns the given pointer into a constant.
3168 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3169                                           const void *Ptr) {
3170   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3171   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3172   return llvm::ConstantInt::get(i64, PtrInt);
3173 }
3174 
3175 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3176                                    llvm::NamedMDNode *&GlobalMetadata,
3177                                    GlobalDecl D,
3178                                    llvm::GlobalValue *Addr) {
3179   if (!GlobalMetadata)
3180     GlobalMetadata =
3181       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3182 
3183   // TODO: should we report variant information for ctors/dtors?
3184   llvm::Value *Ops[] = {
3185     Addr,
3186     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3187   };
3188   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3189 }
3190 
3191 /// For each function which is declared within an extern "C" region and marked
3192 /// as 'used', but has internal linkage, create an alias from the unmangled
3193 /// name to the mangled name if possible. People expect to be able to refer
3194 /// to such functions with an unmangled name from inline assembly within the
3195 /// same translation unit.
3196 void CodeGenModule::EmitStaticExternCAliases() {
3197   for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3198                                   E = StaticExternCValues.end();
3199        I != E; ++I) {
3200     IdentifierInfo *Name = I->first;
3201     llvm::GlobalValue *Val = I->second;
3202     if (Val && !getModule().getNamedValue(Name->getName()))
3203       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(),
3204                                               cast<llvm::GlobalObject>(Val)));
3205   }
3206 }
3207 
3208 /// Emits metadata nodes associating all the global values in the
3209 /// current module with the Decls they came from.  This is useful for
3210 /// projects using IR gen as a subroutine.
3211 ///
3212 /// Since there's currently no way to associate an MDNode directly
3213 /// with an llvm::GlobalValue, we create a global named metadata
3214 /// with the name 'clang.global.decl.ptrs'.
3215 void CodeGenModule::EmitDeclMetadata() {
3216   llvm::NamedMDNode *GlobalMetadata = nullptr;
3217 
3218   // StaticLocalDeclMap
3219   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
3220          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3221        I != E; ++I) {
3222     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3223     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3224   }
3225 }
3226 
3227 /// Emits metadata nodes for all the local variables in the current
3228 /// function.
3229 void CodeGenFunction::EmitDeclMetadata() {
3230   if (LocalDeclMap.empty()) return;
3231 
3232   llvm::LLVMContext &Context = getLLVMContext();
3233 
3234   // Find the unique metadata ID for this name.
3235   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3236 
3237   llvm::NamedMDNode *GlobalMetadata = nullptr;
3238 
3239   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3240          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3241     const Decl *D = I->first;
3242     llvm::Value *Addr = I->second;
3243 
3244     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3245       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3246       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3247     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3248       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3249       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3250     }
3251   }
3252 }
3253 
3254 void CodeGenModule::EmitVersionIdentMetadata() {
3255   llvm::NamedMDNode *IdentMetadata =
3256     TheModule.getOrInsertNamedMetadata("llvm.ident");
3257   std::string Version = getClangFullVersion();
3258   llvm::LLVMContext &Ctx = TheModule.getContext();
3259 
3260   llvm::Value *IdentNode[] = {
3261     llvm::MDString::get(Ctx, Version)
3262   };
3263   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3264 }
3265 
3266 void CodeGenModule::EmitCoverageFile() {
3267   if (!getCodeGenOpts().CoverageFile.empty()) {
3268     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3269       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3270       llvm::LLVMContext &Ctx = TheModule.getContext();
3271       llvm::MDString *CoverageFile =
3272           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3273       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3274         llvm::MDNode *CU = CUNode->getOperand(i);
3275         llvm::Value *node[] = { CoverageFile, CU };
3276         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3277         GCov->addOperand(N);
3278       }
3279     }
3280   }
3281 }
3282 
3283 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3284                                                      QualType GuidType) {
3285   // Sema has checked that all uuid strings are of the form
3286   // "12345678-1234-1234-1234-1234567890ab".
3287   assert(Uuid.size() == 36);
3288   for (unsigned i = 0; i < 36; ++i) {
3289     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3290     else                                         assert(isHexDigit(Uuid[i]));
3291   }
3292 
3293   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3294 
3295   llvm::Constant *Field3[8];
3296   for (unsigned Idx = 0; Idx < 8; ++Idx)
3297     Field3[Idx] = llvm::ConstantInt::get(
3298         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3299 
3300   llvm::Constant *Fields[4] = {
3301     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3302     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3303     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3304     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3305   };
3306 
3307   return llvm::ConstantStruct::getAnon(Fields);
3308 }
3309