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