1 //===--- CodeGenTypes.h - Type translation for LLVM CodeGen -----*- 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 // This is the code that handles AST -> LLVM type lowering.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENTYPES_H
14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENTYPES_H
15 
16 #include "CGCall.h"
17 #include "clang/Basic/ABI.h"
18 #include "clang/CodeGen/CGFunctionInfo.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/IR/Module.h"
21 
22 namespace llvm {
23 class FunctionType;
24 class DataLayout;
25 class Type;
26 class LLVMContext;
27 class StructType;
28 }
29 
30 namespace clang {
31 class ASTContext;
32 template <typename> class CanQual;
33 class CXXConstructorDecl;
34 class CXXMethodDecl;
35 class CodeGenOptions;
36 class FunctionProtoType;
37 class QualType;
38 class RecordDecl;
39 class TagDecl;
40 class TargetInfo;
41 class Type;
42 typedef CanQual<Type> CanQualType;
43 class GlobalDecl;
44 
45 namespace CodeGen {
46 class ABIInfo;
47 class CGCXXABI;
48 class CGRecordLayout;
49 class CodeGenModule;
50 class RequiredArgs;
51 
52 /// This class organizes the cross-module state that is used while lowering
53 /// AST types to LLVM types.
54 class CodeGenTypes {
55   CodeGenModule &CGM;
56   // Some of this stuff should probably be left on the CGM.
57   ASTContext &Context;
58   llvm::Module &TheModule;
59   const TargetInfo &Target;
60   CGCXXABI &TheCXXABI;
61 
62   // This should not be moved earlier, since its initialization depends on some
63   // of the previous reference members being already initialized
64   const ABIInfo &TheABIInfo;
65 
66   /// The opaque type map for Objective-C interfaces. All direct
67   /// manipulation is done by the runtime interfaces, which are
68   /// responsible for coercing to the appropriate type; these opaque
69   /// types are never refined.
70   llvm::DenseMap<const ObjCInterfaceType*, llvm::Type *> InterfaceTypes;
71 
72   /// Maps clang struct type with corresponding record layout info.
73   llvm::DenseMap<const Type*, std::unique_ptr<CGRecordLayout>> CGRecordLayouts;
74 
75   /// Contains the LLVM IR type for any converted RecordDecl.
76   llvm::DenseMap<const Type*, llvm::StructType *> RecordDeclTypes;
77 
78   /// Hold memoized CGFunctionInfo results.
79   llvm::FoldingSet<CGFunctionInfo> FunctionInfos{FunctionInfosLog2InitSize};
80 
81   /// This set keeps track of records that we're currently converting
82   /// to an IR type.  For example, when converting:
83   /// struct A { struct B { int x; } } when processing 'x', the 'A' and 'B'
84   /// types will be in this set.
85   llvm::SmallPtrSet<const Type*, 4> RecordsBeingLaidOut;
86 
87   llvm::SmallPtrSet<const CGFunctionInfo*, 4> FunctionsBeingProcessed;
88 
89   /// True if we didn't layout a function due to a being inside
90   /// a recursive struct conversion, set this to true.
91   bool SkippedLayout;
92 
93   SmallVector<const RecordDecl *, 8> DeferredRecords;
94 
95   /// This map keeps cache of llvm::Types and maps clang::Type to
96   /// corresponding llvm::Type.
97   llvm::DenseMap<const Type *, llvm::Type *> TypeCache;
98 
99   llvm::DenseMap<const Type *, llvm::Type *> RecordsWithOpaqueMemberPointers;
100 
101   static constexpr unsigned FunctionInfosLog2InitSize = 9;
102   /// Helper for ConvertType.
103   llvm::Type *ConvertFunctionTypeInternal(QualType FT);
104 
105 public:
106   CodeGenTypes(CodeGenModule &cgm);
107   ~CodeGenTypes();
108 
109   const llvm::DataLayout &getDataLayout() const {
110     return TheModule.getDataLayout();
111   }
112   CodeGenModule &getCGM() const { return CGM; }
113   ASTContext &getContext() const { return Context; }
114   const ABIInfo &getABIInfo() const { return TheABIInfo; }
115   const TargetInfo &getTarget() const { return Target; }
116   CGCXXABI &getCXXABI() const { return TheCXXABI; }
117   llvm::LLVMContext &getLLVMContext() { return TheModule.getContext(); }
118   const CodeGenOptions &getCodeGenOpts() const;
119 
120   /// Convert clang calling convention to LLVM callilng convention.
121   unsigned ClangCallConvToLLVMCallConv(CallingConv CC);
122 
123   /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
124   /// qualification.
125   CanQualType DeriveThisType(const CXXRecordDecl *RD, const CXXMethodDecl *MD);
126 
127   /// ConvertType - Convert type T into a llvm::Type.
128   llvm::Type *ConvertType(QualType T);
129 
130   /// ConvertTypeForMem - Convert type T into a llvm::Type.  This differs from
131   /// ConvertType in that it is used to convert to the memory representation for
132   /// a type.  For example, the scalar representation for _Bool is i1, but the
133   /// memory representation is usually i8 or i32, depending on the target.
134   llvm::Type *ConvertTypeForMem(QualType T, bool ForBitField = false);
135 
136   /// GetFunctionType - Get the LLVM function type for \arg Info.
137   llvm::FunctionType *GetFunctionType(const CGFunctionInfo &Info);
138 
139   llvm::FunctionType *GetFunctionType(GlobalDecl GD);
140 
141   /// isFuncTypeConvertible - Utility to check whether a function type can
142   /// be converted to an LLVM type (i.e. doesn't depend on an incomplete tag
143   /// type).
144   bool isFuncTypeConvertible(const FunctionType *FT);
145   bool isFuncParamTypeConvertible(QualType Ty);
146 
147   /// Determine if a C++ inheriting constructor should have parameters matching
148   /// those of its inherited constructor.
149   bool inheritingCtorHasParams(const InheritedConstructor &Inherited,
150                                CXXCtorType Type);
151 
152   /// GetFunctionTypeForVTable - Get the LLVM function type for use in a vtable,
153   /// given a CXXMethodDecl. If the method to has an incomplete return type,
154   /// and/or incomplete argument types, this will return the opaque type.
155   llvm::Type *GetFunctionTypeForVTable(GlobalDecl GD);
156 
157   const CGRecordLayout &getCGRecordLayout(const RecordDecl*);
158 
159   /// UpdateCompletedType - When we find the full definition for a TagDecl,
160   /// replace the 'opaque' type we previously made for it if applicable.
161   void UpdateCompletedType(const TagDecl *TD);
162 
163   /// Remove stale types from the type cache when an inheritance model
164   /// gets assigned to a class.
165   void RefreshTypeCacheForClass(const CXXRecordDecl *RD);
166 
167   // The arrangement methods are split into three families:
168   //   - those meant to drive the signature and prologue/epilogue
169   //     of a function declaration or definition,
170   //   - those meant for the computation of the LLVM type for an abstract
171   //     appearance of a function, and
172   //   - those meant for performing the IR-generation of a call.
173   // They differ mainly in how they deal with optional (i.e. variadic)
174   // arguments, as well as unprototyped functions.
175   //
176   // Key points:
177   // - The CGFunctionInfo for emitting a specific call site must include
178   //   entries for the optional arguments.
179   // - The function type used at the call site must reflect the formal
180   //   signature of the declaration being called, or else the call will
181   //   go awry.
182   // - For the most part, unprototyped functions are called by casting to
183   //   a formal signature inferred from the specific argument types used
184   //   at the call-site.  However, some targets (e.g. x86-64) screw with
185   //   this for compatibility reasons.
186 
187   const CGFunctionInfo &arrangeGlobalDeclaration(GlobalDecl GD);
188 
189   /// Given a function info for a declaration, return the function info
190   /// for a call with the given arguments.
191   ///
192   /// Often this will be able to simply return the declaration info.
193   const CGFunctionInfo &arrangeCall(const CGFunctionInfo &declFI,
194                                     const CallArgList &args);
195 
196   /// Free functions are functions that are compatible with an ordinary
197   /// C function pointer type.
198   const CGFunctionInfo &arrangeFunctionDeclaration(const FunctionDecl *FD);
199   const CGFunctionInfo &arrangeFreeFunctionCall(const CallArgList &Args,
200                                                 const FunctionType *Ty,
201                                                 bool ChainCall);
202   const CGFunctionInfo &arrangeFreeFunctionType(CanQual<FunctionProtoType> Ty);
203   const CGFunctionInfo &arrangeFreeFunctionType(CanQual<FunctionNoProtoType> Ty);
204 
205   /// A nullary function is a freestanding function of type 'void ()'.
206   /// This method works for both calls and declarations.
207   const CGFunctionInfo &arrangeNullaryFunction();
208 
209   /// A builtin function is a freestanding function using the default
210   /// C conventions.
211   const CGFunctionInfo &
212   arrangeBuiltinFunctionDeclaration(QualType resultType,
213                                     const FunctionArgList &args);
214   const CGFunctionInfo &
215   arrangeBuiltinFunctionDeclaration(CanQualType resultType,
216                                     ArrayRef<CanQualType> argTypes);
217   const CGFunctionInfo &arrangeBuiltinFunctionCall(QualType resultType,
218                                                    const CallArgList &args);
219 
220   /// Objective-C methods are C functions with some implicit parameters.
221   const CGFunctionInfo &arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD);
222   const CGFunctionInfo &arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
223                                                         QualType receiverType);
224   const CGFunctionInfo &arrangeUnprototypedObjCMessageSend(
225                                                      QualType returnType,
226                                                      const CallArgList &args);
227 
228   /// Block invocation functions are C functions with an implicit parameter.
229   const CGFunctionInfo &arrangeBlockFunctionDeclaration(
230                                                  const FunctionProtoType *type,
231                                                  const FunctionArgList &args);
232   const CGFunctionInfo &arrangeBlockFunctionCall(const CallArgList &args,
233                                                  const FunctionType *type);
234 
235   /// C++ methods have some special rules and also have implicit parameters.
236   const CGFunctionInfo &arrangeCXXMethodDeclaration(const CXXMethodDecl *MD);
237   const CGFunctionInfo &arrangeCXXStructorDeclaration(GlobalDecl GD);
238   const CGFunctionInfo &arrangeCXXConstructorCall(const CallArgList &Args,
239                                                   const CXXConstructorDecl *D,
240                                                   CXXCtorType CtorKind,
241                                                   unsigned ExtraPrefixArgs,
242                                                   unsigned ExtraSuffixArgs,
243                                                   bool PassProtoArgs = true);
244 
245   const CGFunctionInfo &arrangeCXXMethodCall(const CallArgList &args,
246                                              const FunctionProtoType *type,
247                                              RequiredArgs required,
248                                              unsigned numPrefixArgs);
249   const CGFunctionInfo &
250   arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD);
251   const CGFunctionInfo &arrangeMSCtorClosure(const CXXConstructorDecl *CD,
252                                                  CXXCtorType CT);
253   const CGFunctionInfo &arrangeCXXMethodType(const CXXRecordDecl *RD,
254                                              const FunctionProtoType *FTP,
255                                              const CXXMethodDecl *MD);
256 
257   /// "Arrange" the LLVM information for a call or type with the given
258   /// signature.  This is largely an internal method; other clients
259   /// should use one of the above routines, which ultimately defer to
260   /// this.
261   ///
262   /// \param argTypes - must all actually be canonical as params
263   const CGFunctionInfo &arrangeLLVMFunctionInfo(CanQualType returnType,
264                                                 bool instanceMethod,
265                                                 bool chainCall,
266                                                 ArrayRef<CanQualType> argTypes,
267                                                 FunctionType::ExtInfo info,
268                     ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
269                                                 RequiredArgs args);
270 
271   /// Compute a new LLVM record layout object for the given record.
272   std::unique_ptr<CGRecordLayout> ComputeRecordLayout(const RecordDecl *D,
273                                                       llvm::StructType *Ty);
274 
275   /// addRecordTypeName - Compute a name from the given record decl with an
276   /// optional suffix and name the given LLVM type using it.
277   void addRecordTypeName(const RecordDecl *RD, llvm::StructType *Ty,
278                          StringRef suffix);
279 
280 
281 public:  // These are internal details of CGT that shouldn't be used externally.
282   /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
283   llvm::StructType *ConvertRecordDeclType(const RecordDecl *TD);
284 
285   /// getExpandedTypes - Expand the type \arg Ty into the LLVM
286   /// argument types it would be passed as. See ABIArgInfo::Expand.
287   void getExpandedTypes(QualType Ty,
288                         SmallVectorImpl<llvm::Type *>::iterator &TI);
289 
290   /// IsZeroInitializable - Return whether a type can be
291   /// zero-initialized (in the C++ sense) with an LLVM zeroinitializer.
292   bool isZeroInitializable(QualType T);
293 
294   /// Check if the pointer type can be zero-initialized (in the C++ sense)
295   /// with an LLVM zeroinitializer.
296   bool isPointerZeroInitializable(QualType T);
297 
298   /// IsZeroInitializable - Return whether a record type can be
299   /// zero-initialized (in the C++ sense) with an LLVM zeroinitializer.
300   bool isZeroInitializable(const RecordDecl *RD);
301 
302   bool isRecordLayoutComplete(const Type *Ty) const;
303   bool noRecordsBeingLaidOut() const {
304     return RecordsBeingLaidOut.empty();
305   }
306   bool isRecordBeingLaidOut(const Type *Ty) const {
307     return RecordsBeingLaidOut.count(Ty);
308   }
309   unsigned getTargetAddressSpace(QualType T) const;
310 };
311 
312 }  // end namespace CodeGen
313 }  // end namespace clang
314 
315 #endif
316