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