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