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