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