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