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