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