1 //===---- TargetInfo.h - Encapsulate target details -------------*- 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 // These classes wrap the information about a call or function
11 // definition used to handle ABI compliancy.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_LIB_CODEGEN_TARGETINFO_H
16 #define LLVM_CLANG_LIB_CODEGEN_TARGETINFO_H
17 
18 #include "CodeGenModule.h"
19 #include "CGValue.h"
20 #include "clang/AST/Type.h"
21 #include "clang/Basic/LLVM.h"
22 #include "clang/Basic/SyncScope.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringRef.h"
25 
26 namespace llvm {
27 class Constant;
28 class GlobalValue;
29 class Type;
30 class Value;
31 }
32 
33 namespace clang {
34 class Decl;
35 
36 namespace CodeGen {
37 class ABIInfo;
38 class CallArgList;
39 class CodeGenFunction;
40 class CGBlockInfo;
41 class CGFunctionInfo;
42 
43 /// TargetCodeGenInfo - This class organizes various target-specific
44 /// codegeneration issues, like target-specific attributes, builtins and so
45 /// on.
46 class TargetCodeGenInfo {
47   ABIInfo *Info;
48 
49 public:
50   // WARNING: Acquires the ownership of ABIInfo.
Info(info)51   TargetCodeGenInfo(ABIInfo *info = nullptr) : Info(info) {}
52   virtual ~TargetCodeGenInfo();
53 
54   /// getABIInfo() - Returns ABI info helper for the target.
getABIInfo()55   const ABIInfo &getABIInfo() const { return *Info; }
56 
57   /// setTargetAttributes - Provides a convenient hook to handle extra
58   /// target-specific attributes for the given global.
setTargetAttributes(const Decl * D,llvm::GlobalValue * GV,CodeGen::CodeGenModule & M)59   virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
60                                    CodeGen::CodeGenModule &M) const {}
61 
62   /// emitTargetMD - Provides a convenient hook to handle extra
63   /// target-specific metadata for the given global.
emitTargetMD(const Decl * D,llvm::GlobalValue * GV,CodeGen::CodeGenModule & M)64   virtual void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
65                             CodeGen::CodeGenModule &M) const {}
66 
67   /// Determines the size of struct _Unwind_Exception on this platform,
68   /// in 8-bit units.  The Itanium ABI defines this as:
69   ///   struct _Unwind_Exception {
70   ///     uint64 exception_class;
71   ///     _Unwind_Exception_Cleanup_Fn exception_cleanup;
72   ///     uint64 private_1;
73   ///     uint64 private_2;
74   ///   };
75   virtual unsigned getSizeOfUnwindException() const;
76 
77   /// Controls whether __builtin_extend_pointer should sign-extend
78   /// pointers to uint64_t or zero-extend them (the default).  Has
79   /// no effect for targets:
80   ///   - that have 64-bit pointers, or
81   ///   - that cannot address through registers larger than pointers, or
82   ///   - that implicitly ignore/truncate the top bits when addressing
83   ///     through such registers.
extendPointerWithSExt()84   virtual bool extendPointerWithSExt() const { return false; }
85 
86   /// Determines the DWARF register number for the stack pointer, for
87   /// exception-handling purposes.  Implements __builtin_dwarf_sp_column.
88   ///
89   /// Returns -1 if the operation is unsupported by this target.
getDwarfEHStackPointer(CodeGen::CodeGenModule & M)90   virtual int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
91     return -1;
92   }
93 
94   /// Initializes the given DWARF EH register-size table, a char*.
95   /// Implements __builtin_init_dwarf_reg_size_table.
96   ///
97   /// Returns true if the operation is unsupported by this target.
initDwarfEHRegSizeTable(CodeGen::CodeGenFunction & CGF,llvm::Value * Address)98   virtual bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
99                                        llvm::Value *Address) const {
100     return true;
101   }
102 
103   /// Performs the code-generation required to convert a return
104   /// address as stored by the system into the actual address of the
105   /// next instruction that will be executed.
106   ///
107   /// Used by __builtin_extract_return_addr().
decodeReturnAddress(CodeGen::CodeGenFunction & CGF,llvm::Value * Address)108   virtual llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
109                                            llvm::Value *Address) const {
110     return Address;
111   }
112 
113   /// Performs the code-generation required to convert the address
114   /// of an instruction into a return address suitable for storage
115   /// by the system in a return slot.
116   ///
117   /// Used by __builtin_frob_return_addr().
encodeReturnAddress(CodeGen::CodeGenFunction & CGF,llvm::Value * Address)118   virtual llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
119                                            llvm::Value *Address) const {
120     return Address;
121   }
122 
123   /// Corrects the low-level LLVM type for a given constraint and "usual"
124   /// type.
125   ///
126   /// \returns A pointer to a new LLVM type, possibly the same as the original
127   /// on success; 0 on failure.
adjustInlineAsmType(CodeGen::CodeGenFunction & CGF,StringRef Constraint,llvm::Type * Ty)128   virtual llvm::Type *adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
129                                           StringRef Constraint,
130                                           llvm::Type *Ty) const {
131     return Ty;
132   }
133 
134   /// Adds constraints and types for result registers.
addReturnRegisterOutputs(CodeGen::CodeGenFunction & CGF,CodeGen::LValue ReturnValue,std::string & Constraints,std::vector<llvm::Type * > & ResultRegTypes,std::vector<llvm::Type * > & ResultTruncRegTypes,std::vector<CodeGen::LValue> & ResultRegDests,std::string & AsmString,unsigned NumOutputs)135   virtual void addReturnRegisterOutputs(
136       CodeGen::CodeGenFunction &CGF, CodeGen::LValue ReturnValue,
137       std::string &Constraints, std::vector<llvm::Type *> &ResultRegTypes,
138       std::vector<llvm::Type *> &ResultTruncRegTypes,
139       std::vector<CodeGen::LValue> &ResultRegDests, std::string &AsmString,
140       unsigned NumOutputs) const {}
141 
142   /// doesReturnSlotInterfereWithArgs - Return true if the target uses an
143   /// argument slot for an 'sret' type.
doesReturnSlotInterfereWithArgs()144   virtual bool doesReturnSlotInterfereWithArgs() const { return true; }
145 
146   /// Retrieve the address of a function to call immediately before
147   /// calling objc_retainAutoreleasedReturnValue.  The
148   /// implementation of objc_autoreleaseReturnValue sniffs the
149   /// instruction stream following its return address to decide
150   /// whether it's a call to objc_retainAutoreleasedReturnValue.
151   /// This can be prohibitively expensive, depending on the
152   /// relocation model, and so on some targets it instead sniffs for
153   /// a particular instruction sequence.  This functions returns
154   /// that instruction sequence in inline assembly, which will be
155   /// empty if none is required.
getARCRetainAutoreleasedReturnValueMarker()156   virtual StringRef getARCRetainAutoreleasedReturnValueMarker() const {
157     return "";
158   }
159 
160   /// Return a constant used by UBSan as a signature to identify functions
161   /// possessing type information, or 0 if the platform is unsupported.
162   virtual llvm::Constant *
getUBSanFunctionSignature(CodeGen::CodeGenModule & CGM)163   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
164     return nullptr;
165   }
166 
167   /// Determine whether a call to an unprototyped functions under
168   /// the given calling convention should use the variadic
169   /// convention or the non-variadic convention.
170   ///
171   /// There's a good reason to make a platform's variadic calling
172   /// convention be different from its non-variadic calling
173   /// convention: the non-variadic arguments can be passed in
174   /// registers (better for performance), and the variadic arguments
175   /// can be passed on the stack (also better for performance).  If
176   /// this is done, however, unprototyped functions *must* use the
177   /// non-variadic convention, because C99 states that a call
178   /// through an unprototyped function type must succeed if the
179   /// function was defined with a non-variadic prototype with
180   /// compatible parameters.  Therefore, splitting the conventions
181   /// makes it impossible to call a variadic function through an
182   /// unprototyped type.  Since function prototypes came out in the
183   /// late 1970s, this is probably an acceptable trade-off.
184   /// Nonetheless, not all platforms are willing to make it, and in
185   /// particularly x86-64 bends over backwards to make the
186   /// conventions compatible.
187   ///
188   /// The default is false.  This is correct whenever:
189   ///   - the conventions are exactly the same, because it does not
190   ///     matter and the resulting IR will be somewhat prettier in
191   ///     certain cases; or
192   ///   - the conventions are substantively different in how they pass
193   ///     arguments, because in this case using the variadic convention
194   ///     will lead to C99 violations.
195   ///
196   /// However, some platforms make the conventions identical except
197   /// for passing additional out-of-band information to a variadic
198   /// function: for example, x86-64 passes the number of SSE
199   /// arguments in %al.  On these platforms, it is desirable to
200   /// call unprototyped functions using the variadic convention so
201   /// that unprototyped calls to varargs functions still succeed.
202   ///
203   /// Relatedly, platforms which pass the fixed arguments to this:
204   ///   A foo(B, C, D);
205   /// differently than they would pass them to this:
206   ///   A foo(B, C, D, ...);
207   /// may need to adjust the debugger-support code in Sema to do the
208   /// right thing when calling a function with no know signature.
209   virtual bool isNoProtoCallVariadic(const CodeGen::CallArgList &args,
210                                      const FunctionNoProtoType *fnType) const;
211 
212   /// Gets the linker options necessary to link a dependent library on this
213   /// platform.
214   virtual void getDependentLibraryOption(llvm::StringRef Lib,
215                                          llvm::SmallString<24> &Opt) const;
216 
217   /// Gets the linker options necessary to detect object file mismatches on
218   /// this platform.
getDetectMismatchOption(llvm::StringRef Name,llvm::StringRef Value,llvm::SmallString<32> & Opt)219   virtual void getDetectMismatchOption(llvm::StringRef Name,
220                                        llvm::StringRef Value,
221                                        llvm::SmallString<32> &Opt) const {}
222 
223   /// Get LLVM calling convention for OpenCL kernel.
224   virtual unsigned getOpenCLKernelCallingConv() const;
225 
226   /// Get target specific null pointer.
227   /// \param T is the LLVM type of the null pointer.
228   /// \param QT is the clang QualType of the null pointer.
229   /// \return ConstantPointerNull with the given type \p T.
230   /// Each target can override it to return its own desired constant value.
231   virtual llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
232       llvm::PointerType *T, QualType QT) const;
233 
234   /// Get target favored AST address space of a global variable for languages
235   /// other than OpenCL and CUDA.
236   /// If \p D is nullptr, returns the default target favored address space
237   /// for global variable.
238   virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
239                                           const VarDecl *D) const;
240 
241   /// Get the AST address space for alloca.
getASTAllocaAddressSpace()242   virtual LangAS getASTAllocaAddressSpace() const { return LangAS::Default; }
243 
244   /// Perform address space cast of an expression of pointer type.
245   /// \param V is the LLVM value to be casted to another address space.
246   /// \param SrcAddr is the language address space of \p V.
247   /// \param DestAddr is the targeted language address space.
248   /// \param DestTy is the destination LLVM pointer type.
249   /// \param IsNonNull is the flag indicating \p V is known to be non null.
250   virtual llvm::Value *performAddrSpaceCast(CodeGen::CodeGenFunction &CGF,
251                                             llvm::Value *V, LangAS SrcAddr,
252                                             LangAS DestAddr, llvm::Type *DestTy,
253                                             bool IsNonNull = false) const;
254 
255   /// Perform address space cast of a constant expression of pointer type.
256   /// \param V is the LLVM constant to be casted to another address space.
257   /// \param SrcAddr is the language address space of \p V.
258   /// \param DestAddr is the targeted language address space.
259   /// \param DestTy is the destination LLVM pointer type.
260   virtual llvm::Constant *performAddrSpaceCast(CodeGenModule &CGM,
261                                                llvm::Constant *V,
262                                                LangAS SrcAddr, LangAS DestAddr,
263                                                llvm::Type *DestTy) const;
264 
265   /// Get the syncscope used in LLVM IR.
266   virtual llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
267                                                  llvm::LLVMContext &C) const;
268 
269   /// Interface class for filling custom fields of a block literal for OpenCL.
270   class TargetOpenCLBlockHelper {
271   public:
272     typedef std::pair<llvm::Value *, StringRef> ValueTy;
TargetOpenCLBlockHelper()273     TargetOpenCLBlockHelper() {}
~TargetOpenCLBlockHelper()274     virtual ~TargetOpenCLBlockHelper() {}
275     /// Get the custom field types for OpenCL blocks.
276     virtual llvm::SmallVector<llvm::Type *, 1> getCustomFieldTypes() = 0;
277     /// Get the custom field values for OpenCL blocks.
278     virtual llvm::SmallVector<ValueTy, 1>
279     getCustomFieldValues(CodeGenFunction &CGF, const CGBlockInfo &Info) = 0;
280     virtual bool areAllCustomFieldValuesConstant(const CGBlockInfo &Info) = 0;
281     /// Get the custom field values for OpenCL blocks if all values are LLVM
282     /// constants.
283     virtual llvm::SmallVector<llvm::Constant *, 1>
284     getCustomFieldValues(CodeGenModule &CGM, const CGBlockInfo &Info) = 0;
285   };
getTargetOpenCLBlockHelper()286   virtual TargetOpenCLBlockHelper *getTargetOpenCLBlockHelper() const {
287     return nullptr;
288   }
289 
290   /// Create an OpenCL kernel for an enqueued block. The kernel function is
291   /// a wrapper for the block invoke function with target-specific calling
292   /// convention and ABI as an OpenCL kernel. The wrapper function accepts
293   /// block context and block arguments in target-specific way and calls
294   /// the original block invoke function.
295   virtual llvm::Function *
296   createEnqueuedBlockKernel(CodeGenFunction &CGF,
297                             llvm::Function *BlockInvokeFunc,
298                             llvm::Value *BlockLiteral) const;
299 
300   /// \return true if the target supports alias from the unmangled name to the
301   /// mangled name of functions declared within an extern "C" region and marked
302   /// as 'used', and having internal linkage.
shouldEmitStaticExternCAliases()303   virtual bool shouldEmitStaticExternCAliases() const { return true; }
304 
setCUDAKernelCallingConvention(const FunctionType * & FT)305   virtual void setCUDAKernelCallingConvention(const FunctionType *&FT) const {}
306 };
307 
308 } // namespace CodeGen
309 } // namespace clang
310 
311 #endif // LLVM_CLANG_LIB_CODEGEN_TARGETINFO_H
312