xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 28a26c8d996aa82a80e8586720af789d3afa8739)
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 "CGDebugInfo.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenTBAA.h"
18 #include "CGCall.h"
19 #include "CGCUDARuntime.h"
20 #include "CGCXXABI.h"
21 #include "CGObjCRuntime.h"
22 #include "CGOpenCLRuntime.h"
23 #include "TargetInfo.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/CharUnits.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclCXX.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/Diagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "clang/Basic/ConvertUTF.h"
38 #include "llvm/CallingConv.h"
39 #include "llvm/Module.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/LLVMContext.h"
42 #include "llvm/ADT/APSInt.h"
43 #include "llvm/ADT/Triple.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ErrorHandling.h"
48 using namespace clang;
49 using namespace CodeGen;
50 
51 static const char AnnotationSection[] = "llvm.metadata";
52 
53 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
54   switch (CGM.getContext().getTargetInfo().getCXXABI()) {
55   case CXXABI_ARM: return *CreateARMCXXABI(CGM);
56   case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
57   case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
58   }
59 
60   llvm_unreachable("invalid C++ ABI kind");
61 }
62 
63 
64 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
65                              llvm::Module &M, const llvm::TargetData &TD,
66                              DiagnosticsEngine &diags)
67   : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
68     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
69     ABI(createCXXABI(*this)),
70     Types(*this),
71     TBAA(0),
72     VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
73     DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
74     RRData(0), CFConstantStringClassRef(0),
75     ConstantStringClassRef(0), NSConstantStringType(0),
76     VMContext(M.getContext()),
77     NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
78     BlockObjectAssign(0), BlockObjectDispose(0),
79     BlockDescriptorType(0), GenericBlockLiteralType(0) {
80 
81   // Initialize the type cache.
82   llvm::LLVMContext &LLVMContext = M.getContext();
83   VoidTy = llvm::Type::getVoidTy(LLVMContext);
84   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
85   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
86   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
87   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
88   FloatTy = llvm::Type::getFloatTy(LLVMContext);
89   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
90   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
91   PointerAlignInBytes =
92   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
93   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
94   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
95   Int8PtrTy = Int8Ty->getPointerTo(0);
96   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
97 
98   if (LangOpts.ObjC1)
99     createObjCRuntime();
100   if (LangOpts.OpenCL)
101     createOpenCLRuntime();
102   if (LangOpts.CUDA)
103     createCUDARuntime();
104 
105   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
106   if (LangOpts.ThreadSanitizer ||
107       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
108     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
109                            ABI.getMangleContext());
110 
111   // If debug info or coverage generation is enabled, create the CGDebugInfo
112   // object.
113   if (CodeGenOpts.DebugInfo != CodeGenOptions::NoDebugInfo ||
114       CodeGenOpts.EmitGcovArcs ||
115       CodeGenOpts.EmitGcovNotes)
116     DebugInfo = new CGDebugInfo(*this);
117 
118   Block.GlobalUniqueCount = 0;
119 
120   if (C.getLangOpts().ObjCAutoRefCount)
121     ARCData = new ARCEntrypoints();
122   RRData = new RREntrypoints();
123 }
124 
125 CodeGenModule::~CodeGenModule() {
126   delete ObjCRuntime;
127   delete OpenCLRuntime;
128   delete CUDARuntime;
129   delete TheTargetCodeGenInfo;
130   delete &ABI;
131   delete TBAA;
132   delete DebugInfo;
133   delete ARCData;
134   delete RRData;
135 }
136 
137 void CodeGenModule::createObjCRuntime() {
138   // This is just isGNUFamily(), but we want to force implementors of
139   // new ABIs to decide how best to do this.
140   switch (LangOpts.ObjCRuntime.getKind()) {
141   case ObjCRuntime::GNUstep:
142   case ObjCRuntime::GCC:
143   case ObjCRuntime::ObjFW:
144     ObjCRuntime = CreateGNUObjCRuntime(*this);
145     return;
146 
147   case ObjCRuntime::FragileMacOSX:
148   case ObjCRuntime::MacOSX:
149   case ObjCRuntime::iOS:
150     ObjCRuntime = CreateMacObjCRuntime(*this);
151     return;
152   }
153   llvm_unreachable("bad runtime kind");
154 }
155 
156 void CodeGenModule::createOpenCLRuntime() {
157   OpenCLRuntime = new CGOpenCLRuntime(*this);
158 }
159 
160 void CodeGenModule::createCUDARuntime() {
161   CUDARuntime = CreateNVCUDARuntime(*this);
162 }
163 
164 void CodeGenModule::Release() {
165   EmitDeferred();
166   EmitCXXGlobalInitFunc();
167   EmitCXXGlobalDtorFunc();
168   if (ObjCRuntime)
169     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
170       AddGlobalCtor(ObjCInitFunction);
171   EmitCtorList(GlobalCtors, "llvm.global_ctors");
172   EmitCtorList(GlobalDtors, "llvm.global_dtors");
173   EmitGlobalAnnotations();
174   EmitLLVMUsed();
175 
176   SimplifyPersonality();
177 
178   if (getCodeGenOpts().EmitDeclMetadata)
179     EmitDeclMetadata();
180 
181   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
182     EmitCoverageFile();
183 
184   if (DebugInfo)
185     DebugInfo->finalize();
186 }
187 
188 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
189   // Make sure that this type is translated.
190   Types.UpdateCompletedType(TD);
191 }
192 
193 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
194   if (!TBAA)
195     return 0;
196   return TBAA->getTBAAInfo(QTy);
197 }
198 
199 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
200   if (!TBAA)
201     return 0;
202   return TBAA->getTBAAInfoForVTablePtr();
203 }
204 
205 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
206                                         llvm::MDNode *TBAAInfo) {
207   Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
208 }
209 
210 bool CodeGenModule::isTargetDarwin() const {
211   return getContext().getTargetInfo().getTriple().isOSDarwin();
212 }
213 
214 void CodeGenModule::Error(SourceLocation loc, StringRef error) {
215   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
216   getDiags().Report(Context.getFullLoc(loc), diagID);
217 }
218 
219 /// ErrorUnsupported - Print out an error that codegen doesn't support the
220 /// specified stmt yet.
221 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
222                                      bool OmitOnError) {
223   if (OmitOnError && getDiags().hasErrorOccurred())
224     return;
225   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
226                                                "cannot compile this %0 yet");
227   std::string Msg = Type;
228   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
229     << Msg << S->getSourceRange();
230 }
231 
232 /// ErrorUnsupported - Print out an error that codegen doesn't support the
233 /// specified decl yet.
234 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
235                                      bool OmitOnError) {
236   if (OmitOnError && getDiags().hasErrorOccurred())
237     return;
238   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
239                                                "cannot compile this %0 yet");
240   std::string Msg = Type;
241   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
242 }
243 
244 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
245   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
246 }
247 
248 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
249                                         const NamedDecl *D) const {
250   // Internal definitions always have default visibility.
251   if (GV->hasLocalLinkage()) {
252     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
253     return;
254   }
255 
256   // Set visibility for definitions.
257   NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
258   if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
259     GV->setVisibility(GetLLVMVisibility(LV.visibility()));
260 }
261 
262 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
263   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
264       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
265       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
266       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
267       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
268 }
269 
270 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
271     CodeGenOptions::TLSModel M) {
272   switch (M) {
273   case CodeGenOptions::GeneralDynamicTLSModel:
274     return llvm::GlobalVariable::GeneralDynamicTLSModel;
275   case CodeGenOptions::LocalDynamicTLSModel:
276     return llvm::GlobalVariable::LocalDynamicTLSModel;
277   case CodeGenOptions::InitialExecTLSModel:
278     return llvm::GlobalVariable::InitialExecTLSModel;
279   case CodeGenOptions::LocalExecTLSModel:
280     return llvm::GlobalVariable::LocalExecTLSModel;
281   }
282   llvm_unreachable("Invalid TLS model!");
283 }
284 
285 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
286                                const VarDecl &D) const {
287   assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
288 
289   llvm::GlobalVariable::ThreadLocalMode TLM;
290   TLM = GetLLVMTLSModel(CodeGenOpts.DefaultTLSModel);
291 
292   // Override the TLS model if it is explicitly specified.
293   if (D.hasAttr<TLSModelAttr>()) {
294     const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
295     TLM = GetLLVMTLSModel(Attr->getModel());
296   }
297 
298   GV->setThreadLocalMode(TLM);
299 }
300 
301 /// Set the symbol visibility of type information (vtable and RTTI)
302 /// associated with the given type.
303 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
304                                       const CXXRecordDecl *RD,
305                                       TypeVisibilityKind TVK) const {
306   setGlobalVisibility(GV, RD);
307 
308   if (!CodeGenOpts.HiddenWeakVTables)
309     return;
310 
311   // We never want to drop the visibility for RTTI names.
312   if (TVK == TVK_ForRTTIName)
313     return;
314 
315   // We want to drop the visibility to hidden for weak type symbols.
316   // This isn't possible if there might be unresolved references
317   // elsewhere that rely on this symbol being visible.
318 
319   // This should be kept roughly in sync with setThunkVisibility
320   // in CGVTables.cpp.
321 
322   // Preconditions.
323   if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
324       GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
325     return;
326 
327   // Don't override an explicit visibility attribute.
328   if (RD->getExplicitVisibility())
329     return;
330 
331   switch (RD->getTemplateSpecializationKind()) {
332   // We have to disable the optimization if this is an EI definition
333   // because there might be EI declarations in other shared objects.
334   case TSK_ExplicitInstantiationDefinition:
335   case TSK_ExplicitInstantiationDeclaration:
336     return;
337 
338   // Every use of a non-template class's type information has to emit it.
339   case TSK_Undeclared:
340     break;
341 
342   // In theory, implicit instantiations can ignore the possibility of
343   // an explicit instantiation declaration because there necessarily
344   // must be an EI definition somewhere with default visibility.  In
345   // practice, it's possible to have an explicit instantiation for
346   // an arbitrary template class, and linkers aren't necessarily able
347   // to deal with mixed-visibility symbols.
348   case TSK_ExplicitSpecialization:
349   case TSK_ImplicitInstantiation:
350     if (!CodeGenOpts.HiddenWeakTemplateVTables)
351       return;
352     break;
353   }
354 
355   // If there's a key function, there may be translation units
356   // that don't have the key function's definition.  But ignore
357   // this if we're emitting RTTI under -fno-rtti.
358   if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
359     if (Context.getKeyFunction(RD))
360       return;
361   }
362 
363   // Otherwise, drop the visibility to hidden.
364   GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
365   GV->setUnnamedAddr(true);
366 }
367 
368 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
369   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
370 
371   StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
372   if (!Str.empty())
373     return Str;
374 
375   if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
376     IdentifierInfo *II = ND->getIdentifier();
377     assert(II && "Attempt to mangle unnamed decl.");
378 
379     Str = II->getName();
380     return Str;
381   }
382 
383   SmallString<256> Buffer;
384   llvm::raw_svector_ostream Out(Buffer);
385   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
386     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
387   else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
388     getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
389   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
390     getCXXABI().getMangleContext().mangleBlock(BD, Out,
391       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
392   else
393     getCXXABI().getMangleContext().mangleName(ND, Out);
394 
395   // Allocate space for the mangled name.
396   Out.flush();
397   size_t Length = Buffer.size();
398   char *Name = MangledNamesAllocator.Allocate<char>(Length);
399   std::copy(Buffer.begin(), Buffer.end(), Name);
400 
401   Str = StringRef(Name, Length);
402 
403   return Str;
404 }
405 
406 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
407                                         const BlockDecl *BD) {
408   MangleContext &MangleCtx = getCXXABI().getMangleContext();
409   const Decl *D = GD.getDecl();
410   llvm::raw_svector_ostream Out(Buffer.getBuffer());
411   if (D == 0)
412     MangleCtx.mangleGlobalBlock(BD,
413       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
414   else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
415     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
416   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
417     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
418   else
419     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
420 }
421 
422 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
423   return getModule().getNamedValue(Name);
424 }
425 
426 /// AddGlobalCtor - Add a function to the list that will be called before
427 /// main() runs.
428 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
429   // FIXME: Type coercion of void()* types.
430   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
431 }
432 
433 /// AddGlobalDtor - Add a function to the list that will be called
434 /// when the module is unloaded.
435 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
436   // FIXME: Type coercion of void()* types.
437   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
438 }
439 
440 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
441   // Ctor function type is void()*.
442   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
443   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
444 
445   // Get the type of a ctor entry, { i32, void ()* }.
446   llvm::StructType *CtorStructTy =
447     llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
448 
449   // Construct the constructor and destructor arrays.
450   SmallVector<llvm::Constant*, 8> Ctors;
451   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
452     llvm::Constant *S[] = {
453       llvm::ConstantInt::get(Int32Ty, I->second, false),
454       llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
455     };
456     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
457   }
458 
459   if (!Ctors.empty()) {
460     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
461     new llvm::GlobalVariable(TheModule, AT, false,
462                              llvm::GlobalValue::AppendingLinkage,
463                              llvm::ConstantArray::get(AT, Ctors),
464                              GlobalName);
465   }
466 }
467 
468 llvm::GlobalValue::LinkageTypes
469 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
470   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
471 
472   if (Linkage == GVA_Internal)
473     return llvm::Function::InternalLinkage;
474 
475   if (D->hasAttr<DLLExportAttr>())
476     return llvm::Function::DLLExportLinkage;
477 
478   if (D->hasAttr<WeakAttr>())
479     return llvm::Function::WeakAnyLinkage;
480 
481   // In C99 mode, 'inline' functions are guaranteed to have a strong
482   // definition somewhere else, so we can use available_externally linkage.
483   if (Linkage == GVA_C99Inline)
484     return llvm::Function::AvailableExternallyLinkage;
485 
486   // Note that Apple's kernel linker doesn't support symbol
487   // coalescing, so we need to avoid linkonce and weak linkages there.
488   // Normally, this means we just map to internal, but for explicit
489   // instantiations we'll map to external.
490 
491   // In C++, the compiler has to emit a definition in every translation unit
492   // that references the function.  We should use linkonce_odr because
493   // a) if all references in this translation unit are optimized away, we
494   // don't need to codegen it.  b) if the function persists, it needs to be
495   // merged with other definitions. c) C++ has the ODR, so we know the
496   // definition is dependable.
497   if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
498     return !Context.getLangOpts().AppleKext
499              ? llvm::Function::LinkOnceODRLinkage
500              : llvm::Function::InternalLinkage;
501 
502   // An explicit instantiation of a template has weak linkage, since
503   // explicit instantiations can occur in multiple translation units
504   // and must all be equivalent. However, we are not allowed to
505   // throw away these explicit instantiations.
506   if (Linkage == GVA_ExplicitTemplateInstantiation)
507     return !Context.getLangOpts().AppleKext
508              ? llvm::Function::WeakODRLinkage
509              : llvm::Function::ExternalLinkage;
510 
511   // Otherwise, we have strong external linkage.
512   assert(Linkage == GVA_StrongExternal);
513   return llvm::Function::ExternalLinkage;
514 }
515 
516 
517 /// SetFunctionDefinitionAttributes - Set attributes for a global.
518 ///
519 /// FIXME: This is currently only done for aliases and functions, but not for
520 /// variables (these details are set in EmitGlobalVarDefinition for variables).
521 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
522                                                     llvm::GlobalValue *GV) {
523   SetCommonAttributes(D, GV);
524 }
525 
526 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
527                                               const CGFunctionInfo &Info,
528                                               llvm::Function *F) {
529   unsigned CallingConv;
530   AttributeListType AttributeList;
531   ConstructAttributeList(Info, D, AttributeList, CallingConv);
532   F->setAttributes(llvm::AttrListPtr::get(AttributeList));
533   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
534 }
535 
536 /// Determines whether the language options require us to model
537 /// unwind exceptions.  We treat -fexceptions as mandating this
538 /// except under the fragile ObjC ABI with only ObjC exceptions
539 /// enabled.  This means, for example, that C with -fexceptions
540 /// enables this.
541 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
542   // If exceptions are completely disabled, obviously this is false.
543   if (!LangOpts.Exceptions) return false;
544 
545   // If C++ exceptions are enabled, this is true.
546   if (LangOpts.CXXExceptions) return true;
547 
548   // If ObjC exceptions are enabled, this depends on the ABI.
549   if (LangOpts.ObjCExceptions) {
550     return LangOpts.ObjCRuntime.hasUnwindExceptions();
551   }
552 
553   return true;
554 }
555 
556 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
557                                                            llvm::Function *F) {
558   if (CodeGenOpts.UnwindTables)
559     F->setHasUWTable();
560 
561   if (!hasUnwindExceptions(LangOpts))
562     F->addFnAttr(llvm::Attribute::NoUnwind);
563 
564   if (D->hasAttr<NakedAttr>()) {
565     // Naked implies noinline: we should not be inlining such functions.
566     F->addFnAttr(llvm::Attribute::Naked);
567     F->addFnAttr(llvm::Attribute::NoInline);
568   }
569 
570   if (D->hasAttr<NoInlineAttr>())
571     F->addFnAttr(llvm::Attribute::NoInline);
572 
573   // (noinline wins over always_inline, and we can't specify both in IR)
574   if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
575       !F->hasFnAttr(llvm::Attribute::NoInline))
576     F->addFnAttr(llvm::Attribute::AlwaysInline);
577 
578   // FIXME: Communicate hot and cold attributes to LLVM more directly.
579   if (D->hasAttr<ColdAttr>())
580     F->addFnAttr(llvm::Attribute::OptimizeForSize);
581 
582   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
583     F->setUnnamedAddr(true);
584 
585   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
586     F->addFnAttr(llvm::Attribute::StackProtect);
587   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
588     F->addFnAttr(llvm::Attribute::StackProtectReq);
589 
590   if (LangOpts.AddressSanitizer) {
591     // When AddressSanitizer is enabled, set AddressSafety attribute
592     // unless __attribute__((no_address_safety_analysis)) is used.
593     if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
594       F->addFnAttr(llvm::Attribute::AddressSafety);
595   }
596 
597   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
598   if (alignment)
599     F->setAlignment(alignment);
600 
601   // C++ ABI requires 2-byte alignment for member functions.
602   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
603     F->setAlignment(2);
604 }
605 
606 void CodeGenModule::SetCommonAttributes(const Decl *D,
607                                         llvm::GlobalValue *GV) {
608   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
609     setGlobalVisibility(GV, ND);
610   else
611     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
612 
613   if (D->hasAttr<UsedAttr>())
614     AddUsedGlobal(GV);
615 
616   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
617     GV->setSection(SA->getName());
618 
619   getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
620 }
621 
622 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
623                                                   llvm::Function *F,
624                                                   const CGFunctionInfo &FI) {
625   SetLLVMFunctionAttributes(D, FI, F);
626   SetLLVMFunctionAttributesForDefinition(D, F);
627 
628   F->setLinkage(llvm::Function::InternalLinkage);
629 
630   SetCommonAttributes(D, F);
631 }
632 
633 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
634                                           llvm::Function *F,
635                                           bool IsIncompleteFunction) {
636   if (unsigned IID = F->getIntrinsicID()) {
637     // If this is an intrinsic function, set the function's attributes
638     // to the intrinsic's attributes.
639     F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
640     return;
641   }
642 
643   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
644 
645   if (!IsIncompleteFunction)
646     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
647 
648   // Only a few attributes are set on declarations; these may later be
649   // overridden by a definition.
650 
651   if (FD->hasAttr<DLLImportAttr>()) {
652     F->setLinkage(llvm::Function::DLLImportLinkage);
653   } else if (FD->hasAttr<WeakAttr>() ||
654              FD->isWeakImported()) {
655     // "extern_weak" is overloaded in LLVM; we probably should have
656     // separate linkage types for this.
657     F->setLinkage(llvm::Function::ExternalWeakLinkage);
658   } else {
659     F->setLinkage(llvm::Function::ExternalLinkage);
660 
661     NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
662     if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
663       F->setVisibility(GetLLVMVisibility(LV.visibility()));
664     }
665   }
666 
667   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
668     F->setSection(SA->getName());
669 }
670 
671 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
672   assert(!GV->isDeclaration() &&
673          "Only globals with definition can force usage.");
674   LLVMUsed.push_back(GV);
675 }
676 
677 void CodeGenModule::EmitLLVMUsed() {
678   // Don't create llvm.used if there is no need.
679   if (LLVMUsed.empty())
680     return;
681 
682   // Convert LLVMUsed to what ConstantArray needs.
683   SmallVector<llvm::Constant*, 8> UsedArray;
684   UsedArray.resize(LLVMUsed.size());
685   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
686     UsedArray[i] =
687      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
688                                     Int8PtrTy);
689   }
690 
691   if (UsedArray.empty())
692     return;
693   llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
694 
695   llvm::GlobalVariable *GV =
696     new llvm::GlobalVariable(getModule(), ATy, false,
697                              llvm::GlobalValue::AppendingLinkage,
698                              llvm::ConstantArray::get(ATy, UsedArray),
699                              "llvm.used");
700 
701   GV->setSection("llvm.metadata");
702 }
703 
704 void CodeGenModule::EmitDeferred() {
705   // Emit code for any potentially referenced deferred decls.  Since a
706   // previously unused static decl may become used during the generation of code
707   // for a static function, iterate until no changes are made.
708 
709   while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
710     if (!DeferredVTables.empty()) {
711       const CXXRecordDecl *RD = DeferredVTables.back();
712       DeferredVTables.pop_back();
713       getCXXABI().EmitVTables(RD);
714       continue;
715     }
716 
717     GlobalDecl D = DeferredDeclsToEmit.back();
718     DeferredDeclsToEmit.pop_back();
719 
720     // Check to see if we've already emitted this.  This is necessary
721     // for a couple of reasons: first, decls can end up in the
722     // deferred-decls queue multiple times, and second, decls can end
723     // up with definitions in unusual ways (e.g. by an extern inline
724     // function acquiring a strong function redefinition).  Just
725     // ignore these cases.
726     //
727     // TODO: That said, looking this up multiple times is very wasteful.
728     StringRef Name = getMangledName(D);
729     llvm::GlobalValue *CGRef = GetGlobalValue(Name);
730     assert(CGRef && "Deferred decl wasn't referenced?");
731 
732     if (!CGRef->isDeclaration())
733       continue;
734 
735     // GlobalAlias::isDeclaration() defers to the aliasee, but for our
736     // purposes an alias counts as a definition.
737     if (isa<llvm::GlobalAlias>(CGRef))
738       continue;
739 
740     // Otherwise, emit the definition and move on to the next one.
741     EmitGlobalDefinition(D);
742   }
743 }
744 
745 void CodeGenModule::EmitGlobalAnnotations() {
746   if (Annotations.empty())
747     return;
748 
749   // Create a new global variable for the ConstantStruct in the Module.
750   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
751     Annotations[0]->getType(), Annotations.size()), Annotations);
752   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
753     Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
754     "llvm.global.annotations");
755   gv->setSection(AnnotationSection);
756 }
757 
758 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
759   llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
760   if (i != AnnotationStrings.end())
761     return i->second;
762 
763   // Not found yet, create a new global.
764   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
765   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
766     true, llvm::GlobalValue::PrivateLinkage, s, ".str");
767   gv->setSection(AnnotationSection);
768   gv->setUnnamedAddr(true);
769   AnnotationStrings[Str] = gv;
770   return gv;
771 }
772 
773 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
774   SourceManager &SM = getContext().getSourceManager();
775   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
776   if (PLoc.isValid())
777     return EmitAnnotationString(PLoc.getFilename());
778   return EmitAnnotationString(SM.getBufferName(Loc));
779 }
780 
781 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
782   SourceManager &SM = getContext().getSourceManager();
783   PresumedLoc PLoc = SM.getPresumedLoc(L);
784   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
785     SM.getExpansionLineNumber(L);
786   return llvm::ConstantInt::get(Int32Ty, LineNo);
787 }
788 
789 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
790                                                 const AnnotateAttr *AA,
791                                                 SourceLocation L) {
792   // Get the globals for file name, annotation, and the line number.
793   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
794                  *UnitGV = EmitAnnotationUnit(L),
795                  *LineNoCst = EmitAnnotationLineNo(L);
796 
797   // Create the ConstantStruct for the global annotation.
798   llvm::Constant *Fields[4] = {
799     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
800     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
801     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
802     LineNoCst
803   };
804   return llvm::ConstantStruct::getAnon(Fields);
805 }
806 
807 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
808                                          llvm::GlobalValue *GV) {
809   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
810   // Get the struct elements for these annotations.
811   for (specific_attr_iterator<AnnotateAttr>
812        ai = D->specific_attr_begin<AnnotateAttr>(),
813        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
814     Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
815 }
816 
817 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
818   // Never defer when EmitAllDecls is specified.
819   if (LangOpts.EmitAllDecls)
820     return false;
821 
822   return !getContext().DeclMustBeEmitted(Global);
823 }
824 
825 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
826   const AliasAttr *AA = VD->getAttr<AliasAttr>();
827   assert(AA && "No alias?");
828 
829   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
830 
831   // See if there is already something with the target's name in the module.
832   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
833 
834   llvm::Constant *Aliasee;
835   if (isa<llvm::FunctionType>(DeclTy))
836     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
837                                       /*ForVTable=*/false);
838   else
839     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
840                                     llvm::PointerType::getUnqual(DeclTy), 0);
841   if (!Entry) {
842     llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
843     F->setLinkage(llvm::Function::ExternalWeakLinkage);
844     WeakRefReferences.insert(F);
845   }
846 
847   return Aliasee;
848 }
849 
850 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
851   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
852 
853   // Weak references don't produce any output by themselves.
854   if (Global->hasAttr<WeakRefAttr>())
855     return;
856 
857   // If this is an alias definition (which otherwise looks like a declaration)
858   // emit it now.
859   if (Global->hasAttr<AliasAttr>())
860     return EmitAliasDefinition(GD);
861 
862   // If this is CUDA, be selective about which declarations we emit.
863   if (LangOpts.CUDA) {
864     if (CodeGenOpts.CUDAIsDevice) {
865       if (!Global->hasAttr<CUDADeviceAttr>() &&
866           !Global->hasAttr<CUDAGlobalAttr>() &&
867           !Global->hasAttr<CUDAConstantAttr>() &&
868           !Global->hasAttr<CUDASharedAttr>())
869         return;
870     } else {
871       if (!Global->hasAttr<CUDAHostAttr>() && (
872             Global->hasAttr<CUDADeviceAttr>() ||
873             Global->hasAttr<CUDAConstantAttr>() ||
874             Global->hasAttr<CUDASharedAttr>()))
875         return;
876     }
877   }
878 
879   // Ignore declarations, they will be emitted on their first use.
880   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
881     // Forward declarations are emitted lazily on first use.
882     if (!FD->doesThisDeclarationHaveABody()) {
883       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
884         return;
885 
886       const FunctionDecl *InlineDefinition = 0;
887       FD->getBody(InlineDefinition);
888 
889       StringRef MangledName = getMangledName(GD);
890       DeferredDecls.erase(MangledName);
891       EmitGlobalDefinition(InlineDefinition);
892       return;
893     }
894   } else {
895     const VarDecl *VD = cast<VarDecl>(Global);
896     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
897 
898     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
899       return;
900   }
901 
902   // Defer code generation when possible if this is a static definition, inline
903   // function etc.  These we only want to emit if they are used.
904   if (!MayDeferGeneration(Global)) {
905     // Emit the definition if it can't be deferred.
906     EmitGlobalDefinition(GD);
907     return;
908   }
909 
910   // If we're deferring emission of a C++ variable with an
911   // initializer, remember the order in which it appeared in the file.
912   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
913       cast<VarDecl>(Global)->hasInit()) {
914     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
915     CXXGlobalInits.push_back(0);
916   }
917 
918   // If the value has already been used, add it directly to the
919   // DeferredDeclsToEmit list.
920   StringRef MangledName = getMangledName(GD);
921   if (GetGlobalValue(MangledName))
922     DeferredDeclsToEmit.push_back(GD);
923   else {
924     // Otherwise, remember that we saw a deferred decl with this name.  The
925     // first use of the mangled name will cause it to move into
926     // DeferredDeclsToEmit.
927     DeferredDecls[MangledName] = GD;
928   }
929 }
930 
931 namespace {
932   struct FunctionIsDirectlyRecursive :
933     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
934     const StringRef Name;
935     const Builtin::Context &BI;
936     bool Result;
937     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
938       Name(N), BI(C), Result(false) {
939     }
940     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
941 
942     bool TraverseCallExpr(CallExpr *E) {
943       const FunctionDecl *FD = E->getDirectCallee();
944       if (!FD)
945         return true;
946       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
947       if (Attr && Name == Attr->getLabel()) {
948         Result = true;
949         return false;
950       }
951       unsigned BuiltinID = FD->getBuiltinID();
952       if (!BuiltinID)
953         return true;
954       StringRef BuiltinName = BI.GetName(BuiltinID);
955       if (BuiltinName.startswith("__builtin_") &&
956           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
957         Result = true;
958         return false;
959       }
960       return true;
961     }
962   };
963 }
964 
965 // isTriviallyRecursive - Check if this function calls another
966 // decl that, because of the asm attribute or the other decl being a builtin,
967 // ends up pointing to itself.
968 bool
969 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
970   StringRef Name;
971   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
972     // asm labels are a special kind of mangling we have to support.
973     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
974     if (!Attr)
975       return false;
976     Name = Attr->getLabel();
977   } else {
978     Name = FD->getName();
979   }
980 
981   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
982   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
983   return Walker.Result;
984 }
985 
986 bool
987 CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
988   if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
989     return true;
990   if (CodeGenOpts.OptimizationLevel == 0 &&
991       !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
992     return false;
993   // PR9614. Avoid cases where the source code is lying to us. An available
994   // externally function should have an equivalent function somewhere else,
995   // but a function that calls itself is clearly not equivalent to the real
996   // implementation.
997   // This happens in glibc's btowc and in some configure checks.
998   return !isTriviallyRecursive(F);
999 }
1000 
1001 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
1002   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1003 
1004   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1005                                  Context.getSourceManager(),
1006                                  "Generating code for declaration");
1007 
1008   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1009     // At -O0, don't generate IR for functions with available_externally
1010     // linkage.
1011     if (!shouldEmitFunction(Function))
1012       return;
1013 
1014     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1015       // Make sure to emit the definition(s) before we emit the thunks.
1016       // This is necessary for the generation of certain thunks.
1017       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1018         EmitCXXConstructor(CD, GD.getCtorType());
1019       else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1020         EmitCXXDestructor(DD, GD.getDtorType());
1021       else
1022         EmitGlobalFunctionDefinition(GD);
1023 
1024       if (Method->isVirtual())
1025         getVTables().EmitThunks(GD);
1026 
1027       return;
1028     }
1029 
1030     return EmitGlobalFunctionDefinition(GD);
1031   }
1032 
1033   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1034     return EmitGlobalVarDefinition(VD);
1035 
1036   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1037 }
1038 
1039 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1040 /// module, create and return an llvm Function with the specified type. If there
1041 /// is something in the module with the specified name, return it potentially
1042 /// bitcasted to the right type.
1043 ///
1044 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1045 /// to set the attributes on the function when it is first created.
1046 llvm::Constant *
1047 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1048                                        llvm::Type *Ty,
1049                                        GlobalDecl D, bool ForVTable,
1050                                        llvm::Attributes ExtraAttrs) {
1051   // Lookup the entry, lazily creating it if necessary.
1052   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1053   if (Entry) {
1054     if (WeakRefReferences.count(Entry)) {
1055       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1056       if (FD && !FD->hasAttr<WeakAttr>())
1057         Entry->setLinkage(llvm::Function::ExternalLinkage);
1058 
1059       WeakRefReferences.erase(Entry);
1060     }
1061 
1062     if (Entry->getType()->getElementType() == Ty)
1063       return Entry;
1064 
1065     // Make sure the result is of the correct type.
1066     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1067   }
1068 
1069   // This function doesn't have a complete type (for example, the return
1070   // type is an incomplete struct). Use a fake type instead, and make
1071   // sure not to try to set attributes.
1072   bool IsIncompleteFunction = false;
1073 
1074   llvm::FunctionType *FTy;
1075   if (isa<llvm::FunctionType>(Ty)) {
1076     FTy = cast<llvm::FunctionType>(Ty);
1077   } else {
1078     FTy = llvm::FunctionType::get(VoidTy, false);
1079     IsIncompleteFunction = true;
1080   }
1081 
1082   llvm::Function *F = llvm::Function::Create(FTy,
1083                                              llvm::Function::ExternalLinkage,
1084                                              MangledName, &getModule());
1085   assert(F->getName() == MangledName && "name was uniqued!");
1086   if (D.getDecl())
1087     SetFunctionAttributes(D, F, IsIncompleteFunction);
1088   if (ExtraAttrs != llvm::Attribute::None)
1089     F->addFnAttr(ExtraAttrs);
1090 
1091   // This is the first use or definition of a mangled name.  If there is a
1092   // deferred decl with this name, remember that we need to emit it at the end
1093   // of the file.
1094   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1095   if (DDI != DeferredDecls.end()) {
1096     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1097     // list, and remove it from DeferredDecls (since we don't need it anymore).
1098     DeferredDeclsToEmit.push_back(DDI->second);
1099     DeferredDecls.erase(DDI);
1100 
1101   // Otherwise, there are cases we have to worry about where we're
1102   // using a declaration for which we must emit a definition but where
1103   // we might not find a top-level definition:
1104   //   - member functions defined inline in their classes
1105   //   - friend functions defined inline in some class
1106   //   - special member functions with implicit definitions
1107   // If we ever change our AST traversal to walk into class methods,
1108   // this will be unnecessary.
1109   //
1110   // We also don't emit a definition for a function if it's going to be an entry
1111   // in a vtable, unless it's already marked as used.
1112   } else if (getLangOpts().CPlusPlus && D.getDecl()) {
1113     // Look for a declaration that's lexically in a record.
1114     const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1115     FD = FD->getMostRecentDecl();
1116     do {
1117       if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1118         if (FD->isImplicit() && !ForVTable) {
1119           assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1120           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1121           break;
1122         } else if (FD->doesThisDeclarationHaveABody()) {
1123           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1124           break;
1125         }
1126       }
1127       FD = FD->getPreviousDecl();
1128     } while (FD);
1129   }
1130 
1131   // Make sure the result is of the requested type.
1132   if (!IsIncompleteFunction) {
1133     assert(F->getType()->getElementType() == Ty);
1134     return F;
1135   }
1136 
1137   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1138   return llvm::ConstantExpr::getBitCast(F, PTy);
1139 }
1140 
1141 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1142 /// non-null, then this function will use the specified type if it has to
1143 /// create it (this occurs when we see a definition of the function).
1144 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1145                                                  llvm::Type *Ty,
1146                                                  bool ForVTable) {
1147   // If there was no specific requested type, just convert it now.
1148   if (!Ty)
1149     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1150 
1151   StringRef MangledName = getMangledName(GD);
1152   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1153 }
1154 
1155 /// CreateRuntimeFunction - Create a new runtime function with the specified
1156 /// type and name.
1157 llvm::Constant *
1158 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1159                                      StringRef Name,
1160                                      llvm::Attributes ExtraAttrs) {
1161   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1162                                  ExtraAttrs);
1163 }
1164 
1165 /// isTypeConstant - Determine whether an object of this type can be emitted
1166 /// as a constant.
1167 ///
1168 /// If ExcludeCtor is true, the duration when the object's constructor runs
1169 /// will not be considered. The caller will need to verify that the object is
1170 /// not written to during its construction.
1171 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1172   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1173     return false;
1174 
1175   if (Context.getLangOpts().CPlusPlus) {
1176     if (const CXXRecordDecl *Record
1177           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1178       return ExcludeCtor && !Record->hasMutableFields() &&
1179              Record->hasTrivialDestructor();
1180   }
1181 
1182   return true;
1183 }
1184 
1185 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1186 /// create and return an llvm GlobalVariable with the specified type.  If there
1187 /// is something in the module with the specified name, return it potentially
1188 /// bitcasted to the right type.
1189 ///
1190 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1191 /// to set the attributes on the global when it is first created.
1192 llvm::Constant *
1193 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1194                                      llvm::PointerType *Ty,
1195                                      const VarDecl *D,
1196                                      bool UnnamedAddr) {
1197   // Lookup the entry, lazily creating it if necessary.
1198   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1199   if (Entry) {
1200     if (WeakRefReferences.count(Entry)) {
1201       if (D && !D->hasAttr<WeakAttr>())
1202         Entry->setLinkage(llvm::Function::ExternalLinkage);
1203 
1204       WeakRefReferences.erase(Entry);
1205     }
1206 
1207     if (UnnamedAddr)
1208       Entry->setUnnamedAddr(true);
1209 
1210     if (Entry->getType() == Ty)
1211       return Entry;
1212 
1213     // Make sure the result is of the correct type.
1214     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1215   }
1216 
1217   // This is the first use or definition of a mangled name.  If there is a
1218   // deferred decl with this name, remember that we need to emit it at the end
1219   // of the file.
1220   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1221   if (DDI != DeferredDecls.end()) {
1222     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1223     // list, and remove it from DeferredDecls (since we don't need it anymore).
1224     DeferredDeclsToEmit.push_back(DDI->second);
1225     DeferredDecls.erase(DDI);
1226   }
1227 
1228   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1229   llvm::GlobalVariable *GV =
1230     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1231                              llvm::GlobalValue::ExternalLinkage,
1232                              0, MangledName, 0,
1233                              llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1234 
1235   // Handle things which are present even on external declarations.
1236   if (D) {
1237     // FIXME: This code is overly simple and should be merged with other global
1238     // handling.
1239     GV->setConstant(isTypeConstant(D->getType(), false));
1240 
1241     // Set linkage and visibility in case we never see a definition.
1242     NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1243     if (LV.linkage() != ExternalLinkage) {
1244       // Don't set internal linkage on declarations.
1245     } else {
1246       if (D->hasAttr<DLLImportAttr>())
1247         GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1248       else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1249         GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1250 
1251       // Set visibility on a declaration only if it's explicit.
1252       if (LV.visibilityExplicit())
1253         GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1254     }
1255 
1256     if (D->isThreadSpecified())
1257       setTLSMode(GV, *D);
1258   }
1259 
1260   if (AddrSpace != Ty->getAddressSpace())
1261     return llvm::ConstantExpr::getBitCast(GV, Ty);
1262   else
1263     return GV;
1264 }
1265 
1266 
1267 llvm::GlobalVariable *
1268 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1269                                       llvm::Type *Ty,
1270                                       llvm::GlobalValue::LinkageTypes Linkage) {
1271   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1272   llvm::GlobalVariable *OldGV = 0;
1273 
1274 
1275   if (GV) {
1276     // Check if the variable has the right type.
1277     if (GV->getType()->getElementType() == Ty)
1278       return GV;
1279 
1280     // Because C++ name mangling, the only way we can end up with an already
1281     // existing global with the same name is if it has been declared extern "C".
1282       assert(GV->isDeclaration() && "Declaration has wrong type!");
1283     OldGV = GV;
1284   }
1285 
1286   // Create a new variable.
1287   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1288                                 Linkage, 0, Name);
1289 
1290   if (OldGV) {
1291     // Replace occurrences of the old variable if needed.
1292     GV->takeName(OldGV);
1293 
1294     if (!OldGV->use_empty()) {
1295       llvm::Constant *NewPtrForOldDecl =
1296       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1297       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1298     }
1299 
1300     OldGV->eraseFromParent();
1301   }
1302 
1303   return GV;
1304 }
1305 
1306 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1307 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1308 /// then it will be created with the specified type instead of whatever the
1309 /// normal requested type would be.
1310 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1311                                                   llvm::Type *Ty) {
1312   assert(D->hasGlobalStorage() && "Not a global variable");
1313   QualType ASTTy = D->getType();
1314   if (Ty == 0)
1315     Ty = getTypes().ConvertTypeForMem(ASTTy);
1316 
1317   llvm::PointerType *PTy =
1318     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1319 
1320   StringRef MangledName = getMangledName(D);
1321   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1322 }
1323 
1324 /// CreateRuntimeVariable - Create a new runtime global variable with the
1325 /// specified type and name.
1326 llvm::Constant *
1327 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1328                                      StringRef Name) {
1329   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1330                                true);
1331 }
1332 
1333 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1334   assert(!D->getInit() && "Cannot emit definite definitions here!");
1335 
1336   if (MayDeferGeneration(D)) {
1337     // If we have not seen a reference to this variable yet, place it
1338     // into the deferred declarations table to be emitted if needed
1339     // later.
1340     StringRef MangledName = getMangledName(D);
1341     if (!GetGlobalValue(MangledName)) {
1342       DeferredDecls[MangledName] = D;
1343       return;
1344     }
1345   }
1346 
1347   // The tentative definition is the only definition.
1348   EmitGlobalVarDefinition(D);
1349 }
1350 
1351 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1352   if (DefinitionRequired)
1353     getCXXABI().EmitVTables(Class);
1354 }
1355 
1356 llvm::GlobalVariable::LinkageTypes
1357 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1358   if (RD->getLinkage() != ExternalLinkage)
1359     return llvm::GlobalVariable::InternalLinkage;
1360 
1361   if (const CXXMethodDecl *KeyFunction
1362                                     = RD->getASTContext().getKeyFunction(RD)) {
1363     // If this class has a key function, use that to determine the linkage of
1364     // the vtable.
1365     const FunctionDecl *Def = 0;
1366     if (KeyFunction->hasBody(Def))
1367       KeyFunction = cast<CXXMethodDecl>(Def);
1368 
1369     switch (KeyFunction->getTemplateSpecializationKind()) {
1370       case TSK_Undeclared:
1371       case TSK_ExplicitSpecialization:
1372         // When compiling with optimizations turned on, we emit all vtables,
1373         // even if the key function is not defined in the current translation
1374         // unit. If this is the case, use available_externally linkage.
1375         if (!Def && CodeGenOpts.OptimizationLevel)
1376           return llvm::GlobalVariable::AvailableExternallyLinkage;
1377 
1378         if (KeyFunction->isInlined())
1379           return !Context.getLangOpts().AppleKext ?
1380                    llvm::GlobalVariable::LinkOnceODRLinkage :
1381                    llvm::Function::InternalLinkage;
1382 
1383         return llvm::GlobalVariable::ExternalLinkage;
1384 
1385       case TSK_ImplicitInstantiation:
1386         return !Context.getLangOpts().AppleKext ?
1387                  llvm::GlobalVariable::LinkOnceODRLinkage :
1388                  llvm::Function::InternalLinkage;
1389 
1390       case TSK_ExplicitInstantiationDefinition:
1391         return !Context.getLangOpts().AppleKext ?
1392                  llvm::GlobalVariable::WeakODRLinkage :
1393                  llvm::Function::InternalLinkage;
1394 
1395       case TSK_ExplicitInstantiationDeclaration:
1396         // FIXME: Use available_externally linkage. However, this currently
1397         // breaks LLVM's build due to undefined symbols.
1398         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1399         return !Context.getLangOpts().AppleKext ?
1400                  llvm::GlobalVariable::LinkOnceODRLinkage :
1401                  llvm::Function::InternalLinkage;
1402     }
1403   }
1404 
1405   if (Context.getLangOpts().AppleKext)
1406     return llvm::Function::InternalLinkage;
1407 
1408   switch (RD->getTemplateSpecializationKind()) {
1409   case TSK_Undeclared:
1410   case TSK_ExplicitSpecialization:
1411   case TSK_ImplicitInstantiation:
1412     // FIXME: Use available_externally linkage. However, this currently
1413     // breaks LLVM's build due to undefined symbols.
1414     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1415   case TSK_ExplicitInstantiationDeclaration:
1416     return llvm::GlobalVariable::LinkOnceODRLinkage;
1417 
1418   case TSK_ExplicitInstantiationDefinition:
1419       return llvm::GlobalVariable::WeakODRLinkage;
1420   }
1421 
1422   llvm_unreachable("Invalid TemplateSpecializationKind!");
1423 }
1424 
1425 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1426     return Context.toCharUnitsFromBits(
1427       TheTargetData.getTypeStoreSizeInBits(Ty));
1428 }
1429 
1430 llvm::Constant *
1431 CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1432                                                        const Expr *rawInit) {
1433   ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1434   if (const ExprWithCleanups *withCleanups =
1435           dyn_cast<ExprWithCleanups>(rawInit)) {
1436     cleanups = withCleanups->getObjects();
1437     rawInit = withCleanups->getSubExpr();
1438   }
1439 
1440   const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1441   if (!init || !init->initializesStdInitializerList() ||
1442       init->getNumInits() == 0)
1443     return 0;
1444 
1445   ASTContext &ctx = getContext();
1446   unsigned numInits = init->getNumInits();
1447   // FIXME: This check is here because we would otherwise silently miscompile
1448   // nested global std::initializer_lists. Better would be to have a real
1449   // implementation.
1450   for (unsigned i = 0; i < numInits; ++i) {
1451     const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1452     if (inner && inner->initializesStdInitializerList()) {
1453       ErrorUnsupported(inner, "nested global std::initializer_list");
1454       return 0;
1455     }
1456   }
1457 
1458   // Synthesize a fake VarDecl for the array and initialize that.
1459   QualType elementType = init->getInit(0)->getType();
1460   llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1461   QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1462                                                 ArrayType::Normal, 0);
1463 
1464   IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1465   TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1466                                               arrayType, D->getLocation());
1467   VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1468                                                           D->getDeclContext()),
1469                                           D->getLocStart(), D->getLocation(),
1470                                           name, arrayType, sourceInfo,
1471                                           SC_Static, SC_Static);
1472 
1473   // Now clone the InitListExpr to initialize the array instead.
1474   // Incredible hack: we want to use the existing InitListExpr here, so we need
1475   // to tell it that it no longer initializes a std::initializer_list.
1476   Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(),
1477                                     const_cast<InitListExpr*>(init)->getInits(),
1478                                                    init->getNumInits(),
1479                                                    init->getRBraceLoc());
1480   arrayInit->setType(arrayType);
1481 
1482   if (!cleanups.empty())
1483     arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1484 
1485   backingArray->setInit(arrayInit);
1486 
1487   // Emit the definition of the array.
1488   EmitGlobalVarDefinition(backingArray);
1489 
1490   // Inspect the initializer list to validate it and determine its type.
1491   // FIXME: doing this every time is probably inefficient; caching would be nice
1492   RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1493   RecordDecl::field_iterator field = record->field_begin();
1494   if (field == record->field_end()) {
1495     ErrorUnsupported(D, "weird std::initializer_list");
1496     return 0;
1497   }
1498   QualType elementPtr = ctx.getPointerType(elementType.withConst());
1499   // Start pointer.
1500   if (!ctx.hasSameType(field->getType(), elementPtr)) {
1501     ErrorUnsupported(D, "weird std::initializer_list");
1502     return 0;
1503   }
1504   ++field;
1505   if (field == record->field_end()) {
1506     ErrorUnsupported(D, "weird std::initializer_list");
1507     return 0;
1508   }
1509   bool isStartEnd = false;
1510   if (ctx.hasSameType(field->getType(), elementPtr)) {
1511     // End pointer.
1512     isStartEnd = true;
1513   } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1514     ErrorUnsupported(D, "weird std::initializer_list");
1515     return 0;
1516   }
1517 
1518   // Now build an APValue representing the std::initializer_list.
1519   APValue initListValue(APValue::UninitStruct(), 0, 2);
1520   APValue &startField = initListValue.getStructField(0);
1521   APValue::LValuePathEntry startOffsetPathEntry;
1522   startOffsetPathEntry.ArrayIndex = 0;
1523   startField = APValue(APValue::LValueBase(backingArray),
1524                        CharUnits::fromQuantity(0),
1525                        llvm::makeArrayRef(startOffsetPathEntry),
1526                        /*IsOnePastTheEnd=*/false, 0);
1527 
1528   if (isStartEnd) {
1529     APValue &endField = initListValue.getStructField(1);
1530     APValue::LValuePathEntry endOffsetPathEntry;
1531     endOffsetPathEntry.ArrayIndex = numInits;
1532     endField = APValue(APValue::LValueBase(backingArray),
1533                        ctx.getTypeSizeInChars(elementType) * numInits,
1534                        llvm::makeArrayRef(endOffsetPathEntry),
1535                        /*IsOnePastTheEnd=*/true, 0);
1536   } else {
1537     APValue &sizeField = initListValue.getStructField(1);
1538     sizeField = APValue(llvm::APSInt(numElements));
1539   }
1540 
1541   // Emit the constant for the initializer_list.
1542   llvm::Constant *llvmInit =
1543       EmitConstantValueForMemory(initListValue, D->getType());
1544   assert(llvmInit && "failed to initialize as constant");
1545   return llvmInit;
1546 }
1547 
1548 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1549                                                  unsigned AddrSpace) {
1550   if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1551     if (D->hasAttr<CUDAConstantAttr>())
1552       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1553     else if (D->hasAttr<CUDASharedAttr>())
1554       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1555     else
1556       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1557   }
1558 
1559   return AddrSpace;
1560 }
1561 
1562 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1563   llvm::Constant *Init = 0;
1564   QualType ASTTy = D->getType();
1565   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1566   bool NeedsGlobalCtor = false;
1567   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1568 
1569   const VarDecl *InitDecl;
1570   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1571 
1572   if (!InitExpr) {
1573     // This is a tentative definition; tentative definitions are
1574     // implicitly initialized with { 0 }.
1575     //
1576     // Note that tentative definitions are only emitted at the end of
1577     // a translation unit, so they should never have incomplete
1578     // type. In addition, EmitTentativeDefinition makes sure that we
1579     // never attempt to emit a tentative definition if a real one
1580     // exists. A use may still exists, however, so we still may need
1581     // to do a RAUW.
1582     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1583     Init = EmitNullConstant(D->getType());
1584   } else {
1585     // If this is a std::initializer_list, emit the special initializer.
1586     Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1587     // An empty init list will perform zero-initialization, which happens
1588     // to be exactly what we want.
1589     // FIXME: It does so in a global constructor, which is *not* what we
1590     // want.
1591 
1592     if (!Init) {
1593       initializedGlobalDecl = GlobalDecl(D);
1594       Init = EmitConstantInit(*InitDecl);
1595     }
1596     if (!Init) {
1597       QualType T = InitExpr->getType();
1598       if (D->getType()->isReferenceType())
1599         T = D->getType();
1600 
1601       if (getLangOpts().CPlusPlus) {
1602         Init = EmitNullConstant(T);
1603         NeedsGlobalCtor = true;
1604       } else {
1605         ErrorUnsupported(D, "static initializer");
1606         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1607       }
1608     } else {
1609       // We don't need an initializer, so remove the entry for the delayed
1610       // initializer position (just in case this entry was delayed) if we
1611       // also don't need to register a destructor.
1612       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1613         DelayedCXXInitPosition.erase(D);
1614     }
1615   }
1616 
1617   llvm::Type* InitType = Init->getType();
1618   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1619 
1620   // Strip off a bitcast if we got one back.
1621   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1622     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1623            // all zero index gep.
1624            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1625     Entry = CE->getOperand(0);
1626   }
1627 
1628   // Entry is now either a Function or GlobalVariable.
1629   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1630 
1631   // We have a definition after a declaration with the wrong type.
1632   // We must make a new GlobalVariable* and update everything that used OldGV
1633   // (a declaration or tentative definition) with the new GlobalVariable*
1634   // (which will be a definition).
1635   //
1636   // This happens if there is a prototype for a global (e.g.
1637   // "extern int x[];") and then a definition of a different type (e.g.
1638   // "int x[10];"). This also happens when an initializer has a different type
1639   // from the type of the global (this happens with unions).
1640   if (GV == 0 ||
1641       GV->getType()->getElementType() != InitType ||
1642       GV->getType()->getAddressSpace() !=
1643        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1644 
1645     // Move the old entry aside so that we'll create a new one.
1646     Entry->setName(StringRef());
1647 
1648     // Make a new global with the correct type, this is now guaranteed to work.
1649     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1650 
1651     // Replace all uses of the old global with the new global
1652     llvm::Constant *NewPtrForOldDecl =
1653         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1654     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1655 
1656     // Erase the old global, since it is no longer used.
1657     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1658   }
1659 
1660   if (D->hasAttr<AnnotateAttr>())
1661     AddGlobalAnnotations(D, GV);
1662 
1663   GV->setInitializer(Init);
1664 
1665   // If it is safe to mark the global 'constant', do so now.
1666   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1667                   isTypeConstant(D->getType(), true));
1668 
1669   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1670 
1671   // Set the llvm linkage type as appropriate.
1672   llvm::GlobalValue::LinkageTypes Linkage =
1673     GetLLVMLinkageVarDefinition(D, GV);
1674   GV->setLinkage(Linkage);
1675   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1676     // common vars aren't constant even if declared const.
1677     GV->setConstant(false);
1678 
1679   SetCommonAttributes(D, GV);
1680 
1681   // Emit the initializer function if necessary.
1682   if (NeedsGlobalCtor || NeedsGlobalDtor)
1683     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1684 
1685   // If we are compiling with ASan, add metadata indicating dynamically
1686   // initialized globals.
1687   if (LangOpts.AddressSanitizer && NeedsGlobalCtor) {
1688     llvm::Module &M = getModule();
1689 
1690     llvm::NamedMDNode *DynamicInitializers =
1691         M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1692     llvm::Value *GlobalToAdd[] = { GV };
1693     llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1694     DynamicInitializers->addOperand(ThisGlobal);
1695   }
1696 
1697   // Emit global variable debug information.
1698   if (CGDebugInfo *DI = getModuleDebugInfo())
1699     if (getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo)
1700       DI->EmitGlobalVariable(GV, D);
1701 }
1702 
1703 llvm::GlobalValue::LinkageTypes
1704 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1705                                            llvm::GlobalVariable *GV) {
1706   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1707   if (Linkage == GVA_Internal)
1708     return llvm::Function::InternalLinkage;
1709   else if (D->hasAttr<DLLImportAttr>())
1710     return llvm::Function::DLLImportLinkage;
1711   else if (D->hasAttr<DLLExportAttr>())
1712     return llvm::Function::DLLExportLinkage;
1713   else if (D->hasAttr<WeakAttr>()) {
1714     if (GV->isConstant())
1715       return llvm::GlobalVariable::WeakODRLinkage;
1716     else
1717       return llvm::GlobalVariable::WeakAnyLinkage;
1718   } else if (Linkage == GVA_TemplateInstantiation ||
1719              Linkage == GVA_ExplicitTemplateInstantiation)
1720     return llvm::GlobalVariable::WeakODRLinkage;
1721   else if (!getLangOpts().CPlusPlus &&
1722            ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1723              D->getAttr<CommonAttr>()) &&
1724            !D->hasExternalStorage() && !D->getInit() &&
1725            !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1726            !D->getAttr<WeakImportAttr>()) {
1727     // Thread local vars aren't considered common linkage.
1728     return llvm::GlobalVariable::CommonLinkage;
1729   }
1730   return llvm::GlobalVariable::ExternalLinkage;
1731 }
1732 
1733 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1734 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1735 /// existing call uses of the old function in the module, this adjusts them to
1736 /// call the new function directly.
1737 ///
1738 /// This is not just a cleanup: the always_inline pass requires direct calls to
1739 /// functions to be able to inline them.  If there is a bitcast in the way, it
1740 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1741 /// run at -O0.
1742 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1743                                                       llvm::Function *NewFn) {
1744   // If we're redefining a global as a function, don't transform it.
1745   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1746   if (OldFn == 0) return;
1747 
1748   llvm::Type *NewRetTy = NewFn->getReturnType();
1749   SmallVector<llvm::Value*, 4> ArgList;
1750 
1751   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1752        UI != E; ) {
1753     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1754     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1755     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1756     if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1757     llvm::CallSite CS(CI);
1758     if (!CI || !CS.isCallee(I)) continue;
1759 
1760     // If the return types don't match exactly, and if the call isn't dead, then
1761     // we can't transform this call.
1762     if (CI->getType() != NewRetTy && !CI->use_empty())
1763       continue;
1764 
1765     // Get the attribute list.
1766     llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
1767     llvm::AttrListPtr AttrList = CI->getAttributes();
1768 
1769     // Get any return attributes.
1770     llvm::Attributes RAttrs = AttrList.getRetAttributes();
1771 
1772     // Add the return attributes.
1773     if (RAttrs)
1774       AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
1775 
1776     // If the function was passed too few arguments, don't transform.  If extra
1777     // arguments were passed, we silently drop them.  If any of the types
1778     // mismatch, we don't transform.
1779     unsigned ArgNo = 0;
1780     bool DontTransform = false;
1781     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1782          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1783       if (CS.arg_size() == ArgNo ||
1784           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1785         DontTransform = true;
1786         break;
1787       }
1788 
1789       // Add any parameter attributes.
1790       if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
1791         AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1792     }
1793     if (DontTransform)
1794       continue;
1795 
1796     if (llvm::Attributes FnAttrs =  AttrList.getFnAttributes())
1797       AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
1798 
1799     // Okay, we can transform this.  Create the new call instruction and copy
1800     // over the required information.
1801     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1802     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1803     ArgList.clear();
1804     if (!NewCall->getType()->isVoidTy())
1805       NewCall->takeName(CI);
1806     NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec));
1807     NewCall->setCallingConv(CI->getCallingConv());
1808 
1809     // Finally, remove the old call, replacing any uses with the new one.
1810     if (!CI->use_empty())
1811       CI->replaceAllUsesWith(NewCall);
1812 
1813     // Copy debug location attached to CI.
1814     if (!CI->getDebugLoc().isUnknown())
1815       NewCall->setDebugLoc(CI->getDebugLoc());
1816     CI->eraseFromParent();
1817   }
1818 }
1819 
1820 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1821   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1822   // If we have a definition, this might be a deferred decl. If the
1823   // instantiation is explicit, make sure we emit it at the end.
1824   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1825     GetAddrOfGlobalVar(VD);
1826 }
1827 
1828 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1829   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1830 
1831   // Compute the function info and LLVM type.
1832   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1833   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
1834 
1835   // Get or create the prototype for the function.
1836   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1837 
1838   // Strip off a bitcast if we got one back.
1839   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1840     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1841     Entry = CE->getOperand(0);
1842   }
1843 
1844 
1845   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1846     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1847 
1848     // If the types mismatch then we have to rewrite the definition.
1849     assert(OldFn->isDeclaration() &&
1850            "Shouldn't replace non-declaration");
1851 
1852     // F is the Function* for the one with the wrong type, we must make a new
1853     // Function* and update everything that used F (a declaration) with the new
1854     // Function* (which will be a definition).
1855     //
1856     // This happens if there is a prototype for a function
1857     // (e.g. "int f()") and then a definition of a different type
1858     // (e.g. "int f(int x)").  Move the old function aside so that it
1859     // doesn't interfere with GetAddrOfFunction.
1860     OldFn->setName(StringRef());
1861     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1862 
1863     // If this is an implementation of a function without a prototype, try to
1864     // replace any existing uses of the function (which may be calls) with uses
1865     // of the new function
1866     if (D->getType()->isFunctionNoProtoType()) {
1867       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1868       OldFn->removeDeadConstantUsers();
1869     }
1870 
1871     // Replace uses of F with the Function we will endow with a body.
1872     if (!Entry->use_empty()) {
1873       llvm::Constant *NewPtrForOldDecl =
1874         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1875       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1876     }
1877 
1878     // Ok, delete the old function now, which is dead.
1879     OldFn->eraseFromParent();
1880 
1881     Entry = NewFn;
1882   }
1883 
1884   // We need to set linkage and visibility on the function before
1885   // generating code for it because various parts of IR generation
1886   // want to propagate this information down (e.g. to local static
1887   // declarations).
1888   llvm::Function *Fn = cast<llvm::Function>(Entry);
1889   setFunctionLinkage(D, Fn);
1890 
1891   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1892   setGlobalVisibility(Fn, D);
1893 
1894   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1895 
1896   SetFunctionDefinitionAttributes(D, Fn);
1897   SetLLVMFunctionAttributesForDefinition(D, Fn);
1898 
1899   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1900     AddGlobalCtor(Fn, CA->getPriority());
1901   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1902     AddGlobalDtor(Fn, DA->getPriority());
1903   if (D->hasAttr<AnnotateAttr>())
1904     AddGlobalAnnotations(D, Fn);
1905 }
1906 
1907 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1908   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1909   const AliasAttr *AA = D->getAttr<AliasAttr>();
1910   assert(AA && "Not an alias?");
1911 
1912   StringRef MangledName = getMangledName(GD);
1913 
1914   // If there is a definition in the module, then it wins over the alias.
1915   // This is dubious, but allow it to be safe.  Just ignore the alias.
1916   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1917   if (Entry && !Entry->isDeclaration())
1918     return;
1919 
1920   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1921 
1922   // Create a reference to the named value.  This ensures that it is emitted
1923   // if a deferred decl.
1924   llvm::Constant *Aliasee;
1925   if (isa<llvm::FunctionType>(DeclTy))
1926     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1927                                       /*ForVTable=*/false);
1928   else
1929     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1930                                     llvm::PointerType::getUnqual(DeclTy), 0);
1931 
1932   // Create the new alias itself, but don't set a name yet.
1933   llvm::GlobalValue *GA =
1934     new llvm::GlobalAlias(Aliasee->getType(),
1935                           llvm::Function::ExternalLinkage,
1936                           "", Aliasee, &getModule());
1937 
1938   if (Entry) {
1939     assert(Entry->isDeclaration());
1940 
1941     // If there is a declaration in the module, then we had an extern followed
1942     // by the alias, as in:
1943     //   extern int test6();
1944     //   ...
1945     //   int test6() __attribute__((alias("test7")));
1946     //
1947     // Remove it and replace uses of it with the alias.
1948     GA->takeName(Entry);
1949 
1950     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1951                                                           Entry->getType()));
1952     Entry->eraseFromParent();
1953   } else {
1954     GA->setName(MangledName);
1955   }
1956 
1957   // Set attributes which are particular to an alias; this is a
1958   // specialization of the attributes which may be set on a global
1959   // variable/function.
1960   if (D->hasAttr<DLLExportAttr>()) {
1961     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1962       // The dllexport attribute is ignored for undefined symbols.
1963       if (FD->hasBody())
1964         GA->setLinkage(llvm::Function::DLLExportLinkage);
1965     } else {
1966       GA->setLinkage(llvm::Function::DLLExportLinkage);
1967     }
1968   } else if (D->hasAttr<WeakAttr>() ||
1969              D->hasAttr<WeakRefAttr>() ||
1970              D->isWeakImported()) {
1971     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1972   }
1973 
1974   SetCommonAttributes(D, GA);
1975 }
1976 
1977 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
1978                                             ArrayRef<llvm::Type*> Tys) {
1979   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
1980                                          Tys);
1981 }
1982 
1983 static llvm::StringMapEntry<llvm::Constant*> &
1984 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1985                          const StringLiteral *Literal,
1986                          bool TargetIsLSB,
1987                          bool &IsUTF16,
1988                          unsigned &StringLength) {
1989   StringRef String = Literal->getString();
1990   unsigned NumBytes = String.size();
1991 
1992   // Check for simple case.
1993   if (!Literal->containsNonAsciiOrNull()) {
1994     StringLength = NumBytes;
1995     return Map.GetOrCreateValue(String);
1996   }
1997 
1998   // Otherwise, convert the UTF8 literals into a string of shorts.
1999   IsUTF16 = true;
2000 
2001   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2002   const UTF8 *FromPtr = (UTF8 *)String.data();
2003   UTF16 *ToPtr = &ToBuf[0];
2004 
2005   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2006                            &ToPtr, ToPtr + NumBytes,
2007                            strictConversion);
2008 
2009   // ConvertUTF8toUTF16 returns the length in ToPtr.
2010   StringLength = ToPtr - &ToBuf[0];
2011 
2012   // Add an explicit null.
2013   *ToPtr = 0;
2014   return Map.
2015     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2016                                (StringLength + 1) * 2));
2017 }
2018 
2019 static llvm::StringMapEntry<llvm::Constant*> &
2020 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2021                        const StringLiteral *Literal,
2022                        unsigned &StringLength) {
2023   StringRef String = Literal->getString();
2024   StringLength = String.size();
2025   return Map.GetOrCreateValue(String);
2026 }
2027 
2028 llvm::Constant *
2029 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2030   unsigned StringLength = 0;
2031   bool isUTF16 = false;
2032   llvm::StringMapEntry<llvm::Constant*> &Entry =
2033     GetConstantCFStringEntry(CFConstantStringMap, Literal,
2034                              getTargetData().isLittleEndian(),
2035                              isUTF16, StringLength);
2036 
2037   if (llvm::Constant *C = Entry.getValue())
2038     return C;
2039 
2040   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2041   llvm::Constant *Zeros[] = { Zero, Zero };
2042 
2043   // If we don't already have it, get __CFConstantStringClassReference.
2044   if (!CFConstantStringClassRef) {
2045     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2046     Ty = llvm::ArrayType::get(Ty, 0);
2047     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2048                                            "__CFConstantStringClassReference");
2049     // Decay array -> ptr
2050     CFConstantStringClassRef =
2051       llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2052   }
2053 
2054   QualType CFTy = getContext().getCFConstantStringType();
2055 
2056   llvm::StructType *STy =
2057     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2058 
2059   llvm::Constant *Fields[4];
2060 
2061   // Class pointer.
2062   Fields[0] = CFConstantStringClassRef;
2063 
2064   // Flags.
2065   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2066   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2067     llvm::ConstantInt::get(Ty, 0x07C8);
2068 
2069   // String pointer.
2070   llvm::Constant *C = 0;
2071   if (isUTF16) {
2072     ArrayRef<uint16_t> Arr =
2073       llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
2074                                    Entry.getKey().size() / 2);
2075     C = llvm::ConstantDataArray::get(VMContext, Arr);
2076   } else {
2077     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2078   }
2079 
2080   llvm::GlobalValue::LinkageTypes Linkage;
2081   if (isUTF16)
2082     // FIXME: why do utf strings get "_" labels instead of "L" labels?
2083     Linkage = llvm::GlobalValue::InternalLinkage;
2084   else
2085     // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2086     // when using private linkage. It is not clear if this is a bug in ld
2087     // or a reasonable new restriction.
2088     Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2089 
2090   // Note: -fwritable-strings doesn't make the backing store strings of
2091   // CFStrings writable. (See <rdar://problem/10657500>)
2092   llvm::GlobalVariable *GV =
2093     new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2094                              Linkage, C, ".str");
2095   GV->setUnnamedAddr(true);
2096   if (isUTF16) {
2097     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2098     GV->setAlignment(Align.getQuantity());
2099   } else {
2100     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2101     GV->setAlignment(Align.getQuantity());
2102   }
2103 
2104   // String.
2105   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2106 
2107   if (isUTF16)
2108     // Cast the UTF16 string to the correct type.
2109     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2110 
2111   // String length.
2112   Ty = getTypes().ConvertType(getContext().LongTy);
2113   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2114 
2115   // The struct.
2116   C = llvm::ConstantStruct::get(STy, Fields);
2117   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2118                                 llvm::GlobalVariable::PrivateLinkage, C,
2119                                 "_unnamed_cfstring_");
2120   if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
2121     GV->setSection(Sect);
2122   Entry.setValue(GV);
2123 
2124   return GV;
2125 }
2126 
2127 static RecordDecl *
2128 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2129                  DeclContext *DC, IdentifierInfo *Id) {
2130   SourceLocation Loc;
2131   if (Ctx.getLangOpts().CPlusPlus)
2132     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2133   else
2134     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2135 }
2136 
2137 llvm::Constant *
2138 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2139   unsigned StringLength = 0;
2140   llvm::StringMapEntry<llvm::Constant*> &Entry =
2141     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2142 
2143   if (llvm::Constant *C = Entry.getValue())
2144     return C;
2145 
2146   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2147   llvm::Constant *Zeros[] = { Zero, Zero };
2148 
2149   // If we don't already have it, get _NSConstantStringClassReference.
2150   if (!ConstantStringClassRef) {
2151     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2152     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2153     llvm::Constant *GV;
2154     if (LangOpts.ObjCRuntime.isNonFragile()) {
2155       std::string str =
2156         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2157                             : "OBJC_CLASS_$_" + StringClass;
2158       GV = getObjCRuntime().GetClassGlobal(str);
2159       // Make sure the result is of the correct type.
2160       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2161       ConstantStringClassRef =
2162         llvm::ConstantExpr::getBitCast(GV, PTy);
2163     } else {
2164       std::string str =
2165         StringClass.empty() ? "_NSConstantStringClassReference"
2166                             : "_" + StringClass + "ClassReference";
2167       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2168       GV = CreateRuntimeVariable(PTy, str);
2169       // Decay array -> ptr
2170       ConstantStringClassRef =
2171         llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2172     }
2173   }
2174 
2175   if (!NSConstantStringType) {
2176     // Construct the type for a constant NSString.
2177     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2178                                      Context.getTranslationUnitDecl(),
2179                                    &Context.Idents.get("__builtin_NSString"));
2180     D->startDefinition();
2181 
2182     QualType FieldTypes[3];
2183 
2184     // const int *isa;
2185     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2186     // const char *str;
2187     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2188     // unsigned int length;
2189     FieldTypes[2] = Context.UnsignedIntTy;
2190 
2191     // Create fields
2192     for (unsigned i = 0; i < 3; ++i) {
2193       FieldDecl *Field = FieldDecl::Create(Context, D,
2194                                            SourceLocation(),
2195                                            SourceLocation(), 0,
2196                                            FieldTypes[i], /*TInfo=*/0,
2197                                            /*BitWidth=*/0,
2198                                            /*Mutable=*/false,
2199                                            ICIS_NoInit);
2200       Field->setAccess(AS_public);
2201       D->addDecl(Field);
2202     }
2203 
2204     D->completeDefinition();
2205     QualType NSTy = Context.getTagDeclType(D);
2206     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2207   }
2208 
2209   llvm::Constant *Fields[3];
2210 
2211   // Class pointer.
2212   Fields[0] = ConstantStringClassRef;
2213 
2214   // String pointer.
2215   llvm::Constant *C =
2216     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2217 
2218   llvm::GlobalValue::LinkageTypes Linkage;
2219   bool isConstant;
2220   Linkage = llvm::GlobalValue::PrivateLinkage;
2221   isConstant = !LangOpts.WritableStrings;
2222 
2223   llvm::GlobalVariable *GV =
2224   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2225                            ".str");
2226   GV->setUnnamedAddr(true);
2227   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2228   GV->setAlignment(Align.getQuantity());
2229   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2230 
2231   // String length.
2232   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2233   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2234 
2235   // The struct.
2236   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2237   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2238                                 llvm::GlobalVariable::PrivateLinkage, C,
2239                                 "_unnamed_nsstring_");
2240   // FIXME. Fix section.
2241   if (const char *Sect =
2242         LangOpts.ObjCRuntime.isNonFragile()
2243           ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2244           : getContext().getTargetInfo().getNSStringSection())
2245     GV->setSection(Sect);
2246   Entry.setValue(GV);
2247 
2248   return GV;
2249 }
2250 
2251 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2252   if (ObjCFastEnumerationStateType.isNull()) {
2253     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2254                                      Context.getTranslationUnitDecl(),
2255                       &Context.Idents.get("__objcFastEnumerationState"));
2256     D->startDefinition();
2257 
2258     QualType FieldTypes[] = {
2259       Context.UnsignedLongTy,
2260       Context.getPointerType(Context.getObjCIdType()),
2261       Context.getPointerType(Context.UnsignedLongTy),
2262       Context.getConstantArrayType(Context.UnsignedLongTy,
2263                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2264     };
2265 
2266     for (size_t i = 0; i < 4; ++i) {
2267       FieldDecl *Field = FieldDecl::Create(Context,
2268                                            D,
2269                                            SourceLocation(),
2270                                            SourceLocation(), 0,
2271                                            FieldTypes[i], /*TInfo=*/0,
2272                                            /*BitWidth=*/0,
2273                                            /*Mutable=*/false,
2274                                            ICIS_NoInit);
2275       Field->setAccess(AS_public);
2276       D->addDecl(Field);
2277     }
2278 
2279     D->completeDefinition();
2280     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2281   }
2282 
2283   return ObjCFastEnumerationStateType;
2284 }
2285 
2286 llvm::Constant *
2287 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2288   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2289 
2290   // Don't emit it as the address of the string, emit the string data itself
2291   // as an inline array.
2292   if (E->getCharByteWidth() == 1) {
2293     SmallString<64> Str(E->getString());
2294 
2295     // Resize the string to the right size, which is indicated by its type.
2296     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2297     Str.resize(CAT->getSize().getZExtValue());
2298     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2299   }
2300 
2301   llvm::ArrayType *AType =
2302     cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2303   llvm::Type *ElemTy = AType->getElementType();
2304   unsigned NumElements = AType->getNumElements();
2305 
2306   // Wide strings have either 2-byte or 4-byte elements.
2307   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2308     SmallVector<uint16_t, 32> Elements;
2309     Elements.reserve(NumElements);
2310 
2311     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2312       Elements.push_back(E->getCodeUnit(i));
2313     Elements.resize(NumElements);
2314     return llvm::ConstantDataArray::get(VMContext, Elements);
2315   }
2316 
2317   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2318   SmallVector<uint32_t, 32> Elements;
2319   Elements.reserve(NumElements);
2320 
2321   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2322     Elements.push_back(E->getCodeUnit(i));
2323   Elements.resize(NumElements);
2324   return llvm::ConstantDataArray::get(VMContext, Elements);
2325 }
2326 
2327 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2328 /// constant array for the given string literal.
2329 llvm::Constant *
2330 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2331   CharUnits Align = getContext().getTypeAlignInChars(S->getType());
2332   if (S->isAscii() || S->isUTF8()) {
2333     SmallString<64> Str(S->getString());
2334 
2335     // Resize the string to the right size, which is indicated by its type.
2336     const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2337     Str.resize(CAT->getSize().getZExtValue());
2338     return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2339   }
2340 
2341   // FIXME: the following does not memoize wide strings.
2342   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2343   llvm::GlobalVariable *GV =
2344     new llvm::GlobalVariable(getModule(),C->getType(),
2345                              !LangOpts.WritableStrings,
2346                              llvm::GlobalValue::PrivateLinkage,
2347                              C,".str");
2348 
2349   GV->setAlignment(Align.getQuantity());
2350   GV->setUnnamedAddr(true);
2351   return GV;
2352 }
2353 
2354 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2355 /// array for the given ObjCEncodeExpr node.
2356 llvm::Constant *
2357 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2358   std::string Str;
2359   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2360 
2361   return GetAddrOfConstantCString(Str);
2362 }
2363 
2364 
2365 /// GenerateWritableString -- Creates storage for a string literal.
2366 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2367                                              bool constant,
2368                                              CodeGenModule &CGM,
2369                                              const char *GlobalName,
2370                                              unsigned Alignment) {
2371   // Create Constant for this string literal. Don't add a '\0'.
2372   llvm::Constant *C =
2373       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2374 
2375   // Create a global variable for this string
2376   llvm::GlobalVariable *GV =
2377     new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2378                              llvm::GlobalValue::PrivateLinkage,
2379                              C, GlobalName);
2380   GV->setAlignment(Alignment);
2381   GV->setUnnamedAddr(true);
2382   return GV;
2383 }
2384 
2385 /// GetAddrOfConstantString - Returns a pointer to a character array
2386 /// containing the literal. This contents are exactly that of the
2387 /// given string, i.e. it will not be null terminated automatically;
2388 /// see GetAddrOfConstantCString. Note that whether the result is
2389 /// actually a pointer to an LLVM constant depends on
2390 /// Feature.WriteableStrings.
2391 ///
2392 /// The result has pointer to array type.
2393 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2394                                                        const char *GlobalName,
2395                                                        unsigned Alignment) {
2396   // Get the default prefix if a name wasn't specified.
2397   if (!GlobalName)
2398     GlobalName = ".str";
2399 
2400   // Don't share any string literals if strings aren't constant.
2401   if (LangOpts.WritableStrings)
2402     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2403 
2404   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2405     ConstantStringMap.GetOrCreateValue(Str);
2406 
2407   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2408     if (Alignment > GV->getAlignment()) {
2409       GV->setAlignment(Alignment);
2410     }
2411     return GV;
2412   }
2413 
2414   // Create a global variable for this.
2415   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2416                                                    Alignment);
2417   Entry.setValue(GV);
2418   return GV;
2419 }
2420 
2421 /// GetAddrOfConstantCString - Returns a pointer to a character
2422 /// array containing the literal and a terminating '\0'
2423 /// character. The result has pointer to array type.
2424 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2425                                                         const char *GlobalName,
2426                                                         unsigned Alignment) {
2427   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2428   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2429 }
2430 
2431 /// EmitObjCPropertyImplementations - Emit information for synthesized
2432 /// properties for an implementation.
2433 void CodeGenModule::EmitObjCPropertyImplementations(const
2434                                                     ObjCImplementationDecl *D) {
2435   for (ObjCImplementationDecl::propimpl_iterator
2436          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2437     ObjCPropertyImplDecl *PID = *i;
2438 
2439     // Dynamic is just for type-checking.
2440     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2441       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2442 
2443       // Determine which methods need to be implemented, some may have
2444       // been overridden. Note that ::isSynthesized is not the method
2445       // we want, that just indicates if the decl came from a
2446       // property. What we want to know is if the method is defined in
2447       // this implementation.
2448       if (!D->getInstanceMethod(PD->getGetterName()))
2449         CodeGenFunction(*this).GenerateObjCGetter(
2450                                  const_cast<ObjCImplementationDecl *>(D), PID);
2451       if (!PD->isReadOnly() &&
2452           !D->getInstanceMethod(PD->getSetterName()))
2453         CodeGenFunction(*this).GenerateObjCSetter(
2454                                  const_cast<ObjCImplementationDecl *>(D), PID);
2455     }
2456   }
2457 }
2458 
2459 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2460   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2461   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2462        ivar; ivar = ivar->getNextIvar())
2463     if (ivar->getType().isDestructedType())
2464       return true;
2465 
2466   return false;
2467 }
2468 
2469 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2470 /// for an implementation.
2471 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2472   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2473   if (needsDestructMethod(D)) {
2474     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2475     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2476     ObjCMethodDecl *DTORMethod =
2477       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2478                              cxxSelector, getContext().VoidTy, 0, D,
2479                              /*isInstance=*/true, /*isVariadic=*/false,
2480                           /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
2481                              /*isDefined=*/false, ObjCMethodDecl::Required);
2482     D->addInstanceMethod(DTORMethod);
2483     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2484     D->setHasCXXStructors(true);
2485   }
2486 
2487   // If the implementation doesn't have any ivar initializers, we don't need
2488   // a .cxx_construct.
2489   if (D->getNumIvarInitializers() == 0)
2490     return;
2491 
2492   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2493   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2494   // The constructor returns 'self'.
2495   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2496                                                 D->getLocation(),
2497                                                 D->getLocation(),
2498                                                 cxxSelector,
2499                                                 getContext().getObjCIdType(), 0,
2500                                                 D, /*isInstance=*/true,
2501                                                 /*isVariadic=*/false,
2502                                                 /*isSynthesized=*/true,
2503                                                 /*isImplicitlyDeclared=*/true,
2504                                                 /*isDefined=*/false,
2505                                                 ObjCMethodDecl::Required);
2506   D->addInstanceMethod(CTORMethod);
2507   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2508   D->setHasCXXStructors(true);
2509 }
2510 
2511 /// EmitNamespace - Emit all declarations in a namespace.
2512 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2513   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2514        I != E; ++I)
2515     EmitTopLevelDecl(*I);
2516 }
2517 
2518 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2519 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2520   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2521       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2522     ErrorUnsupported(LSD, "linkage spec");
2523     return;
2524   }
2525 
2526   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2527        I != E; ++I)
2528     EmitTopLevelDecl(*I);
2529 }
2530 
2531 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2532 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2533   // If an error has occurred, stop code generation, but continue
2534   // parsing and semantic analysis (to ensure all warnings and errors
2535   // are emitted).
2536   if (Diags.hasErrorOccurred())
2537     return;
2538 
2539   // Ignore dependent declarations.
2540   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2541     return;
2542 
2543   switch (D->getKind()) {
2544   case Decl::CXXConversion:
2545   case Decl::CXXMethod:
2546   case Decl::Function:
2547     // Skip function templates
2548     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2549         cast<FunctionDecl>(D)->isLateTemplateParsed())
2550       return;
2551 
2552     EmitGlobal(cast<FunctionDecl>(D));
2553     break;
2554 
2555   case Decl::Var:
2556     EmitGlobal(cast<VarDecl>(D));
2557     break;
2558 
2559   // Indirect fields from global anonymous structs and unions can be
2560   // ignored; only the actual variable requires IR gen support.
2561   case Decl::IndirectField:
2562     break;
2563 
2564   // C++ Decls
2565   case Decl::Namespace:
2566     EmitNamespace(cast<NamespaceDecl>(D));
2567     break;
2568     // No code generation needed.
2569   case Decl::UsingShadow:
2570   case Decl::Using:
2571   case Decl::UsingDirective:
2572   case Decl::ClassTemplate:
2573   case Decl::FunctionTemplate:
2574   case Decl::TypeAliasTemplate:
2575   case Decl::NamespaceAlias:
2576   case Decl::Block:
2577   case Decl::Import:
2578     break;
2579   case Decl::CXXConstructor:
2580     // Skip function templates
2581     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2582         cast<FunctionDecl>(D)->isLateTemplateParsed())
2583       return;
2584 
2585     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2586     break;
2587   case Decl::CXXDestructor:
2588     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2589       return;
2590     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2591     break;
2592 
2593   case Decl::StaticAssert:
2594     // Nothing to do.
2595     break;
2596 
2597   // Objective-C Decls
2598 
2599   // Forward declarations, no (immediate) code generation.
2600   case Decl::ObjCInterface:
2601   case Decl::ObjCCategory:
2602     break;
2603 
2604   case Decl::ObjCProtocol: {
2605     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2606     if (Proto->isThisDeclarationADefinition())
2607       ObjCRuntime->GenerateProtocol(Proto);
2608     break;
2609   }
2610 
2611   case Decl::ObjCCategoryImpl:
2612     // Categories have properties but don't support synthesize so we
2613     // can ignore them here.
2614     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2615     break;
2616 
2617   case Decl::ObjCImplementation: {
2618     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2619     EmitObjCPropertyImplementations(OMD);
2620     EmitObjCIvarInitializations(OMD);
2621     ObjCRuntime->GenerateClass(OMD);
2622     // Emit global variable debug information.
2623     if (CGDebugInfo *DI = getModuleDebugInfo())
2624       DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()),
2625 				   OMD->getLocation());
2626 
2627     break;
2628   }
2629   case Decl::ObjCMethod: {
2630     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2631     // If this is not a prototype, emit the body.
2632     if (OMD->getBody())
2633       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2634     break;
2635   }
2636   case Decl::ObjCCompatibleAlias:
2637     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2638     break;
2639 
2640   case Decl::LinkageSpec:
2641     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2642     break;
2643 
2644   case Decl::FileScopeAsm: {
2645     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2646     StringRef AsmString = AD->getAsmString()->getString();
2647 
2648     const std::string &S = getModule().getModuleInlineAsm();
2649     if (S.empty())
2650       getModule().setModuleInlineAsm(AsmString);
2651     else if (S.end()[-1] == '\n')
2652       getModule().setModuleInlineAsm(S + AsmString.str());
2653     else
2654       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2655     break;
2656   }
2657 
2658   default:
2659     // Make sure we handled everything we should, every other kind is a
2660     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2661     // function. Need to recode Decl::Kind to do that easily.
2662     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2663   }
2664 }
2665 
2666 /// Turns the given pointer into a constant.
2667 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2668                                           const void *Ptr) {
2669   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2670   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2671   return llvm::ConstantInt::get(i64, PtrInt);
2672 }
2673 
2674 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2675                                    llvm::NamedMDNode *&GlobalMetadata,
2676                                    GlobalDecl D,
2677                                    llvm::GlobalValue *Addr) {
2678   if (!GlobalMetadata)
2679     GlobalMetadata =
2680       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2681 
2682   // TODO: should we report variant information for ctors/dtors?
2683   llvm::Value *Ops[] = {
2684     Addr,
2685     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2686   };
2687   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2688 }
2689 
2690 /// Emits metadata nodes associating all the global values in the
2691 /// current module with the Decls they came from.  This is useful for
2692 /// projects using IR gen as a subroutine.
2693 ///
2694 /// Since there's currently no way to associate an MDNode directly
2695 /// with an llvm::GlobalValue, we create a global named metadata
2696 /// with the name 'clang.global.decl.ptrs'.
2697 void CodeGenModule::EmitDeclMetadata() {
2698   llvm::NamedMDNode *GlobalMetadata = 0;
2699 
2700   // StaticLocalDeclMap
2701   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2702          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2703        I != E; ++I) {
2704     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2705     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2706   }
2707 }
2708 
2709 /// Emits metadata nodes for all the local variables in the current
2710 /// function.
2711 void CodeGenFunction::EmitDeclMetadata() {
2712   if (LocalDeclMap.empty()) return;
2713 
2714   llvm::LLVMContext &Context = getLLVMContext();
2715 
2716   // Find the unique metadata ID for this name.
2717   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2718 
2719   llvm::NamedMDNode *GlobalMetadata = 0;
2720 
2721   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2722          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2723     const Decl *D = I->first;
2724     llvm::Value *Addr = I->second;
2725 
2726     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2727       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2728       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2729     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2730       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2731       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2732     }
2733   }
2734 }
2735 
2736 void CodeGenModule::EmitCoverageFile() {
2737   if (!getCodeGenOpts().CoverageFile.empty()) {
2738     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2739       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2740       llvm::LLVMContext &Ctx = TheModule.getContext();
2741       llvm::MDString *CoverageFile =
2742           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
2743       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2744         llvm::MDNode *CU = CUNode->getOperand(i);
2745         llvm::Value *node[] = { CoverageFile, CU };
2746         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2747         GCov->addOperand(N);
2748       }
2749     }
2750   }
2751 }
2752