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