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