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