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