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/LangOptions.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "CGBlocks.h"
22 #include "CGCall.h"
23 #include "CGCXX.h"
24 #include "CGVtable.h"
25 #include "CodeGenTypes.h"
26 #include "GlobalDecl.h"
27 #include "Mangle.h"
28 #include "llvm/Module.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/StringSet.h"
32 #include "llvm/Support/ValueHandle.h"
33 #include <list>
34 
35 namespace llvm {
36   class Module;
37   class Constant;
38   class Function;
39   class GlobalValue;
40   class TargetData;
41   class FunctionType;
42   class LLVMContext;
43 }
44 
45 namespace clang {
46   class ASTContext;
47   class FunctionDecl;
48   class IdentifierInfo;
49   class ObjCMethodDecl;
50   class ObjCImplementationDecl;
51   class ObjCCategoryImplDecl;
52   class ObjCProtocolDecl;
53   class ObjCEncodeExpr;
54   class BlockExpr;
55   class 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 Diagnostic;
65   class AnnotateAttr;
66   class CXXDestructorDecl;
67 
68 namespace CodeGen {
69 
70   class CodeGenFunction;
71   class CGDebugInfo;
72   class CGObjCRuntime;
73 
74 
75 /// CodeGenModule - This class organizes the cross-function state that is used
76 /// while generating LLVM code.
77 class CodeGenModule : public BlockModule {
78   CodeGenModule(const CodeGenModule&);  // DO NOT IMPLEMENT
79   void operator=(const CodeGenModule&); // DO NOT IMPLEMENT
80 
81   typedef std::vector<std::pair<llvm::Constant*, int> > CtorList;
82 
83   ASTContext &Context;
84   const LangOptions &Features;
85   const CodeGenOptions &CodeGenOpts;
86   llvm::Module &TheModule;
87   const llvm::TargetData &TheTargetData;
88   Diagnostic &Diags;
89   CodeGenTypes Types;
90   MangleContext MangleCtx;
91 
92   /// VtableInfo - Holds information about C++ vtables.
93   CGVtableInfo VtableInfo;
94 
95   CGObjCRuntime* Runtime;
96   CGDebugInfo* DebugInfo;
97 
98   llvm::Function *MemCpyFn;
99   llvm::Function *MemMoveFn;
100   llvm::Function *MemSetFn;
101 
102   /// GlobalDeclMap - Mapping of decl names (represented as unique
103   /// character pointers from either the identifier table or the set
104   /// of mangled names) to global variables we have already
105   /// emitted. Note that the entries in this map are the actual
106   /// globals and therefore may not be of the same type as the decl,
107   /// they should be bitcasted on retrieval. Also note that the
108   /// globals are keyed on their source mangled name, not the global name
109   /// (which may change with attributes such as asm-labels).  The key
110   /// to this map should be generated using getMangledName().
111   ///
112   /// Note that this map always lines up exactly with the contents of the LLVM
113   /// IR symbol table, but this is quicker to query since it is doing uniqued
114   /// pointer lookups instead of full string lookups.
115   llvm::DenseMap<const char*, llvm::GlobalValue*> GlobalDeclMap;
116 
117   /// \brief Contains the strings used for mangled names.
118   ///
119   /// FIXME: Eventually, this should map from the semantic/canonical
120   /// declaration for each global entity to its mangled name (if it
121   /// has one).
122   llvm::StringSet<> MangledNames;
123 
124   /// DeferredDecls - This contains all the decls which have definitions but
125   /// which are deferred for emission and therefore should only be output if
126   /// they are actually used.  If a decl is in this, then it is known to have
127   /// not been referenced yet.  The key to this map is a uniqued mangled name.
128   llvm::DenseMap<const char*, GlobalDecl> DeferredDecls;
129 
130   /// DeferredDeclsToEmit - This is a list of deferred decls which we have seen
131   /// that *are* actually referenced.  These get code generated when the module
132   /// is done.
133   std::vector<GlobalDecl> DeferredDeclsToEmit;
134 
135   /// LLVMUsed - List of global values which are required to be
136   /// present in the object file; bitcast to i8*. This is used for
137   /// forcing visibility of symbols which may otherwise be optimized
138   /// out.
139   std::vector<llvm::WeakVH> LLVMUsed;
140 
141   /// GlobalCtors - Store the list of global constructors and their respective
142   /// priorities to be emitted when the translation unit is complete.
143   CtorList GlobalCtors;
144 
145   /// GlobalDtors - Store the list of global destructors and their respective
146   /// priorities to be emitted when the translation unit is complete.
147   CtorList GlobalDtors;
148 
149   std::vector<llvm::Constant*> Annotations;
150 
151   llvm::StringMap<llvm::Constant*> CFConstantStringMap;
152   llvm::StringMap<llvm::Constant*> ConstantStringMap;
153 
154   /// CXXGlobalInits - Variables with global initializers that need to run
155   /// before main.
156   std::vector<const VarDecl*> CXXGlobalInits;
157 
158   /// CFConstantStringClassRef - Cached reference to the class for constant
159   /// strings. This value has type int * but is actually an Obj-C class pointer.
160   llvm::Constant *CFConstantStringClassRef;
161 
162   llvm::LLVMContext &VMContext;
163 public:
164   CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
165                 llvm::Module &M, const llvm::TargetData &TD, Diagnostic &Diags);
166 
167   ~CodeGenModule();
168 
169   /// Release - Finalize LLVM code generation.
170   void Release();
171 
172   /// getObjCRuntime() - Return a reference to the configured
173   /// Objective-C runtime.
174   CGObjCRuntime &getObjCRuntime() {
175     assert(Runtime && "No Objective-C runtime has been configured.");
176     return *Runtime;
177   }
178 
179   /// hasObjCRuntime() - Return true iff an Objective-C runtime has
180   /// been configured.
181   bool hasObjCRuntime() { return !!Runtime; }
182 
183   CGDebugInfo *getDebugInfo() { return DebugInfo; }
184   ASTContext &getContext() const { return Context; }
185   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
186   const LangOptions &getLangOptions() const { return Features; }
187   llvm::Module &getModule() const { return TheModule; }
188   CodeGenTypes &getTypes() { return Types; }
189   MangleContext &getMangleContext() { return MangleCtx; }
190   CGVtableInfo &getVtableInfo() { return VtableInfo; }
191   Diagnostic &getDiags() const { return Diags; }
192   const llvm::TargetData &getTargetData() const { return TheTargetData; }
193   llvm::LLVMContext &getLLVMContext() { return VMContext; }
194 
195   /// getDeclVisibilityMode - Compute the visibility of the decl \arg D.
196   LangOptions::VisibilityMode getDeclVisibilityMode(const Decl *D) const;
197 
198   /// setGlobalVisibility - Set the visibility for the given LLVM
199   /// GlobalValue.
200   void setGlobalVisibility(llvm::GlobalValue *GV, const Decl *D) const;
201 
202   /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
203   /// given global variable.  If Ty is non-null and if the global doesn't exist,
204   /// then it will be greated with the specified type instead of whatever the
205   /// normal requested type would be.
206   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
207                                      const llvm::Type *Ty = 0);
208 
209   /// GetAddrOfFunction - Return the address of the given function.  If Ty is
210   /// non-null, then this function will use the specified type if it has to
211   /// create it.
212   llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
213                                     const llvm::Type *Ty = 0);
214 
215   /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor
216   /// for the given type.
217   llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty);
218 
219   llvm::Constant *GetAddrOfThunk(GlobalDecl GD,
220                                  const ThunkAdjustment &ThisAdjustment);
221   llvm::Constant *GetAddrOfCovariantThunk(GlobalDecl GD,
222                                 const CovariantThunkAdjustment &ThisAdjustment);
223   void BuildThunksForVirtual(GlobalDecl GD);
224   void BuildThunksForVirtualRecursive(GlobalDecl GD, GlobalDecl BaseOGD);
225 
226   /// BuildThunk - Build a thunk for the given method.
227   llvm::Constant *BuildThunk(GlobalDecl GD, bool Extern,
228                              const ThunkAdjustment &ThisAdjustment);
229 
230   /// BuildCoVariantThunk - Build a thunk for the given method
231   llvm::Constant *
232   BuildCovariantThunk(const GlobalDecl &GD, bool Extern,
233                       const CovariantThunkAdjustment &Adjustment);
234 
235   typedef std::pair<const CXXRecordDecl *, uint64_t> CtorVtable_t;
236   typedef llvm::DenseMap<CtorVtable_t, int64_t> AddrSubMap_t;
237   typedef llvm::DenseMap<const CXXRecordDecl *, AddrSubMap_t *> AddrMap_t;
238   llvm::DenseMap<const CXXRecordDecl *, AddrMap_t*> AddressPoints;
239 
240   /// GetCXXBaseClassOffset - Returns the offset from a derived class to its
241   /// base class. Returns null if the offset is 0.
242   llvm::Constant *GetCXXBaseClassOffset(const CXXRecordDecl *ClassDecl,
243                                         const CXXRecordDecl *BaseClassDecl);
244 
245   /// ComputeThunkAdjustment - Returns the two parts required to compute the
246   /// offset for an object.
247   ThunkAdjustment ComputeThunkAdjustment(const CXXRecordDecl *ClassDecl,
248                                          const CXXRecordDecl *BaseClassDecl);
249 
250   /// GetStringForStringLiteral - Return the appropriate bytes for a string
251   /// literal, properly padded to match the literal type. If only the address of
252   /// a constant is needed consider using GetAddrOfConstantStringLiteral.
253   std::string GetStringForStringLiteral(const StringLiteral *E);
254 
255   /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
256   /// for the given string.
257   llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
258 
259   /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array
260   /// for the given string literal.
261   llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
262 
263   /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
264   /// array for the given ObjCEncodeExpr node.
265   llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
266 
267   /// GetAddrOfConstantString - Returns a pointer to a character array
268   /// containing the literal. This contents are exactly that of the given
269   /// string, i.e. it will not be null terminated automatically; see
270   /// GetAddrOfConstantCString. Note that whether the result is actually a
271   /// pointer to an LLVM constant depends on Feature.WriteableStrings.
272   ///
273   /// The result has pointer to array type.
274   ///
275   /// \param GlobalName If provided, the name to use for the global
276   /// (if one is created).
277   llvm::Constant *GetAddrOfConstantString(const std::string& str,
278                                           const char *GlobalName=0);
279 
280   /// GetAddrOfConstantCString - Returns a pointer to a character array
281   /// containing the literal and a terminating '\0' character. The result has
282   /// pointer to array type.
283   ///
284   /// \param GlobalName If provided, the name to use for the global (if one is
285   /// created).
286   llvm::Constant *GetAddrOfConstantCString(const std::string &str,
287                                            const char *GlobalName=0);
288 
289   /// GetAddrOfCXXConstructor - Return the address of the constructor of the
290   /// given type.
291   llvm::Function *GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
292                                           CXXCtorType Type);
293 
294   /// GetAddrOfCXXDestructor - Return the address of the constructor of the
295   /// given type.
296   llvm::Function *GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
297                                          CXXDtorType Type);
298 
299   /// getBuiltinLibFunction - Given a builtin id for a function like
300   /// "__builtin_fabsf", return a Function* for "fabsf".
301   llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
302                                      unsigned BuiltinID);
303 
304   llvm::Function *getMemCpyFn();
305   llvm::Function *getMemMoveFn();
306   llvm::Function *getMemSetFn();
307   llvm::Function *getIntrinsic(unsigned IID, const llvm::Type **Tys = 0,
308                                unsigned NumTys = 0);
309 
310   /// EmitTopLevelDecl - Emit code for a single top level declaration.
311   void EmitTopLevelDecl(Decl *D);
312 
313   /// AddUsedGlobal - Add a global which should be forced to be
314   /// present in the object file; these are emitted to the llvm.used
315   /// metadata global.
316   void AddUsedGlobal(llvm::GlobalValue *GV);
317 
318   void AddAnnotation(llvm::Constant *C) { Annotations.push_back(C); }
319 
320   /// CreateRuntimeFunction - Create a new runtime function with the specified
321   /// type and name.
322   llvm::Constant *CreateRuntimeFunction(const llvm::FunctionType *Ty,
323                                         const char *Name);
324   /// CreateRuntimeVariable - Create a new runtime global variable with the
325   /// specified type and name.
326   llvm::Constant *CreateRuntimeVariable(const llvm::Type *Ty,
327                                         const char *Name);
328 
329   void UpdateCompletedType(const TagDecl *TD) {
330     // Make sure that this type is translated.
331     Types.UpdateCompletedType(TD);
332   }
333 
334   /// EmitConstantExpr - Try to emit the given expression as a
335   /// constant; returns 0 if the expression cannot be emitted as a
336   /// constant.
337   llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
338                                    CodeGenFunction *CGF = 0);
339 
340   /// EmitNullConstant - Return the result of value-initializing the given
341   /// type, i.e. a null expression of the given type.  This is usually,
342   /// but not always, an LLVM null constant.
343   llvm::Constant *EmitNullConstant(QualType T);
344 
345   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
346                                    const AnnotateAttr *AA, unsigned LineNo);
347 
348   /// ErrorUnsupported - Print out an error that codegen doesn't support the
349   /// specified stmt yet.
350   /// \param OmitOnError - If true, then this error should only be emitted if no
351   /// other errors have been reported.
352   void ErrorUnsupported(const Stmt *S, const char *Type,
353                         bool OmitOnError=false);
354 
355   /// ErrorUnsupported - Print out an error that codegen doesn't support the
356   /// specified decl yet.
357   /// \param OmitOnError - If true, then this error should only be emitted if no
358   /// other errors have been reported.
359   void ErrorUnsupported(const Decl *D, const char *Type,
360                         bool OmitOnError=false);
361 
362   /// SetInternalFunctionAttributes - Set the attributes on the LLVM
363   /// function for the given decl and function info. This applies
364   /// attributes necessary for handling the ABI as well as user
365   /// specified attributes like section.
366   void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
367                                      const CGFunctionInfo &FI);
368 
369   /// SetLLVMFunctionAttributes - Set the LLVM function attributes
370   /// (sext, zext, etc).
371   void SetLLVMFunctionAttributes(const Decl *D,
372                                  const CGFunctionInfo &Info,
373                                  llvm::Function *F);
374 
375   /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
376   /// which only apply to a function definintion.
377   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
378 
379   /// ReturnTypeUsesSret - Return true iff the given type uses 'sret' when used
380   /// as a return type.
381   bool ReturnTypeUsesSret(const CGFunctionInfo &FI);
382 
383   /// ConstructAttributeList - Get the LLVM attributes and calling convention to
384   /// use for a particular function type.
385   ///
386   /// \param Info - The function type information.
387   /// \param TargetDecl - The decl these attributes are being constructed
388   /// for. If supplied the attributes applied to this decl may contribute to the
389   /// function attributes and calling convention.
390   /// \param PAL [out] - On return, the attribute list to use.
391   /// \param CallingConv [out] - On return, the LLVM calling convention to use.
392   void ConstructAttributeList(const CGFunctionInfo &Info,
393                               const Decl *TargetDecl,
394                               AttributeListType &PAL,
395                               unsigned &CallingConv);
396 
397   const char *getMangledName(const GlobalDecl &D);
398 
399   const char *getMangledName(const NamedDecl *ND);
400   const char *getMangledCXXCtorName(const CXXConstructorDecl *D,
401                                     CXXCtorType Type);
402   const char *getMangledCXXDtorName(const CXXDestructorDecl *D,
403                                     CXXDtorType Type);
404 
405   void EmitTentativeDefinition(const VarDecl *D);
406 
407   enum GVALinkage {
408     GVA_Internal,
409     GVA_C99Inline,
410     GVA_CXXInline,
411     GVA_StrongExternal,
412     GVA_TemplateInstantiation
413   };
414 
415 private:
416   /// UniqueMangledName - Unique a name by (if necessary) inserting it into the
417   /// MangledNames string map.
418   const char *UniqueMangledName(const char *NameStart, const char *NameEnd);
419 
420   llvm::Constant *GetOrCreateLLVMFunction(const char *MangledName,
421                                           const llvm::Type *Ty,
422                                           GlobalDecl D);
423   llvm::Constant *GetOrCreateLLVMGlobal(const char *MangledName,
424                                         const llvm::PointerType *PTy,
425                                         const VarDecl *D);
426 
427   /// SetCommonAttributes - Set attributes which are common to any
428   /// form of a global definition (alias, Objective-C method,
429   /// function, global variable).
430   ///
431   /// NOTE: This should only be called for definitions.
432   void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
433 
434   /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
435   void SetFunctionDefinitionAttributes(const FunctionDecl *D,
436                                        llvm::GlobalValue *GV);
437 
438   /// SetFunctionAttributes - Set function attributes for a function
439   /// declaration.
440   void SetFunctionAttributes(const FunctionDecl *FD,
441                              llvm::Function *F,
442                              bool IsIncompleteFunction);
443 
444   /// EmitGlobal - Emit code for a singal global function or var decl. Forward
445   /// declarations are emitted lazily.
446   void EmitGlobal(GlobalDecl D);
447 
448   void EmitGlobalDefinition(GlobalDecl D);
449 
450   void EmitGlobalFunctionDefinition(GlobalDecl GD);
451   void EmitGlobalVarDefinition(const VarDecl *D);
452   void EmitAliasDefinition(const ValueDecl *D);
453   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
454 
455   // C++ related functions.
456 
457   void EmitNamespace(const NamespaceDecl *D);
458   void EmitLinkageSpec(const LinkageSpecDecl *D);
459 
460   /// EmitCXXConstructors - Emit constructors (base, complete) from a
461   /// C++ constructor Decl.
462   void EmitCXXConstructors(const CXXConstructorDecl *D);
463 
464   /// EmitCXXConstructor - Emit a single constructor with the given type from
465   /// a C++ constructor Decl.
466   void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
467 
468   /// EmitCXXDestructors - Emit destructors (base, complete) from a
469   /// C++ destructor Decl.
470   void EmitCXXDestructors(const CXXDestructorDecl *D);
471 
472   /// EmitCXXDestructor - Emit a single destructor with the given type from
473   /// a C++ destructor Decl.
474   void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
475 
476   /// EmitCXXGlobalInitFunc - Emit a function that initializes C++ globals.
477   void EmitCXXGlobalInitFunc();
478 
479   // FIXME: Hardcoding priority here is gross.
480   void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
481   void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
482 
483   /// EmitCtorList - Generates a global array of functions and priorities using
484   /// the given list and name. This array will have appending linkage and is
485   /// suitable for use as a LLVM constructor or destructor array.
486   void EmitCtorList(const CtorList &Fns, const char *GlobalName);
487 
488   void EmitAnnotations(void);
489 
490   /// EmitDeferred - Emit any needed decls for which code generation
491   /// was deferred.
492   void EmitDeferred(void);
493 
494   /// EmitLLVMUsed - Emit the llvm.used metadata used to force
495   /// references to global which may otherwise be optimized out.
496   void EmitLLVMUsed(void);
497 
498   /// MayDeferGeneration - Determine if the given decl can be emitted
499   /// lazily; this is only relevant for definitions. The given decl
500   /// must be either a function or var decl.
501   bool MayDeferGeneration(const ValueDecl *D);
502 };
503 }  // end namespace CodeGen
504 }  // end namespace clang
505 
506 #endif
507