1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the internal per-translation-unit state used for llvm translation.
12 //===----------------------------------------------------------------------===//
14 #ifndef CLANG_CODEGEN_CODEGENMODULE_H
15 #define CLANG_CODEGEN_CODEGENMODULE_H
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
24 #include "CGVTables.h"
26 #include "CodeGenTypes.h"
27 #include "GlobalDecl.h"
29 #include "llvm/Module.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/ADT/StringSet.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/Support/ValueHandle.h"
47 class TargetCodeGenInfo;
52 class ObjCImplementationDecl;
53 class ObjCCategoryImplDecl;
54 class ObjCProtocolDecl;
69 class CXXDestructorDecl;
73 class CodeGenFunction;
78 struct OrderGlobalInits {
79 unsigned int priority;
80 unsigned int lex_order;
81 OrderGlobalInits(unsigned int p, unsigned int l)
82 : priority(p), lex_order(l) {}
84 bool operator==(const OrderGlobalInits &RHS) const {
85 return priority == RHS.priority &&
86 lex_order == RHS.lex_order;
89 bool operator<(const OrderGlobalInits &RHS) const {
90 if (priority < RHS.priority)
93 return priority == RHS.priority && lex_order < RHS.lex_order;
97 /// CodeGenModule - This class organizes the cross-function state that is used
98 /// while generating LLVM code.
99 class CodeGenModule : public BlockModule {
100 CodeGenModule(const CodeGenModule&); // DO NOT IMPLEMENT
101 void operator=(const CodeGenModule&); // DO NOT IMPLEMENT
103 typedef std::vector<std::pair<llvm::Constant*, int> > CtorList;
106 const LangOptions &Features;
107 const CodeGenOptions &CodeGenOpts;
108 llvm::Module &TheModule;
109 const llvm::TargetData &TheTargetData;
110 mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
114 /// VTables - Holds information about C++ vtables.
115 CodeGenVTables VTables;
116 friend class CodeGenVTables;
118 CGObjCRuntime* Runtime;
120 CGDebugInfo* DebugInfo;
122 // WeakRefReferences - A set of references that have only been seen via
123 // a weakref so far. This is used to remove the weak of the reference if we ever
124 // see a direct reference or a definition.
125 llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
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.
131 llvm::StringMap<GlobalDecl> DeferredDecls;
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
136 std::vector<GlobalDecl> DeferredDeclsToEmit;
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
142 std::vector<llvm::WeakVH> LLVMUsed;
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;
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;
152 /// MangledDeclNames - A map of canonical GlobalDecls to their mangled names.
153 llvm::DenseMap<GlobalDecl, llvm::StringRef> MangledDeclNames;
154 llvm::BumpPtrAllocator MangledNamesAllocator;
156 std::vector<llvm::Constant*> Annotations;
158 llvm::StringMap<llvm::Constant*> CFConstantStringMap;
159 llvm::StringMap<llvm::Constant*> ConstantStringMap;
160 llvm::DenseMap<const Decl*, llvm::Value*> StaticLocalDeclMap;
162 /// CXXGlobalInits - Global variables with initializers that need to run
164 std::vector<llvm::Constant*> CXXGlobalInits;
166 /// - Global variables with initializers whose order of initialization
167 /// is set by init_priority attribute.
169 llvm::SmallVector<std::pair<OrderGlobalInits, llvm::Function*>, 8>
170 PrioritizedCXXGlobalInits;
172 /// CXXGlobalDtors - Global destructor functions and arguments that need to
173 /// run on termination.
174 std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
176 /// CFConstantStringClassRef - Cached reference to the class for constant
177 /// strings. This value has type int * but is actually an Obj-C class pointer.
178 llvm::Constant *CFConstantStringClassRef;
180 /// NSConstantStringClassRef - Cached reference to the class for constant
181 /// strings. This value has type int * but is actually an Obj-C class pointer.
182 llvm::Constant *NSConstantStringClassRef;
184 /// Lazily create the Objective-C runtime
185 void createObjCRuntime();
186 /// Lazily create the C++ ABI
189 llvm::LLVMContext &VMContext;
191 CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
192 llvm::Module &M, const llvm::TargetData &TD, Diagnostic &Diags);
196 /// Release - Finalize LLVM code generation.
199 /// getObjCRuntime() - Return a reference to the configured
200 /// Objective-C runtime.
201 CGObjCRuntime &getObjCRuntime() {
202 if (!Runtime) createObjCRuntime();
206 /// hasObjCRuntime() - Return true iff an Objective-C runtime has
208 bool hasObjCRuntime() { return !!Runtime; }
210 /// getCXXABI() - Return a reference to the configured
212 CXXABI &getCXXABI() {
213 if (!ABI) createCXXABI();
217 /// hasCXXABI() - Return true iff a C++ ABI has been configured.
218 bool hasCXXABI() { return !!ABI; }
220 llvm::Value *getStaticLocalDeclAddress(const VarDecl *VD) {
221 return StaticLocalDeclMap[VD];
223 void setStaticLocalDeclAddress(const VarDecl *D,
224 llvm::GlobalVariable *GV) {
225 StaticLocalDeclMap[D] = GV;
228 CGDebugInfo *getDebugInfo() { return DebugInfo; }
229 ASTContext &getContext() const { return Context; }
230 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
231 const LangOptions &getLangOptions() const { return Features; }
232 llvm::Module &getModule() const { return TheModule; }
233 CodeGenTypes &getTypes() { return Types; }
234 MangleContext &getMangleContext() {
235 if (!ABI) createCXXABI();
236 return ABI->getMangleContext();
238 CodeGenVTables &getVTables() { return VTables; }
239 Diagnostic &getDiags() const { return Diags; }
240 const llvm::TargetData &getTargetData() const { return TheTargetData; }
241 llvm::LLVMContext &getLLVMContext() { return VMContext; }
242 const TargetCodeGenInfo &getTargetCodeGenInfo() const;
243 bool isTargetDarwin() const;
245 /// getDeclVisibilityMode - Compute the visibility of the decl \arg D.
246 LangOptions::VisibilityMode getDeclVisibilityMode(const Decl *D) const;
248 /// setGlobalVisibility - Set the visibility for the given LLVM
250 void setGlobalVisibility(llvm::GlobalValue *GV, const Decl *D) const;
252 llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
253 if (isa<CXXConstructorDecl>(GD.getDecl()))
254 return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
256 else if (isa<CXXDestructorDecl>(GD.getDecl()))
257 return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
259 else if (isa<FunctionDecl>(GD.getDecl()))
260 return GetAddrOfFunction(GD);
262 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
265 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
266 /// given global variable. If Ty is non-null and if the global doesn't exist,
267 /// then it will be greated with the specified type instead of whatever the
268 /// normal requested type would be.
269 llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
270 const llvm::Type *Ty = 0);
272 /// GetAddrOfFunction - Return the address of the given function. If Ty is
273 /// non-null, then this function will use the specified type if it has to
275 llvm::Constant *GetAddrOfFunction(GlobalDecl GD,
276 const llvm::Type *Ty = 0);
278 /// GetAddrOfRTTIDescriptor - Get the address of the RTTI descriptor
279 /// for the given type.
280 llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
282 /// GetAddrOfThunk - Get the address of the thunk for the given global decl.
283 llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
285 /// GetWeakRefReference - Get a reference to the target of VD.
286 llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
288 /// GetNonVirtualBaseClassOffset - Returns the offset from a derived class to
289 /// a class. Returns null if the offset is 0.
291 GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
292 const CXXBaseSpecifierArray &BasePath);
294 /// GetStringForStringLiteral - Return the appropriate bytes for a string
295 /// literal, properly padded to match the literal type. If only the address of
296 /// a constant is needed consider using GetAddrOfConstantStringLiteral.
297 std::string GetStringForStringLiteral(const StringLiteral *E);
299 /// GetAddrOfConstantCFString - Return a pointer to a constant CFString object
300 /// for the given string.
301 llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
303 /// GetAddrOfConstantNSString - Return a pointer to a constant NSString object
304 /// for the given string.
305 llvm::Constant *GetAddrOfConstantNSString(const StringLiteral *Literal);
307 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant array
308 /// for the given string literal.
309 llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
311 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
312 /// array for the given ObjCEncodeExpr node.
313 llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
315 /// GetAddrOfConstantString - Returns a pointer to a character array
316 /// containing the literal. This contents are exactly that of the given
317 /// string, i.e. it will not be null terminated automatically; see
318 /// GetAddrOfConstantCString. Note that whether the result is actually a
319 /// pointer to an LLVM constant depends on Feature.WriteableStrings.
321 /// The result has pointer to array type.
323 /// \param GlobalName If provided, the name to use for the global
324 /// (if one is created).
325 llvm::Constant *GetAddrOfConstantString(const std::string& str,
326 const char *GlobalName=0);
328 /// GetAddrOfConstantCString - Returns a pointer to a character array
329 /// containing the literal and a terminating '\0' character. The result has
330 /// pointer to array type.
332 /// \param GlobalName If provided, the name to use for the global (if one is
334 llvm::Constant *GetAddrOfConstantCString(const std::string &str,
335 const char *GlobalName=0);
337 /// GetAddrOfCXXConstructor - Return the address of the constructor of the
339 llvm::GlobalValue *GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
342 /// GetAddrOfCXXDestructor - Return the address of the constructor of the
344 llvm::GlobalValue *GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
347 // GetCXXMemberFunctionPointerValue - Given a method declaration, return the
348 // integer used in a member function pointer to refer to that value.
349 llvm::Constant *GetCXXMemberFunctionPointerValue(const CXXMethodDecl *MD);
351 /// getBuiltinLibFunction - Given a builtin id for a function like
352 /// "__builtin_fabsf", return a Function* for "fabsf".
353 llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
356 llvm::Function *getMemCpyFn(const llvm::Type *DestType,
357 const llvm::Type *SrcType,
358 const llvm::Type *SizeType);
360 llvm::Function *getMemMoveFn(const llvm::Type *DestType,
361 const llvm::Type *SrcType,
362 const llvm::Type *SizeType);
364 llvm::Function *getMemSetFn(const llvm::Type *DestType,
365 const llvm::Type *SizeType);
367 llvm::Function *getIntrinsic(unsigned IID, const llvm::Type **Tys = 0,
368 unsigned NumTys = 0);
370 /// EmitTopLevelDecl - Emit code for a single top level declaration.
371 void EmitTopLevelDecl(Decl *D);
373 /// AddUsedGlobal - Add a global which should be forced to be
374 /// present in the object file; these are emitted to the llvm.used
376 void AddUsedGlobal(llvm::GlobalValue *GV);
378 void AddAnnotation(llvm::Constant *C) { Annotations.push_back(C); }
380 /// AddCXXDtorEntry - Add a destructor and object to add to the C++ global
381 /// destructor function.
382 void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
383 CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object));
386 /// CreateRuntimeFunction - Create a new runtime function with the specified
388 llvm::Constant *CreateRuntimeFunction(const llvm::FunctionType *Ty,
389 llvm::StringRef Name);
390 /// CreateRuntimeVariable - Create a new runtime global variable with the
391 /// specified type and name.
392 llvm::Constant *CreateRuntimeVariable(const llvm::Type *Ty,
393 llvm::StringRef Name);
395 void UpdateCompletedType(const TagDecl *TD) {
396 // Make sure that this type is translated.
397 Types.UpdateCompletedType(TD);
400 /// EmitConstantExpr - Try to emit the given expression as a
401 /// constant; returns 0 if the expression cannot be emitted as a
403 llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
404 CodeGenFunction *CGF = 0);
406 /// EmitNullConstant - Return the result of value-initializing the given
407 /// type, i.e. a null expression of the given type. This is usually,
408 /// but not always, an LLVM null constant.
409 llvm::Constant *EmitNullConstant(QualType T);
411 llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
412 const AnnotateAttr *AA, unsigned LineNo);
414 llvm::Constant *EmitPointerToDataMember(const FieldDecl *FD);
416 /// ErrorUnsupported - Print out an error that codegen doesn't support the
417 /// specified stmt yet.
418 /// \param OmitOnError - If true, then this error should only be emitted if no
419 /// other errors have been reported.
420 void ErrorUnsupported(const Stmt *S, const char *Type,
421 bool OmitOnError=false);
423 /// ErrorUnsupported - Print out an error that codegen doesn't support the
424 /// specified decl yet.
425 /// \param OmitOnError - If true, then this error should only be emitted if no
426 /// other errors have been reported.
427 void ErrorUnsupported(const Decl *D, const char *Type,
428 bool OmitOnError=false);
430 /// SetInternalFunctionAttributes - Set the attributes on the LLVM
431 /// function for the given decl and function info. This applies
432 /// attributes necessary for handling the ABI as well as user
433 /// specified attributes like section.
434 void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
435 const CGFunctionInfo &FI);
437 /// SetLLVMFunctionAttributes - Set the LLVM function attributes
438 /// (sext, zext, etc).
439 void SetLLVMFunctionAttributes(const Decl *D,
440 const CGFunctionInfo &Info,
443 /// SetLLVMFunctionAttributesForDefinition - Set the LLVM function attributes
444 /// which only apply to a function definintion.
445 void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
447 /// ReturnTypeUsesSret - Return true iff the given type uses 'sret' when used
448 /// as a return type.
449 bool ReturnTypeUsesSret(const CGFunctionInfo &FI);
451 /// ConstructAttributeList - Get the LLVM attributes and calling convention to
452 /// use for a particular function type.
454 /// \param Info - The function type information.
455 /// \param TargetDecl - The decl these attributes are being constructed
456 /// for. If supplied the attributes applied to this decl may contribute to the
457 /// function attributes and calling convention.
458 /// \param PAL [out] - On return, the attribute list to use.
459 /// \param CallingConv [out] - On return, the LLVM calling convention to use.
460 void ConstructAttributeList(const CGFunctionInfo &Info,
461 const Decl *TargetDecl,
462 AttributeListType &PAL,
463 unsigned &CallingConv);
465 llvm::StringRef getMangledName(GlobalDecl GD);
466 void getMangledName(GlobalDecl GD, MangleBuffer &Buffer, const BlockDecl *BD);
468 void EmitTentativeDefinition(const VarDecl *D);
470 void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
477 GVA_TemplateInstantiation,
478 GVA_ExplicitTemplateInstantiation
481 llvm::GlobalVariable::LinkageTypes
482 getFunctionLinkage(const FunctionDecl *FD);
484 void setFunctionLinkage(const FunctionDecl *FD, llvm::GlobalValue *V) {
485 V->setLinkage(getFunctionLinkage(FD));
488 /// getVTableLinkage - Return the appropriate linkage for the vtable, VTT,
489 /// and type information of the given class.
490 static llvm::GlobalVariable::LinkageTypes
491 getVTableLinkage(const CXXRecordDecl *RD);
493 /// GetTargetTypeStoreSize - Return the store size, in character units, of
494 /// the given LLVM type.
495 CharUnits GetTargetTypeStoreSize(const llvm::Type *Ty) const;
497 std::vector<const CXXRecordDecl*> DeferredVTables;
500 llvm::GlobalValue *GetGlobalValue(llvm::StringRef Ref);
502 llvm::Constant *GetOrCreateLLVMFunction(llvm::StringRef MangledName,
503 const llvm::Type *Ty,
505 llvm::Constant *GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
506 const llvm::PointerType *PTy,
509 /// SetCommonAttributes - Set attributes which are common to any
510 /// form of a global definition (alias, Objective-C method,
511 /// function, global variable).
513 /// NOTE: This should only be called for definitions.
514 void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
516 /// SetFunctionDefinitionAttributes - Set attributes for a global definition.
517 void SetFunctionDefinitionAttributes(const FunctionDecl *D,
518 llvm::GlobalValue *GV);
520 /// SetFunctionAttributes - Set function attributes for a function
522 void SetFunctionAttributes(GlobalDecl GD,
524 bool IsIncompleteFunction);
526 /// EmitGlobal - Emit code for a singal global function or var decl. Forward
527 /// declarations are emitted lazily.
528 void EmitGlobal(GlobalDecl D);
530 void EmitGlobalDefinition(GlobalDecl D);
532 void EmitGlobalFunctionDefinition(GlobalDecl GD);
533 void EmitGlobalVarDefinition(const VarDecl *D);
534 void EmitAliasDefinition(GlobalDecl GD);
535 void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
536 void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
538 // C++ related functions.
540 bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target);
541 bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
543 void EmitNamespace(const NamespaceDecl *D);
544 void EmitLinkageSpec(const LinkageSpecDecl *D);
546 /// EmitCXXConstructors - Emit constructors (base, complete) from a
547 /// C++ constructor Decl.
548 void EmitCXXConstructors(const CXXConstructorDecl *D);
550 /// EmitCXXConstructor - Emit a single constructor with the given type from
551 /// a C++ constructor Decl.
552 void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
554 /// EmitCXXDestructors - Emit destructors (base, complete) from a
555 /// C++ destructor Decl.
556 void EmitCXXDestructors(const CXXDestructorDecl *D);
558 /// EmitCXXDestructor - Emit a single destructor with the given type from
559 /// a C++ destructor Decl.
560 void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
562 /// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals.
563 void EmitCXXGlobalInitFunc();
565 /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals.
566 void EmitCXXGlobalDtorFunc();
568 void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D);
570 // FIXME: Hardcoding priority here is gross.
571 void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535);
572 void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535);
574 /// EmitCtorList - Generates a global array of functions and priorities using
575 /// the given list and name. This array will have appending linkage and is
576 /// suitable for use as a LLVM constructor or destructor array.
577 void EmitCtorList(const CtorList &Fns, const char *GlobalName);
579 void EmitAnnotations(void);
581 /// EmitFundamentalRTTIDescriptor - Emit the RTTI descriptors for the
583 void EmitFundamentalRTTIDescriptor(QualType Type);
585 /// EmitFundamentalRTTIDescriptors - Emit the RTTI descriptors for the
587 void EmitFundamentalRTTIDescriptors();
589 /// EmitDeferred - Emit any needed decls for which code generation
591 void EmitDeferred(void);
593 /// EmitLLVMUsed - Emit the llvm.used metadata used to force
594 /// references to global which may otherwise be optimized out.
595 void EmitLLVMUsed(void);
597 void EmitDeclMetadata();
599 /// MayDeferGeneration - Determine if the given decl can be emitted
600 /// lazily; this is only relevant for definitions. The given decl
601 /// must be either a function or var decl.
602 bool MayDeferGeneration(const ValueDecl *D);
604 } // end namespace CodeGen
605 } // end namespace clang