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