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