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