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