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