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