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