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