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