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