]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.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 "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGCall.h"
18 #include "CGDebugInfo.h"
19 #include "CGObjCRuntime.h"
20 #include "CGOpenCLRuntime.h"
21 #include "CodeGenFunction.h"
22 #include "CodeGenTBAA.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/CharUnits.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclTemplate.h"
29 #include "clang/AST/Mangle.h"
30 #include "clang/AST/RecordLayout.h"
31 #include "clang/AST/RecursiveASTVisitor.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/CharInfo.h"
34 #include "clang/Basic/Diagnostic.h"
35 #include "clang/Basic/Module.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Frontend/CodeGenOptions.h"
39 #include "llvm/ADT/APSInt.h"
40 #include "llvm/ADT/Triple.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ConvertUTF.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Target/Mangler.h"
50
51 using namespace clang;
52 using namespace CodeGen;
53
54 static const char AnnotationSection[] = "llvm.metadata";
55
56 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
57   switch (CGM.getTarget().getCXXABI().getKind()) {
58   case TargetCXXABI::GenericAArch64:
59   case TargetCXXABI::GenericARM:
60   case TargetCXXABI::iOS:
61   case TargetCXXABI::GenericItanium:
62     return *CreateItaniumCXXABI(CGM);
63   case TargetCXXABI::Microsoft:
64     return *CreateMicrosoftCXXABI(CGM);
65   }
66
67   llvm_unreachable("invalid C++ ABI kind");
68 }
69
70
71 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
72                              llvm::Module &M, const llvm::DataLayout &TD,
73                              DiagnosticsEngine &diags)
74   : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
75     Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
76     ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
77     TheTargetCodeGenInfo(0), Types(*this), VTables(*this),
78     ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
79     DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
80     RRData(0), CFConstantStringClassRef(0),
81     ConstantStringClassRef(0), NSConstantStringType(0),
82     NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
83     BlockObjectAssign(0), BlockObjectDispose(0),
84     BlockDescriptorType(0), GenericBlockLiteralType(0),
85     LifetimeStartFn(0), LifetimeEndFn(0),
86     SanitizerBlacklist(CGO.SanitizerBlacklistFile),
87     SanOpts(SanitizerBlacklist.isIn(M) ?
88             SanitizerOptions::Disabled : LangOpts.Sanitize) {
89
90   // Initialize the type cache.
91   llvm::LLVMContext &LLVMContext = M.getContext();
92   VoidTy = llvm::Type::getVoidTy(LLVMContext);
93   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
94   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
95   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
96   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
97   FloatTy = llvm::Type::getFloatTy(LLVMContext);
98   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
99   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
100   PointerAlignInBytes =
101   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
102   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
103   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
104   Int8PtrTy = Int8Ty->getPointerTo(0);
105   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
106
107   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
108
109   if (LangOpts.ObjC1)
110     createObjCRuntime();
111   if (LangOpts.OpenCL)
112     createOpenCLRuntime();
113   if (LangOpts.CUDA)
114     createCUDARuntime();
115
116   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
117   if (SanOpts.Thread ||
118       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
119     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
120                            ABI.getMangleContext());
121
122   // If debug info or coverage generation is enabled, create the CGDebugInfo
123   // object.
124   if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
125       CodeGenOpts.EmitGcovArcs ||
126       CodeGenOpts.EmitGcovNotes)
127     DebugInfo = new CGDebugInfo(*this);
128
129   Block.GlobalUniqueCount = 0;
130
131   if (C.getLangOpts().ObjCAutoRefCount)
132     ARCData = new ARCEntrypoints();
133   RRData = new RREntrypoints();
134 }
135
136 CodeGenModule::~CodeGenModule() {
137   delete ObjCRuntime;
138   delete OpenCLRuntime;
139   delete CUDARuntime;
140   delete TheTargetCodeGenInfo;
141   delete &ABI;
142   delete TBAA;
143   delete DebugInfo;
144   delete ARCData;
145   delete RRData;
146 }
147
148 void CodeGenModule::createObjCRuntime() {
149   // This is just isGNUFamily(), but we want to force implementors of
150   // new ABIs to decide how best to do this.
151   switch (LangOpts.ObjCRuntime.getKind()) {
152   case ObjCRuntime::GNUstep:
153   case ObjCRuntime::GCC:
154   case ObjCRuntime::ObjFW:
155     ObjCRuntime = CreateGNUObjCRuntime(*this);
156     return;
157
158   case ObjCRuntime::FragileMacOSX:
159   case ObjCRuntime::MacOSX:
160   case ObjCRuntime::iOS:
161     ObjCRuntime = CreateMacObjCRuntime(*this);
162     return;
163   }
164   llvm_unreachable("bad runtime kind");
165 }
166
167 void CodeGenModule::createOpenCLRuntime() {
168   OpenCLRuntime = new CGOpenCLRuntime(*this);
169 }
170
171 void CodeGenModule::createCUDARuntime() {
172   CUDARuntime = CreateNVCUDARuntime(*this);
173 }
174
175 void CodeGenModule::Release() {
176   EmitDeferred();
177   EmitCXXGlobalInitFunc();
178   EmitCXXGlobalDtorFunc();
179   EmitCXXThreadLocalInitFunc();
180   if (ObjCRuntime)
181     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
182       AddGlobalCtor(ObjCInitFunction);
183   EmitCtorList(GlobalCtors, "llvm.global_ctors");
184   EmitCtorList(GlobalDtors, "llvm.global_dtors");
185   EmitGlobalAnnotations();
186   EmitStaticExternCAliases();
187   EmitLLVMUsed();
188
189   if (CodeGenOpts.Autolink && Context.getLangOpts().Modules) {
190     EmitModuleLinkOptions();
191   }
192
193   SimplifyPersonality();
194
195   if (getCodeGenOpts().EmitDeclMetadata)
196     EmitDeclMetadata();
197
198   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
199     EmitCoverageFile();
200
201   if (DebugInfo)
202     DebugInfo->finalize();
203 }
204
205 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
206   // Make sure that this type is translated.
207   Types.UpdateCompletedType(TD);
208 }
209
210 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
211   if (!TBAA)
212     return 0;
213   return TBAA->getTBAAInfo(QTy);
214 }
215
216 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
217   if (!TBAA)
218     return 0;
219   return TBAA->getTBAAInfoForVTablePtr();
220 }
221
222 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
223   if (!TBAA)
224     return 0;
225   return TBAA->getTBAAStructInfo(QTy);
226 }
227
228 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
229   if (!TBAA)
230     return 0;
231   return TBAA->getTBAAStructTypeInfo(QTy);
232 }
233
234 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
235                                                   llvm::MDNode *AccessN,
236                                                   uint64_t O) {
237   if (!TBAA)
238     return 0;
239   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
240 }
241
242 /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
243 /// is the same as the type. For struct-path aware TBAA, the tag
244 /// is different from the type: base type, access type and offset.
245 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
246 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
247                                         llvm::MDNode *TBAAInfo,
248                                         bool ConvertTypeToTag) {
249   if (ConvertTypeToTag && TBAA && CodeGenOpts.StructPathTBAA)
250     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
251                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
252   else
253     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
254 }
255
256 void CodeGenModule::Error(SourceLocation loc, StringRef error) {
257   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
258   getDiags().Report(Context.getFullLoc(loc), diagID);
259 }
260
261 /// ErrorUnsupported - Print out an error that codegen doesn't support the
262 /// specified stmt yet.
263 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
264                                      bool OmitOnError) {
265   if (OmitOnError && getDiags().hasErrorOccurred())
266     return;
267   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
268                                                "cannot compile this %0 yet");
269   std::string Msg = Type;
270   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
271     << Msg << S->getSourceRange();
272 }
273
274 /// ErrorUnsupported - Print out an error that codegen doesn't support the
275 /// specified decl yet.
276 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
277                                      bool OmitOnError) {
278   if (OmitOnError && getDiags().hasErrorOccurred())
279     return;
280   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
281                                                "cannot compile this %0 yet");
282   std::string Msg = Type;
283   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
284 }
285
286 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
287   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
288 }
289
290 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
291                                         const NamedDecl *D) const {
292   // Internal definitions always have default visibility.
293   if (GV->hasLocalLinkage()) {
294     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
295     return;
296   }
297
298   // Set visibility for definitions.
299   LinkageInfo LV = D->getLinkageAndVisibility();
300   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
301     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
302 }
303
304 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
305   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
306       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
307       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
308       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
309       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
310 }
311
312 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
313     CodeGenOptions::TLSModel M) {
314   switch (M) {
315   case CodeGenOptions::GeneralDynamicTLSModel:
316     return llvm::GlobalVariable::GeneralDynamicTLSModel;
317   case CodeGenOptions::LocalDynamicTLSModel:
318     return llvm::GlobalVariable::LocalDynamicTLSModel;
319   case CodeGenOptions::InitialExecTLSModel:
320     return llvm::GlobalVariable::InitialExecTLSModel;
321   case CodeGenOptions::LocalExecTLSModel:
322     return llvm::GlobalVariable::LocalExecTLSModel;
323   }
324   llvm_unreachable("Invalid TLS model!");
325 }
326
327 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
328                                const VarDecl &D) const {
329   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
330
331   llvm::GlobalVariable::ThreadLocalMode TLM;
332   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
333
334   // Override the TLS model if it is explicitly specified.
335   if (D.hasAttr<TLSModelAttr>()) {
336     const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
337     TLM = GetLLVMTLSModel(Attr->getModel());
338   }
339
340   GV->setThreadLocalMode(TLM);
341 }
342
343 /// Set the symbol visibility of type information (vtable and RTTI)
344 /// associated with the given type.
345 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
346                                       const CXXRecordDecl *RD,
347                                       TypeVisibilityKind TVK) const {
348   setGlobalVisibility(GV, RD);
349
350   if (!CodeGenOpts.HiddenWeakVTables)
351     return;
352
353   // We never want to drop the visibility for RTTI names.
354   if (TVK == TVK_ForRTTIName)
355     return;
356
357   // We want to drop the visibility to hidden for weak type symbols.
358   // This isn't possible if there might be unresolved references
359   // elsewhere that rely on this symbol being visible.
360
361   // This should be kept roughly in sync with setThunkVisibility
362   // in CGVTables.cpp.
363
364   // Preconditions.
365   if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
366       GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
367     return;
368
369   // Don't override an explicit visibility attribute.
370   if (RD->getExplicitVisibility(NamedDecl::VisibilityForType))
371     return;
372
373   switch (RD->getTemplateSpecializationKind()) {
374   // We have to disable the optimization if this is an EI definition
375   // because there might be EI declarations in other shared objects.
376   case TSK_ExplicitInstantiationDefinition:
377   case TSK_ExplicitInstantiationDeclaration:
378     return;
379
380   // Every use of a non-template class's type information has to emit it.
381   case TSK_Undeclared:
382     break;
383
384   // In theory, implicit instantiations can ignore the possibility of
385   // an explicit instantiation declaration because there necessarily
386   // must be an EI definition somewhere with default visibility.  In
387   // practice, it's possible to have an explicit instantiation for
388   // an arbitrary template class, and linkers aren't necessarily able
389   // to deal with mixed-visibility symbols.
390   case TSK_ExplicitSpecialization:
391   case TSK_ImplicitInstantiation:
392     return;
393   }
394
395   // If there's a key function, there may be translation units
396   // that don't have the key function's definition.  But ignore
397   // this if we're emitting RTTI under -fno-rtti.
398   if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
399     // FIXME: what should we do if we "lose" the key function during
400     // the emission of the file?
401     if (Context.getCurrentKeyFunction(RD))
402       return;
403   }
404
405   // Otherwise, drop the visibility to hidden.
406   GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
407   GV->setUnnamedAddr(true);
408 }
409
410 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
411   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
412
413   StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
414   if (!Str.empty())
415     return Str;
416
417   if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
418     IdentifierInfo *II = ND->getIdentifier();
419     assert(II && "Attempt to mangle unnamed decl.");
420
421     Str = II->getName();
422     return Str;
423   }
424   
425   SmallString<256> Buffer;
426   llvm::raw_svector_ostream Out(Buffer);
427   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
428     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
429   else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
430     getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
431   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
432     getCXXABI().getMangleContext().mangleBlock(BD, Out,
433       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
434   else
435     getCXXABI().getMangleContext().mangleName(ND, Out);
436
437   // Allocate space for the mangled name.
438   Out.flush();
439   size_t Length = Buffer.size();
440   char *Name = MangledNamesAllocator.Allocate<char>(Length);
441   std::copy(Buffer.begin(), Buffer.end(), Name);
442   
443   Str = StringRef(Name, Length);
444   
445   return Str;
446 }
447
448 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
449                                         const BlockDecl *BD) {
450   MangleContext &MangleCtx = getCXXABI().getMangleContext();
451   const Decl *D = GD.getDecl();
452   llvm::raw_svector_ostream Out(Buffer.getBuffer());
453   if (D == 0)
454     MangleCtx.mangleGlobalBlock(BD, 
455       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
456   else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
457     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
458   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
459     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
460   else
461     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
462 }
463
464 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
465   return getModule().getNamedValue(Name);
466 }
467
468 /// AddGlobalCtor - Add a function to the list that will be called before
469 /// main() runs.
470 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
471   // FIXME: Type coercion of void()* types.
472   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
473 }
474
475 /// AddGlobalDtor - Add a function to the list that will be called
476 /// when the module is unloaded.
477 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
478   // FIXME: Type coercion of void()* types.
479   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
480 }
481
482 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
483   // Ctor function type is void()*.
484   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
485   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
486
487   // Get the type of a ctor entry, { i32, void ()* }.
488   llvm::StructType *CtorStructTy =
489     llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
490
491   // Construct the constructor and destructor arrays.
492   SmallVector<llvm::Constant*, 8> Ctors;
493   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
494     llvm::Constant *S[] = {
495       llvm::ConstantInt::get(Int32Ty, I->second, false),
496       llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
497     };
498     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
499   }
500
501   if (!Ctors.empty()) {
502     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
503     new llvm::GlobalVariable(TheModule, AT, false,
504                              llvm::GlobalValue::AppendingLinkage,
505                              llvm::ConstantArray::get(AT, Ctors),
506                              GlobalName);
507   }
508 }
509
510 llvm::GlobalValue::LinkageTypes
511 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
512   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
513
514   if (Linkage == GVA_Internal)
515     return llvm::Function::InternalLinkage;
516   
517   if (D->hasAttr<DLLExportAttr>())
518     return llvm::Function::DLLExportLinkage;
519   
520   if (D->hasAttr<WeakAttr>())
521     return llvm::Function::WeakAnyLinkage;
522   
523   // In C99 mode, 'inline' functions are guaranteed to have a strong
524   // definition somewhere else, so we can use available_externally linkage.
525   if (Linkage == GVA_C99Inline)
526     return llvm::Function::AvailableExternallyLinkage;
527
528   // Note that Apple's kernel linker doesn't support symbol
529   // coalescing, so we need to avoid linkonce and weak linkages there.
530   // Normally, this means we just map to internal, but for explicit
531   // instantiations we'll map to external.
532
533   // In C++, the compiler has to emit a definition in every translation unit
534   // that references the function.  We should use linkonce_odr because
535   // a) if all references in this translation unit are optimized away, we
536   // don't need to codegen it.  b) if the function persists, it needs to be
537   // merged with other definitions. c) C++ has the ODR, so we know the
538   // definition is dependable.
539   if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
540     return !Context.getLangOpts().AppleKext 
541              ? llvm::Function::LinkOnceODRLinkage 
542              : llvm::Function::InternalLinkage;
543   
544   // An explicit instantiation of a template has weak linkage, since
545   // explicit instantiations can occur in multiple translation units
546   // and must all be equivalent. However, we are not allowed to
547   // throw away these explicit instantiations.
548   if (Linkage == GVA_ExplicitTemplateInstantiation)
549     return !Context.getLangOpts().AppleKext
550              ? llvm::Function::WeakODRLinkage
551              : llvm::Function::ExternalLinkage;
552   
553   // Otherwise, we have strong external linkage.
554   assert(Linkage == GVA_StrongExternal);
555   return llvm::Function::ExternalLinkage;
556 }
557
558
559 /// SetFunctionDefinitionAttributes - Set attributes for a global.
560 ///
561 /// FIXME: This is currently only done for aliases and functions, but not for
562 /// variables (these details are set in EmitGlobalVarDefinition for variables).
563 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
564                                                     llvm::GlobalValue *GV) {
565   SetCommonAttributes(D, GV);
566 }
567
568 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
569                                               const CGFunctionInfo &Info,
570                                               llvm::Function *F) {
571   unsigned CallingConv;
572   AttributeListType AttributeList;
573   ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
574   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
575   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
576 }
577
578 /// Determines whether the language options require us to model
579 /// unwind exceptions.  We treat -fexceptions as mandating this
580 /// except under the fragile ObjC ABI with only ObjC exceptions
581 /// enabled.  This means, for example, that C with -fexceptions
582 /// enables this.
583 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
584   // If exceptions are completely disabled, obviously this is false.
585   if (!LangOpts.Exceptions) return false;
586
587   // If C++ exceptions are enabled, this is true.
588   if (LangOpts.CXXExceptions) return true;
589
590   // If ObjC exceptions are enabled, this depends on the ABI.
591   if (LangOpts.ObjCExceptions) {
592     return LangOpts.ObjCRuntime.hasUnwindExceptions();
593   }
594
595   return true;
596 }
597
598 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
599                                                            llvm::Function *F) {
600   if (CodeGenOpts.UnwindTables)
601     F->setHasUWTable();
602
603   if (!hasUnwindExceptions(LangOpts))
604     F->addFnAttr(llvm::Attribute::NoUnwind);
605
606   if (D->hasAttr<NakedAttr>()) {
607     // Naked implies noinline: we should not be inlining such functions.
608     F->addFnAttr(llvm::Attribute::Naked);
609     F->addFnAttr(llvm::Attribute::NoInline);
610   }
611
612   if (D->hasAttr<NoInlineAttr>())
613     F->addFnAttr(llvm::Attribute::NoInline);
614
615   // (noinline wins over always_inline, and we can't specify both in IR)
616   if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
617       !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
618                                        llvm::Attribute::NoInline))
619     F->addFnAttr(llvm::Attribute::AlwaysInline);
620
621   // FIXME: Communicate hot and cold attributes to LLVM more directly.
622   if (D->hasAttr<ColdAttr>())
623     F->addFnAttr(llvm::Attribute::OptimizeForSize);
624
625   if (D->hasAttr<MinSizeAttr>())
626     F->addFnAttr(llvm::Attribute::MinSize);
627
628   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
629     F->setUnnamedAddr(true);
630
631   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
632     if (MD->isVirtual())
633       F->setUnnamedAddr(true);
634
635   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
636     F->addFnAttr(llvm::Attribute::StackProtect);
637   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
638     F->addFnAttr(llvm::Attribute::StackProtectReq);
639
640   // Add sanitizer attributes if function is not blacklisted.
641   if (!SanitizerBlacklist.isIn(*F)) {
642     // When AddressSanitizer is enabled, set SanitizeAddress attribute
643     // unless __attribute__((no_sanitize_address)) is used.
644     if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
645       F->addFnAttr(llvm::Attribute::SanitizeAddress);
646     // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
647     if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
648       F->addFnAttr(llvm::Attribute::SanitizeThread);
649     }
650     // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
651     if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
652       F->addFnAttr(llvm::Attribute::SanitizeMemory);
653   }
654
655   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
656   if (alignment)
657     F->setAlignment(alignment);
658
659   // C++ ABI requires 2-byte alignment for member functions.
660   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
661     F->setAlignment(2);
662 }
663
664 void CodeGenModule::SetCommonAttributes(const Decl *D,
665                                         llvm::GlobalValue *GV) {
666   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
667     setGlobalVisibility(GV, ND);
668   else
669     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
670
671   if (D->hasAttr<UsedAttr>())
672     AddUsedGlobal(GV);
673
674   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
675     GV->setSection(SA->getName());
676
677   // Alias cannot have attributes. Filter them here.
678   if (!isa<llvm::GlobalAlias>(GV))
679     getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
680 }
681
682 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
683                                                   llvm::Function *F,
684                                                   const CGFunctionInfo &FI) {
685   SetLLVMFunctionAttributes(D, FI, F);
686   SetLLVMFunctionAttributesForDefinition(D, F);
687
688   F->setLinkage(llvm::Function::InternalLinkage);
689
690   SetCommonAttributes(D, F);
691 }
692
693 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
694                                           llvm::Function *F,
695                                           bool IsIncompleteFunction) {
696   if (unsigned IID = F->getIntrinsicID()) {
697     // If this is an intrinsic function, set the function's attributes
698     // to the intrinsic's attributes.
699     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
700                                                     (llvm::Intrinsic::ID)IID));
701     return;
702   }
703
704   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
705
706   if (!IsIncompleteFunction)
707     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
708
709   // Only a few attributes are set on declarations; these may later be
710   // overridden by a definition.
711
712   if (FD->hasAttr<DLLImportAttr>()) {
713     F->setLinkage(llvm::Function::DLLImportLinkage);
714   } else if (FD->hasAttr<WeakAttr>() ||
715              FD->isWeakImported()) {
716     // "extern_weak" is overloaded in LLVM; we probably should have
717     // separate linkage types for this.
718     F->setLinkage(llvm::Function::ExternalWeakLinkage);
719   } else {
720     F->setLinkage(llvm::Function::ExternalLinkage);
721
722     LinkageInfo LV = FD->getLinkageAndVisibility();
723     if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
724       F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
725     }
726   }
727
728   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
729     F->setSection(SA->getName());
730 }
731
732 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
733   assert(!GV->isDeclaration() &&
734          "Only globals with definition can force usage.");
735   LLVMUsed.push_back(GV);
736 }
737
738 void CodeGenModule::EmitLLVMUsed() {
739   // Don't create llvm.used if there is no need.
740   if (LLVMUsed.empty())
741     return;
742
743   // Convert LLVMUsed to what ConstantArray needs.
744   SmallVector<llvm::Constant*, 8> UsedArray;
745   UsedArray.resize(LLVMUsed.size());
746   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
747     UsedArray[i] =
748      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
749                                     Int8PtrTy);
750   }
751
752   if (UsedArray.empty())
753     return;
754   llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
755
756   llvm::GlobalVariable *GV =
757     new llvm::GlobalVariable(getModule(), ATy, false,
758                              llvm::GlobalValue::AppendingLinkage,
759                              llvm::ConstantArray::get(ATy, UsedArray),
760                              "llvm.used");
761
762   GV->setSection("llvm.metadata");
763 }
764
765 /// \brief Add link options implied by the given module, including modules
766 /// it depends on, using a postorder walk.
767 static void addLinkOptionsPostorder(llvm::LLVMContext &Context,
768                                     Module *Mod,
769                                     SmallVectorImpl<llvm::Value *> &Metadata,
770                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
771   // Import this module's parent.
772   if (Mod->Parent && Visited.insert(Mod->Parent)) {
773     addLinkOptionsPostorder(Context, Mod->Parent, Metadata, Visited);
774   }
775
776   // Import this module's dependencies.
777   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
778     if (Visited.insert(Mod->Imports[I-1]))
779       addLinkOptionsPostorder(Context, Mod->Imports[I-1], Metadata, Visited);
780   }
781
782   // Add linker options to link against the libraries/frameworks
783   // described by this module.
784   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
785     // FIXME: -lfoo is Unix-centric and -framework Foo is Darwin-centric.
786     // We need to know more about the linker to know how to encode these
787     // options propertly.
788
789     // Link against a framework.
790     if (Mod->LinkLibraries[I-1].IsFramework) {
791       llvm::Value *Args[2] = {
792         llvm::MDString::get(Context, "-framework"),
793         llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
794       };
795
796       Metadata.push_back(llvm::MDNode::get(Context, Args));
797       continue;
798     }
799
800     // Link against a library.
801     llvm::Value *OptString
802     = llvm::MDString::get(Context,
803                           "-l" + Mod->LinkLibraries[I-1].Library);
804     Metadata.push_back(llvm::MDNode::get(Context, OptString));
805   }
806 }
807
808 void CodeGenModule::EmitModuleLinkOptions() {
809   // Collect the set of all of the modules we want to visit to emit link
810   // options, which is essentially the imported modules and all of their
811   // non-explicit child modules.
812   llvm::SetVector<clang::Module *> LinkModules;
813   llvm::SmallPtrSet<clang::Module *, 16> Visited;
814   SmallVector<clang::Module *, 16> Stack;
815
816   // Seed the stack with imported modules.
817   for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
818                                                MEnd = ImportedModules.end();
819        M != MEnd; ++M) {
820     if (Visited.insert(*M))
821       Stack.push_back(*M);
822   }
823
824   // Find all of the modules to import, making a little effort to prune
825   // non-leaf modules.
826   while (!Stack.empty()) {
827     clang::Module *Mod = Stack.back();
828     Stack.pop_back();
829
830     bool AnyChildren = false;
831
832     // Visit the submodules of this module.
833     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
834                                         SubEnd = Mod->submodule_end();
835          Sub != SubEnd; ++Sub) {
836       // Skip explicit children; they need to be explicitly imported to be
837       // linked against.
838       if ((*Sub)->IsExplicit)
839         continue;
840
841       if (Visited.insert(*Sub)) {
842         Stack.push_back(*Sub);
843         AnyChildren = true;
844       }
845     }
846
847     // We didn't find any children, so add this module to the list of
848     // modules to link against.
849     if (!AnyChildren) {
850       LinkModules.insert(Mod);
851     }
852   }
853
854   // Add link options for all of the imported modules in reverse topological
855   // order.
856   SmallVector<llvm::Value *, 16> MetadataArgs;
857   Visited.clear();
858   for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
859                                                MEnd = LinkModules.end();
860        M != MEnd; ++M) {
861     if (Visited.insert(*M))
862       addLinkOptionsPostorder(getLLVMContext(), *M, MetadataArgs, Visited);
863   }
864   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
865
866   // Add the linker options metadata flag.
867   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
868                             llvm::MDNode::get(getLLVMContext(), MetadataArgs));
869 }
870
871 void CodeGenModule::EmitDeferred() {
872   // Emit code for any potentially referenced deferred decls.  Since a
873   // previously unused static decl may become used during the generation of code
874   // for a static function, iterate until no changes are made.
875
876   while (true) {
877     if (!DeferredVTables.empty()) {
878       EmitDeferredVTables();
879
880       // Emitting a v-table doesn't directly cause more v-tables to
881       // become deferred, although it can cause functions to be
882       // emitted that then need those v-tables.
883       assert(DeferredVTables.empty());
884     }
885
886     // Stop if we're out of both deferred v-tables and deferred declarations.
887     if (DeferredDeclsToEmit.empty()) break;
888
889     GlobalDecl D = DeferredDeclsToEmit.back();
890     DeferredDeclsToEmit.pop_back();
891
892     // Check to see if we've already emitted this.  This is necessary
893     // for a couple of reasons: first, decls can end up in the
894     // deferred-decls queue multiple times, and second, decls can end
895     // up with definitions in unusual ways (e.g. by an extern inline
896     // function acquiring a strong function redefinition).  Just
897     // ignore these cases.
898     //
899     // TODO: That said, looking this up multiple times is very wasteful.
900     StringRef Name = getMangledName(D);
901     llvm::GlobalValue *CGRef = GetGlobalValue(Name);
902     assert(CGRef && "Deferred decl wasn't referenced?");
903
904     if (!CGRef->isDeclaration())
905       continue;
906
907     // GlobalAlias::isDeclaration() defers to the aliasee, but for our
908     // purposes an alias counts as a definition.
909     if (isa<llvm::GlobalAlias>(CGRef))
910       continue;
911
912     // Otherwise, emit the definition and move on to the next one.
913     EmitGlobalDefinition(D);
914   }
915 }
916
917 void CodeGenModule::EmitGlobalAnnotations() {
918   if (Annotations.empty())
919     return;
920
921   // Create a new global variable for the ConstantStruct in the Module.
922   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
923     Annotations[0]->getType(), Annotations.size()), Annotations);
924   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
925     Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
926     "llvm.global.annotations");
927   gv->setSection(AnnotationSection);
928 }
929
930 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
931   llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
932   if (i != AnnotationStrings.end())
933     return i->second;
934
935   // Not found yet, create a new global.
936   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
937   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
938     true, llvm::GlobalValue::PrivateLinkage, s, ".str");
939   gv->setSection(AnnotationSection);
940   gv->setUnnamedAddr(true);
941   AnnotationStrings[Str] = gv;
942   return gv;
943 }
944
945 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
946   SourceManager &SM = getContext().getSourceManager();
947   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
948   if (PLoc.isValid())
949     return EmitAnnotationString(PLoc.getFilename());
950   return EmitAnnotationString(SM.getBufferName(Loc));
951 }
952
953 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
954   SourceManager &SM = getContext().getSourceManager();
955   PresumedLoc PLoc = SM.getPresumedLoc(L);
956   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
957     SM.getExpansionLineNumber(L);
958   return llvm::ConstantInt::get(Int32Ty, LineNo);
959 }
960
961 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
962                                                 const AnnotateAttr *AA,
963                                                 SourceLocation L) {
964   // Get the globals for file name, annotation, and the line number.
965   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
966                  *UnitGV = EmitAnnotationUnit(L),
967                  *LineNoCst = EmitAnnotationLineNo(L);
968
969   // Create the ConstantStruct for the global annotation.
970   llvm::Constant *Fields[4] = {
971     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
972     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
973     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
974     LineNoCst
975   };
976   return llvm::ConstantStruct::getAnon(Fields);
977 }
978
979 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
980                                          llvm::GlobalValue *GV) {
981   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
982   // Get the struct elements for these annotations.
983   for (specific_attr_iterator<AnnotateAttr>
984        ai = D->specific_attr_begin<AnnotateAttr>(),
985        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
986     Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
987 }
988
989 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
990   // Never defer when EmitAllDecls is specified.
991   if (LangOpts.EmitAllDecls)
992     return false;
993
994   return !getContext().DeclMustBeEmitted(Global);
995 }
996
997 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
998     const CXXUuidofExpr* E) {
999   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1000   // well-formed.
1001   StringRef Uuid;
1002   if (E->isTypeOperand())
1003     Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
1004   else {
1005     // Special case: __uuidof(0) means an all-zero GUID.
1006     Expr *Op = E->getExprOperand();
1007     if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1008       Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
1009     else
1010       Uuid = "00000000-0000-0000-0000-000000000000";
1011   }
1012   std::string Name = "__uuid_" + Uuid.str();
1013
1014   // Look for an existing global.
1015   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1016     return GV;
1017
1018   llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1019   assert(Init && "failed to initialize as constant");
1020
1021   // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
1022   // first field is declared as "long", which for many targets is 8 bytes.
1023   // Those architectures are not supported. (With the MS abi, long is always 4
1024   // bytes.)
1025   llvm::Type *GuidType = getTypes().ConvertType(E->getType());
1026   if (Init->getType() != GuidType) {
1027     DiagnosticsEngine &Diags = getDiags();
1028     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1029         "__uuidof codegen is not supported on this architecture");
1030     Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
1031     Init = llvm::UndefValue::get(GuidType);
1032   }
1033
1034   llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
1035       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
1036   GV->setUnnamedAddr(true);
1037   return GV;
1038 }
1039
1040 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1041   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1042   assert(AA && "No alias?");
1043
1044   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1045
1046   // See if there is already something with the target's name in the module.
1047   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1048   if (Entry) {
1049     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1050     return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1051   }
1052
1053   llvm::Constant *Aliasee;
1054   if (isa<llvm::FunctionType>(DeclTy))
1055     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1056                                       GlobalDecl(cast<FunctionDecl>(VD)),
1057                                       /*ForVTable=*/false);
1058   else
1059     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1060                                     llvm::PointerType::getUnqual(DeclTy), 0);
1061
1062   llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1063   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1064   WeakRefReferences.insert(F);
1065
1066   return Aliasee;
1067 }
1068
1069 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1070   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
1071
1072   // Weak references don't produce any output by themselves.
1073   if (Global->hasAttr<WeakRefAttr>())
1074     return;
1075
1076   // If this is an alias definition (which otherwise looks like a declaration)
1077   // emit it now.
1078   if (Global->hasAttr<AliasAttr>())
1079     return EmitAliasDefinition(GD);
1080
1081   // If this is CUDA, be selective about which declarations we emit.
1082   if (LangOpts.CUDA) {
1083     if (CodeGenOpts.CUDAIsDevice) {
1084       if (!Global->hasAttr<CUDADeviceAttr>() &&
1085           !Global->hasAttr<CUDAGlobalAttr>() &&
1086           !Global->hasAttr<CUDAConstantAttr>() &&
1087           !Global->hasAttr<CUDASharedAttr>())
1088         return;
1089     } else {
1090       if (!Global->hasAttr<CUDAHostAttr>() && (
1091             Global->hasAttr<CUDADeviceAttr>() ||
1092             Global->hasAttr<CUDAConstantAttr>() ||
1093             Global->hasAttr<CUDASharedAttr>()))
1094         return;
1095     }
1096   }
1097
1098   // Ignore declarations, they will be emitted on their first use.
1099   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
1100     // Forward declarations are emitted lazily on first use.
1101     if (!FD->doesThisDeclarationHaveABody()) {
1102       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1103         return;
1104
1105       const FunctionDecl *InlineDefinition = 0;
1106       FD->getBody(InlineDefinition);
1107
1108       StringRef MangledName = getMangledName(GD);
1109       DeferredDecls.erase(MangledName);
1110       EmitGlobalDefinition(InlineDefinition);
1111       return;
1112     }
1113   } else {
1114     const VarDecl *VD = cast<VarDecl>(Global);
1115     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1116
1117     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
1118       return;
1119   }
1120
1121   // Defer code generation when possible if this is a static definition, inline
1122   // function etc.  These we only want to emit if they are used.
1123   if (!MayDeferGeneration(Global)) {
1124     // Emit the definition if it can't be deferred.
1125     EmitGlobalDefinition(GD);
1126     return;
1127   }
1128
1129   // If we're deferring emission of a C++ variable with an
1130   // initializer, remember the order in which it appeared in the file.
1131   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1132       cast<VarDecl>(Global)->hasInit()) {
1133     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1134     CXXGlobalInits.push_back(0);
1135   }
1136   
1137   // If the value has already been used, add it directly to the
1138   // DeferredDeclsToEmit list.
1139   StringRef MangledName = getMangledName(GD);
1140   if (GetGlobalValue(MangledName))
1141     DeferredDeclsToEmit.push_back(GD);
1142   else {
1143     // Otherwise, remember that we saw a deferred decl with this name.  The
1144     // first use of the mangled name will cause it to move into
1145     // DeferredDeclsToEmit.
1146     DeferredDecls[MangledName] = GD;
1147   }
1148 }
1149
1150 namespace {
1151   struct FunctionIsDirectlyRecursive :
1152     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1153     const StringRef Name;
1154     const Builtin::Context &BI;
1155     bool Result;
1156     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1157       Name(N), BI(C), Result(false) {
1158     }
1159     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1160
1161     bool TraverseCallExpr(CallExpr *E) {
1162       const FunctionDecl *FD = E->getDirectCallee();
1163       if (!FD)
1164         return true;
1165       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1166       if (Attr && Name == Attr->getLabel()) {
1167         Result = true;
1168         return false;
1169       }
1170       unsigned BuiltinID = FD->getBuiltinID();
1171       if (!BuiltinID)
1172         return true;
1173       StringRef BuiltinName = BI.GetName(BuiltinID);
1174       if (BuiltinName.startswith("__builtin_") &&
1175           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1176         Result = true;
1177         return false;
1178       }
1179       return true;
1180     }
1181   };
1182 }
1183
1184 // isTriviallyRecursive - Check if this function calls another
1185 // decl that, because of the asm attribute or the other decl being a builtin,
1186 // ends up pointing to itself.
1187 bool
1188 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1189   StringRef Name;
1190   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1191     // asm labels are a special kind of mangling we have to support.
1192     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1193     if (!Attr)
1194       return false;
1195     Name = Attr->getLabel();
1196   } else {
1197     Name = FD->getName();
1198   }
1199
1200   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1201   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1202   return Walker.Result;
1203 }
1204
1205 bool
1206 CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
1207   if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
1208     return true;
1209   if (CodeGenOpts.OptimizationLevel == 0 &&
1210       !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
1211     return false;
1212   // PR9614. Avoid cases where the source code is lying to us. An available
1213   // externally function should have an equivalent function somewhere else,
1214   // but a function that calls itself is clearly not equivalent to the real
1215   // implementation.
1216   // This happens in glibc's btowc and in some configure checks.
1217   return !isTriviallyRecursive(F);
1218 }
1219
1220 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
1221   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1222
1223   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 
1224                                  Context.getSourceManager(),
1225                                  "Generating code for declaration");
1226   
1227   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1228     // At -O0, don't generate IR for functions with available_externally 
1229     // linkage.
1230     if (!shouldEmitFunction(Function))
1231       return;
1232
1233     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1234       // Make sure to emit the definition(s) before we emit the thunks.
1235       // This is necessary for the generation of certain thunks.
1236       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1237         EmitCXXConstructor(CD, GD.getCtorType());
1238       else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1239         EmitCXXDestructor(DD, GD.getDtorType());
1240       else
1241         EmitGlobalFunctionDefinition(GD);
1242
1243       if (Method->isVirtual())
1244         getVTables().EmitThunks(GD);
1245
1246       return;
1247     }
1248
1249     return EmitGlobalFunctionDefinition(GD);
1250   }
1251   
1252   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1253     return EmitGlobalVarDefinition(VD);
1254   
1255   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1256 }
1257
1258 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1259 /// module, create and return an llvm Function with the specified type. If there
1260 /// is something in the module with the specified name, return it potentially
1261 /// bitcasted to the right type.
1262 ///
1263 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1264 /// to set the attributes on the function when it is first created.
1265 llvm::Constant *
1266 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1267                                        llvm::Type *Ty,
1268                                        GlobalDecl D, bool ForVTable,
1269                                        llvm::AttributeSet ExtraAttrs) {
1270   // Lookup the entry, lazily creating it if necessary.
1271   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1272   if (Entry) {
1273     if (WeakRefReferences.erase(Entry)) {
1274       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1275       if (FD && !FD->hasAttr<WeakAttr>())
1276         Entry->setLinkage(llvm::Function::ExternalLinkage);
1277     }
1278
1279     if (Entry->getType()->getElementType() == Ty)
1280       return Entry;
1281
1282     // Make sure the result is of the correct type.
1283     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1284   }
1285
1286   // This function doesn't have a complete type (for example, the return
1287   // type is an incomplete struct). Use a fake type instead, and make
1288   // sure not to try to set attributes.
1289   bool IsIncompleteFunction = false;
1290
1291   llvm::FunctionType *FTy;
1292   if (isa<llvm::FunctionType>(Ty)) {
1293     FTy = cast<llvm::FunctionType>(Ty);
1294   } else {
1295     FTy = llvm::FunctionType::get(VoidTy, false);
1296     IsIncompleteFunction = true;
1297   }
1298   
1299   llvm::Function *F = llvm::Function::Create(FTy,
1300                                              llvm::Function::ExternalLinkage,
1301                                              MangledName, &getModule());
1302   assert(F->getName() == MangledName && "name was uniqued!");
1303   if (D.getDecl())
1304     SetFunctionAttributes(D, F, IsIncompleteFunction);
1305   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1306     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1307     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1308                      llvm::AttributeSet::get(VMContext,
1309                                              llvm::AttributeSet::FunctionIndex,
1310                                              B));
1311   }
1312
1313   // This is the first use or definition of a mangled name.  If there is a
1314   // deferred decl with this name, remember that we need to emit it at the end
1315   // of the file.
1316   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1317   if (DDI != DeferredDecls.end()) {
1318     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1319     // list, and remove it from DeferredDecls (since we don't need it anymore).
1320     DeferredDeclsToEmit.push_back(DDI->second);
1321     DeferredDecls.erase(DDI);
1322
1323   // Otherwise, there are cases we have to worry about where we're
1324   // using a declaration for which we must emit a definition but where
1325   // we might not find a top-level definition:
1326   //   - member functions defined inline in their classes
1327   //   - friend functions defined inline in some class
1328   //   - special member functions with implicit definitions
1329   // If we ever change our AST traversal to walk into class methods,
1330   // this will be unnecessary.
1331   //
1332   // We also don't emit a definition for a function if it's going to be an entry
1333   // in a vtable, unless it's already marked as used.
1334   } else if (getLangOpts().CPlusPlus && D.getDecl()) {
1335     // Look for a declaration that's lexically in a record.
1336     const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1337     FD = FD->getMostRecentDecl();
1338     do {
1339       if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1340         if (FD->isImplicit() && !ForVTable) {
1341           assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1342           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1343           break;
1344         } else if (FD->doesThisDeclarationHaveABody()) {
1345           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1346           break;
1347         }
1348       }
1349       FD = FD->getPreviousDecl();
1350     } while (FD);
1351   }
1352
1353   // Make sure the result is of the requested type.
1354   if (!IsIncompleteFunction) {
1355     assert(F->getType()->getElementType() == Ty);
1356     return F;
1357   }
1358
1359   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1360   return llvm::ConstantExpr::getBitCast(F, PTy);
1361 }
1362
1363 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1364 /// non-null, then this function will use the specified type if it has to
1365 /// create it (this occurs when we see a definition of the function).
1366 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1367                                                  llvm::Type *Ty,
1368                                                  bool ForVTable) {
1369   // If there was no specific requested type, just convert it now.
1370   if (!Ty)
1371     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1372   
1373   StringRef MangledName = getMangledName(GD);
1374   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1375 }
1376
1377 /// CreateRuntimeFunction - Create a new runtime function with the specified
1378 /// type and name.
1379 llvm::Constant *
1380 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1381                                      StringRef Name,
1382                                      llvm::AttributeSet ExtraAttrs) {
1383   llvm::Constant *C
1384     = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1385                               ExtraAttrs);
1386   if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1387     if (F->empty())
1388       F->setCallingConv(getRuntimeCC());
1389   return C;
1390 }
1391
1392 /// isTypeConstant - Determine whether an object of this type can be emitted
1393 /// as a constant.
1394 ///
1395 /// If ExcludeCtor is true, the duration when the object's constructor runs
1396 /// will not be considered. The caller will need to verify that the object is
1397 /// not written to during its construction.
1398 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1399   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1400     return false;
1401
1402   if (Context.getLangOpts().CPlusPlus) {
1403     if (const CXXRecordDecl *Record
1404           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1405       return ExcludeCtor && !Record->hasMutableFields() &&
1406              Record->hasTrivialDestructor();
1407   }
1408
1409   return true;
1410 }
1411
1412 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1413 /// create and return an llvm GlobalVariable with the specified type.  If there
1414 /// is something in the module with the specified name, return it potentially
1415 /// bitcasted to the right type.
1416 ///
1417 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1418 /// to set the attributes on the global when it is first created.
1419 llvm::Constant *
1420 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1421                                      llvm::PointerType *Ty,
1422                                      const VarDecl *D,
1423                                      bool UnnamedAddr) {
1424   // Lookup the entry, lazily creating it if necessary.
1425   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1426   if (Entry) {
1427     if (WeakRefReferences.erase(Entry)) {
1428       if (D && !D->hasAttr<WeakAttr>())
1429         Entry->setLinkage(llvm::Function::ExternalLinkage);
1430     }
1431
1432     if (UnnamedAddr)
1433       Entry->setUnnamedAddr(true);
1434
1435     if (Entry->getType() == Ty)
1436       return Entry;
1437
1438     // Make sure the result is of the correct type.
1439     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1440   }
1441
1442   // This is the first use or definition of a mangled name.  If there is a
1443   // deferred decl with this name, remember that we need to emit it at the end
1444   // of the file.
1445   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1446   if (DDI != DeferredDecls.end()) {
1447     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1448     // list, and remove it from DeferredDecls (since we don't need it anymore).
1449     DeferredDeclsToEmit.push_back(DDI->second);
1450     DeferredDecls.erase(DDI);
1451   }
1452
1453   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1454   llvm::GlobalVariable *GV =
1455     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1456                              llvm::GlobalValue::ExternalLinkage,
1457                              0, MangledName, 0,
1458                              llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1459
1460   // Handle things which are present even on external declarations.
1461   if (D) {
1462     // FIXME: This code is overly simple and should be merged with other global
1463     // handling.
1464     GV->setConstant(isTypeConstant(D->getType(), false));
1465
1466     // Set linkage and visibility in case we never see a definition.
1467     LinkageInfo LV = D->getLinkageAndVisibility();
1468     if (LV.getLinkage() != ExternalLinkage) {
1469       // Don't set internal linkage on declarations.
1470     } else {
1471       if (D->hasAttr<DLLImportAttr>())
1472         GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1473       else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1474         GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1475
1476       // Set visibility on a declaration only if it's explicit.
1477       if (LV.isVisibilityExplicit())
1478         GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1479     }
1480
1481     if (D->getTLSKind()) {
1482       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1483         CXXThreadLocals.push_back(std::make_pair(D, GV));
1484       setTLSMode(GV, *D);
1485     }
1486   }
1487
1488   if (AddrSpace != Ty->getAddressSpace())
1489     return llvm::ConstantExpr::getBitCast(GV, Ty);
1490   else
1491     return GV;
1492 }
1493
1494
1495 llvm::GlobalVariable *
1496 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 
1497                                       llvm::Type *Ty,
1498                                       llvm::GlobalValue::LinkageTypes Linkage) {
1499   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1500   llvm::GlobalVariable *OldGV = 0;
1501
1502   
1503   if (GV) {
1504     // Check if the variable has the right type.
1505     if (GV->getType()->getElementType() == Ty)
1506       return GV;
1507
1508     // Because C++ name mangling, the only way we can end up with an already
1509     // existing global with the same name is if it has been declared extern "C".
1510     assert(GV->isDeclaration() && "Declaration has wrong type!");
1511     OldGV = GV;
1512   }
1513   
1514   // Create a new variable.
1515   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1516                                 Linkage, 0, Name);
1517   
1518   if (OldGV) {
1519     // Replace occurrences of the old variable if needed.
1520     GV->takeName(OldGV);
1521     
1522     if (!OldGV->use_empty()) {
1523       llvm::Constant *NewPtrForOldDecl =
1524       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1525       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1526     }
1527     
1528     OldGV->eraseFromParent();
1529   }
1530   
1531   return GV;
1532 }
1533
1534 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1535 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1536 /// then it will be created with the specified type instead of whatever the
1537 /// normal requested type would be.
1538 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1539                                                   llvm::Type *Ty) {
1540   assert(D->hasGlobalStorage() && "Not a global variable");
1541   QualType ASTTy = D->getType();
1542   if (Ty == 0)
1543     Ty = getTypes().ConvertTypeForMem(ASTTy);
1544
1545   llvm::PointerType *PTy =
1546     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1547
1548   StringRef MangledName = getMangledName(D);
1549   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1550 }
1551
1552 /// CreateRuntimeVariable - Create a new runtime global variable with the
1553 /// specified type and name.
1554 llvm::Constant *
1555 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1556                                      StringRef Name) {
1557   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1558                                true);
1559 }
1560
1561 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1562   assert(!D->getInit() && "Cannot emit definite definitions here!");
1563
1564   if (MayDeferGeneration(D)) {
1565     // If we have not seen a reference to this variable yet, place it
1566     // into the deferred declarations table to be emitted if needed
1567     // later.
1568     StringRef MangledName = getMangledName(D);
1569     if (!GetGlobalValue(MangledName)) {
1570       DeferredDecls[MangledName] = D;
1571       return;
1572     }
1573   }
1574
1575   // The tentative definition is the only definition.
1576   EmitGlobalVarDefinition(D);
1577 }
1578
1579 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1580     return Context.toCharUnitsFromBits(
1581       TheDataLayout.getTypeStoreSizeInBits(Ty));
1582 }
1583
1584 llvm::Constant *
1585 CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1586                                                        const Expr *rawInit) {
1587   ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1588   if (const ExprWithCleanups *withCleanups =
1589           dyn_cast<ExprWithCleanups>(rawInit)) {
1590     cleanups = withCleanups->getObjects();
1591     rawInit = withCleanups->getSubExpr();
1592   }
1593
1594   const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1595   if (!init || !init->initializesStdInitializerList() ||
1596       init->getNumInits() == 0)
1597     return 0;
1598
1599   ASTContext &ctx = getContext();
1600   unsigned numInits = init->getNumInits();
1601   // FIXME: This check is here because we would otherwise silently miscompile
1602   // nested global std::initializer_lists. Better would be to have a real
1603   // implementation.
1604   for (unsigned i = 0; i < numInits; ++i) {
1605     const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1606     if (inner && inner->initializesStdInitializerList()) {
1607       ErrorUnsupported(inner, "nested global std::initializer_list");
1608       return 0;
1609     }
1610   }
1611
1612   // Synthesize a fake VarDecl for the array and initialize that.
1613   QualType elementType = init->getInit(0)->getType();
1614   llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1615   QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1616                                                 ArrayType::Normal, 0);
1617
1618   IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1619   TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1620                                               arrayType, D->getLocation());
1621   VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1622                                                           D->getDeclContext()),
1623                                           D->getLocStart(), D->getLocation(),
1624                                           name, arrayType, sourceInfo,
1625                                           SC_Static);
1626   backingArray->setTSCSpec(D->getTSCSpec());
1627
1628   // Now clone the InitListExpr to initialize the array instead.
1629   // Incredible hack: we want to use the existing InitListExpr here, so we need
1630   // to tell it that it no longer initializes a std::initializer_list.
1631   ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
1632                         init->getNumInits());
1633   Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
1634                                            init->getRBraceLoc());
1635   arrayInit->setType(arrayType);
1636
1637   if (!cleanups.empty())
1638     arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1639
1640   backingArray->setInit(arrayInit);
1641
1642   // Emit the definition of the array.
1643   EmitGlobalVarDefinition(backingArray);
1644
1645   // Inspect the initializer list to validate it and determine its type.
1646   // FIXME: doing this every time is probably inefficient; caching would be nice
1647   RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1648   RecordDecl::field_iterator field = record->field_begin();
1649   if (field == record->field_end()) {
1650     ErrorUnsupported(D, "weird std::initializer_list");
1651     return 0;
1652   }
1653   QualType elementPtr = ctx.getPointerType(elementType.withConst());
1654   // Start pointer.
1655   if (!ctx.hasSameType(field->getType(), elementPtr)) {
1656     ErrorUnsupported(D, "weird std::initializer_list");
1657     return 0;
1658   }
1659   ++field;
1660   if (field == record->field_end()) {
1661     ErrorUnsupported(D, "weird std::initializer_list");
1662     return 0;
1663   }
1664   bool isStartEnd = false;
1665   if (ctx.hasSameType(field->getType(), elementPtr)) {
1666     // End pointer.
1667     isStartEnd = true;
1668   } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1669     ErrorUnsupported(D, "weird std::initializer_list");
1670     return 0;
1671   }
1672
1673   // Now build an APValue representing the std::initializer_list.
1674   APValue initListValue(APValue::UninitStruct(), 0, 2);
1675   APValue &startField = initListValue.getStructField(0);
1676   APValue::LValuePathEntry startOffsetPathEntry;
1677   startOffsetPathEntry.ArrayIndex = 0;
1678   startField = APValue(APValue::LValueBase(backingArray),
1679                        CharUnits::fromQuantity(0),
1680                        llvm::makeArrayRef(startOffsetPathEntry),
1681                        /*IsOnePastTheEnd=*/false, 0);
1682
1683   if (isStartEnd) {
1684     APValue &endField = initListValue.getStructField(1);
1685     APValue::LValuePathEntry endOffsetPathEntry;
1686     endOffsetPathEntry.ArrayIndex = numInits;
1687     endField = APValue(APValue::LValueBase(backingArray),
1688                        ctx.getTypeSizeInChars(elementType) * numInits,
1689                        llvm::makeArrayRef(endOffsetPathEntry),
1690                        /*IsOnePastTheEnd=*/true, 0);
1691   } else {
1692     APValue &sizeField = initListValue.getStructField(1);
1693     sizeField = APValue(llvm::APSInt(numElements));
1694   }
1695
1696   // Emit the constant for the initializer_list.
1697   llvm::Constant *llvmInit =
1698       EmitConstantValueForMemory(initListValue, D->getType());
1699   assert(llvmInit && "failed to initialize as constant");
1700   return llvmInit;
1701 }
1702
1703 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1704                                                  unsigned AddrSpace) {
1705   if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1706     if (D->hasAttr<CUDAConstantAttr>())
1707       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1708     else if (D->hasAttr<CUDASharedAttr>())
1709       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1710     else
1711       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1712   }
1713
1714   return AddrSpace;
1715 }
1716
1717 template<typename SomeDecl>
1718 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1719                                                llvm::GlobalValue *GV) {
1720   if (!getLangOpts().CPlusPlus)
1721     return;
1722
1723   // Must have 'used' attribute, or else inline assembly can't rely on
1724   // the name existing.
1725   if (!D->template hasAttr<UsedAttr>())
1726     return;
1727
1728   // Must have internal linkage and an ordinary name.
1729   if (!D->getIdentifier() || D->getLinkage() != InternalLinkage)
1730     return;
1731
1732   // Must be in an extern "C" context. Entities declared directly within
1733   // a record are not extern "C" even if the record is in such a context.
1734   const SomeDecl *First = D->getFirstDeclaration();
1735   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1736     return;
1737
1738   // OK, this is an internal linkage entity inside an extern "C" linkage
1739   // specification. Make a note of that so we can give it the "expected"
1740   // mangled name if nothing else is using that name.
1741   std::pair<StaticExternCMap::iterator, bool> R =
1742       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1743
1744   // If we have multiple internal linkage entities with the same name
1745   // in extern "C" regions, none of them gets that name.
1746   if (!R.second)
1747     R.first->second = 0;
1748 }
1749
1750 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1751   llvm::Constant *Init = 0;
1752   QualType ASTTy = D->getType();
1753   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1754   bool NeedsGlobalCtor = false;
1755   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1756
1757   const VarDecl *InitDecl;
1758   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1759
1760   if (!InitExpr) {
1761     // This is a tentative definition; tentative definitions are
1762     // implicitly initialized with { 0 }.
1763     //
1764     // Note that tentative definitions are only emitted at the end of
1765     // a translation unit, so they should never have incomplete
1766     // type. In addition, EmitTentativeDefinition makes sure that we
1767     // never attempt to emit a tentative definition if a real one
1768     // exists. A use may still exists, however, so we still may need
1769     // to do a RAUW.
1770     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1771     Init = EmitNullConstant(D->getType());
1772   } else {
1773     // If this is a std::initializer_list, emit the special initializer.
1774     Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1775     // An empty init list will perform zero-initialization, which happens
1776     // to be exactly what we want.
1777     // FIXME: It does so in a global constructor, which is *not* what we
1778     // want.
1779
1780     if (!Init) {
1781       initializedGlobalDecl = GlobalDecl(D);
1782       Init = EmitConstantInit(*InitDecl);
1783     }
1784     if (!Init) {
1785       QualType T = InitExpr->getType();
1786       if (D->getType()->isReferenceType())
1787         T = D->getType();
1788
1789       if (getLangOpts().CPlusPlus) {
1790         Init = EmitNullConstant(T);
1791         NeedsGlobalCtor = true;
1792       } else {
1793         ErrorUnsupported(D, "static initializer");
1794         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1795       }
1796     } else {
1797       // We don't need an initializer, so remove the entry for the delayed
1798       // initializer position (just in case this entry was delayed) if we
1799       // also don't need to register a destructor.
1800       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1801         DelayedCXXInitPosition.erase(D);
1802     }
1803   }
1804
1805   llvm::Type* InitType = Init->getType();
1806   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1807
1808   // Strip off a bitcast if we got one back.
1809   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1810     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1811            // all zero index gep.
1812            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1813     Entry = CE->getOperand(0);
1814   }
1815
1816   // Entry is now either a Function or GlobalVariable.
1817   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1818
1819   // We have a definition after a declaration with the wrong type.
1820   // We must make a new GlobalVariable* and update everything that used OldGV
1821   // (a declaration or tentative definition) with the new GlobalVariable*
1822   // (which will be a definition).
1823   //
1824   // This happens if there is a prototype for a global (e.g.
1825   // "extern int x[];") and then a definition of a different type (e.g.
1826   // "int x[10];"). This also happens when an initializer has a different type
1827   // from the type of the global (this happens with unions).
1828   if (GV == 0 ||
1829       GV->getType()->getElementType() != InitType ||
1830       GV->getType()->getAddressSpace() !=
1831        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1832
1833     // Move the old entry aside so that we'll create a new one.
1834     Entry->setName(StringRef());
1835
1836     // Make a new global with the correct type, this is now guaranteed to work.
1837     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1838
1839     // Replace all uses of the old global with the new global
1840     llvm::Constant *NewPtrForOldDecl =
1841         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1842     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1843
1844     // Erase the old global, since it is no longer used.
1845     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1846   }
1847
1848   MaybeHandleStaticInExternC(D, GV);
1849
1850   if (D->hasAttr<AnnotateAttr>())
1851     AddGlobalAnnotations(D, GV);
1852
1853   GV->setInitializer(Init);
1854
1855   // If it is safe to mark the global 'constant', do so now.
1856   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1857                   isTypeConstant(D->getType(), true));
1858
1859   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1860
1861   // Set the llvm linkage type as appropriate.
1862   llvm::GlobalValue::LinkageTypes Linkage = 
1863     GetLLVMLinkageVarDefinition(D, GV);
1864   GV->setLinkage(Linkage);
1865   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1866     // common vars aren't constant even if declared const.
1867     GV->setConstant(false);
1868
1869   SetCommonAttributes(D, GV);
1870
1871   // Emit the initializer function if necessary.
1872   if (NeedsGlobalCtor || NeedsGlobalDtor)
1873     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1874
1875   // If we are compiling with ASan, add metadata indicating dynamically
1876   // initialized globals.
1877   if (SanOpts.Address && NeedsGlobalCtor) {
1878     llvm::Module &M = getModule();
1879
1880     llvm::NamedMDNode *DynamicInitializers =
1881         M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1882     llvm::Value *GlobalToAdd[] = { GV };
1883     llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1884     DynamicInitializers->addOperand(ThisGlobal);
1885   }
1886
1887   // Emit global variable debug information.
1888   if (CGDebugInfo *DI = getModuleDebugInfo())
1889     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1890       DI->EmitGlobalVariable(GV, D);
1891 }
1892
1893 llvm::GlobalValue::LinkageTypes
1894 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1895                                            llvm::GlobalVariable *GV) {
1896   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1897   if (Linkage == GVA_Internal)
1898     return llvm::Function::InternalLinkage;
1899   else if (D->hasAttr<DLLImportAttr>())
1900     return llvm::Function::DLLImportLinkage;
1901   else if (D->hasAttr<DLLExportAttr>())
1902     return llvm::Function::DLLExportLinkage;
1903   else if (D->hasAttr<WeakAttr>()) {
1904     if (GV->isConstant())
1905       return llvm::GlobalVariable::WeakODRLinkage;
1906     else
1907       return llvm::GlobalVariable::WeakAnyLinkage;
1908   } else if (Linkage == GVA_TemplateInstantiation ||
1909              Linkage == GVA_ExplicitTemplateInstantiation)
1910     return llvm::GlobalVariable::WeakODRLinkage;
1911   else if (!getLangOpts().CPlusPlus && 
1912            ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1913              D->getAttr<CommonAttr>()) &&
1914            !D->hasExternalStorage() && !D->getInit() &&
1915            !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
1916            !D->getAttr<WeakImportAttr>()) {
1917     // Thread local vars aren't considered common linkage.
1918     return llvm::GlobalVariable::CommonLinkage;
1919   } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1920              getTarget().getTriple().isMacOSX())
1921     // On Darwin, the backing variable for a C++11 thread_local variable always
1922     // has internal linkage; all accesses should just be calls to the
1923     // Itanium-specified entry point, which has the normal linkage of the
1924     // variable.
1925     return llvm::GlobalValue::InternalLinkage;
1926   return llvm::GlobalVariable::ExternalLinkage;
1927 }
1928
1929 /// Replace the uses of a function that was declared with a non-proto type.
1930 /// We want to silently drop extra arguments from call sites
1931 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1932                                           llvm::Function *newFn) {
1933   // Fast path.
1934   if (old->use_empty()) return;
1935
1936   llvm::Type *newRetTy = newFn->getReturnType();
1937   SmallVector<llvm::Value*, 4> newArgs;
1938
1939   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1940          ui != ue; ) {
1941     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1942     llvm::User *user = *use;
1943
1944     // Recognize and replace uses of bitcasts.  Most calls to
1945     // unprototyped functions will use bitcasts.
1946     if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1947       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1948         replaceUsesOfNonProtoConstant(bitcast, newFn);
1949       continue;
1950     }
1951
1952     // Recognize calls to the function.
1953     llvm::CallSite callSite(user);
1954     if (!callSite) continue;
1955     if (!callSite.isCallee(use)) continue;
1956
1957     // If the return types don't match exactly, then we can't
1958     // transform this call unless it's dead.
1959     if (callSite->getType() != newRetTy && !callSite->use_empty())
1960       continue;
1961
1962     // Get the call site's attribute list.
1963     SmallVector<llvm::AttributeSet, 8> newAttrs;
1964     llvm::AttributeSet oldAttrs = callSite.getAttributes();
1965
1966     // Collect any return attributes from the call.
1967     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
1968       newAttrs.push_back(
1969         llvm::AttributeSet::get(newFn->getContext(),
1970                                 oldAttrs.getRetAttributes()));
1971
1972     // If the function was passed too few arguments, don't transform.
1973     unsigned newNumArgs = newFn->arg_size();
1974     if (callSite.arg_size() < newNumArgs) continue;
1975
1976     // If extra arguments were passed, we silently drop them.
1977     // If any of the types mismatch, we don't transform.
1978     unsigned argNo = 0;
1979     bool dontTransform = false;
1980     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1981            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1982       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1983         dontTransform = true;
1984         break;
1985       }
1986
1987       // Add any parameter attributes.
1988       if (oldAttrs.hasAttributes(argNo + 1))
1989         newAttrs.
1990           push_back(llvm::
1991                     AttributeSet::get(newFn->getContext(),
1992                                       oldAttrs.getParamAttributes(argNo + 1)));
1993     }
1994     if (dontTransform)
1995       continue;
1996
1997     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
1998       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
1999                                                  oldAttrs.getFnAttributes()));
2000
2001     // Okay, we can transform this.  Create the new call instruction and copy
2002     // over the required information.
2003     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2004
2005     llvm::CallSite newCall;
2006     if (callSite.isCall()) {
2007       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2008                                        callSite.getInstruction());
2009     } else {
2010       llvm::InvokeInst *oldInvoke =
2011         cast<llvm::InvokeInst>(callSite.getInstruction());
2012       newCall = llvm::InvokeInst::Create(newFn,
2013                                          oldInvoke->getNormalDest(),
2014                                          oldInvoke->getUnwindDest(),
2015                                          newArgs, "",
2016                                          callSite.getInstruction());
2017     }
2018     newArgs.clear(); // for the next iteration
2019
2020     if (!newCall->getType()->isVoidTy())
2021       newCall->takeName(callSite.getInstruction());
2022     newCall.setAttributes(
2023                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2024     newCall.setCallingConv(callSite.getCallingConv());
2025
2026     // Finally, remove the old call, replacing any uses with the new one.
2027     if (!callSite->use_empty())
2028       callSite->replaceAllUsesWith(newCall.getInstruction());
2029
2030     // Copy debug location attached to CI.
2031     if (!callSite->getDebugLoc().isUnknown())
2032       newCall->setDebugLoc(callSite->getDebugLoc());
2033     callSite->eraseFromParent();
2034   }
2035 }
2036
2037 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2038 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2039 /// existing call uses of the old function in the module, this adjusts them to
2040 /// call the new function directly.
2041 ///
2042 /// This is not just a cleanup: the always_inline pass requires direct calls to
2043 /// functions to be able to inline them.  If there is a bitcast in the way, it
2044 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2045 /// run at -O0.
2046 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2047                                                       llvm::Function *NewFn) {
2048   // If we're redefining a global as a function, don't transform it.
2049   if (!isa<llvm::Function>(Old)) return;
2050
2051   replaceUsesOfNonProtoConstant(Old, NewFn);
2052 }
2053
2054 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2055   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2056   // If we have a definition, this might be a deferred decl. If the
2057   // instantiation is explicit, make sure we emit it at the end.
2058   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2059     GetAddrOfGlobalVar(VD);
2060
2061   EmitTopLevelDecl(VD);
2062 }
2063
2064 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
2065   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2066
2067   // Compute the function info and LLVM type.
2068   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2069   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2070
2071   // Get or create the prototype for the function.
2072   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
2073
2074   // Strip off a bitcast if we got one back.
2075   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2076     assert(CE->getOpcode() == llvm::Instruction::BitCast);
2077     Entry = CE->getOperand(0);
2078   }
2079
2080
2081   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2082     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
2083
2084     // If the types mismatch then we have to rewrite the definition.
2085     assert(OldFn->isDeclaration() &&
2086            "Shouldn't replace non-declaration");
2087
2088     // F is the Function* for the one with the wrong type, we must make a new
2089     // Function* and update everything that used F (a declaration) with the new
2090     // Function* (which will be a definition).
2091     //
2092     // This happens if there is a prototype for a function
2093     // (e.g. "int f()") and then a definition of a different type
2094     // (e.g. "int f(int x)").  Move the old function aside so that it
2095     // doesn't interfere with GetAddrOfFunction.
2096     OldFn->setName(StringRef());
2097     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2098
2099     // This might be an implementation of a function without a
2100     // prototype, in which case, try to do special replacement of
2101     // calls which match the new prototype.  The really key thing here
2102     // is that we also potentially drop arguments from the call site
2103     // so as to make a direct call, which makes the inliner happier
2104     // and suppresses a number of optimizer warnings (!) about
2105     // dropping arguments.
2106     if (!OldFn->use_empty()) {
2107       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
2108       OldFn->removeDeadConstantUsers();
2109     }
2110
2111     // Replace uses of F with the Function we will endow with a body.
2112     if (!Entry->use_empty()) {
2113       llvm::Constant *NewPtrForOldDecl =
2114         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2115       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2116     }
2117
2118     // Ok, delete the old function now, which is dead.
2119     OldFn->eraseFromParent();
2120
2121     Entry = NewFn;
2122   }
2123
2124   // We need to set linkage and visibility on the function before
2125   // generating code for it because various parts of IR generation
2126   // want to propagate this information down (e.g. to local static
2127   // declarations).
2128   llvm::Function *Fn = cast<llvm::Function>(Entry);
2129   setFunctionLinkage(D, Fn);
2130
2131   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
2132   setGlobalVisibility(Fn, D);
2133
2134   MaybeHandleStaticInExternC(D, Fn);
2135
2136   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2137
2138   SetFunctionDefinitionAttributes(D, Fn);
2139   SetLLVMFunctionAttributesForDefinition(D, Fn);
2140
2141   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2142     AddGlobalCtor(Fn, CA->getPriority());
2143   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2144     AddGlobalDtor(Fn, DA->getPriority());
2145   if (D->hasAttr<AnnotateAttr>())
2146     AddGlobalAnnotations(D, Fn);
2147 }
2148
2149 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2150   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
2151   const AliasAttr *AA = D->getAttr<AliasAttr>();
2152   assert(AA && "Not an alias?");
2153
2154   StringRef MangledName = getMangledName(GD);
2155
2156   // If there is a definition in the module, then it wins over the alias.
2157   // This is dubious, but allow it to be safe.  Just ignore the alias.
2158   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2159   if (Entry && !Entry->isDeclaration())
2160     return;
2161
2162   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2163
2164   // Create a reference to the named value.  This ensures that it is emitted
2165   // if a deferred decl.
2166   llvm::Constant *Aliasee;
2167   if (isa<llvm::FunctionType>(DeclTy))
2168     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2169                                       /*ForVTable=*/false);
2170   else
2171     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2172                                     llvm::PointerType::getUnqual(DeclTy), 0);
2173
2174   // Create the new alias itself, but don't set a name yet.
2175   llvm::GlobalValue *GA =
2176     new llvm::GlobalAlias(Aliasee->getType(),
2177                           llvm::Function::ExternalLinkage,
2178                           "", Aliasee, &getModule());
2179
2180   if (Entry) {
2181     assert(Entry->isDeclaration());
2182
2183     // If there is a declaration in the module, then we had an extern followed
2184     // by the alias, as in:
2185     //   extern int test6();
2186     //   ...
2187     //   int test6() __attribute__((alias("test7")));
2188     //
2189     // Remove it and replace uses of it with the alias.
2190     GA->takeName(Entry);
2191
2192     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2193                                                           Entry->getType()));
2194     Entry->eraseFromParent();
2195   } else {
2196     GA->setName(MangledName);
2197   }
2198
2199   // Set attributes which are particular to an alias; this is a
2200   // specialization of the attributes which may be set on a global
2201   // variable/function.
2202   if (D->hasAttr<DLLExportAttr>()) {
2203     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2204       // The dllexport attribute is ignored for undefined symbols.
2205       if (FD->hasBody())
2206         GA->setLinkage(llvm::Function::DLLExportLinkage);
2207     } else {
2208       GA->setLinkage(llvm::Function::DLLExportLinkage);
2209     }
2210   } else if (D->hasAttr<WeakAttr>() ||
2211              D->hasAttr<WeakRefAttr>() ||
2212              D->isWeakImported()) {
2213     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2214   }
2215
2216   SetCommonAttributes(D, GA);
2217 }
2218
2219 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2220                                             ArrayRef<llvm::Type*> Tys) {
2221   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2222                                          Tys);
2223 }
2224
2225 static llvm::StringMapEntry<llvm::Constant*> &
2226 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2227                          const StringLiteral *Literal,
2228                          bool TargetIsLSB,
2229                          bool &IsUTF16,
2230                          unsigned &StringLength) {
2231   StringRef String = Literal->getString();
2232   unsigned NumBytes = String.size();
2233
2234   // Check for simple case.
2235   if (!Literal->containsNonAsciiOrNull()) {
2236     StringLength = NumBytes;
2237     return Map.GetOrCreateValue(String);
2238   }
2239
2240   // Otherwise, convert the UTF8 literals into a string of shorts.
2241   IsUTF16 = true;
2242
2243   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2244   const UTF8 *FromPtr = (const UTF8 *)String.data();
2245   UTF16 *ToPtr = &ToBuf[0];
2246
2247   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2248                            &ToPtr, ToPtr + NumBytes,
2249                            strictConversion);
2250
2251   // ConvertUTF8toUTF16 returns the length in ToPtr.
2252   StringLength = ToPtr - &ToBuf[0];
2253
2254   // Add an explicit null.
2255   *ToPtr = 0;
2256   return Map.
2257     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2258                                (StringLength + 1) * 2));
2259 }
2260
2261 static llvm::StringMapEntry<llvm::Constant*> &
2262 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2263                        const StringLiteral *Literal,
2264                        unsigned &StringLength) {
2265   StringRef String = Literal->getString();
2266   StringLength = String.size();
2267   return Map.GetOrCreateValue(String);
2268 }
2269
2270 llvm::Constant *
2271 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2272   unsigned StringLength = 0;
2273   bool isUTF16 = false;
2274   llvm::StringMapEntry<llvm::Constant*> &Entry =
2275     GetConstantCFStringEntry(CFConstantStringMap, Literal,
2276                              getDataLayout().isLittleEndian(),
2277                              isUTF16, StringLength);
2278
2279   if (llvm::Constant *C = Entry.getValue())
2280     return C;
2281
2282   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2283   llvm::Constant *Zeros[] = { Zero, Zero };
2284   llvm::Value *V;
2285   
2286   // If we don't already have it, get __CFConstantStringClassReference.
2287   if (!CFConstantStringClassRef) {
2288     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2289     Ty = llvm::ArrayType::get(Ty, 0);
2290     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2291                                            "__CFConstantStringClassReference");
2292     // Decay array -> ptr
2293     V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2294     CFConstantStringClassRef = V;
2295   }
2296   else
2297     V = CFConstantStringClassRef;
2298
2299   QualType CFTy = getContext().getCFConstantStringType();
2300
2301   llvm::StructType *STy =
2302     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2303
2304   llvm::Constant *Fields[4];
2305
2306   // Class pointer.
2307   Fields[0] = cast<llvm::ConstantExpr>(V);
2308
2309   // Flags.
2310   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2311   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2312     llvm::ConstantInt::get(Ty, 0x07C8);
2313
2314   // String pointer.
2315   llvm::Constant *C = 0;
2316   if (isUTF16) {
2317     ArrayRef<uint16_t> Arr =
2318       llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2319                                      const_cast<char *>(Entry.getKey().data())),
2320                                    Entry.getKey().size() / 2);
2321     C = llvm::ConstantDataArray::get(VMContext, Arr);
2322   } else {
2323     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2324   }
2325
2326   llvm::GlobalValue::LinkageTypes Linkage;
2327   if (isUTF16)
2328     // FIXME: why do utf strings get "_" labels instead of "L" labels?
2329     Linkage = llvm::GlobalValue::InternalLinkage;
2330   else
2331     // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2332     // when using private linkage. It is not clear if this is a bug in ld
2333     // or a reasonable new restriction.
2334     Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2335   
2336   // Note: -fwritable-strings doesn't make the backing store strings of
2337   // CFStrings writable. (See <rdar://problem/10657500>)
2338   llvm::GlobalVariable *GV =
2339     new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2340                              Linkage, C, ".str");
2341   GV->setUnnamedAddr(true);
2342   // Don't enforce the target's minimum global alignment, since the only use
2343   // of the string is via this class initializer.
2344   if (isUTF16) {
2345     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2346     GV->setAlignment(Align.getQuantity());
2347   } else {
2348     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2349     GV->setAlignment(Align.getQuantity());
2350   }
2351
2352   // String.
2353   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2354
2355   if (isUTF16)
2356     // Cast the UTF16 string to the correct type.
2357     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2358
2359   // String length.
2360   Ty = getTypes().ConvertType(getContext().LongTy);
2361   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2362
2363   // The struct.
2364   C = llvm::ConstantStruct::get(STy, Fields);
2365   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2366                                 llvm::GlobalVariable::PrivateLinkage, C,
2367                                 "_unnamed_cfstring_");
2368   if (const char *Sect = getTarget().getCFStringSection())
2369     GV->setSection(Sect);
2370   Entry.setValue(GV);
2371
2372   return GV;
2373 }
2374
2375 static RecordDecl *
2376 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2377                  DeclContext *DC, IdentifierInfo *Id) {
2378   SourceLocation Loc;
2379   if (Ctx.getLangOpts().CPlusPlus)
2380     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2381   else
2382     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2383 }
2384
2385 llvm::Constant *
2386 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2387   unsigned StringLength = 0;
2388   llvm::StringMapEntry<llvm::Constant*> &Entry =
2389     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2390   
2391   if (llvm::Constant *C = Entry.getValue())
2392     return C;
2393   
2394   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2395   llvm::Constant *Zeros[] = { Zero, Zero };
2396   llvm::Value *V;
2397   // If we don't already have it, get _NSConstantStringClassReference.
2398   if (!ConstantStringClassRef) {
2399     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2400     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2401     llvm::Constant *GV;
2402     if (LangOpts.ObjCRuntime.isNonFragile()) {
2403       std::string str = 
2404         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 
2405                             : "OBJC_CLASS_$_" + StringClass;
2406       GV = getObjCRuntime().GetClassGlobal(str);
2407       // Make sure the result is of the correct type.
2408       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2409       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2410       ConstantStringClassRef = V;
2411     } else {
2412       std::string str =
2413         StringClass.empty() ? "_NSConstantStringClassReference"
2414                             : "_" + StringClass + "ClassReference";
2415       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2416       GV = CreateRuntimeVariable(PTy, str);
2417       // Decay array -> ptr
2418       V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2419       ConstantStringClassRef = V;
2420     }
2421   }
2422   else
2423     V = ConstantStringClassRef;
2424
2425   if (!NSConstantStringType) {
2426     // Construct the type for a constant NSString.
2427     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 
2428                                      Context.getTranslationUnitDecl(),
2429                                    &Context.Idents.get("__builtin_NSString"));
2430     D->startDefinition();
2431       
2432     QualType FieldTypes[3];
2433     
2434     // const int *isa;
2435     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2436     // const char *str;
2437     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2438     // unsigned int length;
2439     FieldTypes[2] = Context.UnsignedIntTy;
2440     
2441     // Create fields
2442     for (unsigned i = 0; i < 3; ++i) {
2443       FieldDecl *Field = FieldDecl::Create(Context, D,
2444                                            SourceLocation(),
2445                                            SourceLocation(), 0,
2446                                            FieldTypes[i], /*TInfo=*/0,
2447                                            /*BitWidth=*/0,
2448                                            /*Mutable=*/false,
2449                                            ICIS_NoInit);
2450       Field->setAccess(AS_public);
2451       D->addDecl(Field);
2452     }
2453     
2454     D->completeDefinition();
2455     QualType NSTy = Context.getTagDeclType(D);
2456     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2457   }
2458   
2459   llvm::Constant *Fields[3];
2460   
2461   // Class pointer.
2462   Fields[0] = cast<llvm::ConstantExpr>(V);
2463   
2464   // String pointer.
2465   llvm::Constant *C =
2466     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2467   
2468   llvm::GlobalValue::LinkageTypes Linkage;
2469   bool isConstant;
2470   Linkage = llvm::GlobalValue::PrivateLinkage;
2471   isConstant = !LangOpts.WritableStrings;
2472   
2473   llvm::GlobalVariable *GV =
2474   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2475                            ".str");
2476   GV->setUnnamedAddr(true);
2477   // Don't enforce the target's minimum global alignment, since the only use
2478   // of the string is via this class initializer.
2479   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2480   GV->setAlignment(Align.getQuantity());
2481   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2482   
2483   // String length.
2484   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2485   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2486   
2487   // The struct.
2488   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2489   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2490                                 llvm::GlobalVariable::PrivateLinkage, C,
2491                                 "_unnamed_nsstring_");
2492   // FIXME. Fix section.
2493   if (const char *Sect = 
2494         LangOpts.ObjCRuntime.isNonFragile() 
2495           ? getTarget().getNSStringNonFragileABISection() 
2496           : getTarget().getNSStringSection())
2497     GV->setSection(Sect);
2498   Entry.setValue(GV);
2499   
2500   return GV;
2501 }
2502
2503 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2504   if (ObjCFastEnumerationStateType.isNull()) {
2505     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 
2506                                      Context.getTranslationUnitDecl(),
2507                       &Context.Idents.get("__objcFastEnumerationState"));
2508     D->startDefinition();
2509     
2510     QualType FieldTypes[] = {
2511       Context.UnsignedLongTy,
2512       Context.getPointerType(Context.getObjCIdType()),
2513       Context.getPointerType(Context.UnsignedLongTy),
2514       Context.getConstantArrayType(Context.UnsignedLongTy,
2515                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2516     };
2517     
2518     for (size_t i = 0; i < 4; ++i) {
2519       FieldDecl *Field = FieldDecl::Create(Context,
2520                                            D,
2521                                            SourceLocation(),
2522                                            SourceLocation(), 0,
2523                                            FieldTypes[i], /*TInfo=*/0,
2524                                            /*BitWidth=*/0,
2525                                            /*Mutable=*/false,
2526                                            ICIS_NoInit);
2527       Field->setAccess(AS_public);
2528       D->addDecl(Field);
2529     }
2530     
2531     D->completeDefinition();
2532     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2533   }
2534   
2535   return ObjCFastEnumerationStateType;
2536 }
2537
2538 llvm::Constant *
2539 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2540   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2541   
2542   // Don't emit it as the address of the string, emit the string data itself
2543   // as an inline array.
2544   if (E->getCharByteWidth() == 1) {
2545     SmallString<64> Str(E->getString());
2546
2547     // Resize the string to the right size, which is indicated by its type.
2548     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2549     Str.resize(CAT->getSize().getZExtValue());
2550     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2551   }
2552   
2553   llvm::ArrayType *AType =
2554     cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2555   llvm::Type *ElemTy = AType->getElementType();
2556   unsigned NumElements = AType->getNumElements();
2557
2558   // Wide strings have either 2-byte or 4-byte elements.
2559   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2560     SmallVector<uint16_t, 32> Elements;
2561     Elements.reserve(NumElements);
2562
2563     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2564       Elements.push_back(E->getCodeUnit(i));
2565     Elements.resize(NumElements);
2566     return llvm::ConstantDataArray::get(VMContext, Elements);
2567   }
2568   
2569   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2570   SmallVector<uint32_t, 32> Elements;
2571   Elements.reserve(NumElements);
2572   
2573   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2574     Elements.push_back(E->getCodeUnit(i));
2575   Elements.resize(NumElements);
2576   return llvm::ConstantDataArray::get(VMContext, Elements);
2577 }
2578
2579 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2580 /// constant array for the given string literal.
2581 llvm::Constant *
2582 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2583   CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
2584   if (S->isAscii() || S->isUTF8()) {
2585     SmallString<64> Str(S->getString());
2586     
2587     // Resize the string to the right size, which is indicated by its type.
2588     const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2589     Str.resize(CAT->getSize().getZExtValue());
2590     return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2591   }
2592
2593   // FIXME: the following does not memoize wide strings.
2594   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2595   llvm::GlobalVariable *GV =
2596     new llvm::GlobalVariable(getModule(),C->getType(),
2597                              !LangOpts.WritableStrings,
2598                              llvm::GlobalValue::PrivateLinkage,
2599                              C,".str");
2600
2601   GV->setAlignment(Align.getQuantity());
2602   GV->setUnnamedAddr(true);
2603   return GV;
2604 }
2605
2606 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2607 /// array for the given ObjCEncodeExpr node.
2608 llvm::Constant *
2609 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2610   std::string Str;
2611   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2612
2613   return GetAddrOfConstantCString(Str);
2614 }
2615
2616
2617 /// GenerateWritableString -- Creates storage for a string literal.
2618 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2619                                              bool constant,
2620                                              CodeGenModule &CGM,
2621                                              const char *GlobalName,
2622                                              unsigned Alignment) {
2623   // Create Constant for this string literal. Don't add a '\0'.
2624   llvm::Constant *C =
2625       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2626
2627   // Create a global variable for this string
2628   llvm::GlobalVariable *GV =
2629     new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2630                              llvm::GlobalValue::PrivateLinkage,
2631                              C, GlobalName);
2632   GV->setAlignment(Alignment);
2633   GV->setUnnamedAddr(true);
2634   return GV;
2635 }
2636
2637 /// GetAddrOfConstantString - Returns a pointer to a character array
2638 /// containing the literal. This contents are exactly that of the
2639 /// given string, i.e. it will not be null terminated automatically;
2640 /// see GetAddrOfConstantCString. Note that whether the result is
2641 /// actually a pointer to an LLVM constant depends on
2642 /// Feature.WriteableStrings.
2643 ///
2644 /// The result has pointer to array type.
2645 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2646                                                        const char *GlobalName,
2647                                                        unsigned Alignment) {
2648   // Get the default prefix if a name wasn't specified.
2649   if (!GlobalName)
2650     GlobalName = ".str";
2651
2652   if (Alignment == 0)
2653     Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2654       .getQuantity();
2655
2656   // Don't share any string literals if strings aren't constant.
2657   if (LangOpts.WritableStrings)
2658     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2659
2660   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2661     ConstantStringMap.GetOrCreateValue(Str);
2662
2663   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2664     if (Alignment > GV->getAlignment()) {
2665       GV->setAlignment(Alignment);
2666     }
2667     return GV;
2668   }
2669
2670   // Create a global variable for this.
2671   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2672                                                    Alignment);
2673   Entry.setValue(GV);
2674   return GV;
2675 }
2676
2677 /// GetAddrOfConstantCString - Returns a pointer to a character
2678 /// array containing the literal and a terminating '\0'
2679 /// character. The result has pointer to array type.
2680 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2681                                                         const char *GlobalName,
2682                                                         unsigned Alignment) {
2683   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2684   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2685 }
2686
2687 /// EmitObjCPropertyImplementations - Emit information for synthesized
2688 /// properties for an implementation.
2689 void CodeGenModule::EmitObjCPropertyImplementations(const
2690                                                     ObjCImplementationDecl *D) {
2691   for (ObjCImplementationDecl::propimpl_iterator
2692          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2693     ObjCPropertyImplDecl *PID = *i;
2694
2695     // Dynamic is just for type-checking.
2696     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2697       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2698
2699       // Determine which methods need to be implemented, some may have
2700       // been overridden. Note that ::isPropertyAccessor is not the method
2701       // we want, that just indicates if the decl came from a
2702       // property. What we want to know is if the method is defined in
2703       // this implementation.
2704       if (!D->getInstanceMethod(PD->getGetterName()))
2705         CodeGenFunction(*this).GenerateObjCGetter(
2706                                  const_cast<ObjCImplementationDecl *>(D), PID);
2707       if (!PD->isReadOnly() &&
2708           !D->getInstanceMethod(PD->getSetterName()))
2709         CodeGenFunction(*this).GenerateObjCSetter(
2710                                  const_cast<ObjCImplementationDecl *>(D), PID);
2711     }
2712   }
2713 }
2714
2715 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2716   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2717   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2718        ivar; ivar = ivar->getNextIvar())
2719     if (ivar->getType().isDestructedType())
2720       return true;
2721
2722   return false;
2723 }
2724
2725 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2726 /// for an implementation.
2727 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2728   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2729   if (needsDestructMethod(D)) {
2730     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2731     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2732     ObjCMethodDecl *DTORMethod =
2733       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2734                              cxxSelector, getContext().VoidTy, 0, D,
2735                              /*isInstance=*/true, /*isVariadic=*/false,
2736                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2737                              /*isDefined=*/false, ObjCMethodDecl::Required);
2738     D->addInstanceMethod(DTORMethod);
2739     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2740     D->setHasDestructors(true);
2741   }
2742
2743   // If the implementation doesn't have any ivar initializers, we don't need
2744   // a .cxx_construct.
2745   if (D->getNumIvarInitializers() == 0)
2746     return;
2747   
2748   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2749   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2750   // The constructor returns 'self'.
2751   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 
2752                                                 D->getLocation(),
2753                                                 D->getLocation(),
2754                                                 cxxSelector,
2755                                                 getContext().getObjCIdType(), 0, 
2756                                                 D, /*isInstance=*/true,
2757                                                 /*isVariadic=*/false,
2758                                                 /*isPropertyAccessor=*/true,
2759                                                 /*isImplicitlyDeclared=*/true,
2760                                                 /*isDefined=*/false,
2761                                                 ObjCMethodDecl::Required);
2762   D->addInstanceMethod(CTORMethod);
2763   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2764   D->setHasNonZeroConstructors(true);
2765 }
2766
2767 /// EmitNamespace - Emit all declarations in a namespace.
2768 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2769   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2770        I != E; ++I)
2771     EmitTopLevelDecl(*I);
2772 }
2773
2774 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2775 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2776   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2777       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2778     ErrorUnsupported(LSD, "linkage spec");
2779     return;
2780   }
2781
2782   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2783        I != E; ++I) {
2784     // Meta-data for ObjC class includes references to implemented methods.
2785     // Generate class's method definitions first.
2786     if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2787       for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2788            MEnd = OID->meth_end();
2789            M != MEnd; ++M)
2790         EmitTopLevelDecl(*M);
2791     }
2792     EmitTopLevelDecl(*I);
2793   }
2794 }
2795
2796 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2797 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2798   // If an error has occurred, stop code generation, but continue
2799   // parsing and semantic analysis (to ensure all warnings and errors
2800   // are emitted).
2801   if (Diags.hasErrorOccurred())
2802     return;
2803
2804   // Ignore dependent declarations.
2805   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2806     return;
2807
2808   switch (D->getKind()) {
2809   case Decl::CXXConversion:
2810   case Decl::CXXMethod:
2811   case Decl::Function:
2812     // Skip function templates
2813     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2814         cast<FunctionDecl>(D)->isLateTemplateParsed())
2815       return;
2816
2817     EmitGlobal(cast<FunctionDecl>(D));
2818     break;
2819       
2820   case Decl::Var:
2821     EmitGlobal(cast<VarDecl>(D));
2822     break;
2823
2824   // Indirect fields from global anonymous structs and unions can be
2825   // ignored; only the actual variable requires IR gen support.
2826   case Decl::IndirectField:
2827     break;
2828
2829   // C++ Decls
2830   case Decl::Namespace:
2831     EmitNamespace(cast<NamespaceDecl>(D));
2832     break;
2833     // No code generation needed.
2834   case Decl::UsingShadow:
2835   case Decl::Using:
2836   case Decl::ClassTemplate:
2837   case Decl::FunctionTemplate:
2838   case Decl::TypeAliasTemplate:
2839   case Decl::NamespaceAlias:
2840   case Decl::Block:
2841   case Decl::Empty:
2842     break;
2843   case Decl::UsingDirective: // using namespace X; [C++]
2844     if (CGDebugInfo *DI = getModuleDebugInfo())
2845       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2846     return;
2847   case Decl::CXXConstructor:
2848     // Skip function templates
2849     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2850         cast<FunctionDecl>(D)->isLateTemplateParsed())
2851       return;
2852       
2853     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2854     break;
2855   case Decl::CXXDestructor:
2856     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2857       return;
2858     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2859     break;
2860
2861   case Decl::StaticAssert:
2862     // Nothing to do.
2863     break;
2864
2865   // Objective-C Decls
2866
2867   // Forward declarations, no (immediate) code generation.
2868   case Decl::ObjCInterface:
2869   case Decl::ObjCCategory:
2870     break;
2871
2872   case Decl::ObjCProtocol: {
2873     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2874     if (Proto->isThisDeclarationADefinition())
2875       ObjCRuntime->GenerateProtocol(Proto);
2876     break;
2877   }
2878       
2879   case Decl::ObjCCategoryImpl:
2880     // Categories have properties but don't support synthesize so we
2881     // can ignore them here.
2882     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2883     break;
2884
2885   case Decl::ObjCImplementation: {
2886     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2887     EmitObjCPropertyImplementations(OMD);
2888     EmitObjCIvarInitializations(OMD);
2889     ObjCRuntime->GenerateClass(OMD);
2890     // Emit global variable debug information.
2891     if (CGDebugInfo *DI = getModuleDebugInfo())
2892       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2893         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2894             OMD->getClassInterface()), OMD->getLocation());
2895     break;
2896   }
2897   case Decl::ObjCMethod: {
2898     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2899     // If this is not a prototype, emit the body.
2900     if (OMD->getBody())
2901       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2902     break;
2903   }
2904   case Decl::ObjCCompatibleAlias:
2905     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2906     break;
2907
2908   case Decl::LinkageSpec:
2909     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2910     break;
2911
2912   case Decl::FileScopeAsm: {
2913     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2914     StringRef AsmString = AD->getAsmString()->getString();
2915
2916     const std::string &S = getModule().getModuleInlineAsm();
2917     if (S.empty())
2918       getModule().setModuleInlineAsm(AsmString);
2919     else if (S.end()[-1] == '\n')
2920       getModule().setModuleInlineAsm(S + AsmString.str());
2921     else
2922       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2923     break;
2924   }
2925
2926   case Decl::Import: {
2927     ImportDecl *Import = cast<ImportDecl>(D);
2928
2929     // Ignore import declarations that come from imported modules.
2930     if (clang::Module *Owner = Import->getOwningModule()) {
2931       if (getLangOpts().CurrentModule.empty() ||
2932           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
2933         break;
2934     }
2935
2936     ImportedModules.insert(Import->getImportedModule());
2937     break;
2938  }
2939
2940   default:
2941     // Make sure we handled everything we should, every other kind is a
2942     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2943     // function. Need to recode Decl::Kind to do that easily.
2944     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2945   }
2946 }
2947
2948 /// Turns the given pointer into a constant.
2949 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2950                                           const void *Ptr) {
2951   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2952   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2953   return llvm::ConstantInt::get(i64, PtrInt);
2954 }
2955
2956 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2957                                    llvm::NamedMDNode *&GlobalMetadata,
2958                                    GlobalDecl D,
2959                                    llvm::GlobalValue *Addr) {
2960   if (!GlobalMetadata)
2961     GlobalMetadata =
2962       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2963
2964   // TODO: should we report variant information for ctors/dtors?
2965   llvm::Value *Ops[] = {
2966     Addr,
2967     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2968   };
2969   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2970 }
2971
2972 /// For each function which is declared within an extern "C" region and marked
2973 /// as 'used', but has internal linkage, create an alias from the unmangled
2974 /// name to the mangled name if possible. People expect to be able to refer
2975 /// to such functions with an unmangled name from inline assembly within the
2976 /// same translation unit.
2977 void CodeGenModule::EmitStaticExternCAliases() {
2978   for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
2979                                   E = StaticExternCValues.end();
2980        I != E; ++I) {
2981     IdentifierInfo *Name = I->first;
2982     llvm::GlobalValue *Val = I->second;
2983     if (Val && !getModule().getNamedValue(Name->getName()))
2984       AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
2985                                           Name->getName(), Val, &getModule()));
2986   }
2987 }
2988
2989 /// Emits metadata nodes associating all the global values in the
2990 /// current module with the Decls they came from.  This is useful for
2991 /// projects using IR gen as a subroutine.
2992 ///
2993 /// Since there's currently no way to associate an MDNode directly
2994 /// with an llvm::GlobalValue, we create a global named metadata
2995 /// with the name 'clang.global.decl.ptrs'.
2996 void CodeGenModule::EmitDeclMetadata() {
2997   llvm::NamedMDNode *GlobalMetadata = 0;
2998
2999   // StaticLocalDeclMap
3000   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
3001          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3002        I != E; ++I) {
3003     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3004     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3005   }
3006 }
3007
3008 /// Emits metadata nodes for all the local variables in the current
3009 /// function.
3010 void CodeGenFunction::EmitDeclMetadata() {
3011   if (LocalDeclMap.empty()) return;
3012
3013   llvm::LLVMContext &Context = getLLVMContext();
3014
3015   // Find the unique metadata ID for this name.
3016   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3017
3018   llvm::NamedMDNode *GlobalMetadata = 0;
3019
3020   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3021          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3022     const Decl *D = I->first;
3023     llvm::Value *Addr = I->second;
3024
3025     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3026       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3027       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3028     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3029       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3030       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3031     }
3032   }
3033 }
3034
3035 void CodeGenModule::EmitCoverageFile() {
3036   if (!getCodeGenOpts().CoverageFile.empty()) {
3037     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3038       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3039       llvm::LLVMContext &Ctx = TheModule.getContext();
3040       llvm::MDString *CoverageFile =
3041           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3042       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3043         llvm::MDNode *CU = CUNode->getOperand(i);
3044         llvm::Value *node[] = { CoverageFile, CU };
3045         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3046         GCov->addOperand(N);
3047       }
3048     }
3049   }
3050 }
3051
3052 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3053                                                      QualType GuidType) {
3054   // Sema has checked that all uuid strings are of the form
3055   // "12345678-1234-1234-1234-1234567890ab".
3056   assert(Uuid.size() == 36);
3057   const char *Uuidstr = Uuid.data();
3058   for (int i = 0; i < 36; ++i) {
3059     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
3060     else                                         assert(isHexDigit(Uuidstr[i]));
3061   }
3062   
3063   llvm::APInt Field0(32, StringRef(Uuidstr     , 8), 16);
3064   llvm::APInt Field1(16, StringRef(Uuidstr +  9, 4), 16);
3065   llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
3066   static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3067
3068   APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
3069   InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
3070   InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
3071   InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
3072   APValue& Arr = InitStruct.getStructField(3);
3073   Arr = APValue(APValue::UninitArray(), 8, 8);
3074   for (int t = 0; t < 8; ++t)
3075     Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
3076           llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
3077
3078   return EmitConstantValue(InitStruct, GuidType);
3079 }