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