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