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