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