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