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