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