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