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