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