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