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