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