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