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