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