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