1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
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 is the internal per-translation-unit state used for llvm translation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef CLANG_CODEGEN_CODEGENMODULE_H
15 #define CLANG_CODEGEN_CODEGENMODULE_H
16 
17 #include "clang/Basic/ABI.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/GlobalDecl.h"
23 #include "clang/AST/Mangle.h"
24 #include "CGVTables.h"
25 #include "CodeGenTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/StringSet.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/Support/ValueHandle.h"
32 
33 namespace llvm {
34   class Module;
35   class Constant;
36   class ConstantInt;
37   class Function;
38   class GlobalValue;
39   class TargetData;
40   class FunctionType;
41   class LLVMContext;
42 }
43 
44 namespace clang {
45   class TargetCodeGenInfo;
46   class ASTContext;
47   class FunctionDecl;
48   class IdentifierInfo;
49   class ObjCMethodDecl;
50   class ObjCImplementationDecl;
51   class ObjCCategoryImplDecl;
52   class ObjCProtocolDecl;
53   class ObjCEncodeExpr;
54   class BlockExpr;
55   class CharUnits;
56   class Decl;
57   class Expr;
58   class Stmt;
59   class StringLiteral;
60   class NamedDecl;
61   class ValueDecl;
62   class VarDecl;
63   class LangOptions;
64   class CodeGenOptions;
65   class Diagnostic;
66   class AnnotateAttr;
67   class CXXDestructorDecl;
68   class MangleBuffer;
69 
70 namespace CodeGen {
71 
72   class CallArgList;
73   class CodeGenFunction;
74   class CodeGenTBAA;
75   class CGCXXABI;
76   class CGDebugInfo;
77   class CGObjCRuntime;
78   class BlockFieldFlags;
79   class FunctionArgList;
80 
81   struct OrderGlobalInits {
82     unsigned int priority;
83     unsigned int lex_order;
84     OrderGlobalInits(unsigned int p, unsigned int l)
85       : priority(p), lex_order(l) {}
86 
87     bool operator==(const OrderGlobalInits &RHS) const {
88       return priority == RHS.priority &&
89              lex_order == RHS.lex_order;
90     }
91 
92     bool operator<(const OrderGlobalInits &RHS) const {
93       if (priority < RHS.priority)
94         return true;
95 
96       return priority == RHS.priority && lex_order < RHS.lex_order;
97     }
98   };
99 
100   struct CodeGenTypeCache {
101     /// void
102     llvm::Type *VoidTy;
103 
104     /// i8, i32, and i64
105     llvm::IntegerType *Int8Ty, *Int32Ty, *Int64Ty;
106 
107     /// int
108     llvm::IntegerType *IntTy;
109 
110     /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
111     union {
112       llvm::IntegerType *IntPtrTy;
113       llvm::IntegerType *SizeTy;
114       llvm::IntegerType *PtrDiffTy;
115     };
116 
117     /// void* in address space 0
118     union {
119       llvm::PointerType *VoidPtrTy;
120       llvm::PointerType *Int8PtrTy;
121     };
122 
123     /// void** in address space 0
124     union {
125       llvm::PointerType *VoidPtrPtrTy;
126       llvm::PointerType *Int8PtrPtrTy;
127     };
128 
129     /// The width of a pointer into the generic address space.
130     unsigned char PointerWidthInBits;
131 
132     /// The alignment of a pointer into the generic address space.
133     unsigned char PointerAlignInBytes;
134   };
135 
136 struct RREntrypoints {
137   RREntrypoints() { memset(this, 0, sizeof(*this)); }
138   /// void objc_autoreleasePoolPop(void*);
139   llvm::Constant *objc_autoreleasePoolPop;
140 
141   /// void *objc_autoreleasePoolPush(void);
142   llvm::Constant *objc_autoreleasePoolPush;
143 };
144 
145 struct ARCEntrypoints {
146   ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
147 
148   /// id objc_autorelease(id);
149   llvm::Constant *objc_autorelease;
150 
151   /// id objc_autoreleaseReturnValue(id);
152   llvm::Constant *objc_autoreleaseReturnValue;
153 
154   /// void objc_copyWeak(id *dest, id *src);
155   llvm::Constant *objc_copyWeak;
156 
157   /// void objc_destroyWeak(id*);
158   llvm::Constant *objc_destroyWeak;
159 
160   /// id objc_initWeak(id*, id);
161   llvm::Constant *objc_initWeak;
162 
163   /// id objc_loadWeak(id*);
164   llvm::Constant *objc_loadWeak;
165 
166   /// id objc_loadWeakRetained(id*);
167   llvm::Constant *objc_loadWeakRetained;
168 
169   /// void objc_moveWeak(id *dest, id *src);
170   llvm::Constant *objc_moveWeak;
171 
172   /// id objc_retain(id);
173   llvm::Constant *objc_retain;
174 
175   /// id objc_retainAutorelease(id);
176   llvm::Constant *objc_retainAutorelease;
177 
178   /// id objc_retainAutoreleaseReturnValue(id);
179   llvm::Constant *objc_retainAutoreleaseReturnValue;
180 
181   /// id objc_retainAutoreleasedReturnValue(id);
182   llvm::Constant *objc_retainAutoreleasedReturnValue;
183 
184   /// id objc_retainBlock(id);
185   llvm::Constant *objc_retainBlock;
186 
187   /// void objc_release(id);
188   llvm::Constant *objc_release;
189 
190   /// id objc_storeStrong(id*, id);
191   llvm::Constant *objc_storeStrong;
192 
193   /// id objc_storeWeak(id*, id);
194   llvm::Constant *objc_storeWeak;
195 
196   /// A void(void) inline asm to use to mark that the return value of
197   /// a call will be immediately retain.
198   llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
199 };
200 
201 /// CodeGenModule - This class organizes the cross-function state that is used
202 /// while generating LLVM code.
203 class CodeGenModule : public CodeGenTypeCache {
204   CodeGenModule(const CodeGenModule&);  // DO NOT IMPLEMENT
205   void operator=(const CodeGenModule&); // DO NOT IMPLEMENT
206 
207   typedef std::vector<std::pair<llvm::Constant*, int> > CtorList;
208 
209   ASTContext &Context;
210   const LangOptions &Features;
211   const CodeGenOptions &CodeGenOpts;
212   llvm::Module &TheModule;
213   const llvm::TargetData &TheTargetData;
214   mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
215   Diagnostic &Diags;
216   CGCXXABI &ABI;
217   CodeGenTypes Types;
218   CodeGenTBAA *TBAA;
219 
220   /// VTables - Holds information about C++ vtables.
221   CodeGenVTables VTables;
222   friend class CodeGenVTables;
223 
224   CGObjCRuntime* ObjCRuntime;
225   CGDebugInfo* DebugInfo;
226   ARCEntrypoints *ARCData;
227   RREntrypoints *RRData;
228 
229   // WeakRefReferences - A set of references that have only been seen via
230   // a weakref so far. This is used to remove the weak of the reference if we ever
231   // see a direct reference or a definition.
232   llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
233 
234   /// DeferredDecls - This contains all the decls which have definitions but
235   /// which are deferred for emission and therefore should only be output if
236   /// they are actually used.  If a decl is in this, then it is known to have
237   /// not been referenced yet.
238   llvm::StringMap<GlobalDecl> DeferredDecls;
239 
240   /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen
241   /// that *are* actually referenced.  These get code generated when the module
242   /// is done.
243   std::vector<GlobalDecl> DeferredDeclsToEmit;
244 
245   /// LLVMUsed - List of global values which are required to be
246   /// present in the object file; bitcast to i8*. This is used for
247   /// forcing visibility of symbols which may otherwise be optimized
248   /// out.
249   std::vector<llvm::WeakVH> LLVMUsed;
250 
251   /// GlobalCtors - Store the list of global constructors and their respective
252   /// priorities to be emitted when the translation unit is complete.
253   CtorList GlobalCtors;
254 
255   /// GlobalDtors - Store the list of global destructors and their respective
256   /// priorities to be emitted when the translation unit is complete.
257   CtorList GlobalDtors;
258 
259   /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names.
260   llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames;
261   llvm::BumpPtrAllocator MangledNamesAllocator;
262 
263   std::vector<llvm::Constant*> Annotations;
264 
265   llvm::StringMap<llvm::Constant*> CFConstantStringMap;
266   llvm::StringMap<llvm::GlobalVariable*> ConstantStringMap;
267   llvm::DenseMap<const Decl*, llvm::Value*> StaticLocalDeclMap;
268 
269   /// CXXGlobalInits - Global variables with initializers that need to run
270   /// before main.
271   std::vector<llvm::Constant*> CXXGlobalInits;
272 
273   /// When a C++ decl with an initializer is deferred, null is
274   /// appended to CXXGlobalInits, and the index of that null is placed
275   /// here so that the initializer will be performed in the correct
276   /// order.
277   llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
278 
279   /// - Global variables with initializers whose order of initialization
280   /// is set by init_priority attribute.
281 
282   SmallVector<std::pair<OrderGlobalInits, llvm::Function*>, 8>
283     PrioritizedCXXGlobalInits;
284 
285   /// CXXGlobalDtors - Global destructor functions and arguments that need to
286   /// run on termination.
287   std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
288 
289   /// @name Cache for Objective-C runtime types
290   /// @{
291 
292   /// CFConstantStringClassRef - Cached reference to the class for constant
293   /// strings. This value has type int * but is actually an Obj-C class pointer.
294   llvm::Constant *CFConstantStringClassRef;
295 
296   /// ConstantStringClassRef - Cached reference to the class for constant
297   /// strings. This value has type int * but is actually an Obj-C class pointer.
298   llvm::Constant *ConstantStringClassRef;
299 
300   /// \brief The LLVM type corresponding to NSConstantString.
301   llvm::StructType *NSConstantStringType;
302 
303   /// \brief The type used to describe the state of a fast enumeration in
304   /// Objective-C's for..in loop.
305   QualType ObjCFastEnumerationStateType;
306 
307   /// @}
308 
309   /// Lazily create the Objective-C runtime
310   void createObjCRuntime();
311 
312   llvm::LLVMContext &VMContext;
313 
314   /// @name Cache for Blocks Runtime Globals
315   /// @{
316 
317   const VarDecl *NSConcreteGlobalBlockDecl;
318   const VarDecl *NSConcreteStackBlockDecl;
319   llvm::Constant *NSConcreteGlobalBlock;
320   llvm::Constant *NSConcreteStackBlock;
321 
322   const FunctionDecl *BlockObjectAssignDecl;
323   const FunctionDecl *BlockObjectDisposeDecl;
324   llvm::Constant *BlockObjectAssign;
325   llvm::Constant *BlockObjectDispose;
326 
327   llvm::Type *BlockDescriptorType;
328   llvm::Type *GenericBlockLiteralType;
329 
330   struct {
331     int GlobalUniqueCount;
332   } Block;
333 
334   /// @}
335 public:
336   CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
337                 llvm::Module &M, const llvm::TargetData &TD, Diagnostic &Diags);
338 
339   ~CodeGenModule();
340 
341   /// Release - Finalize LLVM code generation.
342   void Release();
343 
344   /// getObjCRuntime() - Return a reference to the configured
345   /// Objective-C runtime.
346   CGObjCRuntime &getObjCRuntime() {
347     if (!ObjCRuntime) createObjCRuntime();
348     return *ObjCRuntime;
349   }
350 
351   /// hasObjCRuntime() - Return true iff an Objective-C runtime has
352   /// been configured.
353   bool hasObjCRuntime() { return !!ObjCRuntime; }
354 
355   /// getCXXABI() - Return a reference to the configured C++ ABI.
356   CGCXXABI &getCXXABI() { return ABI; }
357 
358   ARCEntrypoints &getARCEntrypoints() const {
359     assert(getLangOptions().ObjCAutoRefCount && ARCData != 0);
360     return *ARCData;
361   }
362 
363   RREntrypoints &getRREntrypoints() const {
364     assert(RRData != 0);
365     return *RRData;
366   }
367 
368   llvm::Value *getStaticLocalDeclAddress(const VarDecl *VD) {
369     return StaticLocalDeclMap[VD];
370   }
371   void setStaticLocalDeclAddress(const VarDecl *D,
372                              llvm::GlobalVariable *GV) {
373     StaticLocalDeclMap[D] = GV;
374   }
375 
376   CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
377 
378   ASTContext &getContext() const { return Context; }
379   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
380   const LangOptions &getLangOptions() const { return Features; }
381   llvm::Module &getModule() const { return TheModule; }
382   CodeGenTypes &getTypes() { return Types; }
383   CodeGenVTables &getVTables() { return VTables; }
384   Diagnostic &getDiags() const { return Diags; }
385   const llvm::TargetData &getTargetData() const { return TheTargetData; }
386   const TargetInfo &getTarget() const { return Context.Target; }
387   llvm::LLVMContext &getLLVMContext() { return VMContext; }
388   const TargetCodeGenInfo &getTargetCodeGenInfo();
389   bool isTargetDarwin() const;
390 
391   bool shouldUseTBAA() const { return TBAA != 0; }
392 
393   llvm::MDNode *getTBAAInfo(QualType QTy);
394 
395   static void DecorateInstruction(llvm::Instruction *Inst,
396                                   llvm::MDNode *TBAAInfo);
397 
398   /// getSize - Emit the given number of characters as a value of type size_t.
399   llvm::ConstantInt *getSize(CharUnits numChars);
400 
401   /// setGlobalVisibility - Set the visibility for the given LLVM
402   /// GlobalValue.
403   void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
404 
405   /// TypeVisibilityKind - The kind of global variable that is passed to
406   /// setTypeVisibility
407   enum TypeVisibilityKind {
408     TVK_ForVTT,
409     TVK_ForVTable,
410     TVK_ForConstructionVTable,
411     TVK_ForRTTI,
412     TVK_ForRTTIName
413   };
414 
415   /// setTypeVisibility - Set the visibility for the given global
416   /// value which holds information about a type.
417   void setTypeVisibility(llvm::GlobalValue *GV, const CXXRecordDecl *D,
418                          TypeVisibilityKind TVK) const;
419 
420   static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
421     switch (V) {
422     case DefaultVisibility:   return llvm::GlobalValue::DefaultVisibility;
423     case HiddenVisibility:    return llvm::GlobalValue::HiddenVisibility;
424     case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
425     }
426     llvm_unreachable("unknown visibility!");
427     return llvm::GlobalValue::DefaultVisibility;
428   }
429 
430   llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
431     if (isa<CXXConstructorDecl>(GD.getDecl()))
432       return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
433                                      GD.getCtorType());
434     else if (isa<CXXDestructorDecl>(GD.getDecl()))
435       return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
436                                      GD.getDtorType());
437     else if (isa<FunctionDecl>(GD.getDecl()))
438       return GetAddrOfFunction(GD);
439     else
440       return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
441   }
442 
443   /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the given
444   /// type. If a variable with a different type already exists then a new
445   /// variable with the right type will be created and all uses of the old
446   /// variable will be replaced with a bitcast to the new variable.
447   llvm::GlobalVariable *
448   CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
449                                     llvm::GlobalValue::LinkageTypes Linkage);
450 
451   /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
452   /// given global variable.  If Ty is non-null and if the global doesn't exist,
453   /// then it will be greated with the specified type instead of whatever the
454   /// normal requested type would be.
455   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
456                                      llvm::Type *Ty = 0);
457 
458 
459   /// GetAddrOfFunction - Return the address of the given function.  If Ty is
460   /// non-null, then this function will use the specified type if it has to
461   /// create it.
462   llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
463                                     llvm::Type *Ty = 0,
464                                     bool ForVTable = false);
465 
466   /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor
467   /// for the given type.
468   llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
469 
470   /// GetAddrOfThunk - Get the address of the thunk for the given global decl.
471   llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
472 
473   /// GetWeakRefReference - Get a reference to the target of VD.
474   llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
475 
476   /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to
477   /// a class. Returns null if the offset is 0.
478   llvm::Constant *
479   GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
480                                CastExpr::path_const_iterator PathBegin,
481                                CastExpr::path_const_iterator PathEnd);
482 
483   /// A pair of helper functions for a __block variable.
484   class ByrefHelpers : public llvm::FoldingSetNode {
485   public:
486     llvm::Constant *CopyHelper;
487     llvm::Constant *DisposeHelper;
488 
489     /// The alignment of the field.  This is important because
490     /// different offsets to the field within the byref struct need to
491     /// have different helper functions.
492     CharUnits Alignment;
493 
494     ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
495     virtual ~ByrefHelpers();
496 
497     void Profile(llvm::FoldingSetNodeID &id) const {
498       id.AddInteger(Alignment.getQuantity());
499       profileImpl(id);
500     }
501     virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
502 
503     virtual bool needsCopy() const { return true; }
504     virtual void emitCopy(CodeGenFunction &CGF,
505                           llvm::Value *dest, llvm::Value *src) = 0;
506 
507     virtual bool needsDispose() const { return true; }
508     virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
509   };
510 
511   llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
512 
513   /// getUniqueBlockCount - Fetches the global unique block count.
514   int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
515 
516   /// getBlockDescriptorType - Fetches the type of a generic block
517   /// descriptor.
518   llvm::Type *getBlockDescriptorType();
519 
520   /// getGenericBlockLiteralType - The type of a generic block literal.
521   llvm::Type *getGenericBlockLiteralType();
522 
523   /// GetAddrOfGlobalBlock - Gets the address of a block which
524   /// requires no captures.
525   llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
526 
527   /// GetStringForStringLiteral - Return the appropriate bytes for a string
528   /// literal, properly padded to match the literal type. If only the address of
529   /// a constant is needed consider using GetAddrOfConstantStringLiteral.
530   std::string GetStringForStringLiteral(const StringLiteral *E);
531 
532   /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
533   /// for the given string.
534   llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
535 
536   /// GetAddrOfConstantString - Return a pointer to a constant NSString object
537   /// for the given string. Or a user defined String object as defined via
538   /// -fconstant-string-class=class_name option.
539   llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal);
540 
541   /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array
542   /// for the given string literal.
543   llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
544 
545   /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
546   /// array for the given ObjCEncodeExpr node.
547   llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
548 
549   /// GetAddrOfConstantString - Returns a pointer to a character array
550   /// containing the literal. This contents are exactly that of the given
551   /// string, i.e. it will not be null terminated automatically; see
552   /// GetAddrOfConstantCString. Note that whether the result is actually a
553   /// pointer to an LLVM constant depends on Feature.WriteableStrings.
554   ///
555   /// The result has pointer to array type.
556   ///
557   /// \param GlobalName If provided, the name to use for the global
558   /// (if one is created).
559   llvm::Constant *GetAddrOfConstantString(StringRef Str,
560                                           const char *GlobalName=0,
561                                           unsigned Alignment=1);
562 
563   /// GetAddrOfConstantCString - Returns a pointer to a character array
564   /// containing the literal and a terminating '\0' character. The result has
565   /// pointer to array type.
566   ///
567   /// \param GlobalName If provided, the name to use for the global (if one is
568   /// created).
569   llvm::Constant *GetAddrOfConstantCString(const std::string &str,
570                                            const char *GlobalName=0,
571                                            unsigned Alignment=1);
572 
573   /// \brief Retrieve the record type that describes the state of an
574   /// Objective-C fast enumeration loop (for..in).
575   QualType getObjCFastEnumerationStateType();
576 
577   /// GetAddrOfCXXConstructor - Return the address of the constructor of the
578   /// given type.
579   llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
580                                              CXXCtorType ctorType,
581                                              const CGFunctionInfo *fnInfo = 0);
582 
583   /// GetAddrOfCXXDestructor - Return the address of the constructor of the
584   /// given type.
585   llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
586                                             CXXDtorType dtorType,
587                                             const CGFunctionInfo *fnInfo = 0);
588 
589   /// getBuiltinLibFunction - Given a builtin id for a function like
590   /// "__builtin_fabsf", return a Function* for "fabsf".
591   llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
592                                      unsigned BuiltinID);
593 
594   llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys =
595                                                  ArrayRef<llvm::Type*>());
596 
597   /// EmitTopLevelDecl - Emit code for a single top level declaration.
598   void EmitTopLevelDecl(Decl *D);
599 
600   /// AddUsedGlobal - Add a global which should be forced to be
601   /// present in the object file; these are emitted to the llvm.used
602   /// metadata global.
603   void AddUsedGlobal(llvm::GlobalValue *GV);
604 
605   void AddAnnotation(llvm::Constant *C) { Annotations.push_back(C); }
606 
607   /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global
608   /// destructor function.
609   void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
610     CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object));
611   }
612 
613   /// CreateRuntimeFunction - Create a new runtime function with the specified
614   /// type and name.
615   llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
616                                         StringRef Name,
617                                         llvm::Attributes ExtraAttrs =
618                                           llvm::Attribute::None);
619   /// CreateRuntimeVariable - Create a new runtime global variable with the
620   /// specified type and name.
621   llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
622                                         StringRef Name);
623 
624   ///@name Custom Blocks Runtime Interfaces
625   ///@{
626 
627   llvm::Constant *getNSConcreteGlobalBlock();
628   llvm::Constant *getNSConcreteStackBlock();
629   llvm::Constant *getBlockObjectAssign();
630   llvm::Constant *getBlockObjectDispose();
631 
632   ///@}
633 
634   // UpdateCompleteType - Make sure that this type is translated.
635   void UpdateCompletedType(const TagDecl *TD);
636 
637   llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
638 
639   /// EmitConstantExpr - Try to emit the given expression as a
640   /// constant; returns 0 if the expression cannot be emitted as a
641   /// constant.
642   llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
643                                    CodeGenFunction *CGF = 0);
644 
645   /// EmitNullConstant - Return the result of value-initializing the given
646   /// type, i.e. a null expression of the given type.  This is usually,
647   /// but not always, an LLVM null constant.
648   llvm::Constant *EmitNullConstant(QualType T);
649 
650   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
651                                    const AnnotateAttr *AA, unsigned LineNo);
652 
653   /// Error - Emit a general error that something can't be done.
654   void Error(SourceLocation loc, StringRef error);
655 
656   /// ErrorUnsupported - Print out an error that codegen doesn't support the
657   /// specified stmt yet.
658   /// \param OmitOnError - If true, then this error should only be emitted if no
659   /// other errors have been reported.
660   void ErrorUnsupported(const Stmt *S, const char *Type,
661                         bool OmitOnError=false);
662 
663   /// ErrorUnsupported - Print out an error that codegen doesn't support the
664   /// specified decl yet.
665   /// \param OmitOnError - If true, then this error should only be emitted if no
666   /// other errors have been reported.
667   void ErrorUnsupported(const Decl *D, const char *Type,
668                         bool OmitOnError=false);
669 
670   /// SetInternalFunctionAttributes - Set the attributes on the LLVM
671   /// function for the given decl and function info. This applies
672   /// attributes necessary for handling the ABI as well as user
673   /// specified attributes like section.
674   void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
675                                      const CGFunctionInfo &FI);
676 
677   /// SetLLVMFunctionAttributes - Set the LLVM function attributes
678   /// (sext, zext, etc).
679   void SetLLVMFunctionAttributes(const Decl *D,
680                                  const CGFunctionInfo &Info,
681                                  llvm::Function *F);
682 
683   /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
684   /// which only apply to a function definintion.
685   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
686 
687   /// ReturnTypeUsesSRet - Return true iff the given type uses 'sret' when used
688   /// as a return type.
689   bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
690 
691   /// ReturnTypeUsesSret - Return true iff the given type uses 'fpret' when used
692   /// as a return type.
693   bool ReturnTypeUsesFPRet(QualType ResultType);
694 
695   /// ConstructAttributeList - Get the LLVM attributes and calling convention to
696   /// use for a particular function type.
697   ///
698   /// \param Info - The function type information.
699   /// \param TargetDecl - The decl these attributes are being constructed
700   /// for. If supplied the attributes applied to this decl may contribute to the
701   /// function attributes and calling convention.
702   /// \param PAL [out] - On return, the attribute list to use.
703   /// \param CallingConv [out] - On return, the LLVM calling convention to use.
704   void ConstructAttributeList(const CGFunctionInfo &Info,
705                               const Decl *TargetDecl,
706                               AttributeListType &PAL,
707                               unsigned &CallingConv);
708 
709   StringRef getMangledName(GlobalDecl GD);
710   void getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
711                            const BlockDecl *BD);
712 
713   void EmitTentativeDefinition(const VarDecl *D);
714 
715   void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
716 
717   llvm::GlobalVariable::LinkageTypes
718   getFunctionLinkage(const FunctionDecl *FD);
719 
720   void setFunctionLinkage(const FunctionDecl *FD, llvm::GlobalValue *V) {
721     V->setLinkage(getFunctionLinkage(FD));
722   }
723 
724   /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT,
725   /// and type information of the given class.
726   llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
727 
728   /// GetTargetTypeStoreSize - Return the store size, in character units, of
729   /// the given LLVM type.
730   CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
731 
732   /// GetLLVMLinkageVarDefinition - Returns LLVM linkage for a global
733   /// variable.
734   llvm::GlobalValue::LinkageTypes
735   GetLLVMLinkageVarDefinition(const VarDecl *D,
736                               llvm::GlobalVariable *GV);
737 
738   std::vector<const CXXRecordDecl*> DeferredVTables;
739 
740 private:
741   llvm::GlobalValue *GetGlobalValue(StringRef Ref);
742 
743   llvm::Constant *GetOrCreateLLVMFunction(StringRef MangledName,
744                                           llvm::Type *Ty,
745                                           GlobalDecl D,
746                                           bool ForVTable,
747                                           llvm::Attributes ExtraAttrs =
748                                             llvm::Attribute::None);
749   llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
750                                         llvm::PointerType *PTy,
751                                         const VarDecl *D,
752                                         bool UnnamedAddr = false);
753 
754   /// SetCommonAttributes - Set attributes which are common to any
755   /// form of a global definition (alias, Objective-C method,
756   /// function, global variable).
757   ///
758   /// NOTE: This should only be called for definitions.
759   void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
760 
761   /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
762   void SetFunctionDefinitionAttributes(const FunctionDecl *D,
763                                        llvm::GlobalValue *GV);
764 
765   /// SetFunctionAttributes - Set function attributes for a function
766   /// declaration.
767   void SetFunctionAttributes(GlobalDecl GD,
768                              llvm::Function *F,
769                              bool IsIncompleteFunction);
770 
771   /// EmitGlobal - Emit code for a singal global function or var decl. Forward
772   /// declarations are emitted lazily.
773   void EmitGlobal(GlobalDecl D);
774 
775   void EmitGlobalDefinition(GlobalDecl D);
776 
777   void EmitGlobalFunctionDefinition(GlobalDecl GD);
778   void EmitGlobalVarDefinition(const VarDecl *D);
779   void EmitAliasDefinition(GlobalDecl GD);
780   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
781   void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
782 
783   // C++ related functions.
784 
785   bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target);
786   bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
787 
788   void EmitNamespace(const NamespaceDecl *D);
789   void EmitLinkageSpec(const LinkageSpecDecl *D);
790 
791   /// EmitCXXConstructors - Emit constructors (base, complete) from a
792   /// C++ constructor Decl.
793   void EmitCXXConstructors(const CXXConstructorDecl *D);
794 
795   /// EmitCXXConstructor - Emit a single constructor with the given type from
796   /// a C++ constructor Decl.
797   void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
798 
799   /// EmitCXXDestructors - Emit destructors (base, complete) from a
800   /// C++ destructor Decl.
801   void EmitCXXDestructors(const CXXDestructorDecl *D);
802 
803   /// EmitCXXDestructor - Emit a single destructor with the given type from
804   /// a C++ destructor Decl.
805   void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
806 
807   /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals.
808   void EmitCXXGlobalInitFunc();
809 
810   /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals.
811   void EmitCXXGlobalDtorFunc();
812 
813   void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
814                                     llvm::GlobalVariable *Addr);
815 
816   // FIXME: Hardcoding priority here is gross.
817   void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
818   void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
819 
820   /// EmitCtorList - Generates a global array of functions and priorities using
821   /// the given list and name. This array will have appending linkage and is
822   /// suitable for use as a LLVM constructor or destructor array.
823   void EmitCtorList(const CtorList &Fns, const char *GlobalName);
824 
825   void EmitAnnotations(void);
826 
827   /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the
828   /// given type.
829   void EmitFundamentalRTTIDescriptor(QualType Type);
830 
831   /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the
832   /// builtin types.
833   void EmitFundamentalRTTIDescriptors();
834 
835   /// EmitDeferred - Emit any needed decls for which code generation
836   /// was deferred.
837   void EmitDeferred(void);
838 
839   /// EmitLLVMUsed - Emit the llvm.used metadata used to force
840   /// references to global which may otherwise be optimized out.
841   void EmitLLVMUsed(void);
842 
843   void EmitDeclMetadata();
844 
845   /// EmitCoverageFile - Emit the llvm.gcov metadata used to tell LLVM where
846   /// to emit the .gcno and .gcda files in a way that persists in .bc files.
847   void EmitCoverageFile();
848 
849   /// MayDeferGeneration - Determine if the given decl can be emitted
850   /// lazily; this is only relevant for definitions. The given decl
851   /// must be either a function or var decl.
852   bool MayDeferGeneration(const ValueDecl *D);
853 
854   /// SimplifyPersonality - Check whether we can use a "simpler", more
855   /// core exceptions personality function.
856   void SimplifyPersonality();
857 };
858 }  // end namespace CodeGen
859 }  // end namespace clang
860 
861 #endif
862