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