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