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