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