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