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