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