xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 3f465c095b22400c1d08295b8890477fa4e6ffda)
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 "CGBlocks.h"
16 #include "CGCUDARuntime.h"
17 #include "CGCXXABI.h"
18 #include "CGCall.h"
19 #include "CGDebugInfo.h"
20 #include "CGObjCRuntime.h"
21 #include "CGOpenCLRuntime.h"
22 #include "CGOpenMPRuntime.h"
23 #include "CGOpenMPRuntimeNVPTX.h"
24 #include "CodeGenFunction.h"
25 #include "CodeGenPGO.h"
26 #include "CodeGenTBAA.h"
27 #include "CoverageMappingGen.h"
28 #include "TargetInfo.h"
29 #include "clang/AST/ASTContext.h"
30 #include "clang/AST/CharUnits.h"
31 #include "clang/AST/DeclCXX.h"
32 #include "clang/AST/DeclObjC.h"
33 #include "clang/AST/DeclTemplate.h"
34 #include "clang/AST/Mangle.h"
35 #include "clang/AST/RecordLayout.h"
36 #include "clang/AST/RecursiveASTVisitor.h"
37 #include "clang/Basic/Builtins.h"
38 #include "clang/Basic/CharInfo.h"
39 #include "clang/Basic/Diagnostic.h"
40 #include "clang/Basic/Module.h"
41 #include "clang/Basic/SourceManager.h"
42 #include "clang/Basic/TargetInfo.h"
43 #include "clang/Basic/Version.h"
44 #include "clang/Frontend/CodeGenOptions.h"
45 #include "clang/Sema/SemaDiagnostic.h"
46 #include "llvm/ADT/APSInt.h"
47 #include "llvm/ADT/Triple.h"
48 #include "llvm/IR/CallSite.h"
49 #include "llvm/IR/CallingConv.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/ProfileData/InstrProfReader.h"
55 #include "llvm/Support/ConvertUTF.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MD5.h"
58 
59 using namespace clang;
60 using namespace CodeGen;
61 
62 static const char AnnotationSection[] = "llvm.metadata";
63 
64 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
65   switch (CGM.getTarget().getCXXABI().getKind()) {
66   case TargetCXXABI::GenericAArch64:
67   case TargetCXXABI::GenericARM:
68   case TargetCXXABI::iOS:
69   case TargetCXXABI::iOS64:
70   case TargetCXXABI::WatchOS:
71   case TargetCXXABI::GenericMIPS:
72   case TargetCXXABI::GenericItanium:
73   case TargetCXXABI::WebAssembly:
74     return CreateItaniumCXXABI(CGM);
75   case TargetCXXABI::Microsoft:
76     return CreateMicrosoftCXXABI(CGM);
77   }
78 
79   llvm_unreachable("invalid C++ ABI kind");
80 }
81 
82 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
83                              const PreprocessorOptions &PPO,
84                              const CodeGenOptions &CGO, llvm::Module &M,
85                              DiagnosticsEngine &diags,
86                              CoverageSourceInfo *CoverageInfo)
87     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
88       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
89       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
90       VMContext(M.getContext()), TBAA(nullptr), TheTargetCodeGenInfo(nullptr),
91       Types(*this), VTables(*this), ObjCRuntime(nullptr),
92       OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), CUDARuntime(nullptr),
93       DebugInfo(nullptr), ObjCData(nullptr),
94       NoObjCARCExceptionsMetadata(nullptr), PGOReader(nullptr),
95       CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
96       NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
97       NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
98       BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
99       GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
100       LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
101 
102   // Initialize the type cache.
103   llvm::LLVMContext &LLVMContext = M.getContext();
104   VoidTy = llvm::Type::getVoidTy(LLVMContext);
105   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
106   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
107   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
108   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
109   FloatTy = llvm::Type::getFloatTy(LLVMContext);
110   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
111   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
112   PointerAlignInBytes =
113     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
114   IntAlignInBytes =
115     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
116   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
117   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
118   Int8PtrTy = Int8Ty->getPointerTo(0);
119   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
120 
121   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
122   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
123 
124   if (LangOpts.ObjC1)
125     createObjCRuntime();
126   if (LangOpts.OpenCL)
127     createOpenCLRuntime();
128   if (LangOpts.OpenMP)
129     createOpenMPRuntime();
130   if (LangOpts.CUDA)
131     createCUDARuntime();
132 
133   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
134   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
135       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
136     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
137                            getCXXABI().getMangleContext());
138 
139   // If debug info or coverage generation is enabled, create the CGDebugInfo
140   // object.
141   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
142       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
143     DebugInfo = new CGDebugInfo(*this);
144 
145   Block.GlobalUniqueCount = 0;
146 
147   if (C.getLangOpts().ObjC1)
148     ObjCData = new ObjCEntrypoints();
149 
150   if (!CodeGenOpts.InstrProfileInput.empty()) {
151     auto ReaderOrErr =
152         llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput);
153     if (std::error_code EC = ReaderOrErr.getError()) {
154       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
155                                               "Could not read profile %0: %1");
156       getDiags().Report(DiagID) << CodeGenOpts.InstrProfileInput
157                                 << EC.message();
158     } else
159       PGOReader = std::move(ReaderOrErr.get());
160   }
161 
162   // If coverage mapping generation is enabled, create the
163   // CoverageMappingModuleGen object.
164   if (CodeGenOpts.CoverageMapping)
165     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
166 }
167 
168 CodeGenModule::~CodeGenModule() {
169   delete ObjCRuntime;
170   delete OpenCLRuntime;
171   delete OpenMPRuntime;
172   delete CUDARuntime;
173   delete TheTargetCodeGenInfo;
174   delete TBAA;
175   delete DebugInfo;
176   delete ObjCData;
177 }
178 
179 void CodeGenModule::createObjCRuntime() {
180   // This is just isGNUFamily(), but we want to force implementors of
181   // new ABIs to decide how best to do this.
182   switch (LangOpts.ObjCRuntime.getKind()) {
183   case ObjCRuntime::GNUstep:
184   case ObjCRuntime::GCC:
185   case ObjCRuntime::ObjFW:
186     ObjCRuntime = CreateGNUObjCRuntime(*this);
187     return;
188 
189   case ObjCRuntime::FragileMacOSX:
190   case ObjCRuntime::MacOSX:
191   case ObjCRuntime::iOS:
192   case ObjCRuntime::WatchOS:
193     ObjCRuntime = CreateMacObjCRuntime(*this);
194     return;
195   }
196   llvm_unreachable("bad runtime kind");
197 }
198 
199 void CodeGenModule::createOpenCLRuntime() {
200   OpenCLRuntime = new CGOpenCLRuntime(*this);
201 }
202 
203 void CodeGenModule::createOpenMPRuntime() {
204   // Select a specialized code generation class based on the target, if any.
205   // If it does not exist use the default implementation.
206   switch (getTarget().getTriple().getArch()) {
207 
208   case llvm::Triple::nvptx:
209   case llvm::Triple::nvptx64:
210     assert(getLangOpts().OpenMPIsDevice &&
211            "OpenMP NVPTX is only prepared to deal with device code.");
212     OpenMPRuntime = new CGOpenMPRuntimeNVPTX(*this);
213     break;
214   default:
215     OpenMPRuntime = new CGOpenMPRuntime(*this);
216     break;
217   }
218 }
219 
220 void CodeGenModule::createCUDARuntime() {
221   CUDARuntime = CreateNVCUDARuntime(*this);
222 }
223 
224 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
225   Replacements[Name] = C;
226 }
227 
228 void CodeGenModule::applyReplacements() {
229   for (auto &I : Replacements) {
230     StringRef MangledName = I.first();
231     llvm::Constant *Replacement = I.second;
232     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
233     if (!Entry)
234       continue;
235     auto *OldF = cast<llvm::Function>(Entry);
236     auto *NewF = dyn_cast<llvm::Function>(Replacement);
237     if (!NewF) {
238       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
239         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
240       } else {
241         auto *CE = cast<llvm::ConstantExpr>(Replacement);
242         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
243                CE->getOpcode() == llvm::Instruction::GetElementPtr);
244         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
245       }
246     }
247 
248     // Replace old with new, but keep the old order.
249     OldF->replaceAllUsesWith(Replacement);
250     if (NewF) {
251       NewF->removeFromParent();
252       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
253                                                        NewF);
254     }
255     OldF->eraseFromParent();
256   }
257 }
258 
259 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
260   GlobalValReplacements.push_back(std::make_pair(GV, C));
261 }
262 
263 void CodeGenModule::applyGlobalValReplacements() {
264   for (auto &I : GlobalValReplacements) {
265     llvm::GlobalValue *GV = I.first;
266     llvm::Constant *C = I.second;
267 
268     GV->replaceAllUsesWith(C);
269     GV->eraseFromParent();
270   }
271 }
272 
273 // This is only used in aliases that we created and we know they have a
274 // linear structure.
275 static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
276   llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
277   const llvm::Constant *C = &GA;
278   for (;;) {
279     C = C->stripPointerCasts();
280     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
281       return GO;
282     // stripPointerCasts will not walk over weak aliases.
283     auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
284     if (!GA2)
285       return nullptr;
286     if (!Visited.insert(GA2).second)
287       return nullptr;
288     C = GA2->getAliasee();
289   }
290 }
291 
292 void CodeGenModule::checkAliases() {
293   // Check if the constructed aliases are well formed. It is really unfortunate
294   // that we have to do this in CodeGen, but we only construct mangled names
295   // and aliases during codegen.
296   bool Error = false;
297   DiagnosticsEngine &Diags = getDiags();
298   for (const GlobalDecl &GD : Aliases) {
299     const auto *D = cast<ValueDecl>(GD.getDecl());
300     const AliasAttr *AA = D->getAttr<AliasAttr>();
301     StringRef MangledName = getMangledName(GD);
302     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
303     auto *Alias = cast<llvm::GlobalAlias>(Entry);
304     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
305     if (!GV) {
306       Error = true;
307       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
308     } else if (GV->isDeclaration()) {
309       Error = true;
310       Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
311     }
312 
313     llvm::Constant *Aliasee = Alias->getAliasee();
314     llvm::GlobalValue *AliaseeGV;
315     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
316       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
317     else
318       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
319 
320     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
321       StringRef AliasSection = SA->getName();
322       if (AliasSection != AliaseeGV->getSection())
323         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
324             << AliasSection;
325     }
326 
327     // We have to handle alias to weak aliases in here. LLVM itself disallows
328     // this since the object semantics would not match the IL one. For
329     // compatibility with gcc we implement it by just pointing the alias
330     // to its aliasee's aliasee. We also warn, since the user is probably
331     // expecting the link to be weak.
332     if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
333       if (GA->mayBeOverridden()) {
334         Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
335             << GV->getName() << GA->getName();
336         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
337             GA->getAliasee(), Alias->getType());
338         Alias->setAliasee(Aliasee);
339       }
340     }
341   }
342   if (!Error)
343     return;
344 
345   for (const GlobalDecl &GD : Aliases) {
346     StringRef MangledName = getMangledName(GD);
347     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
348     auto *Alias = cast<llvm::GlobalAlias>(Entry);
349     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
350     Alias->eraseFromParent();
351   }
352 }
353 
354 void CodeGenModule::clear() {
355   DeferredDeclsToEmit.clear();
356   if (OpenMPRuntime)
357     OpenMPRuntime->clear();
358 }
359 
360 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
361                                        StringRef MainFile) {
362   if (!hasDiagnostics())
363     return;
364   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
365     if (MainFile.empty())
366       MainFile = "<stdin>";
367     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
368   } else
369     Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
370                                                       << Mismatched;
371 }
372 
373 void CodeGenModule::Release() {
374   EmitDeferred();
375   applyGlobalValReplacements();
376   applyReplacements();
377   checkAliases();
378   EmitCXXGlobalInitFunc();
379   EmitCXXGlobalDtorFunc();
380   EmitCXXThreadLocalInitFunc();
381   if (ObjCRuntime)
382     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
383       AddGlobalCtor(ObjCInitFunction);
384   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
385       CUDARuntime) {
386     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
387       AddGlobalCtor(CudaCtorFunction);
388     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
389       AddGlobalDtor(CudaDtorFunction);
390   }
391   if (OpenMPRuntime)
392     if (llvm::Function *OpenMPRegistrationFunction =
393             OpenMPRuntime->emitRegistrationFunction())
394       AddGlobalCtor(OpenMPRegistrationFunction, 0);
395   if (PGOReader) {
396     getModule().setMaximumFunctionCount(PGOReader->getMaximumFunctionCount());
397     if (PGOStats.hasDiagnostics())
398       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
399   }
400   EmitCtorList(GlobalCtors, "llvm.global_ctors");
401   EmitCtorList(GlobalDtors, "llvm.global_dtors");
402   EmitGlobalAnnotations();
403   EmitStaticExternCAliases();
404   EmitDeferredUnusedCoverageMappings();
405   if (CoverageMapping)
406     CoverageMapping->emit();
407   if (CodeGenOpts.SanitizeCfiCrossDso)
408     CodeGenFunction(*this).EmitCfiCheckFail();
409   emitLLVMUsed();
410   if (SanStats)
411     SanStats->finish();
412 
413   if (CodeGenOpts.Autolink &&
414       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
415     EmitModuleLinkOptions();
416   }
417   if (CodeGenOpts.DwarfVersion) {
418     // We actually want the latest version when there are conflicts.
419     // We can change from Warning to Latest if such mode is supported.
420     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
421                               CodeGenOpts.DwarfVersion);
422   }
423   if (CodeGenOpts.EmitCodeView) {
424     // Indicate that we want CodeView in the metadata.
425     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
426   }
427   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
428     // We don't support LTO with 2 with different StrictVTablePointers
429     // FIXME: we could support it by stripping all the information introduced
430     // by StrictVTablePointers.
431 
432     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
433 
434     llvm::Metadata *Ops[2] = {
435               llvm::MDString::get(VMContext, "StrictVTablePointers"),
436               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
437                   llvm::Type::getInt32Ty(VMContext), 1))};
438 
439     getModule().addModuleFlag(llvm::Module::Require,
440                               "StrictVTablePointersRequirement",
441                               llvm::MDNode::get(VMContext, Ops));
442   }
443   if (DebugInfo)
444     // We support a single version in the linked module. The LLVM
445     // parser will drop debug info with a different version number
446     // (and warn about it, too).
447     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
448                               llvm::DEBUG_METADATA_VERSION);
449 
450   // We need to record the widths of enums and wchar_t, so that we can generate
451   // the correct build attributes in the ARM backend.
452   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
453   if (   Arch == llvm::Triple::arm
454       || Arch == llvm::Triple::armeb
455       || Arch == llvm::Triple::thumb
456       || Arch == llvm::Triple::thumbeb) {
457     // Width of wchar_t in bytes
458     uint64_t WCharWidth =
459         Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
460     getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
461 
462     // The minimum width of an enum in bytes
463     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
464     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
465   }
466 
467   if (CodeGenOpts.SanitizeCfiCrossDso) {
468     // Indicate that we want cross-DSO control flow integrity checks.
469     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
470   }
471 
472   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
473     llvm::PICLevel::Level PL = llvm::PICLevel::Default;
474     switch (PLevel) {
475     case 0: break;
476     case 1: PL = llvm::PICLevel::Small; break;
477     case 2: PL = llvm::PICLevel::Large; break;
478     default: llvm_unreachable("Invalid PIC Level");
479     }
480 
481     getModule().setPICLevel(PL);
482   }
483 
484   SimplifyPersonality();
485 
486   if (getCodeGenOpts().EmitDeclMetadata)
487     EmitDeclMetadata();
488 
489   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
490     EmitCoverageFile();
491 
492   if (DebugInfo)
493     DebugInfo->finalize();
494 
495   EmitVersionIdentMetadata();
496 
497   EmitTargetMetadata();
498 }
499 
500 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
501   // Make sure that this type is translated.
502   Types.UpdateCompletedType(TD);
503 }
504 
505 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
506   // Make sure that this type is translated.
507   Types.RefreshTypeCacheForClass(RD);
508 }
509 
510 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
511   if (!TBAA)
512     return nullptr;
513   return TBAA->getTBAAInfo(QTy);
514 }
515 
516 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
517   if (!TBAA)
518     return nullptr;
519   return TBAA->getTBAAInfoForVTablePtr();
520 }
521 
522 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
523   if (!TBAA)
524     return nullptr;
525   return TBAA->getTBAAStructInfo(QTy);
526 }
527 
528 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
529                                                   llvm::MDNode *AccessN,
530                                                   uint64_t O) {
531   if (!TBAA)
532     return nullptr;
533   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
534 }
535 
536 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
537 /// and struct-path aware TBAA, the tag has the same format:
538 /// base type, access type and offset.
539 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
540 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
541                                                 llvm::MDNode *TBAAInfo,
542                                                 bool ConvertTypeToTag) {
543   if (ConvertTypeToTag && TBAA)
544     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
545                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
546   else
547     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
548 }
549 
550 void CodeGenModule::DecorateInstructionWithInvariantGroup(
551     llvm::Instruction *I, const CXXRecordDecl *RD) {
552   llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
553   auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
554   // Check if we have to wrap MDString in MDNode.
555   if (!MetaDataNode)
556     MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
557   I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
558 }
559 
560 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
561   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
562   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
563 }
564 
565 /// ErrorUnsupported - Print out an error that codegen doesn't support the
566 /// specified stmt yet.
567 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
568   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
569                                                "cannot compile this %0 yet");
570   std::string Msg = Type;
571   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
572     << Msg << S->getSourceRange();
573 }
574 
575 /// ErrorUnsupported - Print out an error that codegen doesn't support the
576 /// specified decl yet.
577 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
578   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
579                                                "cannot compile this %0 yet");
580   std::string Msg = Type;
581   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
582 }
583 
584 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
585   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
586 }
587 
588 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
589                                         const NamedDecl *D) const {
590   // Internal definitions always have default visibility.
591   if (GV->hasLocalLinkage()) {
592     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
593     return;
594   }
595 
596   // Set visibility for definitions.
597   LinkageInfo LV = D->getLinkageAndVisibility();
598   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
599     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
600 }
601 
602 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
603   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
604       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
605       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
606       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
607       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
608 }
609 
610 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
611     CodeGenOptions::TLSModel M) {
612   switch (M) {
613   case CodeGenOptions::GeneralDynamicTLSModel:
614     return llvm::GlobalVariable::GeneralDynamicTLSModel;
615   case CodeGenOptions::LocalDynamicTLSModel:
616     return llvm::GlobalVariable::LocalDynamicTLSModel;
617   case CodeGenOptions::InitialExecTLSModel:
618     return llvm::GlobalVariable::InitialExecTLSModel;
619   case CodeGenOptions::LocalExecTLSModel:
620     return llvm::GlobalVariable::LocalExecTLSModel;
621   }
622   llvm_unreachable("Invalid TLS model!");
623 }
624 
625 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
626   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
627 
628   llvm::GlobalValue::ThreadLocalMode TLM;
629   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
630 
631   // Override the TLS model if it is explicitly specified.
632   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
633     TLM = GetLLVMTLSModel(Attr->getModel());
634   }
635 
636   GV->setThreadLocalMode(TLM);
637 }
638 
639 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
640   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
641 
642   // Some ABIs don't have constructor variants.  Make sure that base and
643   // complete constructors get mangled the same.
644   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
645     if (!getTarget().getCXXABI().hasConstructorVariants()) {
646       CXXCtorType OrigCtorType = GD.getCtorType();
647       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
648       if (OrigCtorType == Ctor_Base)
649         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
650     }
651   }
652 
653   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
654   if (!FoundStr.empty())
655     return FoundStr;
656 
657   const auto *ND = cast<NamedDecl>(GD.getDecl());
658   SmallString<256> Buffer;
659   StringRef Str;
660   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
661     llvm::raw_svector_ostream Out(Buffer);
662     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
663       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
664     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
665       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
666     else
667       getCXXABI().getMangleContext().mangleName(ND, Out);
668     Str = Out.str();
669   } else {
670     IdentifierInfo *II = ND->getIdentifier();
671     assert(II && "Attempt to mangle unnamed decl.");
672     Str = II->getName();
673   }
674 
675   // Keep the first result in the case of a mangling collision.
676   auto Result = Manglings.insert(std::make_pair(Str, GD));
677   return FoundStr = Result.first->first();
678 }
679 
680 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
681                                              const BlockDecl *BD) {
682   MangleContext &MangleCtx = getCXXABI().getMangleContext();
683   const Decl *D = GD.getDecl();
684 
685   SmallString<256> Buffer;
686   llvm::raw_svector_ostream Out(Buffer);
687   if (!D)
688     MangleCtx.mangleGlobalBlock(BD,
689       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
690   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
691     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
692   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
693     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
694   else
695     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
696 
697   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
698   return Result.first->first();
699 }
700 
701 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
702   return getModule().getNamedValue(Name);
703 }
704 
705 /// AddGlobalCtor - Add a function to the list that will be called before
706 /// main() runs.
707 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
708                                   llvm::Constant *AssociatedData) {
709   // FIXME: Type coercion of void()* types.
710   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
711 }
712 
713 /// AddGlobalDtor - Add a function to the list that will be called
714 /// when the module is unloaded.
715 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
716   // FIXME: Type coercion of void()* types.
717   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
718 }
719 
720 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
721   // Ctor function type is void()*.
722   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
723   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
724 
725   // Get the type of a ctor entry, { i32, void ()*, i8* }.
726   llvm::StructType *CtorStructTy = llvm::StructType::get(
727       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
728 
729   // Construct the constructor and destructor arrays.
730   SmallVector<llvm::Constant *, 8> Ctors;
731   for (const auto &I : Fns) {
732     llvm::Constant *S[] = {
733         llvm::ConstantInt::get(Int32Ty, I.Priority, false),
734         llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy),
735         (I.AssociatedData
736              ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)
737              : llvm::Constant::getNullValue(VoidPtrTy))};
738     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
739   }
740 
741   if (!Ctors.empty()) {
742     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
743     new llvm::GlobalVariable(TheModule, AT, false,
744                              llvm::GlobalValue::AppendingLinkage,
745                              llvm::ConstantArray::get(AT, Ctors),
746                              GlobalName);
747   }
748 }
749 
750 llvm::GlobalValue::LinkageTypes
751 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
752   const auto *D = cast<FunctionDecl>(GD.getDecl());
753 
754   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
755 
756   if (isa<CXXDestructorDecl>(D) &&
757       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
758                                          GD.getDtorType())) {
759     // Destructor variants in the Microsoft C++ ABI are always internal or
760     // linkonce_odr thunks emitted on an as-needed basis.
761     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
762                                    : llvm::GlobalValue::LinkOnceODRLinkage;
763   }
764 
765   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
766 }
767 
768 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
769   const auto *FD = cast<FunctionDecl>(GD.getDecl());
770 
771   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
772     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
773       // Don't dllexport/import destructor thunks.
774       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
775       return;
776     }
777   }
778 
779   if (FD->hasAttr<DLLImportAttr>())
780     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
781   else if (FD->hasAttr<DLLExportAttr>())
782     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
783   else
784     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
785 }
786 
787 llvm::ConstantInt *
788 CodeGenModule::CreateCfiIdForTypeMetadata(llvm::Metadata *MD) {
789   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
790   if (!MDS) return nullptr;
791 
792   llvm::MD5 md5;
793   llvm::MD5::MD5Result result;
794   md5.update(MDS->getString());
795   md5.final(result);
796   uint64_t id = 0;
797   for (int i = 0; i < 8; ++i)
798     id |= static_cast<uint64_t>(result[i]) << (i * 8);
799   return llvm::ConstantInt::get(Int64Ty, id);
800 }
801 
802 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
803                                                     llvm::Function *F) {
804   setNonAliasAttributes(D, F);
805 }
806 
807 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
808                                               const CGFunctionInfo &Info,
809                                               llvm::Function *F) {
810   unsigned CallingConv;
811   AttributeListType AttributeList;
812   ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
813                          false);
814   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
815   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
816 }
817 
818 /// Determines whether the language options require us to model
819 /// unwind exceptions.  We treat -fexceptions as mandating this
820 /// except under the fragile ObjC ABI with only ObjC exceptions
821 /// enabled.  This means, for example, that C with -fexceptions
822 /// enables this.
823 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
824   // If exceptions are completely disabled, obviously this is false.
825   if (!LangOpts.Exceptions) return false;
826 
827   // If C++ exceptions are enabled, this is true.
828   if (LangOpts.CXXExceptions) return true;
829 
830   // If ObjC exceptions are enabled, this depends on the ABI.
831   if (LangOpts.ObjCExceptions) {
832     return LangOpts.ObjCRuntime.hasUnwindExceptions();
833   }
834 
835   return true;
836 }
837 
838 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
839                                                            llvm::Function *F) {
840   llvm::AttrBuilder B;
841 
842   if (CodeGenOpts.UnwindTables)
843     B.addAttribute(llvm::Attribute::UWTable);
844 
845   if (!hasUnwindExceptions(LangOpts))
846     B.addAttribute(llvm::Attribute::NoUnwind);
847 
848   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
849     B.addAttribute(llvm::Attribute::StackProtect);
850   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
851     B.addAttribute(llvm::Attribute::StackProtectStrong);
852   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
853     B.addAttribute(llvm::Attribute::StackProtectReq);
854 
855   if (!D) {
856     F->addAttributes(llvm::AttributeSet::FunctionIndex,
857                      llvm::AttributeSet::get(
858                          F->getContext(),
859                          llvm::AttributeSet::FunctionIndex, B));
860     return;
861   }
862 
863   if (D->hasAttr<NakedAttr>()) {
864     // Naked implies noinline: we should not be inlining such functions.
865     B.addAttribute(llvm::Attribute::Naked);
866     B.addAttribute(llvm::Attribute::NoInline);
867   } else if (D->hasAttr<NoDuplicateAttr>()) {
868     B.addAttribute(llvm::Attribute::NoDuplicate);
869   } else if (D->hasAttr<NoInlineAttr>()) {
870     B.addAttribute(llvm::Attribute::NoInline);
871   } else if (D->hasAttr<AlwaysInlineAttr>() &&
872              !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
873                                               llvm::Attribute::NoInline)) {
874     // (noinline wins over always_inline, and we can't specify both in IR)
875     B.addAttribute(llvm::Attribute::AlwaysInline);
876   }
877 
878   if (D->hasAttr<ColdAttr>()) {
879     if (!D->hasAttr<OptimizeNoneAttr>())
880       B.addAttribute(llvm::Attribute::OptimizeForSize);
881     B.addAttribute(llvm::Attribute::Cold);
882   }
883 
884   if (D->hasAttr<MinSizeAttr>())
885     B.addAttribute(llvm::Attribute::MinSize);
886 
887   F->addAttributes(llvm::AttributeSet::FunctionIndex,
888                    llvm::AttributeSet::get(
889                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
890 
891   if (D->hasAttr<OptimizeNoneAttr>()) {
892     // OptimizeNone implies noinline; we should not be inlining such functions.
893     F->addFnAttr(llvm::Attribute::OptimizeNone);
894     F->addFnAttr(llvm::Attribute::NoInline);
895 
896     // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
897     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
898     F->removeFnAttr(llvm::Attribute::MinSize);
899     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
900            "OptimizeNone and AlwaysInline on same function!");
901 
902     // Attribute 'inlinehint' has no effect on 'optnone' functions.
903     // Explicitly remove it from the set of function attributes.
904     F->removeFnAttr(llvm::Attribute::InlineHint);
905   }
906 
907   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
908     F->setUnnamedAddr(true);
909   else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
910     if (MD->isVirtual())
911       F->setUnnamedAddr(true);
912 
913   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
914   if (alignment)
915     F->setAlignment(alignment);
916 
917   // Some C++ ABIs require 2-byte alignment for member functions, in order to
918   // reserve a bit for differentiating between virtual and non-virtual member
919   // functions. If the current target's C++ ABI requires this and this is a
920   // member function, set its alignment accordingly.
921   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
922     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
923       F->setAlignment(2);
924   }
925 }
926 
927 void CodeGenModule::SetCommonAttributes(const Decl *D,
928                                         llvm::GlobalValue *GV) {
929   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
930     setGlobalVisibility(GV, ND);
931   else
932     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
933 
934   if (D && D->hasAttr<UsedAttr>())
935     addUsedGlobal(GV);
936 }
937 
938 void CodeGenModule::setAliasAttributes(const Decl *D,
939                                        llvm::GlobalValue *GV) {
940   SetCommonAttributes(D, GV);
941 
942   // Process the dllexport attribute based on whether the original definition
943   // (not necessarily the aliasee) was exported.
944   if (D->hasAttr<DLLExportAttr>())
945     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
946 }
947 
948 void CodeGenModule::setNonAliasAttributes(const Decl *D,
949                                           llvm::GlobalObject *GO) {
950   SetCommonAttributes(D, GO);
951 
952   if (D)
953     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
954       GO->setSection(SA->getName());
955 
956   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
957 }
958 
959 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
960                                                   llvm::Function *F,
961                                                   const CGFunctionInfo &FI) {
962   SetLLVMFunctionAttributes(D, FI, F);
963   SetLLVMFunctionAttributesForDefinition(D, F);
964 
965   F->setLinkage(llvm::Function::InternalLinkage);
966 
967   setNonAliasAttributes(D, F);
968 }
969 
970 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
971                                          const NamedDecl *ND) {
972   // Set linkage and visibility in case we never see a definition.
973   LinkageInfo LV = ND->getLinkageAndVisibility();
974   if (LV.getLinkage() != ExternalLinkage) {
975     // Don't set internal linkage on declarations.
976   } else {
977     if (ND->hasAttr<DLLImportAttr>()) {
978       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
979       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
980     } else if (ND->hasAttr<DLLExportAttr>()) {
981       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
982       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
983     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
984       // "extern_weak" is overloaded in LLVM; we probably should have
985       // separate linkage types for this.
986       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
987     }
988 
989     // Set visibility on a declaration only if it's explicit.
990     if (LV.isVisibilityExplicit())
991       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
992   }
993 }
994 
995 void CodeGenModule::CreateFunctionBitSetEntry(const FunctionDecl *FD,
996                                               llvm::Function *F) {
997   // Only if we are checking indirect calls.
998   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
999     return;
1000 
1001   // Non-static class methods are handled via vtable pointer checks elsewhere.
1002   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1003     return;
1004 
1005   // Additionally, if building with cross-DSO support...
1006   if (CodeGenOpts.SanitizeCfiCrossDso) {
1007     // Don't emit entries for function declarations. In cross-DSO mode these are
1008     // handled with better precision at run time.
1009     if (!FD->hasBody())
1010       return;
1011     // Skip available_externally functions. They won't be codegen'ed in the
1012     // current module anyway.
1013     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1014       return;
1015   }
1016 
1017   llvm::NamedMDNode *BitsetsMD =
1018       getModule().getOrInsertNamedMetadata("llvm.bitsets");
1019 
1020   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1021   llvm::Metadata *BitsetOps[] = {
1022       MD, llvm::ConstantAsMetadata::get(F),
1023       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))};
1024   BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps));
1025 
1026   // Emit a hash-based bit set entry for cross-DSO calls.
1027   if (CodeGenOpts.SanitizeCfiCrossDso) {
1028     if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) {
1029       llvm::Metadata *BitsetOps2[] = {
1030           llvm::ConstantAsMetadata::get(TypeId),
1031           llvm::ConstantAsMetadata::get(F),
1032           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))};
1033       BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2));
1034     }
1035   }
1036 }
1037 
1038 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1039                                           bool IsIncompleteFunction,
1040                                           bool IsThunk) {
1041   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1042     // If this is an intrinsic function, set the function's attributes
1043     // to the intrinsic's attributes.
1044     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1045     return;
1046   }
1047 
1048   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1049 
1050   if (!IsIncompleteFunction)
1051     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1052 
1053   // Add the Returned attribute for "this", except for iOS 5 and earlier
1054   // where substantial code, including the libstdc++ dylib, was compiled with
1055   // GCC and does not actually return "this".
1056   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1057       !(getTarget().getTriple().isiOS() &&
1058         getTarget().getTriple().isOSVersionLT(6))) {
1059     assert(!F->arg_empty() &&
1060            F->arg_begin()->getType()
1061              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1062            "unexpected this return");
1063     F->addAttribute(1, llvm::Attribute::Returned);
1064   }
1065 
1066   // Only a few attributes are set on declarations; these may later be
1067   // overridden by a definition.
1068 
1069   setLinkageAndVisibilityForGV(F, FD);
1070 
1071   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1072     F->setSection(SA->getName());
1073 
1074   // A replaceable global allocation function does not act like a builtin by
1075   // default, only if it is invoked by a new-expression or delete-expression.
1076   if (FD->isReplaceableGlobalAllocationFunction())
1077     F->addAttribute(llvm::AttributeSet::FunctionIndex,
1078                     llvm::Attribute::NoBuiltin);
1079 
1080   CreateFunctionBitSetEntry(FD, F);
1081 }
1082 
1083 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1084   assert(!GV->isDeclaration() &&
1085          "Only globals with definition can force usage.");
1086   LLVMUsed.emplace_back(GV);
1087 }
1088 
1089 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1090   assert(!GV->isDeclaration() &&
1091          "Only globals with definition can force usage.");
1092   LLVMCompilerUsed.emplace_back(GV);
1093 }
1094 
1095 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1096                      std::vector<llvm::WeakVH> &List) {
1097   // Don't create llvm.used if there is no need.
1098   if (List.empty())
1099     return;
1100 
1101   // Convert List to what ConstantArray needs.
1102   SmallVector<llvm::Constant*, 8> UsedArray;
1103   UsedArray.resize(List.size());
1104   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1105     UsedArray[i] =
1106         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1107             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1108   }
1109 
1110   if (UsedArray.empty())
1111     return;
1112   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1113 
1114   auto *GV = new llvm::GlobalVariable(
1115       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1116       llvm::ConstantArray::get(ATy, UsedArray), Name);
1117 
1118   GV->setSection("llvm.metadata");
1119 }
1120 
1121 void CodeGenModule::emitLLVMUsed() {
1122   emitUsed(*this, "llvm.used", LLVMUsed);
1123   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1124 }
1125 
1126 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1127   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1128   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1129 }
1130 
1131 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1132   llvm::SmallString<32> Opt;
1133   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1134   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1135   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1136 }
1137 
1138 void CodeGenModule::AddDependentLib(StringRef Lib) {
1139   llvm::SmallString<24> Opt;
1140   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1141   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1142   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1143 }
1144 
1145 /// \brief Add link options implied by the given module, including modules
1146 /// it depends on, using a postorder walk.
1147 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1148                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
1149                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1150   // Import this module's parent.
1151   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1152     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1153   }
1154 
1155   // Import this module's dependencies.
1156   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1157     if (Visited.insert(Mod->Imports[I - 1]).second)
1158       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1159   }
1160 
1161   // Add linker options to link against the libraries/frameworks
1162   // described by this module.
1163   llvm::LLVMContext &Context = CGM.getLLVMContext();
1164   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1165     // Link against a framework.  Frameworks are currently Darwin only, so we
1166     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1167     if (Mod->LinkLibraries[I-1].IsFramework) {
1168       llvm::Metadata *Args[2] = {
1169           llvm::MDString::get(Context, "-framework"),
1170           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1171 
1172       Metadata.push_back(llvm::MDNode::get(Context, Args));
1173       continue;
1174     }
1175 
1176     // Link against a library.
1177     llvm::SmallString<24> Opt;
1178     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1179       Mod->LinkLibraries[I-1].Library, Opt);
1180     auto *OptString = llvm::MDString::get(Context, Opt);
1181     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1182   }
1183 }
1184 
1185 void CodeGenModule::EmitModuleLinkOptions() {
1186   // Collect the set of all of the modules we want to visit to emit link
1187   // options, which is essentially the imported modules and all of their
1188   // non-explicit child modules.
1189   llvm::SetVector<clang::Module *> LinkModules;
1190   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1191   SmallVector<clang::Module *, 16> Stack;
1192 
1193   // Seed the stack with imported modules.
1194   for (Module *M : ImportedModules)
1195     if (Visited.insert(M).second)
1196       Stack.push_back(M);
1197 
1198   // Find all of the modules to import, making a little effort to prune
1199   // non-leaf modules.
1200   while (!Stack.empty()) {
1201     clang::Module *Mod = Stack.pop_back_val();
1202 
1203     bool AnyChildren = false;
1204 
1205     // Visit the submodules of this module.
1206     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1207                                         SubEnd = Mod->submodule_end();
1208          Sub != SubEnd; ++Sub) {
1209       // Skip explicit children; they need to be explicitly imported to be
1210       // linked against.
1211       if ((*Sub)->IsExplicit)
1212         continue;
1213 
1214       if (Visited.insert(*Sub).second) {
1215         Stack.push_back(*Sub);
1216         AnyChildren = true;
1217       }
1218     }
1219 
1220     // We didn't find any children, so add this module to the list of
1221     // modules to link against.
1222     if (!AnyChildren) {
1223       LinkModules.insert(Mod);
1224     }
1225   }
1226 
1227   // Add link options for all of the imported modules in reverse topological
1228   // order.  We don't do anything to try to order import link flags with respect
1229   // to linker options inserted by things like #pragma comment().
1230   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1231   Visited.clear();
1232   for (Module *M : LinkModules)
1233     if (Visited.insert(M).second)
1234       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1235   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1236   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1237 
1238   // Add the linker options metadata flag.
1239   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1240                             llvm::MDNode::get(getLLVMContext(),
1241                                               LinkerOptionsMetadata));
1242 }
1243 
1244 void CodeGenModule::EmitDeferred() {
1245   // Emit code for any potentially referenced deferred decls.  Since a
1246   // previously unused static decl may become used during the generation of code
1247   // for a static function, iterate until no changes are made.
1248 
1249   if (!DeferredVTables.empty()) {
1250     EmitDeferredVTables();
1251 
1252     // Emitting a vtable doesn't directly cause more vtables to
1253     // become deferred, although it can cause functions to be
1254     // emitted that then need those vtables.
1255     assert(DeferredVTables.empty());
1256   }
1257 
1258   // Stop if we're out of both deferred vtables and deferred declarations.
1259   if (DeferredDeclsToEmit.empty())
1260     return;
1261 
1262   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1263   // work, it will not interfere with this.
1264   std::vector<DeferredGlobal> CurDeclsToEmit;
1265   CurDeclsToEmit.swap(DeferredDeclsToEmit);
1266 
1267   for (DeferredGlobal &G : CurDeclsToEmit) {
1268     GlobalDecl D = G.GD;
1269     G.GV = nullptr;
1270 
1271     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1272     // to get GlobalValue with exactly the type we need, not something that
1273     // might had been created for another decl with the same mangled name but
1274     // different type.
1275     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1276         GetAddrOfGlobal(D, /*IsForDefinition=*/true));
1277 
1278     // In case of different address spaces, we may still get a cast, even with
1279     // IsForDefinition equal to true. Query mangled names table to get
1280     // GlobalValue.
1281     if (!GV)
1282       GV = GetGlobalValue(getMangledName(D));
1283 
1284     // Make sure GetGlobalValue returned non-null.
1285     assert(GV);
1286 
1287     // Check to see if we've already emitted this.  This is necessary
1288     // for a couple of reasons: first, decls can end up in the
1289     // deferred-decls queue multiple times, and second, decls can end
1290     // up with definitions in unusual ways (e.g. by an extern inline
1291     // function acquiring a strong function redefinition).  Just
1292     // ignore these cases.
1293     if (!GV->isDeclaration())
1294       continue;
1295 
1296     // Otherwise, emit the definition and move on to the next one.
1297     EmitGlobalDefinition(D, GV);
1298 
1299     // If we found out that we need to emit more decls, do that recursively.
1300     // This has the advantage that the decls are emitted in a DFS and related
1301     // ones are close together, which is convenient for testing.
1302     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1303       EmitDeferred();
1304       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1305     }
1306   }
1307 }
1308 
1309 void CodeGenModule::EmitGlobalAnnotations() {
1310   if (Annotations.empty())
1311     return;
1312 
1313   // Create a new global variable for the ConstantStruct in the Module.
1314   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1315     Annotations[0]->getType(), Annotations.size()), Annotations);
1316   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1317                                       llvm::GlobalValue::AppendingLinkage,
1318                                       Array, "llvm.global.annotations");
1319   gv->setSection(AnnotationSection);
1320 }
1321 
1322 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1323   llvm::Constant *&AStr = AnnotationStrings[Str];
1324   if (AStr)
1325     return AStr;
1326 
1327   // Not found yet, create a new global.
1328   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1329   auto *gv =
1330       new llvm::GlobalVariable(getModule(), s->getType(), true,
1331                                llvm::GlobalValue::PrivateLinkage, s, ".str");
1332   gv->setSection(AnnotationSection);
1333   gv->setUnnamedAddr(true);
1334   AStr = gv;
1335   return gv;
1336 }
1337 
1338 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1339   SourceManager &SM = getContext().getSourceManager();
1340   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1341   if (PLoc.isValid())
1342     return EmitAnnotationString(PLoc.getFilename());
1343   return EmitAnnotationString(SM.getBufferName(Loc));
1344 }
1345 
1346 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1347   SourceManager &SM = getContext().getSourceManager();
1348   PresumedLoc PLoc = SM.getPresumedLoc(L);
1349   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1350     SM.getExpansionLineNumber(L);
1351   return llvm::ConstantInt::get(Int32Ty, LineNo);
1352 }
1353 
1354 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1355                                                 const AnnotateAttr *AA,
1356                                                 SourceLocation L) {
1357   // Get the globals for file name, annotation, and the line number.
1358   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1359                  *UnitGV = EmitAnnotationUnit(L),
1360                  *LineNoCst = EmitAnnotationLineNo(L);
1361 
1362   // Create the ConstantStruct for the global annotation.
1363   llvm::Constant *Fields[4] = {
1364     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1365     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1366     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1367     LineNoCst
1368   };
1369   return llvm::ConstantStruct::getAnon(Fields);
1370 }
1371 
1372 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1373                                          llvm::GlobalValue *GV) {
1374   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1375   // Get the struct elements for these annotations.
1376   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1377     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1378 }
1379 
1380 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1381                                            SourceLocation Loc) const {
1382   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1383   // Blacklist by function name.
1384   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1385     return true;
1386   // Blacklist by location.
1387   if (Loc.isValid())
1388     return SanitizerBL.isBlacklistedLocation(Loc);
1389   // If location is unknown, this may be a compiler-generated function. Assume
1390   // it's located in the main file.
1391   auto &SM = Context.getSourceManager();
1392   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1393     return SanitizerBL.isBlacklistedFile(MainFile->getName());
1394   }
1395   return false;
1396 }
1397 
1398 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1399                                            SourceLocation Loc, QualType Ty,
1400                                            StringRef Category) const {
1401   // For now globals can be blacklisted only in ASan and KASan.
1402   if (!LangOpts.Sanitize.hasOneOf(
1403           SanitizerKind::Address | SanitizerKind::KernelAddress))
1404     return false;
1405   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1406   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1407     return true;
1408   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1409     return true;
1410   // Check global type.
1411   if (!Ty.isNull()) {
1412     // Drill down the array types: if global variable of a fixed type is
1413     // blacklisted, we also don't instrument arrays of them.
1414     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1415       Ty = AT->getElementType();
1416     Ty = Ty.getCanonicalType().getUnqualifiedType();
1417     // We allow to blacklist only record types (classes, structs etc.)
1418     if (Ty->isRecordType()) {
1419       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1420       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1421         return true;
1422     }
1423   }
1424   return false;
1425 }
1426 
1427 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1428   // Never defer when EmitAllDecls is specified.
1429   if (LangOpts.EmitAllDecls)
1430     return true;
1431 
1432   return getContext().DeclMustBeEmitted(Global);
1433 }
1434 
1435 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1436   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1437     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1438       // Implicit template instantiations may change linkage if they are later
1439       // explicitly instantiated, so they should not be emitted eagerly.
1440       return false;
1441   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1442   // codegen for global variables, because they may be marked as threadprivate.
1443   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1444       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1445     return false;
1446 
1447   return true;
1448 }
1449 
1450 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1451     const CXXUuidofExpr* E) {
1452   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1453   // well-formed.
1454   StringRef Uuid = E->getUuidAsStringRef(Context);
1455   std::string Name = "_GUID_" + Uuid.lower();
1456   std::replace(Name.begin(), Name.end(), '-', '_');
1457 
1458   // Contains a 32-bit field.
1459   CharUnits Alignment = CharUnits::fromQuantity(4);
1460 
1461   // Look for an existing global.
1462   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1463     return ConstantAddress(GV, Alignment);
1464 
1465   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1466   assert(Init && "failed to initialize as constant");
1467 
1468   auto *GV = new llvm::GlobalVariable(
1469       getModule(), Init->getType(),
1470       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1471   if (supportsCOMDAT())
1472     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1473   return ConstantAddress(GV, Alignment);
1474 }
1475 
1476 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1477   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1478   assert(AA && "No alias?");
1479 
1480   CharUnits Alignment = getContext().getDeclAlign(VD);
1481   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1482 
1483   // See if there is already something with the target's name in the module.
1484   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1485   if (Entry) {
1486     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1487     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1488     return ConstantAddress(Ptr, Alignment);
1489   }
1490 
1491   llvm::Constant *Aliasee;
1492   if (isa<llvm::FunctionType>(DeclTy))
1493     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1494                                       GlobalDecl(cast<FunctionDecl>(VD)),
1495                                       /*ForVTable=*/false);
1496   else
1497     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1498                                     llvm::PointerType::getUnqual(DeclTy),
1499                                     nullptr);
1500 
1501   auto *F = cast<llvm::GlobalValue>(Aliasee);
1502   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1503   WeakRefReferences.insert(F);
1504 
1505   return ConstantAddress(Aliasee, Alignment);
1506 }
1507 
1508 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1509   const auto *Global = cast<ValueDecl>(GD.getDecl());
1510 
1511   // Weak references don't produce any output by themselves.
1512   if (Global->hasAttr<WeakRefAttr>())
1513     return;
1514 
1515   // If this is an alias definition (which otherwise looks like a declaration)
1516   // emit it now.
1517   if (Global->hasAttr<AliasAttr>())
1518     return EmitAliasDefinition(GD);
1519 
1520   // If this is CUDA, be selective about which declarations we emit.
1521   if (LangOpts.CUDA) {
1522     if (LangOpts.CUDAIsDevice) {
1523       if (!Global->hasAttr<CUDADeviceAttr>() &&
1524           !Global->hasAttr<CUDAGlobalAttr>() &&
1525           !Global->hasAttr<CUDAConstantAttr>() &&
1526           !Global->hasAttr<CUDASharedAttr>())
1527         return;
1528     } else {
1529       if (!Global->hasAttr<CUDAHostAttr>() && (
1530             Global->hasAttr<CUDADeviceAttr>() ||
1531             Global->hasAttr<CUDAConstantAttr>() ||
1532             Global->hasAttr<CUDASharedAttr>()))
1533         return;
1534     }
1535   }
1536 
1537   // If this is OpenMP device, check if it is legal to emit this global
1538   // normally.
1539   if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1540     return;
1541 
1542   // Ignore declarations, they will be emitted on their first use.
1543   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1544     // Forward declarations are emitted lazily on first use.
1545     if (!FD->doesThisDeclarationHaveABody()) {
1546       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1547         return;
1548 
1549       StringRef MangledName = getMangledName(GD);
1550 
1551       // Compute the function info and LLVM type.
1552       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1553       llvm::Type *Ty = getTypes().GetFunctionType(FI);
1554 
1555       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1556                               /*DontDefer=*/false);
1557       return;
1558     }
1559   } else {
1560     const auto *VD = cast<VarDecl>(Global);
1561     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1562 
1563     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1564         !Context.isMSStaticDataMemberInlineDefinition(VD))
1565       return;
1566   }
1567 
1568   // Defer code generation to first use when possible, e.g. if this is an inline
1569   // function. If the global must always be emitted, do it eagerly if possible
1570   // to benefit from cache locality.
1571   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1572     // Emit the definition if it can't be deferred.
1573     EmitGlobalDefinition(GD);
1574     return;
1575   }
1576 
1577   // If we're deferring emission of a C++ variable with an
1578   // initializer, remember the order in which it appeared in the file.
1579   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1580       cast<VarDecl>(Global)->hasInit()) {
1581     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1582     CXXGlobalInits.push_back(nullptr);
1583   }
1584 
1585   StringRef MangledName = getMangledName(GD);
1586   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1587     // The value has already been used and should therefore be emitted.
1588     addDeferredDeclToEmit(GV, GD);
1589   } else if (MustBeEmitted(Global)) {
1590     // The value must be emitted, but cannot be emitted eagerly.
1591     assert(!MayBeEmittedEagerly(Global));
1592     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1593   } else {
1594     // Otherwise, remember that we saw a deferred decl with this name.  The
1595     // first use of the mangled name will cause it to move into
1596     // DeferredDeclsToEmit.
1597     DeferredDecls[MangledName] = GD;
1598   }
1599 }
1600 
1601 namespace {
1602   struct FunctionIsDirectlyRecursive :
1603     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1604     const StringRef Name;
1605     const Builtin::Context &BI;
1606     bool Result;
1607     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1608       Name(N), BI(C), Result(false) {
1609     }
1610     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1611 
1612     bool TraverseCallExpr(CallExpr *E) {
1613       const FunctionDecl *FD = E->getDirectCallee();
1614       if (!FD)
1615         return true;
1616       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1617       if (Attr && Name == Attr->getLabel()) {
1618         Result = true;
1619         return false;
1620       }
1621       unsigned BuiltinID = FD->getBuiltinID();
1622       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1623         return true;
1624       StringRef BuiltinName = BI.getName(BuiltinID);
1625       if (BuiltinName.startswith("__builtin_") &&
1626           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1627         Result = true;
1628         return false;
1629       }
1630       return true;
1631     }
1632   };
1633 
1634   struct DLLImportFunctionVisitor
1635       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1636     bool SafeToInline = true;
1637 
1638     bool VisitVarDecl(VarDecl *VD) {
1639       // A thread-local variable cannot be imported.
1640       SafeToInline = !VD->getTLSKind();
1641       return SafeToInline;
1642     }
1643 
1644     // Make sure we're not referencing non-imported vars or functions.
1645     bool VisitDeclRefExpr(DeclRefExpr *E) {
1646       ValueDecl *VD = E->getDecl();
1647       if (isa<FunctionDecl>(VD))
1648         SafeToInline = VD->hasAttr<DLLImportAttr>();
1649       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1650         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1651       return SafeToInline;
1652     }
1653     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1654       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1655       return SafeToInline;
1656     }
1657     bool VisitCXXNewExpr(CXXNewExpr *E) {
1658       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1659       return SafeToInline;
1660     }
1661   };
1662 }
1663 
1664 // isTriviallyRecursive - Check if this function calls another
1665 // decl that, because of the asm attribute or the other decl being a builtin,
1666 // ends up pointing to itself.
1667 bool
1668 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1669   StringRef Name;
1670   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1671     // asm labels are a special kind of mangling we have to support.
1672     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1673     if (!Attr)
1674       return false;
1675     Name = Attr->getLabel();
1676   } else {
1677     Name = FD->getName();
1678   }
1679 
1680   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1681   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1682   return Walker.Result;
1683 }
1684 
1685 bool
1686 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1687   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1688     return true;
1689   const auto *F = cast<FunctionDecl>(GD.getDecl());
1690   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1691     return false;
1692 
1693   if (F->hasAttr<DLLImportAttr>()) {
1694     // Check whether it would be safe to inline this dllimport function.
1695     DLLImportFunctionVisitor Visitor;
1696     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1697     if (!Visitor.SafeToInline)
1698       return false;
1699   }
1700 
1701   // PR9614. Avoid cases where the source code is lying to us. An available
1702   // externally function should have an equivalent function somewhere else,
1703   // but a function that calls itself is clearly not equivalent to the real
1704   // implementation.
1705   // This happens in glibc's btowc and in some configure checks.
1706   return !isTriviallyRecursive(F);
1707 }
1708 
1709 /// If the type for the method's class was generated by
1710 /// CGDebugInfo::createContextChain(), the cache contains only a
1711 /// limited DIType without any declarations. Since EmitFunctionStart()
1712 /// needs to find the canonical declaration for each method, we need
1713 /// to construct the complete type prior to emitting the method.
1714 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1715   if (!D->isInstance())
1716     return;
1717 
1718   if (CGDebugInfo *DI = getModuleDebugInfo())
1719     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
1720       const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1721       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1722     }
1723 }
1724 
1725 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1726   const auto *D = cast<ValueDecl>(GD.getDecl());
1727 
1728   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1729                                  Context.getSourceManager(),
1730                                  "Generating code for declaration");
1731 
1732   if (isa<FunctionDecl>(D)) {
1733     // At -O0, don't generate IR for functions with available_externally
1734     // linkage.
1735     if (!shouldEmitFunction(GD))
1736       return;
1737 
1738     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1739       CompleteDIClassType(Method);
1740       // Make sure to emit the definition(s) before we emit the thunks.
1741       // This is necessary for the generation of certain thunks.
1742       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1743         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1744       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1745         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1746       else
1747         EmitGlobalFunctionDefinition(GD, GV);
1748 
1749       if (Method->isVirtual())
1750         getVTables().EmitThunks(GD);
1751 
1752       return;
1753     }
1754 
1755     return EmitGlobalFunctionDefinition(GD, GV);
1756   }
1757 
1758   if (const auto *VD = dyn_cast<VarDecl>(D))
1759     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1760 
1761   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1762 }
1763 
1764 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1765                                                       llvm::Function *NewFn);
1766 
1767 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1768 /// module, create and return an llvm Function with the specified type. If there
1769 /// is something in the module with the specified name, return it potentially
1770 /// bitcasted to the right type.
1771 ///
1772 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1773 /// to set the attributes on the function when it is first created.
1774 llvm::Constant *
1775 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1776                                        llvm::Type *Ty,
1777                                        GlobalDecl GD, bool ForVTable,
1778                                        bool DontDefer, bool IsThunk,
1779                                        llvm::AttributeSet ExtraAttrs,
1780                                        bool IsForDefinition) {
1781   const Decl *D = GD.getDecl();
1782 
1783   // Lookup the entry, lazily creating it if necessary.
1784   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1785   if (Entry) {
1786     if (WeakRefReferences.erase(Entry)) {
1787       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1788       if (FD && !FD->hasAttr<WeakAttr>())
1789         Entry->setLinkage(llvm::Function::ExternalLinkage);
1790     }
1791 
1792     // Handle dropped DLL attributes.
1793     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1794       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1795 
1796     // If there are two attempts to define the same mangled name, issue an
1797     // error.
1798     if (IsForDefinition && !Entry->isDeclaration()) {
1799       GlobalDecl OtherGD;
1800       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1801       // to make sure that we issue an error only once.
1802       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1803           (GD.getCanonicalDecl().getDecl() !=
1804            OtherGD.getCanonicalDecl().getDecl()) &&
1805           DiagnosedConflictingDefinitions.insert(GD).second) {
1806         getDiags().Report(D->getLocation(),
1807                           diag::err_duplicate_mangled_name);
1808         getDiags().Report(OtherGD.getDecl()->getLocation(),
1809                           diag::note_previous_definition);
1810       }
1811     }
1812 
1813     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1814         (Entry->getType()->getElementType() == Ty)) {
1815       return Entry;
1816     }
1817 
1818     // Make sure the result is of the correct type.
1819     // (If function is requested for a definition, we always need to create a new
1820     // function, not just return a bitcast.)
1821     if (!IsForDefinition)
1822       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1823   }
1824 
1825   // This function doesn't have a complete type (for example, the return
1826   // type is an incomplete struct). Use a fake type instead, and make
1827   // sure not to try to set attributes.
1828   bool IsIncompleteFunction = false;
1829 
1830   llvm::FunctionType *FTy;
1831   if (isa<llvm::FunctionType>(Ty)) {
1832     FTy = cast<llvm::FunctionType>(Ty);
1833   } else {
1834     FTy = llvm::FunctionType::get(VoidTy, false);
1835     IsIncompleteFunction = true;
1836   }
1837 
1838   llvm::Function *F =
1839       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
1840                              Entry ? StringRef() : MangledName, &getModule());
1841 
1842   // If we already created a function with the same mangled name (but different
1843   // type) before, take its name and add it to the list of functions to be
1844   // replaced with F at the end of CodeGen.
1845   //
1846   // This happens if there is a prototype for a function (e.g. "int f()") and
1847   // then a definition of a different type (e.g. "int f(int x)").
1848   if (Entry) {
1849     F->takeName(Entry);
1850 
1851     // This might be an implementation of a function without a prototype, in
1852     // which case, try to do special replacement of calls which match the new
1853     // prototype.  The really key thing here is that we also potentially drop
1854     // arguments from the call site so as to make a direct call, which makes the
1855     // inliner happier and suppresses a number of optimizer warnings (!) about
1856     // dropping arguments.
1857     if (!Entry->use_empty()) {
1858       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
1859       Entry->removeDeadConstantUsers();
1860     }
1861 
1862     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
1863         F, Entry->getType()->getElementType()->getPointerTo());
1864     addGlobalValReplacement(Entry, BC);
1865   }
1866 
1867   assert(F->getName() == MangledName && "name was uniqued!");
1868   if (D)
1869     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1870   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1871     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1872     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1873                      llvm::AttributeSet::get(VMContext,
1874                                              llvm::AttributeSet::FunctionIndex,
1875                                              B));
1876   }
1877 
1878   if (!DontDefer) {
1879     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1880     // each other bottoming out with the base dtor.  Therefore we emit non-base
1881     // dtors on usage, even if there is no dtor definition in the TU.
1882     if (D && isa<CXXDestructorDecl>(D) &&
1883         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1884                                            GD.getDtorType()))
1885       addDeferredDeclToEmit(F, GD);
1886 
1887     // This is the first use or definition of a mangled name.  If there is a
1888     // deferred decl with this name, remember that we need to emit it at the end
1889     // of the file.
1890     auto DDI = DeferredDecls.find(MangledName);
1891     if (DDI != DeferredDecls.end()) {
1892       // Move the potentially referenced deferred decl to the
1893       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1894       // don't need it anymore).
1895       addDeferredDeclToEmit(F, DDI->second);
1896       DeferredDecls.erase(DDI);
1897 
1898       // Otherwise, there are cases we have to worry about where we're
1899       // using a declaration for which we must emit a definition but where
1900       // we might not find a top-level definition:
1901       //   - member functions defined inline in their classes
1902       //   - friend functions defined inline in some class
1903       //   - special member functions with implicit definitions
1904       // If we ever change our AST traversal to walk into class methods,
1905       // this will be unnecessary.
1906       //
1907       // We also don't emit a definition for a function if it's going to be an
1908       // entry in a vtable, unless it's already marked as used.
1909     } else if (getLangOpts().CPlusPlus && D) {
1910       // Look for a declaration that's lexically in a record.
1911       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1912            FD = FD->getPreviousDecl()) {
1913         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1914           if (FD->doesThisDeclarationHaveABody()) {
1915             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1916             break;
1917           }
1918         }
1919       }
1920     }
1921   }
1922 
1923   // Make sure the result is of the requested type.
1924   if (!IsIncompleteFunction) {
1925     assert(F->getType()->getElementType() == Ty);
1926     return F;
1927   }
1928 
1929   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1930   return llvm::ConstantExpr::getBitCast(F, PTy);
1931 }
1932 
1933 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1934 /// non-null, then this function will use the specified type if it has to
1935 /// create it (this occurs when we see a definition of the function).
1936 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1937                                                  llvm::Type *Ty,
1938                                                  bool ForVTable,
1939                                                  bool DontDefer,
1940                                                  bool IsForDefinition) {
1941   // If there was no specific requested type, just convert it now.
1942   if (!Ty) {
1943     const auto *FD = cast<FunctionDecl>(GD.getDecl());
1944     auto CanonTy = Context.getCanonicalType(FD->getType());
1945     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
1946   }
1947 
1948   StringRef MangledName = getMangledName(GD);
1949   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
1950                                  /*IsThunk=*/false, llvm::AttributeSet(),
1951                                  IsForDefinition);
1952 }
1953 
1954 /// CreateRuntimeFunction - Create a new runtime function with the specified
1955 /// type and name.
1956 llvm::Constant *
1957 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1958                                      StringRef Name,
1959                                      llvm::AttributeSet ExtraAttrs) {
1960   llvm::Constant *C =
1961       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1962                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1963   if (auto *F = dyn_cast<llvm::Function>(C))
1964     if (F->empty())
1965       F->setCallingConv(getRuntimeCC());
1966   return C;
1967 }
1968 
1969 /// CreateBuiltinFunction - Create a new builtin function with the specified
1970 /// type and name.
1971 llvm::Constant *
1972 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
1973                                      StringRef Name,
1974                                      llvm::AttributeSet ExtraAttrs) {
1975   llvm::Constant *C =
1976       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1977                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1978   if (auto *F = dyn_cast<llvm::Function>(C))
1979     if (F->empty())
1980       F->setCallingConv(getBuiltinCC());
1981   return C;
1982 }
1983 
1984 /// isTypeConstant - Determine whether an object of this type can be emitted
1985 /// as a constant.
1986 ///
1987 /// If ExcludeCtor is true, the duration when the object's constructor runs
1988 /// will not be considered. The caller will need to verify that the object is
1989 /// not written to during its construction.
1990 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1991   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1992     return false;
1993 
1994   if (Context.getLangOpts().CPlusPlus) {
1995     if (const CXXRecordDecl *Record
1996           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1997       return ExcludeCtor && !Record->hasMutableFields() &&
1998              Record->hasTrivialDestructor();
1999   }
2000 
2001   return true;
2002 }
2003 
2004 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2005 /// create and return an llvm GlobalVariable with the specified type.  If there
2006 /// is something in the module with the specified name, return it potentially
2007 /// bitcasted to the right type.
2008 ///
2009 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2010 /// to set the attributes on the global when it is first created.
2011 ///
2012 /// If IsForDefinition is true, it is guranteed that an actual global with
2013 /// type Ty will be returned, not conversion of a variable with the same
2014 /// mangled name but some other type.
2015 llvm::Constant *
2016 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2017                                      llvm::PointerType *Ty,
2018                                      const VarDecl *D,
2019                                      bool IsForDefinition) {
2020   // Lookup the entry, lazily creating it if necessary.
2021   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2022   if (Entry) {
2023     if (WeakRefReferences.erase(Entry)) {
2024       if (D && !D->hasAttr<WeakAttr>())
2025         Entry->setLinkage(llvm::Function::ExternalLinkage);
2026     }
2027 
2028     // Handle dropped DLL attributes.
2029     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2030       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2031 
2032     if (Entry->getType() == Ty)
2033       return Entry;
2034 
2035     // If there are two attempts to define the same mangled name, issue an
2036     // error.
2037     if (IsForDefinition && !Entry->isDeclaration()) {
2038       GlobalDecl OtherGD;
2039       const VarDecl *OtherD;
2040 
2041       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2042       // to make sure that we issue an error only once.
2043       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2044           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2045           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2046           OtherD->hasInit() &&
2047           DiagnosedConflictingDefinitions.insert(D).second) {
2048         getDiags().Report(D->getLocation(),
2049                           diag::err_duplicate_mangled_name);
2050         getDiags().Report(OtherGD.getDecl()->getLocation(),
2051                           diag::note_previous_definition);
2052       }
2053     }
2054 
2055     // Make sure the result is of the correct type.
2056     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2057       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2058 
2059     // (If global is requested for a definition, we always need to create a new
2060     // global, not just return a bitcast.)
2061     if (!IsForDefinition)
2062       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2063   }
2064 
2065   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2066   auto *GV = new llvm::GlobalVariable(
2067       getModule(), Ty->getElementType(), false,
2068       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2069       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2070 
2071   // If we already created a global with the same mangled name (but different
2072   // type) before, take its name and remove it from its parent.
2073   if (Entry) {
2074     GV->takeName(Entry);
2075 
2076     if (!Entry->use_empty()) {
2077       llvm::Constant *NewPtrForOldDecl =
2078           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2079       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2080     }
2081 
2082     Entry->eraseFromParent();
2083   }
2084 
2085   // This is the first use or definition of a mangled name.  If there is a
2086   // deferred decl with this name, remember that we need to emit it at the end
2087   // of the file.
2088   auto DDI = DeferredDecls.find(MangledName);
2089   if (DDI != DeferredDecls.end()) {
2090     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2091     // list, and remove it from DeferredDecls (since we don't need it anymore).
2092     addDeferredDeclToEmit(GV, DDI->second);
2093     DeferredDecls.erase(DDI);
2094   }
2095 
2096   // Handle things which are present even on external declarations.
2097   if (D) {
2098     // FIXME: This code is overly simple and should be merged with other global
2099     // handling.
2100     GV->setConstant(isTypeConstant(D->getType(), false));
2101 
2102     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2103 
2104     setLinkageAndVisibilityForGV(GV, D);
2105 
2106     if (D->getTLSKind()) {
2107       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2108         CXXThreadLocals.push_back(D);
2109       setTLSMode(GV, *D);
2110     }
2111 
2112     // If required by the ABI, treat declarations of static data members with
2113     // inline initializers as definitions.
2114     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2115       EmitGlobalVarDefinition(D);
2116     }
2117 
2118     // Handle XCore specific ABI requirements.
2119     if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
2120         D->getLanguageLinkage() == CLanguageLinkage &&
2121         D->getType().isConstant(Context) &&
2122         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2123       GV->setSection(".cp.rodata");
2124   }
2125 
2126   if (AddrSpace != Ty->getAddressSpace())
2127     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2128 
2129   return GV;
2130 }
2131 
2132 llvm::Constant *
2133 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2134                                bool IsForDefinition) {
2135   if (isa<CXXConstructorDecl>(GD.getDecl()))
2136     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
2137                                 getFromCtorType(GD.getCtorType()),
2138                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2139                                 /*DontDefer=*/false, IsForDefinition);
2140   else if (isa<CXXDestructorDecl>(GD.getDecl()))
2141     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
2142                                 getFromDtorType(GD.getDtorType()),
2143                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2144                                 /*DontDefer=*/false, IsForDefinition);
2145   else if (isa<CXXMethodDecl>(GD.getDecl())) {
2146     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2147         cast<CXXMethodDecl>(GD.getDecl()));
2148     auto Ty = getTypes().GetFunctionType(*FInfo);
2149     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2150                              IsForDefinition);
2151   } else if (isa<FunctionDecl>(GD.getDecl())) {
2152     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2153     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2154     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2155                              IsForDefinition);
2156   } else
2157     return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()), /*Ty=*/nullptr,
2158                               IsForDefinition);
2159 }
2160 
2161 llvm::GlobalVariable *
2162 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2163                                       llvm::Type *Ty,
2164                                       llvm::GlobalValue::LinkageTypes Linkage) {
2165   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2166   llvm::GlobalVariable *OldGV = nullptr;
2167 
2168   if (GV) {
2169     // Check if the variable has the right type.
2170     if (GV->getType()->getElementType() == Ty)
2171       return GV;
2172 
2173     // Because C++ name mangling, the only way we can end up with an already
2174     // existing global with the same name is if it has been declared extern "C".
2175     assert(GV->isDeclaration() && "Declaration has wrong type!");
2176     OldGV = GV;
2177   }
2178 
2179   // Create a new variable.
2180   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2181                                 Linkage, nullptr, Name);
2182 
2183   if (OldGV) {
2184     // Replace occurrences of the old variable if needed.
2185     GV->takeName(OldGV);
2186 
2187     if (!OldGV->use_empty()) {
2188       llvm::Constant *NewPtrForOldDecl =
2189       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2190       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2191     }
2192 
2193     OldGV->eraseFromParent();
2194   }
2195 
2196   if (supportsCOMDAT() && GV->isWeakForLinker() &&
2197       !GV->hasAvailableExternallyLinkage())
2198     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2199 
2200   return GV;
2201 }
2202 
2203 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2204 /// given global variable.  If Ty is non-null and if the global doesn't exist,
2205 /// then it will be created with the specified type instead of whatever the
2206 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2207 /// that an actual global with type Ty will be returned, not conversion of a
2208 /// variable with the same mangled name but some other type.
2209 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2210                                                   llvm::Type *Ty,
2211                                                   bool IsForDefinition) {
2212   assert(D->hasGlobalStorage() && "Not a global variable");
2213   QualType ASTTy = D->getType();
2214   if (!Ty)
2215     Ty = getTypes().ConvertTypeForMem(ASTTy);
2216 
2217   llvm::PointerType *PTy =
2218     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2219 
2220   StringRef MangledName = getMangledName(D);
2221   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2222 }
2223 
2224 /// CreateRuntimeVariable - Create a new runtime global variable with the
2225 /// specified type and name.
2226 llvm::Constant *
2227 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2228                                      StringRef Name) {
2229   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2230 }
2231 
2232 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2233   assert(!D->getInit() && "Cannot emit definite definitions here!");
2234 
2235   StringRef MangledName = getMangledName(D);
2236   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2237 
2238   // We already have a definition, not declaration, with the same mangled name.
2239   // Emitting of declaration is not required (and actually overwrites emitted
2240   // definition).
2241   if (GV && !GV->isDeclaration())
2242     return;
2243 
2244   // If we have not seen a reference to this variable yet, place it into the
2245   // deferred declarations table to be emitted if needed later.
2246   if (!MustBeEmitted(D) && !GV) {
2247       DeferredDecls[MangledName] = D;
2248       return;
2249   }
2250 
2251   // The tentative definition is the only definition.
2252   EmitGlobalVarDefinition(D);
2253 }
2254 
2255 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2256   return Context.toCharUnitsFromBits(
2257       getDataLayout().getTypeStoreSizeInBits(Ty));
2258 }
2259 
2260 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2261                                                  unsigned AddrSpace) {
2262   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2263     if (D->hasAttr<CUDAConstantAttr>())
2264       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2265     else if (D->hasAttr<CUDASharedAttr>())
2266       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2267     else
2268       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2269   }
2270 
2271   return AddrSpace;
2272 }
2273 
2274 template<typename SomeDecl>
2275 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2276                                                llvm::GlobalValue *GV) {
2277   if (!getLangOpts().CPlusPlus)
2278     return;
2279 
2280   // Must have 'used' attribute, or else inline assembly can't rely on
2281   // the name existing.
2282   if (!D->template hasAttr<UsedAttr>())
2283     return;
2284 
2285   // Must have internal linkage and an ordinary name.
2286   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2287     return;
2288 
2289   // Must be in an extern "C" context. Entities declared directly within
2290   // a record are not extern "C" even if the record is in such a context.
2291   const SomeDecl *First = D->getFirstDecl();
2292   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2293     return;
2294 
2295   // OK, this is an internal linkage entity inside an extern "C" linkage
2296   // specification. Make a note of that so we can give it the "expected"
2297   // mangled name if nothing else is using that name.
2298   std::pair<StaticExternCMap::iterator, bool> R =
2299       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2300 
2301   // If we have multiple internal linkage entities with the same name
2302   // in extern "C" regions, none of them gets that name.
2303   if (!R.second)
2304     R.first->second = nullptr;
2305 }
2306 
2307 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2308   if (!CGM.supportsCOMDAT())
2309     return false;
2310 
2311   if (D.hasAttr<SelectAnyAttr>())
2312     return true;
2313 
2314   GVALinkage Linkage;
2315   if (auto *VD = dyn_cast<VarDecl>(&D))
2316     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2317   else
2318     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2319 
2320   switch (Linkage) {
2321   case GVA_Internal:
2322   case GVA_AvailableExternally:
2323   case GVA_StrongExternal:
2324     return false;
2325   case GVA_DiscardableODR:
2326   case GVA_StrongODR:
2327     return true;
2328   }
2329   llvm_unreachable("No such linkage");
2330 }
2331 
2332 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2333                                           llvm::GlobalObject &GO) {
2334   if (!shouldBeInCOMDAT(*this, D))
2335     return;
2336   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2337 }
2338 
2339 /// Pass IsTentative as true if you want to create a tentative definition.
2340 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2341                                             bool IsTentative) {
2342   llvm::Constant *Init = nullptr;
2343   QualType ASTTy = D->getType();
2344   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2345   bool NeedsGlobalCtor = false;
2346   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2347 
2348   const VarDecl *InitDecl;
2349   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2350 
2351   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2352   // as part of their declaration."  Sema has already checked for
2353   // error cases, so we just need to set Init to UndefValue.
2354   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2355       D->hasAttr<CUDASharedAttr>())
2356     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2357   else if (!InitExpr) {
2358     // This is a tentative definition; tentative definitions are
2359     // implicitly initialized with { 0 }.
2360     //
2361     // Note that tentative definitions are only emitted at the end of
2362     // a translation unit, so they should never have incomplete
2363     // type. In addition, EmitTentativeDefinition makes sure that we
2364     // never attempt to emit a tentative definition if a real one
2365     // exists. A use may still exists, however, so we still may need
2366     // to do a RAUW.
2367     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2368     Init = EmitNullConstant(D->getType());
2369   } else {
2370     initializedGlobalDecl = GlobalDecl(D);
2371     Init = EmitConstantInit(*InitDecl);
2372 
2373     if (!Init) {
2374       QualType T = InitExpr->getType();
2375       if (D->getType()->isReferenceType())
2376         T = D->getType();
2377 
2378       if (getLangOpts().CPlusPlus) {
2379         Init = EmitNullConstant(T);
2380         NeedsGlobalCtor = true;
2381       } else {
2382         ErrorUnsupported(D, "static initializer");
2383         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2384       }
2385     } else {
2386       // We don't need an initializer, so remove the entry for the delayed
2387       // initializer position (just in case this entry was delayed) if we
2388       // also don't need to register a destructor.
2389       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2390         DelayedCXXInitPosition.erase(D);
2391     }
2392   }
2393 
2394   llvm::Type* InitType = Init->getType();
2395   llvm::Constant *Entry =
2396       GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative);
2397 
2398   // Strip off a bitcast if we got one back.
2399   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2400     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2401            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2402            // All zero index gep.
2403            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2404     Entry = CE->getOperand(0);
2405   }
2406 
2407   // Entry is now either a Function or GlobalVariable.
2408   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2409 
2410   // We have a definition after a declaration with the wrong type.
2411   // We must make a new GlobalVariable* and update everything that used OldGV
2412   // (a declaration or tentative definition) with the new GlobalVariable*
2413   // (which will be a definition).
2414   //
2415   // This happens if there is a prototype for a global (e.g.
2416   // "extern int x[];") and then a definition of a different type (e.g.
2417   // "int x[10];"). This also happens when an initializer has a different type
2418   // from the type of the global (this happens with unions).
2419   if (!GV ||
2420       GV->getType()->getElementType() != InitType ||
2421       GV->getType()->getAddressSpace() !=
2422        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2423 
2424     // Move the old entry aside so that we'll create a new one.
2425     Entry->setName(StringRef());
2426 
2427     // Make a new global with the correct type, this is now guaranteed to work.
2428     GV = cast<llvm::GlobalVariable>(
2429         GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative));
2430 
2431     // Replace all uses of the old global with the new global
2432     llvm::Constant *NewPtrForOldDecl =
2433         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2434     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2435 
2436     // Erase the old global, since it is no longer used.
2437     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2438   }
2439 
2440   MaybeHandleStaticInExternC(D, GV);
2441 
2442   if (D->hasAttr<AnnotateAttr>())
2443     AddGlobalAnnotations(D, GV);
2444 
2445   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2446   // the device. [...]"
2447   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2448   // __device__, declares a variable that: [...]
2449   // Is accessible from all the threads within the grid and from the host
2450   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2451   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2452   if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice &&
2453       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>())) {
2454     GV->setExternallyInitialized(true);
2455   }
2456   GV->setInitializer(Init);
2457 
2458   // If it is safe to mark the global 'constant', do so now.
2459   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2460                   isTypeConstant(D->getType(), true));
2461 
2462   // If it is in a read-only section, mark it 'constant'.
2463   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2464     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2465     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2466       GV->setConstant(true);
2467   }
2468 
2469   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2470 
2471   // Set the llvm linkage type as appropriate.
2472   llvm::GlobalValue::LinkageTypes Linkage =
2473       getLLVMLinkageVarDefinition(D, GV->isConstant());
2474 
2475   // On Darwin, if the normal linkage of a C++ thread_local variable is
2476   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2477   // copies within a linkage unit; otherwise, the backing variable has
2478   // internal linkage and all accesses should just be calls to the
2479   // Itanium-specified entry point, which has the normal linkage of the
2480   // variable. This is to preserve the ability to change the implementation
2481   // behind the scenes.
2482   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2483       Context.getTargetInfo().getTriple().isOSDarwin() &&
2484       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2485       !llvm::GlobalVariable::isWeakLinkage(Linkage))
2486     Linkage = llvm::GlobalValue::InternalLinkage;
2487 
2488   GV->setLinkage(Linkage);
2489   if (D->hasAttr<DLLImportAttr>())
2490     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2491   else if (D->hasAttr<DLLExportAttr>())
2492     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2493   else
2494     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2495 
2496   if (Linkage == llvm::GlobalVariable::CommonLinkage)
2497     // common vars aren't constant even if declared const.
2498     GV->setConstant(false);
2499 
2500   setNonAliasAttributes(D, GV);
2501 
2502   if (D->getTLSKind() && !GV->isThreadLocal()) {
2503     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2504       CXXThreadLocals.push_back(D);
2505     setTLSMode(GV, *D);
2506   }
2507 
2508   maybeSetTrivialComdat(*D, *GV);
2509 
2510   // Emit the initializer function if necessary.
2511   if (NeedsGlobalCtor || NeedsGlobalDtor)
2512     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2513 
2514   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2515 
2516   // Emit global variable debug information.
2517   if (CGDebugInfo *DI = getModuleDebugInfo())
2518     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2519       DI->EmitGlobalVariable(GV, D);
2520 }
2521 
2522 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2523                                       CodeGenModule &CGM, const VarDecl *D,
2524                                       bool NoCommon) {
2525   // Don't give variables common linkage if -fno-common was specified unless it
2526   // was overridden by a NoCommon attribute.
2527   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2528     return true;
2529 
2530   // C11 6.9.2/2:
2531   //   A declaration of an identifier for an object that has file scope without
2532   //   an initializer, and without a storage-class specifier or with the
2533   //   storage-class specifier static, constitutes a tentative definition.
2534   if (D->getInit() || D->hasExternalStorage())
2535     return true;
2536 
2537   // A variable cannot be both common and exist in a section.
2538   if (D->hasAttr<SectionAttr>())
2539     return true;
2540 
2541   // Thread local vars aren't considered common linkage.
2542   if (D->getTLSKind())
2543     return true;
2544 
2545   // Tentative definitions marked with WeakImportAttr are true definitions.
2546   if (D->hasAttr<WeakImportAttr>())
2547     return true;
2548 
2549   // A variable cannot be both common and exist in a comdat.
2550   if (shouldBeInCOMDAT(CGM, *D))
2551     return true;
2552 
2553   // Declarations with a required alignment do not have common linakge in MSVC
2554   // mode.
2555   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2556     if (D->hasAttr<AlignedAttr>())
2557       return true;
2558     QualType VarType = D->getType();
2559     if (Context.isAlignmentRequired(VarType))
2560       return true;
2561 
2562     if (const auto *RT = VarType->getAs<RecordType>()) {
2563       const RecordDecl *RD = RT->getDecl();
2564       for (const FieldDecl *FD : RD->fields()) {
2565         if (FD->isBitField())
2566           continue;
2567         if (FD->hasAttr<AlignedAttr>())
2568           return true;
2569         if (Context.isAlignmentRequired(FD->getType()))
2570           return true;
2571       }
2572     }
2573   }
2574 
2575   return false;
2576 }
2577 
2578 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2579     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2580   if (Linkage == GVA_Internal)
2581     return llvm::Function::InternalLinkage;
2582 
2583   if (D->hasAttr<WeakAttr>()) {
2584     if (IsConstantVariable)
2585       return llvm::GlobalVariable::WeakODRLinkage;
2586     else
2587       return llvm::GlobalVariable::WeakAnyLinkage;
2588   }
2589 
2590   // We are guaranteed to have a strong definition somewhere else,
2591   // so we can use available_externally linkage.
2592   if (Linkage == GVA_AvailableExternally)
2593     return llvm::Function::AvailableExternallyLinkage;
2594 
2595   // Note that Apple's kernel linker doesn't support symbol
2596   // coalescing, so we need to avoid linkonce and weak linkages there.
2597   // Normally, this means we just map to internal, but for explicit
2598   // instantiations we'll map to external.
2599 
2600   // In C++, the compiler has to emit a definition in every translation unit
2601   // that references the function.  We should use linkonce_odr because
2602   // a) if all references in this translation unit are optimized away, we
2603   // don't need to codegen it.  b) if the function persists, it needs to be
2604   // merged with other definitions. c) C++ has the ODR, so we know the
2605   // definition is dependable.
2606   if (Linkage == GVA_DiscardableODR)
2607     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2608                                             : llvm::Function::InternalLinkage;
2609 
2610   // An explicit instantiation of a template has weak linkage, since
2611   // explicit instantiations can occur in multiple translation units
2612   // and must all be equivalent. However, we are not allowed to
2613   // throw away these explicit instantiations.
2614   if (Linkage == GVA_StrongODR)
2615     return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2616                                             : llvm::Function::ExternalLinkage;
2617 
2618   // C++ doesn't have tentative definitions and thus cannot have common
2619   // linkage.
2620   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2621       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2622                                  CodeGenOpts.NoCommon))
2623     return llvm::GlobalVariable::CommonLinkage;
2624 
2625   // selectany symbols are externally visible, so use weak instead of
2626   // linkonce.  MSVC optimizes away references to const selectany globals, so
2627   // all definitions should be the same and ODR linkage should be used.
2628   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2629   if (D->hasAttr<SelectAnyAttr>())
2630     return llvm::GlobalVariable::WeakODRLinkage;
2631 
2632   // Otherwise, we have strong external linkage.
2633   assert(Linkage == GVA_StrongExternal);
2634   return llvm::GlobalVariable::ExternalLinkage;
2635 }
2636 
2637 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2638     const VarDecl *VD, bool IsConstant) {
2639   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2640   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2641 }
2642 
2643 /// Replace the uses of a function that was declared with a non-proto type.
2644 /// We want to silently drop extra arguments from call sites
2645 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2646                                           llvm::Function *newFn) {
2647   // Fast path.
2648   if (old->use_empty()) return;
2649 
2650   llvm::Type *newRetTy = newFn->getReturnType();
2651   SmallVector<llvm::Value*, 4> newArgs;
2652   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2653 
2654   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2655          ui != ue; ) {
2656     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2657     llvm::User *user = use->getUser();
2658 
2659     // Recognize and replace uses of bitcasts.  Most calls to
2660     // unprototyped functions will use bitcasts.
2661     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2662       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2663         replaceUsesOfNonProtoConstant(bitcast, newFn);
2664       continue;
2665     }
2666 
2667     // Recognize calls to the function.
2668     llvm::CallSite callSite(user);
2669     if (!callSite) continue;
2670     if (!callSite.isCallee(&*use)) continue;
2671 
2672     // If the return types don't match exactly, then we can't
2673     // transform this call unless it's dead.
2674     if (callSite->getType() != newRetTy && !callSite->use_empty())
2675       continue;
2676 
2677     // Get the call site's attribute list.
2678     SmallVector<llvm::AttributeSet, 8> newAttrs;
2679     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2680 
2681     // Collect any return attributes from the call.
2682     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2683       newAttrs.push_back(
2684         llvm::AttributeSet::get(newFn->getContext(),
2685                                 oldAttrs.getRetAttributes()));
2686 
2687     // If the function was passed too few arguments, don't transform.
2688     unsigned newNumArgs = newFn->arg_size();
2689     if (callSite.arg_size() < newNumArgs) continue;
2690 
2691     // If extra arguments were passed, we silently drop them.
2692     // If any of the types mismatch, we don't transform.
2693     unsigned argNo = 0;
2694     bool dontTransform = false;
2695     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2696            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2697       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2698         dontTransform = true;
2699         break;
2700       }
2701 
2702       // Add any parameter attributes.
2703       if (oldAttrs.hasAttributes(argNo + 1))
2704         newAttrs.
2705           push_back(llvm::
2706                     AttributeSet::get(newFn->getContext(),
2707                                       oldAttrs.getParamAttributes(argNo + 1)));
2708     }
2709     if (dontTransform)
2710       continue;
2711 
2712     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2713       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2714                                                  oldAttrs.getFnAttributes()));
2715 
2716     // Okay, we can transform this.  Create the new call instruction and copy
2717     // over the required information.
2718     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2719 
2720     // Copy over any operand bundles.
2721     callSite.getOperandBundlesAsDefs(newBundles);
2722 
2723     llvm::CallSite newCall;
2724     if (callSite.isCall()) {
2725       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2726                                        callSite.getInstruction());
2727     } else {
2728       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2729       newCall = llvm::InvokeInst::Create(newFn,
2730                                          oldInvoke->getNormalDest(),
2731                                          oldInvoke->getUnwindDest(),
2732                                          newArgs, newBundles, "",
2733                                          callSite.getInstruction());
2734     }
2735     newArgs.clear(); // for the next iteration
2736 
2737     if (!newCall->getType()->isVoidTy())
2738       newCall->takeName(callSite.getInstruction());
2739     newCall.setAttributes(
2740                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2741     newCall.setCallingConv(callSite.getCallingConv());
2742 
2743     // Finally, remove the old call, replacing any uses with the new one.
2744     if (!callSite->use_empty())
2745       callSite->replaceAllUsesWith(newCall.getInstruction());
2746 
2747     // Copy debug location attached to CI.
2748     if (callSite->getDebugLoc())
2749       newCall->setDebugLoc(callSite->getDebugLoc());
2750 
2751     callSite->eraseFromParent();
2752   }
2753 }
2754 
2755 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2756 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2757 /// existing call uses of the old function in the module, this adjusts them to
2758 /// call the new function directly.
2759 ///
2760 /// This is not just a cleanup: the always_inline pass requires direct calls to
2761 /// functions to be able to inline them.  If there is a bitcast in the way, it
2762 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2763 /// run at -O0.
2764 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2765                                                       llvm::Function *NewFn) {
2766   // If we're redefining a global as a function, don't transform it.
2767   if (!isa<llvm::Function>(Old)) return;
2768 
2769   replaceUsesOfNonProtoConstant(Old, NewFn);
2770 }
2771 
2772 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2773   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2774   // If we have a definition, this might be a deferred decl. If the
2775   // instantiation is explicit, make sure we emit it at the end.
2776   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2777     GetAddrOfGlobalVar(VD);
2778 
2779   EmitTopLevelDecl(VD);
2780 }
2781 
2782 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2783                                                  llvm::GlobalValue *GV) {
2784   const auto *D = cast<FunctionDecl>(GD.getDecl());
2785 
2786   // Compute the function info and LLVM type.
2787   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2788   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2789 
2790   // Get or create the prototype for the function.
2791   if (!GV || (GV->getType()->getElementType() != Ty))
2792     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
2793                                                    /*DontDefer=*/true,
2794                                                    /*IsForDefinition=*/true));
2795 
2796   // Already emitted.
2797   if (!GV->isDeclaration())
2798     return;
2799 
2800   // We need to set linkage and visibility on the function before
2801   // generating code for it because various parts of IR generation
2802   // want to propagate this information down (e.g. to local static
2803   // declarations).
2804   auto *Fn = cast<llvm::Function>(GV);
2805   setFunctionLinkage(GD, Fn);
2806   setFunctionDLLStorageClass(GD, Fn);
2807 
2808   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
2809   setGlobalVisibility(Fn, D);
2810 
2811   MaybeHandleStaticInExternC(D, Fn);
2812 
2813   maybeSetTrivialComdat(*D, *Fn);
2814 
2815   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2816 
2817   setFunctionDefinitionAttributes(D, Fn);
2818   SetLLVMFunctionAttributesForDefinition(D, Fn);
2819 
2820   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2821     AddGlobalCtor(Fn, CA->getPriority());
2822   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2823     AddGlobalDtor(Fn, DA->getPriority());
2824   if (D->hasAttr<AnnotateAttr>())
2825     AddGlobalAnnotations(D, Fn);
2826 }
2827 
2828 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2829   const auto *D = cast<ValueDecl>(GD.getDecl());
2830   const AliasAttr *AA = D->getAttr<AliasAttr>();
2831   assert(AA && "Not an alias?");
2832 
2833   StringRef MangledName = getMangledName(GD);
2834 
2835   if (AA->getAliasee() == MangledName) {
2836     Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2837     return;
2838   }
2839 
2840   // If there is a definition in the module, then it wins over the alias.
2841   // This is dubious, but allow it to be safe.  Just ignore the alias.
2842   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2843   if (Entry && !Entry->isDeclaration())
2844     return;
2845 
2846   Aliases.push_back(GD);
2847 
2848   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2849 
2850   // Create a reference to the named value.  This ensures that it is emitted
2851   // if a deferred decl.
2852   llvm::Constant *Aliasee;
2853   if (isa<llvm::FunctionType>(DeclTy))
2854     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2855                                       /*ForVTable=*/false);
2856   else
2857     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2858                                     llvm::PointerType::getUnqual(DeclTy),
2859                                     /*D=*/nullptr);
2860 
2861   // Create the new alias itself, but don't set a name yet.
2862   auto *GA = llvm::GlobalAlias::create(
2863       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2864 
2865   if (Entry) {
2866     if (GA->getAliasee() == Entry) {
2867       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2868       return;
2869     }
2870 
2871     assert(Entry->isDeclaration());
2872 
2873     // If there is a declaration in the module, then we had an extern followed
2874     // by the alias, as in:
2875     //   extern int test6();
2876     //   ...
2877     //   int test6() __attribute__((alias("test7")));
2878     //
2879     // Remove it and replace uses of it with the alias.
2880     GA->takeName(Entry);
2881 
2882     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2883                                                           Entry->getType()));
2884     Entry->eraseFromParent();
2885   } else {
2886     GA->setName(MangledName);
2887   }
2888 
2889   // Set attributes which are particular to an alias; this is a
2890   // specialization of the attributes which may be set on a global
2891   // variable/function.
2892   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2893       D->isWeakImported()) {
2894     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2895   }
2896 
2897   if (const auto *VD = dyn_cast<VarDecl>(D))
2898     if (VD->getTLSKind())
2899       setTLSMode(GA, *VD);
2900 
2901   setAliasAttributes(D, GA);
2902 }
2903 
2904 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2905                                             ArrayRef<llvm::Type*> Tys) {
2906   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2907                                          Tys);
2908 }
2909 
2910 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2911 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2912                          const StringLiteral *Literal, bool TargetIsLSB,
2913                          bool &IsUTF16, unsigned &StringLength) {
2914   StringRef String = Literal->getString();
2915   unsigned NumBytes = String.size();
2916 
2917   // Check for simple case.
2918   if (!Literal->containsNonAsciiOrNull()) {
2919     StringLength = NumBytes;
2920     return *Map.insert(std::make_pair(String, nullptr)).first;
2921   }
2922 
2923   // Otherwise, convert the UTF8 literals into a string of shorts.
2924   IsUTF16 = true;
2925 
2926   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2927   const UTF8 *FromPtr = (const UTF8 *)String.data();
2928   UTF16 *ToPtr = &ToBuf[0];
2929 
2930   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2931                            &ToPtr, ToPtr + NumBytes,
2932                            strictConversion);
2933 
2934   // ConvertUTF8toUTF16 returns the length in ToPtr.
2935   StringLength = ToPtr - &ToBuf[0];
2936 
2937   // Add an explicit null.
2938   *ToPtr = 0;
2939   return *Map.insert(std::make_pair(
2940                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2941                                    (StringLength + 1) * 2),
2942                          nullptr)).first;
2943 }
2944 
2945 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2946 GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2947                        const StringLiteral *Literal, unsigned &StringLength) {
2948   StringRef String = Literal->getString();
2949   StringLength = String.size();
2950   return *Map.insert(std::make_pair(String, nullptr)).first;
2951 }
2952 
2953 ConstantAddress
2954 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2955   unsigned StringLength = 0;
2956   bool isUTF16 = false;
2957   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2958       GetConstantCFStringEntry(CFConstantStringMap, Literal,
2959                                getDataLayout().isLittleEndian(), isUTF16,
2960                                StringLength);
2961 
2962   if (auto *C = Entry.second)
2963     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
2964 
2965   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2966   llvm::Constant *Zeros[] = { Zero, Zero };
2967   llvm::Value *V;
2968 
2969   // If we don't already have it, get __CFConstantStringClassReference.
2970   if (!CFConstantStringClassRef) {
2971     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2972     Ty = llvm::ArrayType::get(Ty, 0);
2973     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2974                                            "__CFConstantStringClassReference");
2975     // Decay array -> ptr
2976     V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
2977     CFConstantStringClassRef = V;
2978   }
2979   else
2980     V = CFConstantStringClassRef;
2981 
2982   QualType CFTy = getContext().getCFConstantStringType();
2983 
2984   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2985 
2986   llvm::Constant *Fields[4];
2987 
2988   // Class pointer.
2989   Fields[0] = cast<llvm::ConstantExpr>(V);
2990 
2991   // Flags.
2992   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2993   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2994     llvm::ConstantInt::get(Ty, 0x07C8);
2995 
2996   // String pointer.
2997   llvm::Constant *C = nullptr;
2998   if (isUTF16) {
2999     auto Arr = llvm::makeArrayRef(
3000         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3001         Entry.first().size() / 2);
3002     C = llvm::ConstantDataArray::get(VMContext, Arr);
3003   } else {
3004     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3005   }
3006 
3007   // Note: -fwritable-strings doesn't make the backing store strings of
3008   // CFStrings writable. (See <rdar://problem/10657500>)
3009   auto *GV =
3010       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3011                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3012   GV->setUnnamedAddr(true);
3013   // Don't enforce the target's minimum global alignment, since the only use
3014   // of the string is via this class initializer.
3015   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
3016   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
3017   // that changes the section it ends in, which surprises ld64.
3018   if (isUTF16) {
3019     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
3020     GV->setAlignment(Align.getQuantity());
3021     GV->setSection("__TEXT,__ustring");
3022   } else {
3023     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
3024     GV->setAlignment(Align.getQuantity());
3025     GV->setSection("__TEXT,__cstring,cstring_literals");
3026   }
3027 
3028   // String.
3029   Fields[2] =
3030       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3031 
3032   if (isUTF16)
3033     // Cast the UTF16 string to the correct type.
3034     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
3035 
3036   // String length.
3037   Ty = getTypes().ConvertType(getContext().LongTy);
3038   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
3039 
3040   CharUnits Alignment = getPointerAlign();
3041 
3042   // The struct.
3043   C = llvm::ConstantStruct::get(STy, Fields);
3044   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
3045                                 llvm::GlobalVariable::PrivateLinkage, C,
3046                                 "_unnamed_cfstring_");
3047   GV->setSection("__DATA,__cfstring");
3048   GV->setAlignment(Alignment.getQuantity());
3049   Entry.second = GV;
3050 
3051   return ConstantAddress(GV, Alignment);
3052 }
3053 
3054 ConstantAddress
3055 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
3056   unsigned StringLength = 0;
3057   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3058       GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
3059 
3060   if (auto *C = Entry.second)
3061     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3062 
3063   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3064   llvm::Constant *Zeros[] = { Zero, Zero };
3065   llvm::Value *V;
3066   // If we don't already have it, get _NSConstantStringClassReference.
3067   if (!ConstantStringClassRef) {
3068     std::string StringClass(getLangOpts().ObjCConstantStringClass);
3069     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3070     llvm::Constant *GV;
3071     if (LangOpts.ObjCRuntime.isNonFragile()) {
3072       std::string str =
3073         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
3074                             : "OBJC_CLASS_$_" + StringClass;
3075       GV = getObjCRuntime().GetClassGlobal(str);
3076       // Make sure the result is of the correct type.
3077       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3078       V = llvm::ConstantExpr::getBitCast(GV, PTy);
3079       ConstantStringClassRef = V;
3080     } else {
3081       std::string str =
3082         StringClass.empty() ? "_NSConstantStringClassReference"
3083                             : "_" + StringClass + "ClassReference";
3084       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
3085       GV = CreateRuntimeVariable(PTy, str);
3086       // Decay array -> ptr
3087       V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
3088       ConstantStringClassRef = V;
3089     }
3090   } else
3091     V = ConstantStringClassRef;
3092 
3093   if (!NSConstantStringType) {
3094     // Construct the type for a constant NSString.
3095     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
3096     D->startDefinition();
3097 
3098     QualType FieldTypes[3];
3099 
3100     // const int *isa;
3101     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
3102     // const char *str;
3103     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
3104     // unsigned int length;
3105     FieldTypes[2] = Context.UnsignedIntTy;
3106 
3107     // Create fields
3108     for (unsigned i = 0; i < 3; ++i) {
3109       FieldDecl *Field = FieldDecl::Create(Context, D,
3110                                            SourceLocation(),
3111                                            SourceLocation(), nullptr,
3112                                            FieldTypes[i], /*TInfo=*/nullptr,
3113                                            /*BitWidth=*/nullptr,
3114                                            /*Mutable=*/false,
3115                                            ICIS_NoInit);
3116       Field->setAccess(AS_public);
3117       D->addDecl(Field);
3118     }
3119 
3120     D->completeDefinition();
3121     QualType NSTy = Context.getTagDeclType(D);
3122     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
3123   }
3124 
3125   llvm::Constant *Fields[3];
3126 
3127   // Class pointer.
3128   Fields[0] = cast<llvm::ConstantExpr>(V);
3129 
3130   // String pointer.
3131   llvm::Constant *C =
3132       llvm::ConstantDataArray::getString(VMContext, Entry.first());
3133 
3134   llvm::GlobalValue::LinkageTypes Linkage;
3135   bool isConstant;
3136   Linkage = llvm::GlobalValue::PrivateLinkage;
3137   isConstant = !LangOpts.WritableStrings;
3138 
3139   auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
3140                                       Linkage, C, ".str");
3141   GV->setUnnamedAddr(true);
3142   // Don't enforce the target's minimum global alignment, since the only use
3143   // of the string is via this class initializer.
3144   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
3145   GV->setAlignment(Align.getQuantity());
3146   Fields[1] =
3147       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3148 
3149   // String length.
3150   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
3151   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
3152 
3153   // The struct.
3154   CharUnits Alignment = getPointerAlign();
3155   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
3156   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
3157                                 llvm::GlobalVariable::PrivateLinkage, C,
3158                                 "_unnamed_nsstring_");
3159   GV->setAlignment(Alignment.getQuantity());
3160   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
3161   const char *NSStringNonFragileABISection =
3162       "__DATA,__objc_stringobj,regular,no_dead_strip";
3163   // FIXME. Fix section.
3164   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
3165                      ? NSStringNonFragileABISection
3166                      : NSStringSection);
3167   Entry.second = GV;
3168 
3169   return ConstantAddress(GV, Alignment);
3170 }
3171 
3172 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3173   if (ObjCFastEnumerationStateType.isNull()) {
3174     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3175     D->startDefinition();
3176 
3177     QualType FieldTypes[] = {
3178       Context.UnsignedLongTy,
3179       Context.getPointerType(Context.getObjCIdType()),
3180       Context.getPointerType(Context.UnsignedLongTy),
3181       Context.getConstantArrayType(Context.UnsignedLongTy,
3182                            llvm::APInt(32, 5), ArrayType::Normal, 0)
3183     };
3184 
3185     for (size_t i = 0; i < 4; ++i) {
3186       FieldDecl *Field = FieldDecl::Create(Context,
3187                                            D,
3188                                            SourceLocation(),
3189                                            SourceLocation(), nullptr,
3190                                            FieldTypes[i], /*TInfo=*/nullptr,
3191                                            /*BitWidth=*/nullptr,
3192                                            /*Mutable=*/false,
3193                                            ICIS_NoInit);
3194       Field->setAccess(AS_public);
3195       D->addDecl(Field);
3196     }
3197 
3198     D->completeDefinition();
3199     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3200   }
3201 
3202   return ObjCFastEnumerationStateType;
3203 }
3204 
3205 llvm::Constant *
3206 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3207   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3208 
3209   // Don't emit it as the address of the string, emit the string data itself
3210   // as an inline array.
3211   if (E->getCharByteWidth() == 1) {
3212     SmallString<64> Str(E->getString());
3213 
3214     // Resize the string to the right size, which is indicated by its type.
3215     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3216     Str.resize(CAT->getSize().getZExtValue());
3217     return llvm::ConstantDataArray::getString(VMContext, Str, false);
3218   }
3219 
3220   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3221   llvm::Type *ElemTy = AType->getElementType();
3222   unsigned NumElements = AType->getNumElements();
3223 
3224   // Wide strings have either 2-byte or 4-byte elements.
3225   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3226     SmallVector<uint16_t, 32> Elements;
3227     Elements.reserve(NumElements);
3228 
3229     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3230       Elements.push_back(E->getCodeUnit(i));
3231     Elements.resize(NumElements);
3232     return llvm::ConstantDataArray::get(VMContext, Elements);
3233   }
3234 
3235   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3236   SmallVector<uint32_t, 32> Elements;
3237   Elements.reserve(NumElements);
3238 
3239   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3240     Elements.push_back(E->getCodeUnit(i));
3241   Elements.resize(NumElements);
3242   return llvm::ConstantDataArray::get(VMContext, Elements);
3243 }
3244 
3245 static llvm::GlobalVariable *
3246 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3247                       CodeGenModule &CGM, StringRef GlobalName,
3248                       CharUnits Alignment) {
3249   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3250   unsigned AddrSpace = 0;
3251   if (CGM.getLangOpts().OpenCL)
3252     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3253 
3254   llvm::Module &M = CGM.getModule();
3255   // Create a global variable for this string
3256   auto *GV = new llvm::GlobalVariable(
3257       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3258       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3259   GV->setAlignment(Alignment.getQuantity());
3260   GV->setUnnamedAddr(true);
3261   if (GV->isWeakForLinker()) {
3262     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3263     GV->setComdat(M.getOrInsertComdat(GV->getName()));
3264   }
3265 
3266   return GV;
3267 }
3268 
3269 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3270 /// constant array for the given string literal.
3271 ConstantAddress
3272 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3273                                                   StringRef Name) {
3274   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3275 
3276   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3277   llvm::GlobalVariable **Entry = nullptr;
3278   if (!LangOpts.WritableStrings) {
3279     Entry = &ConstantStringMap[C];
3280     if (auto GV = *Entry) {
3281       if (Alignment.getQuantity() > GV->getAlignment())
3282         GV->setAlignment(Alignment.getQuantity());
3283       return ConstantAddress(GV, Alignment);
3284     }
3285   }
3286 
3287   SmallString<256> MangledNameBuffer;
3288   StringRef GlobalVariableName;
3289   llvm::GlobalValue::LinkageTypes LT;
3290 
3291   // Mangle the string literal if the ABI allows for it.  However, we cannot
3292   // do this if  we are compiling with ASan or -fwritable-strings because they
3293   // rely on strings having normal linkage.
3294   if (!LangOpts.WritableStrings &&
3295       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3296       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3297     llvm::raw_svector_ostream Out(MangledNameBuffer);
3298     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3299 
3300     LT = llvm::GlobalValue::LinkOnceODRLinkage;
3301     GlobalVariableName = MangledNameBuffer;
3302   } else {
3303     LT = llvm::GlobalValue::PrivateLinkage;
3304     GlobalVariableName = Name;
3305   }
3306 
3307   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3308   if (Entry)
3309     *Entry = GV;
3310 
3311   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3312                                   QualType());
3313   return ConstantAddress(GV, Alignment);
3314 }
3315 
3316 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3317 /// array for the given ObjCEncodeExpr node.
3318 ConstantAddress
3319 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3320   std::string Str;
3321   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3322 
3323   return GetAddrOfConstantCString(Str);
3324 }
3325 
3326 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3327 /// the literal and a terminating '\0' character.
3328 /// The result has pointer to array type.
3329 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3330     const std::string &Str, const char *GlobalName) {
3331   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3332   CharUnits Alignment =
3333     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3334 
3335   llvm::Constant *C =
3336       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3337 
3338   // Don't share any string literals if strings aren't constant.
3339   llvm::GlobalVariable **Entry = nullptr;
3340   if (!LangOpts.WritableStrings) {
3341     Entry = &ConstantStringMap[C];
3342     if (auto GV = *Entry) {
3343       if (Alignment.getQuantity() > GV->getAlignment())
3344         GV->setAlignment(Alignment.getQuantity());
3345       return ConstantAddress(GV, Alignment);
3346     }
3347   }
3348 
3349   // Get the default prefix if a name wasn't specified.
3350   if (!GlobalName)
3351     GlobalName = ".str";
3352   // Create a global variable for this.
3353   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3354                                   GlobalName, Alignment);
3355   if (Entry)
3356     *Entry = GV;
3357   return ConstantAddress(GV, Alignment);
3358 }
3359 
3360 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3361     const MaterializeTemporaryExpr *E, const Expr *Init) {
3362   assert((E->getStorageDuration() == SD_Static ||
3363           E->getStorageDuration() == SD_Thread) && "not a global temporary");
3364   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3365 
3366   // If we're not materializing a subobject of the temporary, keep the
3367   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3368   QualType MaterializedType = Init->getType();
3369   if (Init == E->GetTemporaryExpr())
3370     MaterializedType = E->getType();
3371 
3372   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3373 
3374   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3375     return ConstantAddress(Slot, Align);
3376 
3377   // FIXME: If an externally-visible declaration extends multiple temporaries,
3378   // we need to give each temporary the same name in every translation unit (and
3379   // we also need to make the temporaries externally-visible).
3380   SmallString<256> Name;
3381   llvm::raw_svector_ostream Out(Name);
3382   getCXXABI().getMangleContext().mangleReferenceTemporary(
3383       VD, E->getManglingNumber(), Out);
3384 
3385   APValue *Value = nullptr;
3386   if (E->getStorageDuration() == SD_Static) {
3387     // We might have a cached constant initializer for this temporary. Note
3388     // that this might have a different value from the value computed by
3389     // evaluating the initializer if the surrounding constant expression
3390     // modifies the temporary.
3391     Value = getContext().getMaterializedTemporaryValue(E, false);
3392     if (Value && Value->isUninit())
3393       Value = nullptr;
3394   }
3395 
3396   // Try evaluating it now, it might have a constant initializer.
3397   Expr::EvalResult EvalResult;
3398   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3399       !EvalResult.hasSideEffects())
3400     Value = &EvalResult.Val;
3401 
3402   llvm::Constant *InitialValue = nullptr;
3403   bool Constant = false;
3404   llvm::Type *Type;
3405   if (Value) {
3406     // The temporary has a constant initializer, use it.
3407     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3408     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3409     Type = InitialValue->getType();
3410   } else {
3411     // No initializer, the initialization will be provided when we
3412     // initialize the declaration which performed lifetime extension.
3413     Type = getTypes().ConvertTypeForMem(MaterializedType);
3414   }
3415 
3416   // Create a global variable for this lifetime-extended temporary.
3417   llvm::GlobalValue::LinkageTypes Linkage =
3418       getLLVMLinkageVarDefinition(VD, Constant);
3419   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3420     const VarDecl *InitVD;
3421     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3422         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3423       // Temporaries defined inside a class get linkonce_odr linkage because the
3424       // class can be defined in multipe translation units.
3425       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3426     } else {
3427       // There is no need for this temporary to have external linkage if the
3428       // VarDecl has external linkage.
3429       Linkage = llvm::GlobalVariable::InternalLinkage;
3430     }
3431   }
3432   unsigned AddrSpace = GetGlobalVarAddressSpace(
3433       VD, getContext().getTargetAddressSpace(MaterializedType));
3434   auto *GV = new llvm::GlobalVariable(
3435       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3436       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3437       AddrSpace);
3438   setGlobalVisibility(GV, VD);
3439   GV->setAlignment(Align.getQuantity());
3440   if (supportsCOMDAT() && GV->isWeakForLinker())
3441     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3442   if (VD->getTLSKind())
3443     setTLSMode(GV, *VD);
3444   MaterializedGlobalTemporaryMap[E] = GV;
3445   return ConstantAddress(GV, Align);
3446 }
3447 
3448 /// EmitObjCPropertyImplementations - Emit information for synthesized
3449 /// properties for an implementation.
3450 void CodeGenModule::EmitObjCPropertyImplementations(const
3451                                                     ObjCImplementationDecl *D) {
3452   for (const auto *PID : D->property_impls()) {
3453     // Dynamic is just for type-checking.
3454     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3455       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3456 
3457       // Determine which methods need to be implemented, some may have
3458       // been overridden. Note that ::isPropertyAccessor is not the method
3459       // we want, that just indicates if the decl came from a
3460       // property. What we want to know is if the method is defined in
3461       // this implementation.
3462       if (!D->getInstanceMethod(PD->getGetterName()))
3463         CodeGenFunction(*this).GenerateObjCGetter(
3464                                  const_cast<ObjCImplementationDecl *>(D), PID);
3465       if (!PD->isReadOnly() &&
3466           !D->getInstanceMethod(PD->getSetterName()))
3467         CodeGenFunction(*this).GenerateObjCSetter(
3468                                  const_cast<ObjCImplementationDecl *>(D), PID);
3469     }
3470   }
3471 }
3472 
3473 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3474   const ObjCInterfaceDecl *iface = impl->getClassInterface();
3475   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3476        ivar; ivar = ivar->getNextIvar())
3477     if (ivar->getType().isDestructedType())
3478       return true;
3479 
3480   return false;
3481 }
3482 
3483 static bool AllTrivialInitializers(CodeGenModule &CGM,
3484                                    ObjCImplementationDecl *D) {
3485   CodeGenFunction CGF(CGM);
3486   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3487        E = D->init_end(); B != E; ++B) {
3488     CXXCtorInitializer *CtorInitExp = *B;
3489     Expr *Init = CtorInitExp->getInit();
3490     if (!CGF.isTrivialInitializer(Init))
3491       return false;
3492   }
3493   return true;
3494 }
3495 
3496 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3497 /// for an implementation.
3498 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3499   // We might need a .cxx_destruct even if we don't have any ivar initializers.
3500   if (needsDestructMethod(D)) {
3501     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3502     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3503     ObjCMethodDecl *DTORMethod =
3504       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3505                              cxxSelector, getContext().VoidTy, nullptr, D,
3506                              /*isInstance=*/true, /*isVariadic=*/false,
3507                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3508                              /*isDefined=*/false, ObjCMethodDecl::Required);
3509     D->addInstanceMethod(DTORMethod);
3510     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3511     D->setHasDestructors(true);
3512   }
3513 
3514   // If the implementation doesn't have any ivar initializers, we don't need
3515   // a .cxx_construct.
3516   if (D->getNumIvarInitializers() == 0 ||
3517       AllTrivialInitializers(*this, D))
3518     return;
3519 
3520   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3521   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3522   // The constructor returns 'self'.
3523   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3524                                                 D->getLocation(),
3525                                                 D->getLocation(),
3526                                                 cxxSelector,
3527                                                 getContext().getObjCIdType(),
3528                                                 nullptr, D, /*isInstance=*/true,
3529                                                 /*isVariadic=*/false,
3530                                                 /*isPropertyAccessor=*/true,
3531                                                 /*isImplicitlyDeclared=*/true,
3532                                                 /*isDefined=*/false,
3533                                                 ObjCMethodDecl::Required);
3534   D->addInstanceMethod(CTORMethod);
3535   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3536   D->setHasNonZeroConstructors(true);
3537 }
3538 
3539 /// EmitNamespace - Emit all declarations in a namespace.
3540 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
3541   for (auto *I : ND->decls()) {
3542     if (const auto *VD = dyn_cast<VarDecl>(I))
3543       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3544           VD->getTemplateSpecializationKind() != TSK_Undeclared)
3545         continue;
3546     EmitTopLevelDecl(I);
3547   }
3548 }
3549 
3550 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3551 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3552   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3553       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3554     ErrorUnsupported(LSD, "linkage spec");
3555     return;
3556   }
3557 
3558   for (auto *I : LSD->decls()) {
3559     // Meta-data for ObjC class includes references to implemented methods.
3560     // Generate class's method definitions first.
3561     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3562       for (auto *M : OID->methods())
3563         EmitTopLevelDecl(M);
3564     }
3565     EmitTopLevelDecl(I);
3566   }
3567 }
3568 
3569 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3570 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3571   // Ignore dependent declarations.
3572   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3573     return;
3574 
3575   switch (D->getKind()) {
3576   case Decl::CXXConversion:
3577   case Decl::CXXMethod:
3578   case Decl::Function:
3579     // Skip function templates
3580     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3581         cast<FunctionDecl>(D)->isLateTemplateParsed())
3582       return;
3583 
3584     EmitGlobal(cast<FunctionDecl>(D));
3585     // Always provide some coverage mapping
3586     // even for the functions that aren't emitted.
3587     AddDeferredUnusedCoverageMapping(D);
3588     break;
3589 
3590   case Decl::Var:
3591     // Skip variable templates
3592     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3593       return;
3594   case Decl::VarTemplateSpecialization:
3595     EmitGlobal(cast<VarDecl>(D));
3596     break;
3597 
3598   // Indirect fields from global anonymous structs and unions can be
3599   // ignored; only the actual variable requires IR gen support.
3600   case Decl::IndirectField:
3601     break;
3602 
3603   // C++ Decls
3604   case Decl::Namespace:
3605     EmitNamespace(cast<NamespaceDecl>(D));
3606     break;
3607     // No code generation needed.
3608   case Decl::UsingShadow:
3609   case Decl::ClassTemplate:
3610   case Decl::VarTemplate:
3611   case Decl::VarTemplatePartialSpecialization:
3612   case Decl::FunctionTemplate:
3613   case Decl::TypeAliasTemplate:
3614   case Decl::Block:
3615   case Decl::Empty:
3616     break;
3617   case Decl::Using:          // using X; [C++]
3618     if (CGDebugInfo *DI = getModuleDebugInfo())
3619         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3620     return;
3621   case Decl::NamespaceAlias:
3622     if (CGDebugInfo *DI = getModuleDebugInfo())
3623         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3624     return;
3625   case Decl::UsingDirective: // using namespace X; [C++]
3626     if (CGDebugInfo *DI = getModuleDebugInfo())
3627       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3628     return;
3629   case Decl::CXXConstructor:
3630     // Skip function templates
3631     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3632         cast<FunctionDecl>(D)->isLateTemplateParsed())
3633       return;
3634 
3635     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3636     break;
3637   case Decl::CXXDestructor:
3638     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3639       return;
3640     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3641     break;
3642 
3643   case Decl::StaticAssert:
3644     // Nothing to do.
3645     break;
3646 
3647   // Objective-C Decls
3648 
3649   // Forward declarations, no (immediate) code generation.
3650   case Decl::ObjCInterface:
3651   case Decl::ObjCCategory:
3652     break;
3653 
3654   case Decl::ObjCProtocol: {
3655     auto *Proto = cast<ObjCProtocolDecl>(D);
3656     if (Proto->isThisDeclarationADefinition())
3657       ObjCRuntime->GenerateProtocol(Proto);
3658     break;
3659   }
3660 
3661   case Decl::ObjCCategoryImpl:
3662     // Categories have properties but don't support synthesize so we
3663     // can ignore them here.
3664     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3665     break;
3666 
3667   case Decl::ObjCImplementation: {
3668     auto *OMD = cast<ObjCImplementationDecl>(D);
3669     EmitObjCPropertyImplementations(OMD);
3670     EmitObjCIvarInitializations(OMD);
3671     ObjCRuntime->GenerateClass(OMD);
3672     // Emit global variable debug information.
3673     if (CGDebugInfo *DI = getModuleDebugInfo())
3674       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3675         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3676             OMD->getClassInterface()), OMD->getLocation());
3677     break;
3678   }
3679   case Decl::ObjCMethod: {
3680     auto *OMD = cast<ObjCMethodDecl>(D);
3681     // If this is not a prototype, emit the body.
3682     if (OMD->getBody())
3683       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3684     break;
3685   }
3686   case Decl::ObjCCompatibleAlias:
3687     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3688     break;
3689 
3690   case Decl::LinkageSpec:
3691     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3692     break;
3693 
3694   case Decl::FileScopeAsm: {
3695     // File-scope asm is ignored during device-side CUDA compilation.
3696     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3697       break;
3698     // File-scope asm is ignored during device-side OpenMP compilation.
3699     if (LangOpts.OpenMPIsDevice)
3700       break;
3701     auto *AD = cast<FileScopeAsmDecl>(D);
3702     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3703     break;
3704   }
3705 
3706   case Decl::Import: {
3707     auto *Import = cast<ImportDecl>(D);
3708 
3709     // Ignore import declarations that come from imported modules.
3710     if (Import->getImportedOwningModule())
3711       break;
3712     if (CGDebugInfo *DI = getModuleDebugInfo())
3713       DI->EmitImportDecl(*Import);
3714 
3715     ImportedModules.insert(Import->getImportedModule());
3716     break;
3717   }
3718 
3719   case Decl::OMPThreadPrivate:
3720     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3721     break;
3722 
3723   case Decl::ClassTemplateSpecialization: {
3724     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3725     if (DebugInfo &&
3726         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3727         Spec->hasDefinition())
3728       DebugInfo->completeTemplateDefinition(*Spec);
3729     break;
3730   }
3731 
3732   default:
3733     // Make sure we handled everything we should, every other kind is a
3734     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3735     // function. Need to recode Decl::Kind to do that easily.
3736     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3737     break;
3738   }
3739 }
3740 
3741 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3742   // Do we need to generate coverage mapping?
3743   if (!CodeGenOpts.CoverageMapping)
3744     return;
3745   switch (D->getKind()) {
3746   case Decl::CXXConversion:
3747   case Decl::CXXMethod:
3748   case Decl::Function:
3749   case Decl::ObjCMethod:
3750   case Decl::CXXConstructor:
3751   case Decl::CXXDestructor: {
3752     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
3753       return;
3754     auto I = DeferredEmptyCoverageMappingDecls.find(D);
3755     if (I == DeferredEmptyCoverageMappingDecls.end())
3756       DeferredEmptyCoverageMappingDecls[D] = true;
3757     break;
3758   }
3759   default:
3760     break;
3761   };
3762 }
3763 
3764 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3765   // Do we need to generate coverage mapping?
3766   if (!CodeGenOpts.CoverageMapping)
3767     return;
3768   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3769     if (Fn->isTemplateInstantiation())
3770       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3771   }
3772   auto I = DeferredEmptyCoverageMappingDecls.find(D);
3773   if (I == DeferredEmptyCoverageMappingDecls.end())
3774     DeferredEmptyCoverageMappingDecls[D] = false;
3775   else
3776     I->second = false;
3777 }
3778 
3779 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3780   std::vector<const Decl *> DeferredDecls;
3781   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
3782     if (!I.second)
3783       continue;
3784     DeferredDecls.push_back(I.first);
3785   }
3786   // Sort the declarations by their location to make sure that the tests get a
3787   // predictable order for the coverage mapping for the unused declarations.
3788   if (CodeGenOpts.DumpCoverageMapping)
3789     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3790               [] (const Decl *LHS, const Decl *RHS) {
3791       return LHS->getLocStart() < RHS->getLocStart();
3792     });
3793   for (const auto *D : DeferredDecls) {
3794     switch (D->getKind()) {
3795     case Decl::CXXConversion:
3796     case Decl::CXXMethod:
3797     case Decl::Function:
3798     case Decl::ObjCMethod: {
3799       CodeGenPGO PGO(*this);
3800       GlobalDecl GD(cast<FunctionDecl>(D));
3801       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3802                                   getFunctionLinkage(GD));
3803       break;
3804     }
3805     case Decl::CXXConstructor: {
3806       CodeGenPGO PGO(*this);
3807       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3808       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3809                                   getFunctionLinkage(GD));
3810       break;
3811     }
3812     case Decl::CXXDestructor: {
3813       CodeGenPGO PGO(*this);
3814       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3815       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3816                                   getFunctionLinkage(GD));
3817       break;
3818     }
3819     default:
3820       break;
3821     };
3822   }
3823 }
3824 
3825 /// Turns the given pointer into a constant.
3826 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3827                                           const void *Ptr) {
3828   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3829   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3830   return llvm::ConstantInt::get(i64, PtrInt);
3831 }
3832 
3833 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3834                                    llvm::NamedMDNode *&GlobalMetadata,
3835                                    GlobalDecl D,
3836                                    llvm::GlobalValue *Addr) {
3837   if (!GlobalMetadata)
3838     GlobalMetadata =
3839       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3840 
3841   // TODO: should we report variant information for ctors/dtors?
3842   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3843                            llvm::ConstantAsMetadata::get(GetPointerConstant(
3844                                CGM.getLLVMContext(), D.getDecl()))};
3845   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3846 }
3847 
3848 /// For each function which is declared within an extern "C" region and marked
3849 /// as 'used', but has internal linkage, create an alias from the unmangled
3850 /// name to the mangled name if possible. People expect to be able to refer
3851 /// to such functions with an unmangled name from inline assembly within the
3852 /// same translation unit.
3853 void CodeGenModule::EmitStaticExternCAliases() {
3854   // Don't do anything if we're generating CUDA device code -- the NVPTX
3855   // assembly target doesn't support aliases.
3856   if (Context.getTargetInfo().getTriple().isNVPTX())
3857     return;
3858   for (auto &I : StaticExternCValues) {
3859     IdentifierInfo *Name = I.first;
3860     llvm::GlobalValue *Val = I.second;
3861     if (Val && !getModule().getNamedValue(Name->getName()))
3862       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
3863   }
3864 }
3865 
3866 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3867                                              GlobalDecl &Result) const {
3868   auto Res = Manglings.find(MangledName);
3869   if (Res == Manglings.end())
3870     return false;
3871   Result = Res->getValue();
3872   return true;
3873 }
3874 
3875 /// Emits metadata nodes associating all the global values in the
3876 /// current module with the Decls they came from.  This is useful for
3877 /// projects using IR gen as a subroutine.
3878 ///
3879 /// Since there's currently no way to associate an MDNode directly
3880 /// with an llvm::GlobalValue, we create a global named metadata
3881 /// with the name 'clang.global.decl.ptrs'.
3882 void CodeGenModule::EmitDeclMetadata() {
3883   llvm::NamedMDNode *GlobalMetadata = nullptr;
3884 
3885   for (auto &I : MangledDeclNames) {
3886     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3887     // Some mangled names don't necessarily have an associated GlobalValue
3888     // in this module, e.g. if we mangled it for DebugInfo.
3889     if (Addr)
3890       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
3891   }
3892 }
3893 
3894 /// Emits metadata nodes for all the local variables in the current
3895 /// function.
3896 void CodeGenFunction::EmitDeclMetadata() {
3897   if (LocalDeclMap.empty()) return;
3898 
3899   llvm::LLVMContext &Context = getLLVMContext();
3900 
3901   // Find the unique metadata ID for this name.
3902   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3903 
3904   llvm::NamedMDNode *GlobalMetadata = nullptr;
3905 
3906   for (auto &I : LocalDeclMap) {
3907     const Decl *D = I.first;
3908     llvm::Value *Addr = I.second.getPointer();
3909     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3910       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3911       Alloca->setMetadata(
3912           DeclPtrKind, llvm::MDNode::get(
3913                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
3914     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3915       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3916       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3917     }
3918   }
3919 }
3920 
3921 void CodeGenModule::EmitVersionIdentMetadata() {
3922   llvm::NamedMDNode *IdentMetadata =
3923     TheModule.getOrInsertNamedMetadata("llvm.ident");
3924   std::string Version = getClangFullVersion();
3925   llvm::LLVMContext &Ctx = TheModule.getContext();
3926 
3927   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3928   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3929 }
3930 
3931 void CodeGenModule::EmitTargetMetadata() {
3932   // Warning, new MangledDeclNames may be appended within this loop.
3933   // We rely on MapVector insertions adding new elements to the end
3934   // of the container.
3935   // FIXME: Move this loop into the one target that needs it, and only
3936   // loop over those declarations for which we couldn't emit the target
3937   // metadata when we emitted the declaration.
3938   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3939     auto Val = *(MangledDeclNames.begin() + I);
3940     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3941     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
3942     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3943   }
3944 }
3945 
3946 void CodeGenModule::EmitCoverageFile() {
3947   if (!getCodeGenOpts().CoverageFile.empty()) {
3948     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3949       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3950       llvm::LLVMContext &Ctx = TheModule.getContext();
3951       llvm::MDString *CoverageFile =
3952           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3953       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3954         llvm::MDNode *CU = CUNode->getOperand(i);
3955         llvm::Metadata *Elts[] = {CoverageFile, CU};
3956         GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3957       }
3958     }
3959   }
3960 }
3961 
3962 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
3963   // Sema has checked that all uuid strings are of the form
3964   // "12345678-1234-1234-1234-1234567890ab".
3965   assert(Uuid.size() == 36);
3966   for (unsigned i = 0; i < 36; ++i) {
3967     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3968     else                                         assert(isHexDigit(Uuid[i]));
3969   }
3970 
3971   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
3972   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3973 
3974   llvm::Constant *Field3[8];
3975   for (unsigned Idx = 0; Idx < 8; ++Idx)
3976     Field3[Idx] = llvm::ConstantInt::get(
3977         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3978 
3979   llvm::Constant *Fields[4] = {
3980     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3981     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3982     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3983     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3984   };
3985 
3986   return llvm::ConstantStruct::getAnon(Fields);
3987 }
3988 
3989 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3990                                                        bool ForEH) {
3991   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3992   // FIXME: should we even be calling this method if RTTI is disabled
3993   // and it's not for EH?
3994   if (!ForEH && !getLangOpts().RTTI)
3995     return llvm::Constant::getNullValue(Int8PtrTy);
3996 
3997   if (ForEH && Ty->isObjCObjectPointerType() &&
3998       LangOpts.ObjCRuntime.isGNUFamily())
3999     return ObjCRuntime->GetEHType(Ty);
4000 
4001   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4002 }
4003 
4004 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4005   for (auto RefExpr : D->varlists()) {
4006     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4007     bool PerformInit =
4008         VD->getAnyInitializer() &&
4009         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4010                                                         /*ForRef=*/false);
4011 
4012     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4013     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4014             VD, Addr, RefExpr->getLocStart(), PerformInit))
4015       CXXGlobalInits.push_back(InitFunction);
4016   }
4017 }
4018 
4019 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4020   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4021   if (InternalId)
4022     return InternalId;
4023 
4024   if (isExternallyVisible(T->getLinkage())) {
4025     std::string OutName;
4026     llvm::raw_string_ostream Out(OutName);
4027     getCXXABI().getMangleContext().mangleTypeName(T, Out);
4028 
4029     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4030   } else {
4031     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4032                                            llvm::ArrayRef<llvm::Metadata *>());
4033   }
4034 
4035   return InternalId;
4036 }
4037 
4038 /// Returns whether this module needs the "all-vtables" bitset.
4039 bool CodeGenModule::NeedAllVtablesBitSet() const {
4040   // Returns true if at least one of vtable-based CFI checkers is enabled and
4041   // is not in the trapping mode.
4042   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4043            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4044           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4045            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4046           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4047            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4048           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4049            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4050 }
4051 
4052 void CodeGenModule::CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD,
4053                                             llvm::GlobalVariable *VTable,
4054                                             CharUnits Offset,
4055                                             const CXXRecordDecl *RD) {
4056   llvm::Metadata *MD =
4057       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4058   llvm::Metadata *BitsetOps[] = {
4059       MD, llvm::ConstantAsMetadata::get(VTable),
4060       llvm::ConstantAsMetadata::get(
4061           llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
4062   BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps));
4063 
4064   if (CodeGenOpts.SanitizeCfiCrossDso) {
4065     if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) {
4066       llvm::Metadata *BitsetOps2[] = {
4067           llvm::ConstantAsMetadata::get(TypeId),
4068           llvm::ConstantAsMetadata::get(VTable),
4069           llvm::ConstantAsMetadata::get(
4070               llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
4071       BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2));
4072     }
4073   }
4074 
4075   if (NeedAllVtablesBitSet()) {
4076     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4077     llvm::Metadata *BitsetOps[] = {
4078         MD, llvm::ConstantAsMetadata::get(VTable),
4079         llvm::ConstantAsMetadata::get(
4080             llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
4081     // Avoid adding a node to BitsetsMD twice.
4082     if (!llvm::MDTuple::getIfExists(getLLVMContext(), BitsetOps))
4083       BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps));
4084   }
4085 }
4086 
4087 // Fills in the supplied string map with the set of target features for the
4088 // passed in function.
4089 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4090                                           const FunctionDecl *FD) {
4091   StringRef TargetCPU = Target.getTargetOpts().CPU;
4092   if (const auto *TD = FD->getAttr<TargetAttr>()) {
4093     // If we have a TargetAttr build up the feature map based on that.
4094     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4095 
4096     // Make a copy of the features as passed on the command line into the
4097     // beginning of the additional features from the function to override.
4098     ParsedAttr.first.insert(ParsedAttr.first.begin(),
4099                             Target.getTargetOpts().FeaturesAsWritten.begin(),
4100                             Target.getTargetOpts().FeaturesAsWritten.end());
4101 
4102     if (ParsedAttr.second != "")
4103       TargetCPU = ParsedAttr.second;
4104 
4105     // Now populate the feature map, first with the TargetCPU which is either
4106     // the default or a new one from the target attribute string. Then we'll use
4107     // the passed in features (FeaturesAsWritten) along with the new ones from
4108     // the attribute.
4109     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4110   } else {
4111     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4112                           Target.getTargetOpts().Features);
4113   }
4114 }
4115 
4116 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4117   if (!SanStats)
4118     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4119 
4120   return *SanStats;
4121 }
4122