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