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