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 "clang/Frontend/CompileOptions.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Basic/ConvertUTF.h"
28 #include "llvm/CallingConv.h"
29 #include "llvm/Module.h"
30 #include "llvm/Intrinsics.h"
31 #include "llvm/Target/TargetData.h"
32 using namespace clang;
33 using namespace CodeGen;
34 
35 
36 CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
37                              llvm::Module &M, const llvm::TargetData &TD,
38                              Diagnostic &diags)
39   : BlockModule(C, M, TD, Types, *this), Context(C),
40     Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M),
41     TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
42     MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
43 
44   if (!Features.ObjC1)
45     Runtime = 0;
46   else if (!Features.NeXTRuntime)
47     Runtime = CreateGNUObjCRuntime(*this);
48   else if (Features.ObjCNonFragileABI)
49     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
50   else
51     Runtime = CreateMacObjCRuntime(*this);
52 
53   // If debug info generation is enabled, create the CGDebugInfo object.
54   DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
55 }
56 
57 CodeGenModule::~CodeGenModule() {
58   delete Runtime;
59   delete DebugInfo;
60 }
61 
62 void CodeGenModule::Release() {
63   EmitDeferred();
64   if (Runtime)
65     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
66       AddGlobalCtor(ObjCInitFunction);
67   EmitCtorList(GlobalCtors, "llvm.global_ctors");
68   EmitCtorList(GlobalDtors, "llvm.global_dtors");
69   EmitAnnotations();
70   EmitLLVMUsed();
71 }
72 
73 /// ErrorUnsupported - Print out an error that codegen doesn't support the
74 /// specified stmt yet.
75 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
76                                      bool OmitOnError) {
77   if (OmitOnError && getDiags().hasErrorOccurred())
78     return;
79   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
80                                                "cannot compile this %0 yet");
81   std::string Msg = Type;
82   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
83     << Msg << S->getSourceRange();
84 }
85 
86 /// ErrorUnsupported - Print out an error that codegen doesn't support the
87 /// specified decl yet.
88 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
89                                      bool OmitOnError) {
90   if (OmitOnError && getDiags().hasErrorOccurred())
91     return;
92   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
93                                                "cannot compile this %0 yet");
94   std::string Msg = Type;
95   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
96 }
97 
98 LangOptions::VisibilityMode
99 CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
100   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
101     if (VD->getStorageClass() == VarDecl::PrivateExtern)
102       return LangOptions::Hidden;
103 
104   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
105     switch (attr->getVisibility()) {
106     default: assert(0 && "Unknown visibility!");
107     case VisibilityAttr::DefaultVisibility:
108       return LangOptions::Default;
109     case VisibilityAttr::HiddenVisibility:
110       return LangOptions::Hidden;
111     case VisibilityAttr::ProtectedVisibility:
112       return LangOptions::Protected;
113     }
114   }
115 
116   return getLangOptions().getVisibilityMode();
117 }
118 
119 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
120                                         const Decl *D) const {
121   // Internal definitions always have default visibility.
122   if (GV->hasLocalLinkage()) {
123     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
124     return;
125   }
126 
127   switch (getDeclVisibilityMode(D)) {
128   default: assert(0 && "Unknown visibility!");
129   case LangOptions::Default:
130     return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
131   case LangOptions::Hidden:
132     return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
133   case LangOptions::Protected:
134     return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
135   }
136 }
137 
138 /// \brief Retrieves the mangled name for the given declaration.
139 ///
140 /// If the given declaration requires a mangled name, returns an
141 /// const char* containing the mangled name.  Otherwise, returns
142 /// the unmangled name.
143 ///
144 const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
145   // In C, functions with no attributes never need to be mangled. Fastpath them.
146   if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
147     assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
148     return ND->getNameAsCString();
149   }
150 
151   llvm::SmallString<256> Name;
152   llvm::raw_svector_ostream Out(Name);
153   if (!mangleName(ND, Context, Out)) {
154     assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
155     return ND->getNameAsCString();
156   }
157 
158   Name += '\0';
159   return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
160 }
161 
162 /// AddGlobalCtor - Add a function to the list that will be called before
163 /// main() runs.
164 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
165   // FIXME: Type coercion of void()* types.
166   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
167 }
168 
169 /// AddGlobalDtor - Add a function to the list that will be called
170 /// when the module is unloaded.
171 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
172   // FIXME: Type coercion of void()* types.
173   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
174 }
175 
176 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
177   // Ctor function type is void()*.
178   llvm::FunctionType* CtorFTy =
179     llvm::FunctionType::get(llvm::Type::VoidTy,
180                             std::vector<const llvm::Type*>(),
181                             false);
182   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
183 
184   // Get the type of a ctor entry, { i32, void ()* }.
185   llvm::StructType* CtorStructTy =
186     llvm::StructType::get(llvm::Type::Int32Ty,
187                           llvm::PointerType::getUnqual(CtorFTy), NULL);
188 
189   // Construct the constructor and destructor arrays.
190   std::vector<llvm::Constant*> Ctors;
191   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
192     std::vector<llvm::Constant*> S;
193     S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
194     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
195     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
196   }
197 
198   if (!Ctors.empty()) {
199     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
200     new llvm::GlobalVariable(AT, false,
201                              llvm::GlobalValue::AppendingLinkage,
202                              llvm::ConstantArray::get(AT, Ctors),
203                              GlobalName,
204                              &TheModule);
205   }
206 }
207 
208 void CodeGenModule::EmitAnnotations() {
209   if (Annotations.empty())
210     return;
211 
212   // Create a new global variable for the ConstantStruct in the Module.
213   llvm::Constant *Array =
214   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
215                                                 Annotations.size()),
216                            Annotations);
217   llvm::GlobalValue *gv =
218   new llvm::GlobalVariable(Array->getType(), false,
219                            llvm::GlobalValue::AppendingLinkage, Array,
220                            "llvm.global.annotations", &TheModule);
221   gv->setSection("llvm.metadata");
222 }
223 
224 /// SetGlobalValueAttributes - Set attributes for a global.
225 ///
226 /// FIXME: This is currently only done for aliases and functions, but
227 /// not for variables (these details are set in
228 /// EmitGlobalVarDefinition for variables).
229 void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
230                                              GVALinkage Linkage,
231                                              llvm::GlobalValue *GV,
232                                              bool ForDefinition) {
233   // FIXME: Set up linkage and many other things.  Note, this is a simple
234   // approximation of what we really want.
235   if (!ForDefinition) {
236     // Only a few attributes are set on declarations.
237 
238     // The dllimport attribute is overridden by a subsequent declaration as
239     // dllexport.
240     if (D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
241       // dllimport attribute can be applied only to function decls, not to
242       // definitions.
243       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
244         if (!FD->getBody())
245           GV->setLinkage(llvm::Function::DLLImportLinkage);
246       } else
247         GV->setLinkage(llvm::Function::DLLImportLinkage);
248     } else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>()) {
249       // "extern_weak" is overloaded in LLVM; we probably should have
250       // separate linkage types for this.
251       GV->setLinkage(llvm::Function::ExternalWeakLinkage);
252     }
253   } else if (Linkage == GVA_Internal) {
254     GV->setLinkage(llvm::Function::InternalLinkage);
255   } else if (D->hasAttr<DLLExportAttr>()) {
256     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
257       // The dllexport attribute is ignored for undefined symbols.
258       if (FD->getBody())
259         GV->setLinkage(llvm::Function::DLLExportLinkage);
260     } else {
261       GV->setLinkage(llvm::Function::DLLExportLinkage);
262     }
263   } else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>()) {
264     GV->setLinkage(llvm::Function::WeakAnyLinkage);
265   } else if (Linkage == GVA_ExternInline) {
266     // "extern inline" always gets available_externally linkage, which is the
267     // strongest linkage type we can give an inline function: we don't have to
268     // codegen the definition at all, yet we know that it is "ODR".
269     GV->setLinkage(llvm::Function::AvailableExternallyLinkage);
270   } else if (Linkage == GVA_Inline) {
271     // The definition of inline changes based on the language.  Note that we
272     // have already handled "static inline" above, with the GVA_Internal case.
273     if (Features.CPlusPlus) {
274       // In C++, the compiler has to emit a definition in every translation unit
275       // that references the function.  We should use linkonce_odr because
276       // a) if all references in this translation unit are optimized away, we
277       // don't need to codegen it.  b) if the function persists, it needs to be
278       // merged with other definitions. c) C++ has the ODR, so we know the
279       // definition is dependable.
280       GV->setLinkage(llvm::Function::LinkOnceODRLinkage);
281     } else if (Features.C99) {
282       // In C99 mode, 'inline' functions are guaranteed to have a strong
283       // definition somewhere else, so we can use available_externally linkage.
284       GV->setLinkage(llvm::Function::AvailableExternallyLinkage);
285     } else {
286       // In C89 mode, an 'inline' function may only occur in one translation
287       // unit in the program, but may be extern'd in others.  Give it strong
288       // external linkage.
289       GV->setLinkage(llvm::Function::ExternalLinkage);
290     }
291   }
292 
293   if (ForDefinition) {
294     setGlobalVisibility(GV, D);
295 
296     // Only add to llvm.used when we see a definition, otherwise we
297     // might add it multiple times or risk the value being replaced by
298     // a subsequent RAUW.
299     if (D->hasAttr<UsedAttr>())
300       AddUsedGlobal(GV);
301   }
302 
303   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
304     GV->setSection(SA->getName());
305 }
306 
307 void CodeGenModule::SetFunctionAttributes(const Decl *D,
308                                           const CGFunctionInfo &Info,
309                                           llvm::Function *F) {
310   AttributeListType AttributeList;
311   ConstructAttributeList(Info, D, AttributeList);
312 
313   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
314                                         AttributeList.size()));
315 
316   // Set the appropriate calling convention for the Function.
317   if (D->hasAttr<FastCallAttr>())
318     F->setCallingConv(llvm::CallingConv::X86_FastCall);
319 
320   if (D->hasAttr<StdCallAttr>())
321     F->setCallingConv(llvm::CallingConv::X86_StdCall);
322 }
323 
324 
325 static CodeGenModule::GVALinkage
326 GetLinkageForFunctionOrMethodDecl(const Decl *D) {
327   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
328     if (FD->getStorageClass() == FunctionDecl::Static)
329       return CodeGenModule::GVA_Internal;
330     if (FD->isInline()) {
331       if (FD->getStorageClass() == FunctionDecl::Extern)
332         return CodeGenModule::GVA_ExternInline;
333       return CodeGenModule::GVA_Inline;
334     }
335   } else {
336     assert(isa<ObjCMethodDecl>(D));
337     return CodeGenModule::GVA_Internal;
338   }
339   return CodeGenModule::GVA_Normal;
340 }
341 
342 /// SetFunctionAttributesForDefinition - Set function attributes
343 /// specific to a function definition.
344 void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
345                                                        llvm::Function *F) {
346   SetGlobalValueAttributes(D, GetLinkageForFunctionOrMethodDecl(D), F, true);
347 
348   if (!Features.Exceptions && !Features.ObjCNonFragileABI)
349     F->addFnAttr(llvm::Attribute::NoUnwind);
350 
351   if (D->hasAttr<AlwaysInlineAttr>())
352     F->addFnAttr(llvm::Attribute::AlwaysInline);
353 
354   if (D->hasAttr<NoinlineAttr>())
355     F->addFnAttr(llvm::Attribute::NoInline);
356 }
357 
358 void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
359                                         llvm::Function *F) {
360   SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
361 
362   SetFunctionAttributesForDefinition(MD, F);
363 }
364 
365 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
366                                           llvm::Function *F) {
367   SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
368 
369   SetGlobalValueAttributes(FD, GetLinkageForFunctionOrMethodDecl(FD), F, false);
370 }
371 
372 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
373   assert(!GV->isDeclaration() &&
374          "Only globals with definition can force usage.");
375   LLVMUsed.push_back(GV);
376 }
377 
378 void CodeGenModule::EmitLLVMUsed() {
379   // Don't create llvm.used if there is no need.
380   if (LLVMUsed.empty())
381     return;
382 
383   llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
384   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, LLVMUsed.size());
385 
386   // Convert LLVMUsed to what ConstantArray needs.
387   std::vector<llvm::Constant*> UsedArray;
388   UsedArray.resize(LLVMUsed.size());
389   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
390     UsedArray[i] =
391      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), i8PTy);
392   }
393 
394   llvm::GlobalVariable *GV =
395     new llvm::GlobalVariable(ATy, false,
396                              llvm::GlobalValue::AppendingLinkage,
397                              llvm::ConstantArray::get(ATy, UsedArray),
398                              "llvm.used", &getModule());
399 
400   GV->setSection("llvm.metadata");
401 }
402 
403 void CodeGenModule::EmitDeferred() {
404   // Emit code for any potentially referenced deferred decls.  Since a
405   // previously unused static decl may become used during the generation of code
406   // for a static function, iterate until no  changes are made.
407   while (!DeferredDeclsToEmit.empty()) {
408     const ValueDecl *D = DeferredDeclsToEmit.back();
409     DeferredDeclsToEmit.pop_back();
410 
411     // The mangled name for the decl must have been emitted in GlobalDeclMap.
412     // Look it up to see if it was defined with a stronger definition (e.g. an
413     // extern inline function with a strong function redefinition).  If so,
414     // just ignore the deferred decl.
415     llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
416     assert(CGRef && "Deferred decl wasn't referenced?");
417 
418     if (!CGRef->isDeclaration())
419       continue;
420 
421     // Otherwise, emit the definition and move on to the next one.
422     EmitGlobalDefinition(D);
423   }
424 }
425 
426 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
427 /// annotation information for a given GlobalValue.  The annotation struct is
428 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
429 /// GlobalValue being annotated.  The second field is the constant string
430 /// created from the AnnotateAttr's annotation.  The third field is a constant
431 /// string containing the name of the translation unit.  The fourth field is
432 /// the line number in the file of the annotated value declaration.
433 ///
434 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
435 ///        appears to.
436 ///
437 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
438                                                 const AnnotateAttr *AA,
439                                                 unsigned LineNo) {
440   llvm::Module *M = &getModule();
441 
442   // get [N x i8] constants for the annotation string, and the filename string
443   // which are the 2nd and 3rd elements of the global annotation structure.
444   const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
445   llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
446   llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
447                                                   true);
448 
449   // Get the two global values corresponding to the ConstantArrays we just
450   // created to hold the bytes of the strings.
451   const char *StringPrefix = getContext().Target.getStringSymbolPrefix(true);
452   llvm::GlobalValue *annoGV =
453   new llvm::GlobalVariable(anno->getType(), false,
454                            llvm::GlobalValue::InternalLinkage, anno,
455                            GV->getName() + StringPrefix, M);
456   // translation unit name string, emitted into the llvm.metadata section.
457   llvm::GlobalValue *unitGV =
458   new llvm::GlobalVariable(unit->getType(), false,
459                            llvm::GlobalValue::InternalLinkage, unit,
460                            StringPrefix, M);
461 
462   // Create the ConstantStruct that is the global annotion.
463   llvm::Constant *Fields[4] = {
464     llvm::ConstantExpr::getBitCast(GV, SBP),
465     llvm::ConstantExpr::getBitCast(annoGV, SBP),
466     llvm::ConstantExpr::getBitCast(unitGV, SBP),
467     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
468   };
469   return llvm::ConstantStruct::get(Fields, 4, false);
470 }
471 
472 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
473   // Never defer when EmitAllDecls is specified or the decl has
474   // attribute used.
475   if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
476     return false;
477 
478   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
479     // Constructors and destructors should never be deferred.
480     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
481       return false;
482 
483     // FIXME: What about inline, and/or extern inline?
484     if (FD->getStorageClass() != FunctionDecl::Static)
485       return false;
486   } else {
487     const VarDecl *VD = cast<VarDecl>(Global);
488     assert(VD->isFileVarDecl() && "Invalid decl");
489 
490     if (VD->getStorageClass() != VarDecl::Static)
491       return false;
492   }
493 
494   return true;
495 }
496 
497 void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
498   // If this is an alias definition (which otherwise looks like a declaration)
499   // emit it now.
500   if (Global->hasAttr<AliasAttr>())
501     return EmitAliasDefinition(Global);
502 
503   // Ignore declarations, they will be emitted on their first use.
504   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
505     // Forward declarations are emitted lazily on first use.
506     if (!FD->isThisDeclarationADefinition())
507       return;
508   } else {
509     const VarDecl *VD = cast<VarDecl>(Global);
510     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
511 
512     // Forward declarations are emitted lazily on first use.
513     if (!VD->getInit() && VD->hasExternalStorage())
514       return;
515   }
516 
517   // Defer code generation when possible if this is a static definition, inline
518   // function etc.  These we only want to emit if they are used.
519   if (MayDeferGeneration(Global)) {
520     // If the value has already been used, add it directly to the
521     // DeferredDeclsToEmit list.
522     const char *MangledName = getMangledName(Global);
523     if (GlobalDeclMap.count(MangledName))
524       DeferredDeclsToEmit.push_back(Global);
525     else {
526       // Otherwise, remember that we saw a deferred decl with this name.  The
527       // first use of the mangled name will cause it to move into
528       // DeferredDeclsToEmit.
529       DeferredDecls[MangledName] = Global;
530     }
531     return;
532   }
533 
534   // Otherwise emit the definition.
535   EmitGlobalDefinition(Global);
536 }
537 
538 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
539   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
540     EmitGlobalFunctionDefinition(FD);
541   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
542     EmitGlobalVarDefinition(VD);
543   } else {
544     assert(0 && "Invalid argument to EmitGlobalDefinition()");
545   }
546 }
547 
548 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
549 /// module, create and return an llvm Function with the specified type. If there
550 /// is something in the module with the specified name, return it potentially
551 /// bitcasted to the right type.
552 ///
553 /// If D is non-null, it specifies a decl that correspond to this.  This is used
554 /// to set the attributes on the function when it is first created.
555 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
556                                                        const llvm::Type *Ty,
557                                                        const FunctionDecl *D) {
558   // Lookup the entry, lazily creating it if necessary.
559   llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
560   if (Entry) {
561     if (Entry->getType()->getElementType() == Ty)
562       return Entry;
563 
564     // Make sure the result is of the correct type.
565     const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
566     return llvm::ConstantExpr::getBitCast(Entry, PTy);
567   }
568 
569   // This is the first use or definition of a mangled name.  If there is a
570   // deferred decl with this name, remember that we need to emit it at the end
571   // of the file.
572   llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
573   DeferredDecls.find(MangledName);
574   if (DDI != DeferredDecls.end()) {
575     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
576     // list, and remove it from DeferredDecls (since we don't need it anymore).
577     DeferredDeclsToEmit.push_back(DDI->second);
578     DeferredDecls.erase(DDI);
579   }
580 
581   // This function doesn't have a complete type (for example, the return
582   // type is an incomplete struct). Use a fake type instead, and make
583   // sure not to try to set attributes.
584   bool ShouldSetAttributes = true;
585   if (!isa<llvm::FunctionType>(Ty)) {
586     Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
587                                  std::vector<const llvm::Type*>(), false);
588     ShouldSetAttributes = false;
589   }
590   llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
591                                              llvm::Function::ExternalLinkage,
592                                              "", &getModule());
593   F->setName(MangledName);
594   if (D && ShouldSetAttributes)
595     SetFunctionAttributes(D, F);
596   Entry = F;
597   return F;
598 }
599 
600 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
601 /// non-null, then this function will use the specified type if it has to
602 /// create it (this occurs when we see a definition of the function).
603 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
604                                                  const llvm::Type *Ty) {
605   // If there was no specific requested type, just convert it now.
606   if (!Ty)
607     Ty = getTypes().ConvertType(D->getType());
608   return GetOrCreateLLVMFunction(getMangledName(D), Ty, D);
609 }
610 
611 /// CreateRuntimeFunction - Create a new runtime function with the specified
612 /// type and name.
613 llvm::Constant *
614 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
615                                      const char *Name) {
616   // Convert Name to be a uniqued string from the IdentifierInfo table.
617   Name = getContext().Idents.get(Name).getName();
618   return GetOrCreateLLVMFunction(Name, FTy, 0);
619 }
620 
621 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
622 /// create and return an llvm GlobalVariable with the specified type.  If there
623 /// is something in the module with the specified name, return it potentially
624 /// bitcasted to the right type.
625 ///
626 /// If D is non-null, it specifies a decl that correspond to this.  This is used
627 /// to set the attributes on the global when it is first created.
628 llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
629                                                      const llvm::PointerType*Ty,
630                                                      const VarDecl *D) {
631   // Lookup the entry, lazily creating it if necessary.
632   llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
633   if (Entry) {
634     if (Entry->getType() == Ty)
635       return Entry;
636 
637     // Make sure the result is of the correct type.
638     return llvm::ConstantExpr::getBitCast(Entry, Ty);
639   }
640 
641   // We don't support __thread yet.
642   if (D && D->isThreadSpecified())
643     ErrorUnsupported(D, "thread local ('__thread') variable", true);
644 
645   // This is the first use or definition of a mangled name.  If there is a
646   // deferred decl with this name, remember that we need to emit it at the end
647   // of the file.
648   llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
649     DeferredDecls.find(MangledName);
650   if (DDI != DeferredDecls.end()) {
651     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
652     // list, and remove it from DeferredDecls (since we don't need it anymore).
653     DeferredDeclsToEmit.push_back(DDI->second);
654     DeferredDecls.erase(DDI);
655   }
656 
657   llvm::GlobalVariable *GV =
658     new llvm::GlobalVariable(Ty->getElementType(), false,
659                              llvm::GlobalValue::ExternalLinkage,
660                              0, "", &getModule(),
661                              0, Ty->getAddressSpace());
662   GV->setName(MangledName);
663 
664   // Handle things which are present even on external declarations.
665   if (D) {
666     // FIXME: This code is overly simple and should be merged with
667     // other global handling.
668     GV->setConstant(D->getType().isConstant(Context));
669 
670     // FIXME: Merge with other attribute handling code.
671     if (D->getStorageClass() == VarDecl::PrivateExtern)
672       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
673 
674     if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
675       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
676   }
677 
678   return Entry = GV;
679 }
680 
681 
682 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
683 /// given global variable.  If Ty is non-null and if the global doesn't exist,
684 /// then it will be greated with the specified type instead of whatever the
685 /// normal requested type would be.
686 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
687                                                   const llvm::Type *Ty) {
688   assert(D->hasGlobalStorage() && "Not a global variable");
689   QualType ASTTy = D->getType();
690   if (Ty == 0)
691     Ty = getTypes().ConvertTypeForMem(ASTTy);
692 
693   const llvm::PointerType *PTy =
694     llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
695   return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
696 }
697 
698 /// CreateRuntimeVariable - Create a new runtime global variable with the
699 /// specified type and name.
700 llvm::Constant *
701 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
702                                      const char *Name) {
703   // Convert Name to be a uniqued string from the IdentifierInfo table.
704   Name = getContext().Idents.get(Name).getName();
705   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
706 }
707 
708 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
709   llvm::Constant *Init = 0;
710   QualType ASTTy = D->getType();
711 
712   if (D->getInit() == 0) {
713     // This is a tentative definition; tentative definitions are
714     // implicitly initialized with { 0 }
715     const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
716     if (ASTTy->isIncompleteArrayType()) {
717       // An incomplete array is normally [ TYPE x 0 ], but we need
718       // to fix it to [ TYPE x 1 ].
719       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
720       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
721     }
722     Init = llvm::Constant::getNullValue(InitTy);
723   } else {
724     Init = EmitConstantExpr(D->getInit(), D->getType());
725     if (!Init) {
726       ErrorUnsupported(D, "static initializer");
727       QualType T = D->getInit()->getType();
728       Init = llvm::UndefValue::get(getTypes().ConvertType(T));
729     }
730   }
731 
732   const llvm::Type* InitType = Init->getType();
733   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
734 
735   // Strip off a bitcast if we got one back.
736   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
737     assert(CE->getOpcode() == llvm::Instruction::BitCast);
738     Entry = CE->getOperand(0);
739   }
740 
741   // Entry is now either a Function or GlobalVariable.
742   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
743 
744   // If we already have this global and it has an initializer, then
745   // we are in the rare situation where we emitted the defining
746   // declaration of the global and are now being asked to emit a
747   // definition which would be common. This occurs, for example, in
748   // the following situation because statics can be emitted out of
749   // order:
750   //
751   //  static int x;
752   //  static int *y = &x;
753   //  static int x = 10;
754   //  int **z = &y;
755   //
756   // Bail here so we don't blow away the definition. Note that if we
757   // can't distinguish here if we emitted a definition with a null
758   // initializer, but this case is safe.
759   if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
760     assert(!D->getInit() && "Emitting multiple definitions of a decl!");
761     return;
762   }
763 
764   // We have a definition after a declaration with the wrong type.
765   // We must make a new GlobalVariable* and update everything that used OldGV
766   // (a declaration or tentative definition) with the new GlobalVariable*
767   // (which will be a definition).
768   //
769   // This happens if there is a prototype for a global (e.g.
770   // "extern int x[];") and then a definition of a different type (e.g.
771   // "int x[10];"). This also happens when an initializer has a different type
772   // from the type of the global (this happens with unions).
773   if (GV == 0 ||
774       GV->getType()->getElementType() != InitType ||
775       GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
776 
777     // Remove the old entry from GlobalDeclMap so that we'll create a new one.
778     GlobalDeclMap.erase(getMangledName(D));
779 
780     // Make a new global with the correct type, this is now guaranteed to work.
781     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
782     GV->takeName(cast<llvm::GlobalValue>(Entry));
783 
784     // Replace all uses of the old global with the new global
785     llvm::Constant *NewPtrForOldDecl =
786         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
787     Entry->replaceAllUsesWith(NewPtrForOldDecl);
788 
789     // Erase the old global, since it is no longer used.
790     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
791   }
792 
793   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
794     SourceManager &SM = Context.getSourceManager();
795     AddAnnotation(EmitAnnotateAttr(GV, AA,
796                               SM.getInstantiationLineNumber(D->getLocation())));
797   }
798 
799   GV->setInitializer(Init);
800   GV->setConstant(D->getType().isConstant(Context));
801   GV->setAlignment(getContext().getDeclAlignInBytes(D));
802 
803   // Set the llvm linkage type as appropriate.
804   if (D->getStorageClass() == VarDecl::Static)
805     GV->setLinkage(llvm::Function::InternalLinkage);
806   else if (D->hasAttr<DLLImportAttr>())
807     GV->setLinkage(llvm::Function::DLLImportLinkage);
808   else if (D->hasAttr<DLLExportAttr>())
809     GV->setLinkage(llvm::Function::DLLExportLinkage);
810   else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
811     GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
812   else if (!CompileOpts.NoCommon &&
813            (!D->hasExternalStorage() && !D->getInit()))
814     GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
815   else
816     GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
817 
818   setGlobalVisibility(GV, D);
819 
820   if (D->hasAttr<UsedAttr>())
821     AddUsedGlobal(GV);
822 
823   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
824     GV->setSection(SA->getName());
825 
826   // Emit global variable debug information.
827   if (CGDebugInfo *DI = getDebugInfo()) {
828     DI->setLocation(D->getLocation());
829     DI->EmitGlobalVariable(GV, D);
830   }
831 }
832 
833 
834 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
835   const llvm::FunctionType *Ty;
836 
837   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
838     bool isVariadic = D->getType()->getAsFunctionProtoType()->isVariadic();
839 
840     Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
841   } else {
842     Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
843 
844     // As a special case, make sure that definitions of K&R function
845     // "type foo()" aren't declared as varargs (which forces the backend
846     // to do unnecessary work).
847     if (D->getType()->isFunctionNoProtoType()) {
848       assert(Ty->isVarArg() && "Didn't lower type as expected");
849       // Due to stret, the lowered function could have arguments.
850       // Just create the same type as was lowered by ConvertType
851       // but strip off the varargs bit.
852       std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
853       Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
854     }
855   }
856 
857   // Get or create the prototype for teh function.
858   llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
859 
860   // Strip off a bitcast if we got one back.
861   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
862     assert(CE->getOpcode() == llvm::Instruction::BitCast);
863     Entry = CE->getOperand(0);
864   }
865 
866 
867   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
868     // If the types mismatch then we have to rewrite the definition.
869     assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
870            "Shouldn't replace non-declaration");
871 
872     // F is the Function* for the one with the wrong type, we must make a new
873     // Function* and update everything that used F (a declaration) with the new
874     // Function* (which will be a definition).
875     //
876     // This happens if there is a prototype for a function
877     // (e.g. "int f()") and then a definition of a different type
878     // (e.g. "int f(int x)").  Start by making a new function of the
879     // correct type, RAUW, then steal the name.
880     GlobalDeclMap.erase(getMangledName(D));
881     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
882     NewFn->takeName(cast<llvm::GlobalValue>(Entry));
883 
884     // Replace uses of F with the Function we will endow with a body.
885     llvm::Constant *NewPtrForOldDecl =
886       llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
887     Entry->replaceAllUsesWith(NewPtrForOldDecl);
888 
889     // Ok, delete the old function now, which is dead.
890     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
891 
892     Entry = NewFn;
893   }
894 
895   llvm::Function *Fn = cast<llvm::Function>(Entry);
896 
897   CodeGenFunction(*this).GenerateCode(D, Fn);
898 
899   SetFunctionAttributesForDefinition(D, Fn);
900 
901   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
902     AddGlobalCtor(Fn, CA->getPriority());
903   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
904     AddGlobalDtor(Fn, DA->getPriority());
905 }
906 
907 void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
908   const AliasAttr *AA = D->getAttr<AliasAttr>();
909   assert(AA && "Not an alias?");
910 
911   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
912 
913   // Unique the name through the identifier table.
914   const char *AliaseeName = AA->getAliasee().c_str();
915   AliaseeName = getContext().Idents.get(AliaseeName).getName();
916 
917   // Create a reference to the named value.  This ensures that it is emitted
918   // if a deferred decl.
919   llvm::Constant *Aliasee;
920   if (isa<llvm::FunctionType>(DeclTy))
921     Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0);
922   else
923     Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
924                                     llvm::PointerType::getUnqual(DeclTy), 0);
925 
926   // Create the new alias itself, but don't set a name yet.
927   llvm::GlobalValue *GA =
928     new llvm::GlobalAlias(Aliasee->getType(),
929                           llvm::Function::ExternalLinkage,
930                           "", Aliasee, &getModule());
931 
932   // See if there is already something with the alias' name in the module.
933   const char *MangledName = getMangledName(D);
934   llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
935 
936   if (Entry && !Entry->isDeclaration()) {
937     // If there is a definition in the module, then it wins over the alias.
938     // This is dubious, but allow it to be safe.  Just ignore the alias.
939     GA->eraseFromParent();
940     return;
941   }
942 
943   if (Entry) {
944     // If there is a declaration in the module, then we had an extern followed
945     // by the alias, as in:
946     //   extern int test6();
947     //   ...
948     //   int test6() __attribute__((alias("test7")));
949     //
950     // Remove it and replace uses of it with the alias.
951 
952     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
953                                                           Entry->getType()));
954     Entry->eraseFromParent();
955   }
956 
957   // Now we know that there is no conflict, set the name.
958   Entry = GA;
959   GA->setName(MangledName);
960 
961   // Alias should never be internal or inline.
962   SetGlobalValueAttributes(D, GVA_Normal, GA, true);
963 }
964 
965 /// getBuiltinLibFunction - Given a builtin id for a function like
966 /// "__builtin_fabsf", return a Function* for "fabsf".
967 llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
968   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
969           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
970          "isn't a lib fn");
971 
972   // Get the name, skip over the __builtin_ prefix (if necessary).
973   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
974   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
975     Name += 10;
976 
977   // Get the type for the builtin.
978   Builtin::Context::GetBuiltinTypeError Error;
979   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
980   assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
981 
982   const llvm::FunctionType *Ty =
983     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
984 
985   // Unique the name through the identifier table.
986   Name = getContext().Idents.get(Name).getName();
987   // FIXME: param attributes for sext/zext etc.
988   return GetOrCreateLLVMFunction(Name, Ty, 0);
989 }
990 
991 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
992                                             unsigned NumTys) {
993   return llvm::Intrinsic::getDeclaration(&getModule(),
994                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
995 }
996 
997 llvm::Function *CodeGenModule::getMemCpyFn() {
998   if (MemCpyFn) return MemCpyFn;
999   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1000   return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
1001 }
1002 
1003 llvm::Function *CodeGenModule::getMemMoveFn() {
1004   if (MemMoveFn) return MemMoveFn;
1005   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1006   return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
1007 }
1008 
1009 llvm::Function *CodeGenModule::getMemSetFn() {
1010   if (MemSetFn) return MemSetFn;
1011   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1012   return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
1013 }
1014 
1015 static void appendFieldAndPadding(CodeGenModule &CGM,
1016                                   std::vector<llvm::Constant*>& Fields,
1017                                   FieldDecl *FieldD, FieldDecl *NextFieldD,
1018                                   llvm::Constant* Field,
1019                                   RecordDecl* RD, const llvm::StructType *STy) {
1020   // Append the field.
1021   Fields.push_back(Field);
1022 
1023   int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
1024 
1025   int NextStructFieldNo;
1026   if (!NextFieldD) {
1027     NextStructFieldNo = STy->getNumElements();
1028   } else {
1029     NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
1030   }
1031 
1032   // Append padding
1033   for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1034     llvm::Constant *C =
1035       llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1036 
1037     Fields.push_back(C);
1038   }
1039 }
1040 
1041 llvm::Constant *CodeGenModule::
1042 GetAddrOfConstantCFString(const StringLiteral *Literal) {
1043   std::string str;
1044   unsigned StringLength;
1045 
1046   bool isUTF16 = false;
1047   if (Literal->containsNonAsciiOrNull()) {
1048     // Convert from UTF-8 to UTF-16.
1049     llvm::SmallVector<UTF16, 128> ToBuf(Literal->getByteLength());
1050     const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1051     UTF16 *ToPtr = &ToBuf[0];
1052 
1053     ConversionResult Result;
1054     Result = ConvertUTF8toUTF16(&FromPtr, FromPtr+Literal->getByteLength(),
1055                                 &ToPtr, ToPtr+Literal->getByteLength(),
1056                                 strictConversion);
1057     if (Result == conversionOK) {
1058       // FIXME: Storing UTF-16 in a C string is a hack to test Unicode strings
1059       // without doing more surgery to this routine. Since we aren't explicitly
1060       // checking for endianness here, it's also a bug (when generating code for
1061       // a target that doesn't match the host endianness). Modeling this as an
1062       // i16 array is likely the cleanest solution.
1063       StringLength = ToPtr-&ToBuf[0];
1064       str.assign((char *)&ToBuf[0], StringLength*2);// Twice as many UTF8 chars.
1065       isUTF16 = true;
1066     } else if (Result == sourceIllegal) {
1067       // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string.
1068       str.assign(Literal->getStrData(), Literal->getByteLength());
1069       StringLength = str.length();
1070     } else
1071       assert(Result == conversionOK && "UTF-8 to UTF-16 conversion failed");
1072 
1073   } else {
1074     str.assign(Literal->getStrData(), Literal->getByteLength());
1075     StringLength = str.length();
1076   }
1077   llvm::StringMapEntry<llvm::Constant *> &Entry =
1078     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1079 
1080   if (llvm::Constant *C = Entry.getValue())
1081     return C;
1082 
1083   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1084   llvm::Constant *Zeros[] = { Zero, Zero };
1085 
1086   if (!CFConstantStringClassRef) {
1087     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1088     Ty = llvm::ArrayType::get(Ty, 0);
1089 
1090     // FIXME: This is fairly broken if
1091     // __CFConstantStringClassReference is already defined, in that it
1092     // will get renamed and the user will most likely see an opaque
1093     // error message. This is a general issue with relying on
1094     // particular names.
1095     llvm::GlobalVariable *GV =
1096       new llvm::GlobalVariable(Ty, false,
1097                                llvm::GlobalVariable::ExternalLinkage, 0,
1098                                "__CFConstantStringClassReference",
1099                                &getModule());
1100 
1101     // Decay array -> ptr
1102     CFConstantStringClassRef =
1103       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1104   }
1105 
1106   QualType CFTy = getContext().getCFConstantStringType();
1107   RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
1108 
1109   const llvm::StructType *STy =
1110     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1111 
1112   std::vector<llvm::Constant*> Fields;
1113   RecordDecl::field_iterator Field = CFRD->field_begin(getContext());
1114 
1115   // Class pointer.
1116   FieldDecl *CurField = *Field++;
1117   FieldDecl *NextField = *Field++;
1118   appendFieldAndPadding(*this, Fields, CurField, NextField,
1119                         CFConstantStringClassRef, CFRD, STy);
1120 
1121   // Flags.
1122   CurField = NextField;
1123   NextField = *Field++;
1124   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1125   appendFieldAndPadding(*this, Fields, CurField, NextField,
1126                         isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0)
1127                                 : llvm::ConstantInt::get(Ty, 0x07C8),
1128                         CFRD, STy);
1129 
1130   // String pointer.
1131   CurField = NextField;
1132   NextField = *Field++;
1133   llvm::Constant *C = llvm::ConstantArray::get(str);
1134 
1135   const char *Sect, *Prefix;
1136   bool isConstant;
1137   if (isUTF16) {
1138     Prefix = getContext().Target.getUnicodeStringSymbolPrefix();
1139     Sect = getContext().Target.getUnicodeStringSection();
1140     // FIXME: Why does GCC not set constant here?
1141     isConstant = false;
1142   } else {
1143     Prefix = getContext().Target.getStringSymbolPrefix(true);
1144     Sect = getContext().Target.getCFStringDataSection();
1145     // FIXME: -fwritable-strings should probably affect this, but we
1146     // are following gcc here.
1147     isConstant = true;
1148   }
1149   llvm::GlobalVariable *GV =
1150     new llvm::GlobalVariable(C->getType(), isConstant,
1151                              llvm::GlobalValue::InternalLinkage,
1152                              C, Prefix, &getModule());
1153   if (Sect)
1154     GV->setSection(Sect);
1155   if (isUTF16) {
1156     unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8;
1157     GV->setAlignment(Align);
1158   }
1159   appendFieldAndPadding(*this, Fields, CurField, NextField,
1160                         llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2),
1161                         CFRD, STy);
1162 
1163   // String length.
1164   CurField = NextField;
1165   NextField = 0;
1166   Ty = getTypes().ConvertType(getContext().LongTy);
1167   appendFieldAndPadding(*this, Fields, CurField, NextField,
1168                         llvm::ConstantInt::get(Ty, StringLength), CFRD, STy);
1169 
1170   // The struct.
1171   C = llvm::ConstantStruct::get(STy, Fields);
1172   GV = new llvm::GlobalVariable(C->getType(), true,
1173                                 llvm::GlobalVariable::InternalLinkage, C,
1174                                 getContext().Target.getCFStringSymbolPrefix(),
1175                                 &getModule());
1176   if (const char *Sect = getContext().Target.getCFStringSection())
1177     GV->setSection(Sect);
1178   Entry.setValue(GV);
1179 
1180   return GV;
1181 }
1182 
1183 /// GetStringForStringLiteral - Return the appropriate bytes for a
1184 /// string literal, properly padded to match the literal type.
1185 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1186   const char *StrData = E->getStrData();
1187   unsigned Len = E->getByteLength();
1188 
1189   const ConstantArrayType *CAT =
1190     getContext().getAsConstantArrayType(E->getType());
1191   assert(CAT && "String isn't pointer or array!");
1192 
1193   // Resize the string to the right size.
1194   std::string Str(StrData, StrData+Len);
1195   uint64_t RealLen = CAT->getSize().getZExtValue();
1196 
1197   if (E->isWide())
1198     RealLen *= getContext().Target.getWCharWidth()/8;
1199 
1200   Str.resize(RealLen, '\0');
1201 
1202   return Str;
1203 }
1204 
1205 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1206 /// constant array for the given string literal.
1207 llvm::Constant *
1208 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1209   // FIXME: This can be more efficient.
1210   return GetAddrOfConstantString(GetStringForStringLiteral(S));
1211 }
1212 
1213 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1214 /// array for the given ObjCEncodeExpr node.
1215 llvm::Constant *
1216 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1217   std::string Str;
1218   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1219 
1220   return GetAddrOfConstantCString(Str);
1221 }
1222 
1223 
1224 /// GenerateWritableString -- Creates storage for a string literal.
1225 static llvm::Constant *GenerateStringLiteral(const std::string &str,
1226                                              bool constant,
1227                                              CodeGenModule &CGM,
1228                                              const char *GlobalName) {
1229   // Create Constant for this string literal. Don't add a '\0'.
1230   llvm::Constant *C = llvm::ConstantArray::get(str, false);
1231 
1232   // Create a global variable for this string
1233   return new llvm::GlobalVariable(C->getType(), constant,
1234                                   llvm::GlobalValue::InternalLinkage,
1235                                   C, GlobalName, &CGM.getModule());
1236 }
1237 
1238 /// GetAddrOfConstantString - Returns a pointer to a character array
1239 /// containing the literal. This contents are exactly that of the
1240 /// given string, i.e. it will not be null terminated automatically;
1241 /// see GetAddrOfConstantCString. Note that whether the result is
1242 /// actually a pointer to an LLVM constant depends on
1243 /// Feature.WriteableStrings.
1244 ///
1245 /// The result has pointer to array type.
1246 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1247                                                        const char *GlobalName) {
1248   bool IsConstant = !Features.WritableStrings;
1249 
1250   // Get the default prefix if a name wasn't specified.
1251   if (!GlobalName)
1252     GlobalName = getContext().Target.getStringSymbolPrefix(IsConstant);
1253 
1254   // Don't share any string literals if strings aren't constant.
1255   if (!IsConstant)
1256     return GenerateStringLiteral(str, false, *this, GlobalName);
1257 
1258   llvm::StringMapEntry<llvm::Constant *> &Entry =
1259   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1260 
1261   if (Entry.getValue())
1262     return Entry.getValue();
1263 
1264   // Create a global variable for this.
1265   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1266   Entry.setValue(C);
1267   return C;
1268 }
1269 
1270 /// GetAddrOfConstantCString - Returns a pointer to a character
1271 /// array containing the literal and a terminating '\-'
1272 /// character. The result has pointer to array type.
1273 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1274                                                         const char *GlobalName){
1275   return GetAddrOfConstantString(str + '\0', GlobalName);
1276 }
1277 
1278 /// EmitObjCPropertyImplementations - Emit information for synthesized
1279 /// properties for an implementation.
1280 void CodeGenModule::EmitObjCPropertyImplementations(const
1281                                                     ObjCImplementationDecl *D) {
1282   for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1283          e = D->propimpl_end(); i != e; ++i) {
1284     ObjCPropertyImplDecl *PID = *i;
1285 
1286     // Dynamic is just for type-checking.
1287     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1288       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1289 
1290       // Determine which methods need to be implemented, some may have
1291       // been overridden. Note that ::isSynthesized is not the method
1292       // we want, that just indicates if the decl came from a
1293       // property. What we want to know is if the method is defined in
1294       // this implementation.
1295       if (!D->getInstanceMethod(PD->getGetterName()))
1296         CodeGenFunction(*this).GenerateObjCGetter(
1297                                  const_cast<ObjCImplementationDecl *>(D), PID);
1298       if (!PD->isReadOnly() &&
1299           !D->getInstanceMethod(PD->getSetterName()))
1300         CodeGenFunction(*this).GenerateObjCSetter(
1301                                  const_cast<ObjCImplementationDecl *>(D), PID);
1302     }
1303   }
1304 }
1305 
1306 /// EmitNamespace - Emit all declarations in a namespace.
1307 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1308   for (RecordDecl::decl_iterator I = ND->decls_begin(getContext()),
1309          E = ND->decls_end(getContext());
1310        I != E; ++I)
1311     EmitTopLevelDecl(*I);
1312 }
1313 
1314 // EmitLinkageSpec - Emit all declarations in a linkage spec.
1315 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1316   if (LSD->getLanguage() != LinkageSpecDecl::lang_c) {
1317     ErrorUnsupported(LSD, "linkage spec");
1318     return;
1319   }
1320 
1321   for (RecordDecl::decl_iterator I = LSD->decls_begin(getContext()),
1322          E = LSD->decls_end(getContext());
1323        I != E; ++I)
1324     EmitTopLevelDecl(*I);
1325 }
1326 
1327 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1328 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1329   // If an error has occurred, stop code generation, but continue
1330   // parsing and semantic analysis (to ensure all warnings and errors
1331   // are emitted).
1332   if (Diags.hasErrorOccurred())
1333     return;
1334 
1335   switch (D->getKind()) {
1336   case Decl::CXXMethod:
1337   case Decl::Function:
1338   case Decl::Var:
1339     EmitGlobal(cast<ValueDecl>(D));
1340     break;
1341 
1342   case Decl::Namespace:
1343     EmitNamespace(cast<NamespaceDecl>(D));
1344     break;
1345 
1346     // Objective-C Decls
1347 
1348   // Forward declarations, no (immediate) code generation.
1349   case Decl::ObjCClass:
1350   case Decl::ObjCForwardProtocol:
1351   case Decl::ObjCCategory:
1352     break;
1353   case Decl::ObjCInterface:
1354     // If we already laid out this interface due to an @class, and if we
1355     // codegen'd a reference it, update the 'opaque' type to be a real type now.
1356     Types.UpdateCompletedType(cast<ObjCInterfaceDecl>(D));
1357     break;
1358 
1359   case Decl::ObjCProtocol:
1360     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1361     break;
1362 
1363   case Decl::ObjCCategoryImpl:
1364     // Categories have properties but don't support synthesize so we
1365     // can ignore them here.
1366     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1367     break;
1368 
1369   case Decl::ObjCImplementation: {
1370     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1371     EmitObjCPropertyImplementations(OMD);
1372     Runtime->GenerateClass(OMD);
1373     break;
1374   }
1375   case Decl::ObjCMethod: {
1376     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1377     // If this is not a prototype, emit the body.
1378     if (OMD->getBody())
1379       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1380     break;
1381   }
1382   case Decl::ObjCCompatibleAlias:
1383     // compatibility-alias is a directive and has no code gen.
1384     break;
1385 
1386   case Decl::LinkageSpec:
1387     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
1388     break;
1389 
1390   case Decl::FileScopeAsm: {
1391     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1392     std::string AsmString(AD->getAsmString()->getStrData(),
1393                           AD->getAsmString()->getByteLength());
1394 
1395     const std::string &S = getModule().getModuleInlineAsm();
1396     if (S.empty())
1397       getModule().setModuleInlineAsm(AsmString);
1398     else
1399       getModule().setModuleInlineAsm(S + '\n' + AsmString);
1400     break;
1401   }
1402 
1403   default:
1404     // Make sure we handled everything we should, every other kind is
1405     // a non-top-level decl.  FIXME: Would be nice to have an
1406     // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1407     // that easily.
1408     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1409   }
1410 }
1411