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