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