1 //===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===//
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 #include "CodeGenTypes.h"
14 #include "CGCXXABI.h"
15 #include "CGCall.h"
16 #include "CGOpenCLRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/CodeGen/CGFunctionInfo.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Module.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
CodeGenTypes(CodeGenModule & cgm)31 CodeGenTypes::CodeGenTypes(CodeGenModule &cgm)
32   : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()),
33     Target(cgm.getTarget()), TheCXXABI(cgm.getCXXABI()),
34     TheABIInfo(cgm.getTargetCodeGenInfo().getABIInfo()) {
35   SkippedLayout = false;
36 }
37 
~CodeGenTypes()38 CodeGenTypes::~CodeGenTypes() {
39   for (llvm::FoldingSet<CGFunctionInfo>::iterator
40        I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
41     delete &*I++;
42 }
43 
getCodeGenOpts() const44 const CodeGenOptions &CodeGenTypes::getCodeGenOpts() const {
45   return CGM.getCodeGenOpts();
46 }
47 
addRecordTypeName(const RecordDecl * RD,llvm::StructType * Ty,StringRef suffix)48 void CodeGenTypes::addRecordTypeName(const RecordDecl *RD,
49                                      llvm::StructType *Ty,
50                                      StringRef suffix) {
51   SmallString<256> TypeName;
52   llvm::raw_svector_ostream OS(TypeName);
53   OS << RD->getKindName() << '.';
54 
55   // Name the codegen type after the typedef name
56   // if there is no tag type name available
57   if (RD->getIdentifier()) {
58     // FIXME: We should not have to check for a null decl context here.
59     // Right now we do it because the implicit Obj-C decls don't have one.
60     if (RD->getDeclContext())
61       RD->printQualifiedName(OS);
62     else
63       RD->printName(OS);
64   } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) {
65     // FIXME: We should not have to check for a null decl context here.
66     // Right now we do it because the implicit Obj-C decls don't have one.
67     if (TDD->getDeclContext())
68       TDD->printQualifiedName(OS);
69     else
70       TDD->printName(OS);
71   } else
72     OS << "anon";
73 
74   if (!suffix.empty())
75     OS << suffix;
76 
77   Ty->setName(OS.str());
78 }
79 
80 /// ConvertTypeForMem - Convert type T into a llvm::Type.  This differs from
81 /// ConvertType in that it is used to convert to the memory representation for
82 /// a type.  For example, the scalar representation for _Bool is i1, but the
83 /// memory representation is usually i8 or i32, depending on the target.
ConvertTypeForMem(QualType T,bool ForBitField)84 llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T, bool ForBitField) {
85   if (T->isConstantMatrixType()) {
86     const Type *Ty = Context.getCanonicalType(T).getTypePtr();
87     const ConstantMatrixType *MT = cast<ConstantMatrixType>(Ty);
88     return llvm::ArrayType::get(ConvertType(MT->getElementType()),
89                                 MT->getNumRows() * MT->getNumColumns());
90   }
91 
92   llvm::Type *R = ConvertType(T);
93 
94   // If this is a bool type, or an ExtIntType in a bitfield representation,
95   // map this integer to the target-specified size.
96   if ((ForBitField && T->isExtIntType()) || R->isIntegerTy(1))
97     return llvm::IntegerType::get(getLLVMContext(),
98                                   (unsigned)Context.getTypeSize(T));
99 
100   // Else, don't map it.
101   return R;
102 }
103 
104 /// isRecordLayoutComplete - Return true if the specified type is already
105 /// completely laid out.
isRecordLayoutComplete(const Type * Ty) const106 bool CodeGenTypes::isRecordLayoutComplete(const Type *Ty) const {
107   llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
108   RecordDeclTypes.find(Ty);
109   return I != RecordDeclTypes.end() && !I->second->isOpaque();
110 }
111 
112 static bool
113 isSafeToConvert(QualType T, CodeGenTypes &CGT,
114                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked);
115 
116 
117 /// isSafeToConvert - Return true if it is safe to convert the specified record
118 /// decl to IR and lay it out, false if doing so would cause us to get into a
119 /// recursive compilation mess.
120 static bool
isSafeToConvert(const RecordDecl * RD,CodeGenTypes & CGT,llvm::SmallPtrSet<const RecordDecl *,16> & AlreadyChecked)121 isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT,
122                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
123   // If we have already checked this type (maybe the same type is used by-value
124   // multiple times in multiple structure fields, don't check again.
125   if (!AlreadyChecked.insert(RD).second)
126     return true;
127 
128   const Type *Key = CGT.getContext().getTagDeclType(RD).getTypePtr();
129 
130   // If this type is already laid out, converting it is a noop.
131   if (CGT.isRecordLayoutComplete(Key)) return true;
132 
133   // If this type is currently being laid out, we can't recursively compile it.
134   if (CGT.isRecordBeingLaidOut(Key))
135     return false;
136 
137   // If this type would require laying out bases that are currently being laid
138   // out, don't do it.  This includes virtual base classes which get laid out
139   // when a class is translated, even though they aren't embedded by-value into
140   // the class.
141   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
142     for (const auto &I : CRD->bases())
143       if (!isSafeToConvert(I.getType()->castAs<RecordType>()->getDecl(), CGT,
144                            AlreadyChecked))
145         return false;
146   }
147 
148   // If this type would require laying out members that are currently being laid
149   // out, don't do it.
150   for (const auto *I : RD->fields())
151     if (!isSafeToConvert(I->getType(), CGT, AlreadyChecked))
152       return false;
153 
154   // If there are no problems, lets do it.
155   return true;
156 }
157 
158 /// isSafeToConvert - Return true if it is safe to convert this field type,
159 /// which requires the structure elements contained by-value to all be
160 /// recursively safe to convert.
161 static bool
isSafeToConvert(QualType T,CodeGenTypes & CGT,llvm::SmallPtrSet<const RecordDecl *,16> & AlreadyChecked)162 isSafeToConvert(QualType T, CodeGenTypes &CGT,
163                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
164   // Strip off atomic type sugar.
165   if (const auto *AT = T->getAs<AtomicType>())
166     T = AT->getValueType();
167 
168   // If this is a record, check it.
169   if (const auto *RT = T->getAs<RecordType>())
170     return isSafeToConvert(RT->getDecl(), CGT, AlreadyChecked);
171 
172   // If this is an array, check the elements, which are embedded inline.
173   if (const auto *AT = CGT.getContext().getAsArrayType(T))
174     return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked);
175 
176   // Otherwise, there is no concern about transforming this.  We only care about
177   // things that are contained by-value in a structure that can have another
178   // structure as a member.
179   return true;
180 }
181 
182 
183 /// isSafeToConvert - Return true if it is safe to convert the specified record
184 /// decl to IR and lay it out, false if doing so would cause us to get into a
185 /// recursive compilation mess.
isSafeToConvert(const RecordDecl * RD,CodeGenTypes & CGT)186 static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) {
187   // If no structs are being laid out, we can certainly do this one.
188   if (CGT.noRecordsBeingLaidOut()) return true;
189 
190   llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked;
191   return isSafeToConvert(RD, CGT, AlreadyChecked);
192 }
193 
194 /// isFuncParamTypeConvertible - Return true if the specified type in a
195 /// function parameter or result position can be converted to an IR type at this
196 /// point.  This boils down to being whether it is complete, as well as whether
197 /// we've temporarily deferred expanding the type because we're in a recursive
198 /// context.
isFuncParamTypeConvertible(QualType Ty)199 bool CodeGenTypes::isFuncParamTypeConvertible(QualType Ty) {
200   // Some ABIs cannot have their member pointers represented in IR unless
201   // certain circumstances have been reached.
202   if (const auto *MPT = Ty->getAs<MemberPointerType>())
203     return getCXXABI().isMemberPointerConvertible(MPT);
204 
205   // If this isn't a tagged type, we can convert it!
206   const TagType *TT = Ty->getAs<TagType>();
207   if (!TT) return true;
208 
209   // Incomplete types cannot be converted.
210   if (TT->isIncompleteType())
211     return false;
212 
213   // If this is an enum, then it is always safe to convert.
214   const RecordType *RT = dyn_cast<RecordType>(TT);
215   if (!RT) return true;
216 
217   // Otherwise, we have to be careful.  If it is a struct that we're in the
218   // process of expanding, then we can't convert the function type.  That's ok
219   // though because we must be in a pointer context under the struct, so we can
220   // just convert it to a dummy type.
221   //
222   // We decide this by checking whether ConvertRecordDeclType returns us an
223   // opaque type for a struct that we know is defined.
224   return isSafeToConvert(RT->getDecl(), *this);
225 }
226 
227 
228 /// Code to verify a given function type is complete, i.e. the return type
229 /// and all of the parameter types are complete.  Also check to see if we are in
230 /// a RS_StructPointer context, and if so whether any struct types have been
231 /// pended.  If so, we don't want to ask the ABI lowering code to handle a type
232 /// that cannot be converted to an IR type.
isFuncTypeConvertible(const FunctionType * FT)233 bool CodeGenTypes::isFuncTypeConvertible(const FunctionType *FT) {
234   if (!isFuncParamTypeConvertible(FT->getReturnType()))
235     return false;
236 
237   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
238     for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
239       if (!isFuncParamTypeConvertible(FPT->getParamType(i)))
240         return false;
241 
242   return true;
243 }
244 
245 /// UpdateCompletedType - When we find the full definition for a TagDecl,
246 /// replace the 'opaque' type we previously made for it if applicable.
UpdateCompletedType(const TagDecl * TD)247 void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) {
248   // If this is an enum being completed, then we flush all non-struct types from
249   // the cache.  This allows function types and other things that may be derived
250   // from the enum to be recomputed.
251   if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) {
252     // Only flush the cache if we've actually already converted this type.
253     if (TypeCache.count(ED->getTypeForDecl())) {
254       // Okay, we formed some types based on this.  We speculated that the enum
255       // would be lowered to i32, so we only need to flush the cache if this
256       // didn't happen.
257       if (!ConvertType(ED->getIntegerType())->isIntegerTy(32))
258         TypeCache.clear();
259     }
260     // If necessary, provide the full definition of a type only used with a
261     // declaration so far.
262     if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
263       DI->completeType(ED);
264     return;
265   }
266 
267   // If we completed a RecordDecl that we previously used and converted to an
268   // anonymous type, then go ahead and complete it now.
269   const RecordDecl *RD = cast<RecordDecl>(TD);
270   if (RD->isDependentType()) return;
271 
272   // Only complete it if we converted it already.  If we haven't converted it
273   // yet, we'll just do it lazily.
274   if (RecordDeclTypes.count(Context.getTagDeclType(RD).getTypePtr()))
275     ConvertRecordDeclType(RD);
276 
277   // If necessary, provide the full definition of a type only used with a
278   // declaration so far.
279   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
280     DI->completeType(RD);
281 }
282 
RefreshTypeCacheForClass(const CXXRecordDecl * RD)283 void CodeGenTypes::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
284   QualType T = Context.getRecordType(RD);
285   T = Context.getCanonicalType(T);
286 
287   const Type *Ty = T.getTypePtr();
288   if (RecordsWithOpaqueMemberPointers.count(Ty)) {
289     TypeCache.clear();
290     RecordsWithOpaqueMemberPointers.clear();
291   }
292 }
293 
getTypeForFormat(llvm::LLVMContext & VMContext,const llvm::fltSemantics & format,bool UseNativeHalf=false)294 static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
295                                     const llvm::fltSemantics &format,
296                                     bool UseNativeHalf = false) {
297   if (&format == &llvm::APFloat::IEEEhalf()) {
298     if (UseNativeHalf)
299       return llvm::Type::getHalfTy(VMContext);
300     else
301       return llvm::Type::getInt16Ty(VMContext);
302   }
303   if (&format == &llvm::APFloat::BFloat())
304     return llvm::Type::getBFloatTy(VMContext);
305   if (&format == &llvm::APFloat::IEEEsingle())
306     return llvm::Type::getFloatTy(VMContext);
307   if (&format == &llvm::APFloat::IEEEdouble())
308     return llvm::Type::getDoubleTy(VMContext);
309   if (&format == &llvm::APFloat::IEEEquad())
310     return llvm::Type::getFP128Ty(VMContext);
311   if (&format == &llvm::APFloat::PPCDoubleDouble())
312     return llvm::Type::getPPC_FP128Ty(VMContext);
313   if (&format == &llvm::APFloat::x87DoubleExtended())
314     return llvm::Type::getX86_FP80Ty(VMContext);
315   llvm_unreachable("Unknown float format!");
316 }
317 
ConvertFunctionTypeInternal(QualType QFT)318 llvm::Type *CodeGenTypes::ConvertFunctionTypeInternal(QualType QFT) {
319   assert(QFT.isCanonical());
320   const Type *Ty = QFT.getTypePtr();
321   const FunctionType *FT = cast<FunctionType>(QFT.getTypePtr());
322   // First, check whether we can build the full function type.  If the
323   // function type depends on an incomplete type (e.g. a struct or enum), we
324   // cannot lower the function type.
325   if (!isFuncTypeConvertible(FT)) {
326     // This function's type depends on an incomplete tag type.
327 
328     // Force conversion of all the relevant record types, to make sure
329     // we re-convert the FunctionType when appropriate.
330     if (const RecordType *RT = FT->getReturnType()->getAs<RecordType>())
331       ConvertRecordDeclType(RT->getDecl());
332     if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
333       for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
334         if (const RecordType *RT = FPT->getParamType(i)->getAs<RecordType>())
335           ConvertRecordDeclType(RT->getDecl());
336 
337     SkippedLayout = true;
338 
339     // Return a placeholder type.
340     return llvm::StructType::get(getLLVMContext());
341   }
342 
343   // While we're converting the parameter types for a function, we don't want
344   // to recursively convert any pointed-to structs.  Converting directly-used
345   // structs is ok though.
346   if (!RecordsBeingLaidOut.insert(Ty).second) {
347     SkippedLayout = true;
348     return llvm::StructType::get(getLLVMContext());
349   }
350 
351   // The function type can be built; call the appropriate routines to
352   // build it.
353   const CGFunctionInfo *FI;
354   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
355     FI = &arrangeFreeFunctionType(
356         CanQual<FunctionProtoType>::CreateUnsafe(QualType(FPT, 0)));
357   } else {
358     const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
359     FI = &arrangeFreeFunctionType(
360         CanQual<FunctionNoProtoType>::CreateUnsafe(QualType(FNPT, 0)));
361   }
362 
363   llvm::Type *ResultType = nullptr;
364   // If there is something higher level prodding our CGFunctionInfo, then
365   // don't recurse into it again.
366   if (FunctionsBeingProcessed.count(FI)) {
367 
368     ResultType = llvm::StructType::get(getLLVMContext());
369     SkippedLayout = true;
370   } else {
371 
372     // Otherwise, we're good to go, go ahead and convert it.
373     ResultType = GetFunctionType(*FI);
374   }
375 
376   RecordsBeingLaidOut.erase(Ty);
377 
378   if (SkippedLayout)
379     TypeCache.clear();
380 
381   if (RecordsBeingLaidOut.empty())
382     while (!DeferredRecords.empty())
383       ConvertRecordDeclType(DeferredRecords.pop_back_val());
384   return ResultType;
385 }
386 
387 /// ConvertType - Convert the specified type to its LLVM form.
ConvertType(QualType T)388 llvm::Type *CodeGenTypes::ConvertType(QualType T) {
389   T = Context.getCanonicalType(T);
390 
391   const Type *Ty = T.getTypePtr();
392 
393   // For the device-side compilation, CUDA device builtin surface/texture types
394   // may be represented in different types.
395   if (Context.getLangOpts().CUDAIsDevice) {
396     if (T->isCUDADeviceBuiltinSurfaceType()) {
397       if (auto *Ty = CGM.getTargetCodeGenInfo()
398                          .getCUDADeviceBuiltinSurfaceDeviceType())
399         return Ty;
400     } else if (T->isCUDADeviceBuiltinTextureType()) {
401       if (auto *Ty = CGM.getTargetCodeGenInfo()
402                          .getCUDADeviceBuiltinTextureDeviceType())
403         return Ty;
404     }
405   }
406 
407   // RecordTypes are cached and processed specially.
408   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
409     return ConvertRecordDeclType(RT->getDecl());
410 
411   // See if type is already cached.
412   llvm::DenseMap<const Type *, llvm::Type *>::iterator TCI = TypeCache.find(Ty);
413   // If type is found in map then use it. Otherwise, convert type T.
414   if (TCI != TypeCache.end())
415     return TCI->second;
416 
417   // If we don't have it in the cache, convert it now.
418   llvm::Type *ResultType = nullptr;
419   switch (Ty->getTypeClass()) {
420   case Type::Record: // Handled above.
421 #define TYPE(Class, Base)
422 #define ABSTRACT_TYPE(Class, Base)
423 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
424 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
425 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
426 #include "clang/AST/TypeNodes.inc"
427     llvm_unreachable("Non-canonical or dependent types aren't possible.");
428 
429   case Type::Builtin: {
430     switch (cast<BuiltinType>(Ty)->getKind()) {
431     case BuiltinType::Void:
432     case BuiltinType::ObjCId:
433     case BuiltinType::ObjCClass:
434     case BuiltinType::ObjCSel:
435       // LLVM void type can only be used as the result of a function call.  Just
436       // map to the same as char.
437       ResultType = llvm::Type::getInt8Ty(getLLVMContext());
438       break;
439 
440     case BuiltinType::Bool:
441       // Note that we always return bool as i1 for use as a scalar type.
442       ResultType = llvm::Type::getInt1Ty(getLLVMContext());
443       break;
444 
445     case BuiltinType::Char_S:
446     case BuiltinType::Char_U:
447     case BuiltinType::SChar:
448     case BuiltinType::UChar:
449     case BuiltinType::Short:
450     case BuiltinType::UShort:
451     case BuiltinType::Int:
452     case BuiltinType::UInt:
453     case BuiltinType::Long:
454     case BuiltinType::ULong:
455     case BuiltinType::LongLong:
456     case BuiltinType::ULongLong:
457     case BuiltinType::WChar_S:
458     case BuiltinType::WChar_U:
459     case BuiltinType::Char8:
460     case BuiltinType::Char16:
461     case BuiltinType::Char32:
462     case BuiltinType::ShortAccum:
463     case BuiltinType::Accum:
464     case BuiltinType::LongAccum:
465     case BuiltinType::UShortAccum:
466     case BuiltinType::UAccum:
467     case BuiltinType::ULongAccum:
468     case BuiltinType::ShortFract:
469     case BuiltinType::Fract:
470     case BuiltinType::LongFract:
471     case BuiltinType::UShortFract:
472     case BuiltinType::UFract:
473     case BuiltinType::ULongFract:
474     case BuiltinType::SatShortAccum:
475     case BuiltinType::SatAccum:
476     case BuiltinType::SatLongAccum:
477     case BuiltinType::SatUShortAccum:
478     case BuiltinType::SatUAccum:
479     case BuiltinType::SatULongAccum:
480     case BuiltinType::SatShortFract:
481     case BuiltinType::SatFract:
482     case BuiltinType::SatLongFract:
483     case BuiltinType::SatUShortFract:
484     case BuiltinType::SatUFract:
485     case BuiltinType::SatULongFract:
486       ResultType = llvm::IntegerType::get(getLLVMContext(),
487                                  static_cast<unsigned>(Context.getTypeSize(T)));
488       break;
489 
490     // We store these as capabilities (and must use capability instructions for
491     // writing them to memory), and must perform some explicit casts for
492     // arithmetic.
493     case BuiltinType::IntCap:
494     case BuiltinType::UIntCap:
495       ResultType =
496           llvm::PointerType::get(llvm::Type::getInt8Ty(getLLVMContext()),
497               CGM.getTargetCodeGenInfo().getCHERICapabilityAS());
498       break;
499     case BuiltinType::Float16:
500       ResultType =
501           getTypeForFormat(getLLVMContext(), Context.getFloatTypeSemantics(T),
502                            /* UseNativeHalf = */ true);
503       break;
504 
505     case BuiltinType::Half:
506       // Half FP can either be storage-only (lowered to i16) or native.
507       ResultType = getTypeForFormat(
508           getLLVMContext(), Context.getFloatTypeSemantics(T),
509           Context.getLangOpts().NativeHalfType ||
510               !Context.getTargetInfo().useFP16ConversionIntrinsics());
511       break;
512     case BuiltinType::BFloat16:
513     case BuiltinType::Float:
514     case BuiltinType::Double:
515     case BuiltinType::LongDouble:
516     case BuiltinType::Float128:
517       ResultType = getTypeForFormat(getLLVMContext(),
518                                     Context.getFloatTypeSemantics(T),
519                                     /* UseNativeHalf = */ false);
520       break;
521 
522     case BuiltinType::NullPtr:
523       // Model std::nullptr_t as i8*
524       ResultType = llvm::Type::getInt8PtrTy(getLLVMContext(),
525         CGM.getTargetCodeGenInfo().getDefaultAS());
526       break;
527 
528     case BuiltinType::UInt128:
529     case BuiltinType::Int128:
530       ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
531       break;
532 
533 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
534     case BuiltinType::Id:
535 #include "clang/Basic/OpenCLImageTypes.def"
536 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
537     case BuiltinType::Id:
538 #include "clang/Basic/OpenCLExtensionTypes.def"
539     case BuiltinType::OCLSampler:
540     case BuiltinType::OCLEvent:
541     case BuiltinType::OCLClkEvent:
542     case BuiltinType::OCLQueue:
543     case BuiltinType::OCLReserveID:
544       ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
545       break;
546 #define GET_SVE_INT_VEC(BITS, ELTS)                                            \
547   llvm::ScalableVectorType::get(                                               \
548       llvm::IntegerType::get(getLLVMContext(), BITS), ELTS);
549     case BuiltinType::SveInt8:
550     case BuiltinType::SveUint8:
551       return GET_SVE_INT_VEC(8, 16);
552     case BuiltinType::SveInt8x2:
553     case BuiltinType::SveUint8x2:
554       return GET_SVE_INT_VEC(8, 32);
555     case BuiltinType::SveInt8x3:
556     case BuiltinType::SveUint8x3:
557       return GET_SVE_INT_VEC(8, 48);
558     case BuiltinType::SveInt8x4:
559     case BuiltinType::SveUint8x4:
560       return GET_SVE_INT_VEC(8, 64);
561     case BuiltinType::SveInt16:
562     case BuiltinType::SveUint16:
563       return GET_SVE_INT_VEC(16, 8);
564     case BuiltinType::SveInt16x2:
565     case BuiltinType::SveUint16x2:
566       return GET_SVE_INT_VEC(16, 16);
567     case BuiltinType::SveInt16x3:
568     case BuiltinType::SveUint16x3:
569       return GET_SVE_INT_VEC(16, 24);
570     case BuiltinType::SveInt16x4:
571     case BuiltinType::SveUint16x4:
572       return GET_SVE_INT_VEC(16, 32);
573     case BuiltinType::SveInt32:
574     case BuiltinType::SveUint32:
575       return GET_SVE_INT_VEC(32, 4);
576     case BuiltinType::SveInt32x2:
577     case BuiltinType::SveUint32x2:
578       return GET_SVE_INT_VEC(32, 8);
579     case BuiltinType::SveInt32x3:
580     case BuiltinType::SveUint32x3:
581       return GET_SVE_INT_VEC(32, 12);
582     case BuiltinType::SveInt32x4:
583     case BuiltinType::SveUint32x4:
584       return GET_SVE_INT_VEC(32, 16);
585     case BuiltinType::SveInt64:
586     case BuiltinType::SveUint64:
587       return GET_SVE_INT_VEC(64, 2);
588     case BuiltinType::SveInt64x2:
589     case BuiltinType::SveUint64x2:
590       return GET_SVE_INT_VEC(64, 4);
591     case BuiltinType::SveInt64x3:
592     case BuiltinType::SveUint64x3:
593       return GET_SVE_INT_VEC(64, 6);
594     case BuiltinType::SveInt64x4:
595     case BuiltinType::SveUint64x4:
596       return GET_SVE_INT_VEC(64, 8);
597     case BuiltinType::SveBool:
598       return GET_SVE_INT_VEC(1, 16);
599 #undef GET_SVE_INT_VEC
600 #define GET_SVE_FP_VEC(TY, ISFP16, ELTS)                                       \
601   llvm::ScalableVectorType::get(                                               \
602       getTypeForFormat(getLLVMContext(),                                       \
603                        Context.getFloatTypeSemantics(Context.TY),              \
604                        /* UseNativeHalf = */ ISFP16),                          \
605       ELTS);
606     case BuiltinType::SveFloat16:
607       return GET_SVE_FP_VEC(HalfTy, true, 8);
608     case BuiltinType::SveFloat16x2:
609       return GET_SVE_FP_VEC(HalfTy, true, 16);
610     case BuiltinType::SveFloat16x3:
611       return GET_SVE_FP_VEC(HalfTy, true, 24);
612     case BuiltinType::SveFloat16x4:
613       return GET_SVE_FP_VEC(HalfTy, true, 32);
614     case BuiltinType::SveFloat32:
615       return GET_SVE_FP_VEC(FloatTy, false, 4);
616     case BuiltinType::SveFloat32x2:
617       return GET_SVE_FP_VEC(FloatTy, false, 8);
618     case BuiltinType::SveFloat32x3:
619       return GET_SVE_FP_VEC(FloatTy, false, 12);
620     case BuiltinType::SveFloat32x4:
621       return GET_SVE_FP_VEC(FloatTy, false, 16);
622     case BuiltinType::SveFloat64:
623       return GET_SVE_FP_VEC(DoubleTy, false, 2);
624     case BuiltinType::SveFloat64x2:
625       return GET_SVE_FP_VEC(DoubleTy, false, 4);
626     case BuiltinType::SveFloat64x3:
627       return GET_SVE_FP_VEC(DoubleTy, false, 6);
628     case BuiltinType::SveFloat64x4:
629       return GET_SVE_FP_VEC(DoubleTy, false, 8);
630     case BuiltinType::SveBFloat16:
631       return GET_SVE_FP_VEC(BFloat16Ty, false, 8);
632     case BuiltinType::SveBFloat16x2:
633       return GET_SVE_FP_VEC(BFloat16Ty, false, 16);
634     case BuiltinType::SveBFloat16x3:
635       return GET_SVE_FP_VEC(BFloat16Ty, false, 24);
636     case BuiltinType::SveBFloat16x4:
637       return GET_SVE_FP_VEC(BFloat16Ty, false, 32);
638 #undef GET_SVE_FP_VEC
639     case BuiltinType::Dependent:
640 #define BUILTIN_TYPE(Id, SingletonId)
641 #define PLACEHOLDER_TYPE(Id, SingletonId) \
642     case BuiltinType::Id:
643 #include "clang/AST/BuiltinTypes.def"
644       llvm_unreachable("Unexpected placeholder builtin type!");
645     }
646     break;
647   }
648   case Type::Auto:
649   case Type::DeducedTemplateSpecialization:
650     llvm_unreachable("Unexpected undeduced type!");
651   case Type::Complex: {
652     llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
653     ResultType = llvm::StructType::get(EltTy, EltTy);
654     break;
655   }
656   case Type::LValueReference:
657   case Type::RValueReference: {
658     const ReferenceType *RTy = cast<ReferenceType>(Ty);
659     QualType ETy = RTy->getPointeeType();
660     llvm::Type *PointeeType = ConvertTypeForMem(ETy);
661     // XXXAR: If Rty is capability, use AS200 otherwise the same as LangAS as
662     // the underlying type
663     unsigned AS = RTy->isCHERICapability()
664                       ? CGM.getTargetCodeGenInfo().getCHERICapabilityAS()
665                       : CGM.getTargetAddressSpace(ETy.getQualifiers());
666     ResultType = llvm::PointerType::get(PointeeType, AS);
667     break;
668   }
669   case Type::Pointer: {
670     const PointerType *PTy = cast<PointerType>(Ty);
671     QualType ETy = PTy->getPointeeType();
672     // CHERI CCallback function pointers are not actually pointers, they are
673     // structs containing three pointers.
674     if (ETy->isFunctionProtoType()) {
675       auto FPT = ETy->getAs<FunctionProtoType>();
676       if (FPT->getCallConv() == CC_CHERICCallback) {
677         auto MethNoTy = llvm::Type::getInt64Ty(getLLVMContext());
678         auto ObjTy = ConvertType(Context.getCHERIClassType());
679         ResultType = llvm::StructType::get(ObjTy, MethNoTy);
680         break;
681       }
682     }
683     llvm::Type *PointeeType = ConvertTypeForMem(ETy);
684     if (PointeeType->isVoidTy())
685       PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
686 
687     unsigned AS = PointeeType->isFunctionTy()
688                       ? getDataLayout().getProgramAddressSpace()
689                       : CGM.getTargetAddressSpace(ETy.getQualifiers());
690     // XXXAR: If Pty is a capability, we have to use AS200
691     if (PTy->isCHERICapability())
692       AS = CGM.getTargetCodeGenInfo().getCHERICapabilityAS();
693     ResultType = llvm::PointerType::get(PointeeType, AS);
694     break;
695   }
696 
697   case Type::VariableArray: {
698     const VariableArrayType *A = cast<VariableArrayType>(Ty);
699     assert(A->getIndexTypeCVRQualifiers() == 0 &&
700            "FIXME: We only handle trivial array types so far!");
701     // VLAs resolve to the innermost element type; this matches
702     // the return of alloca, and there isn't any obviously better choice.
703     ResultType = ConvertTypeForMem(A->getElementType());
704     break;
705   }
706   case Type::IncompleteArray: {
707     const IncompleteArrayType *A = cast<IncompleteArrayType>(Ty);
708     assert(A->getIndexTypeCVRQualifiers() == 0 &&
709            "FIXME: We only handle trivial array types so far!");
710     // int X[] -> [0 x int], unless the element type is not sized.  If it is
711     // unsized (e.g. an incomplete struct) just use [0 x i8].
712     ResultType = ConvertTypeForMem(A->getElementType());
713     if (!ResultType->isSized()) {
714       SkippedLayout = true;
715       ResultType = llvm::Type::getInt8Ty(getLLVMContext());
716     }
717     ResultType = llvm::ArrayType::get(ResultType, 0);
718     break;
719   }
720   case Type::ConstantArray: {
721     const ConstantArrayType *A = cast<ConstantArrayType>(Ty);
722     llvm::Type *EltTy = ConvertTypeForMem(A->getElementType());
723 
724     // Lower arrays of undefined struct type to arrays of i8 just to have a
725     // concrete type.
726     if (!EltTy->isSized()) {
727       SkippedLayout = true;
728       EltTy = llvm::Type::getInt8Ty(getLLVMContext());
729     }
730 
731     ResultType = llvm::ArrayType::get(EltTy, A->getSize().getZExtValue());
732     break;
733   }
734   case Type::ExtVector:
735   case Type::Vector: {
736     const VectorType *VT = cast<VectorType>(Ty);
737     ResultType = llvm::FixedVectorType::get(ConvertType(VT->getElementType()),
738                                             VT->getNumElements());
739     break;
740   }
741   case Type::ConstantMatrix: {
742     const ConstantMatrixType *MT = cast<ConstantMatrixType>(Ty);
743     ResultType =
744         llvm::FixedVectorType::get(ConvertType(MT->getElementType()),
745                                    MT->getNumRows() * MT->getNumColumns());
746     break;
747   }
748   case Type::FunctionNoProto:
749   case Type::FunctionProto:
750     ResultType = ConvertFunctionTypeInternal(T);
751     break;
752   case Type::ObjCObject:
753     ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
754     break;
755 
756   case Type::ObjCInterface: {
757     // Objective-C interfaces are always opaque (outside of the
758     // runtime, which can do whatever it likes); we never refine
759     // these.
760     llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
761     if (!T)
762       T = llvm::StructType::create(getLLVMContext());
763     ResultType = T;
764     break;
765   }
766 
767   case Type::ObjCObjectPointer: {
768     // Protocol qualifications do not influence the LLVM type, we just return a
769     // pointer to the underlying interface type. We don't need to worry about
770     // recursive conversion.
771     llvm::Type *T =
772       ConvertTypeForMem(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
773     ResultType = T->getPointerTo(CGM.getTargetCodeGenInfo().getDefaultAS());
774     break;
775   }
776 
777   case Type::Enum: {
778     const EnumDecl *ED = cast<EnumType>(Ty)->getDecl();
779     if (ED->isCompleteDefinition() || ED->isFixed())
780       return ConvertType(ED->getIntegerType());
781     // Return a placeholder 'i32' type.  This can be changed later when the
782     // type is defined (see UpdateCompletedType), but is likely to be the
783     // "right" answer.
784     ResultType = llvm::Type::getInt32Ty(getLLVMContext());
785     break;
786   }
787 
788   case Type::BlockPointer: {
789     const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
790     llvm::Type *PointeeType = CGM.getLangOpts().OpenCL
791                                   ? CGM.getGenericBlockLiteralType()
792                                   : ConvertTypeForMem(FTy);
793     // XXXAR: If Ty is capability, use AS200 otherwise the same as LangAS as the
794     // underlying type
795     unsigned AS = Ty->isCHERICapabilityType(CGM.getContext())
796                       ? CGM.getTargetCodeGenInfo().getCHERICapabilityAS()
797                       : CGM.getTargetAddressSpace(FTy.getQualifiers());
798     ResultType = llvm::PointerType::get(PointeeType, AS);
799     break;
800   }
801 
802   case Type::MemberPointer: {
803     auto *MPTy = cast<MemberPointerType>(Ty);
804     if (!getCXXABI().isMemberPointerConvertible(MPTy)) {
805       RecordsWithOpaqueMemberPointers.insert(MPTy->getClass());
806       ResultType = llvm::StructType::create(getLLVMContext());
807     } else {
808       ResultType = getCXXABI().ConvertMemberPointerType(MPTy);
809     }
810     break;
811   }
812 
813   case Type::Atomic: {
814     QualType valueType = cast<AtomicType>(Ty)->getValueType();
815     ResultType = ConvertTypeForMem(valueType);
816 
817     // Pad out to the inflated size if necessary.
818     uint64_t valueSize = Context.getTypeSize(valueType);
819     uint64_t atomicSize = Context.getTypeSize(Ty);
820     if (valueSize != atomicSize) {
821       assert(valueSize < atomicSize);
822       llvm::Type *elts[] = {
823         ResultType,
824         llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
825       };
826       ResultType = llvm::StructType::get(getLLVMContext(),
827                                          llvm::makeArrayRef(elts));
828     }
829     break;
830   }
831   case Type::Pipe: {
832     ResultType = CGM.getOpenCLRuntime().getPipeType(cast<PipeType>(Ty));
833     break;
834   }
835   case Type::ExtInt: {
836     const auto &EIT = cast<ExtIntType>(Ty);
837     ResultType = llvm::Type::getIntNTy(getLLVMContext(), EIT->getNumBits());
838     break;
839   }
840   }
841 
842   assert(ResultType && "Didn't convert a type?");
843 
844   TypeCache[Ty] = ResultType;
845   return ResultType;
846 }
847 
isPaddedAtomicType(QualType type)848 bool CodeGenModule::isPaddedAtomicType(QualType type) {
849   return isPaddedAtomicType(type->castAs<AtomicType>());
850 }
851 
isPaddedAtomicType(const AtomicType * type)852 bool CodeGenModule::isPaddedAtomicType(const AtomicType *type) {
853   return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
854 }
855 
856 /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
ConvertRecordDeclType(const RecordDecl * RD)857 llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) {
858   // TagDecl's are not necessarily unique, instead use the (clang)
859   // type connected to the decl.
860   const Type *Key = Context.getTagDeclType(RD).getTypePtr();
861 
862   llvm::StructType *&Entry = RecordDeclTypes[Key];
863 
864   // If we don't have a StructType at all yet, create the forward declaration.
865   if (!Entry) {
866     Entry = llvm::StructType::create(getLLVMContext());
867     addRecordTypeName(RD, Entry, "");
868   }
869   llvm::StructType *Ty = Entry;
870 
871   // If this is still a forward declaration, or the LLVM type is already
872   // complete, there's nothing more to do.
873   RD = RD->getDefinition();
874   if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
875     return Ty;
876 
877   // If converting this type would cause us to infinitely loop, don't do it!
878   if (!isSafeToConvert(RD, *this)) {
879     DeferredRecords.push_back(RD);
880     return Ty;
881   }
882 
883   // Okay, this is a definition of a type.  Compile the implementation now.
884   bool InsertResult = RecordsBeingLaidOut.insert(Key).second;
885   (void)InsertResult;
886   assert(InsertResult && "Recursively compiling a struct?");
887 
888   // Force conversion of non-virtual base classes recursively.
889   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
890     for (const auto &I : CRD->bases()) {
891       if (I.isVirtual()) continue;
892       ConvertRecordDeclType(I.getType()->castAs<RecordType>()->getDecl());
893     }
894   }
895 
896   // Layout fields.
897   std::unique_ptr<CGRecordLayout> Layout = ComputeRecordLayout(RD, Ty);
898   CGRecordLayouts[Key] = std::move(Layout);
899 
900   // We're done laying out this struct.
901   bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult;
902   assert(EraseResult && "struct not in RecordsBeingLaidOut set?");
903 
904   // If this struct blocked a FunctionType conversion, then recompute whatever
905   // was derived from that.
906   // FIXME: This is hugely overconservative.
907   if (SkippedLayout)
908     TypeCache.clear();
909 
910   // If we're done converting the outer-most record, then convert any deferred
911   // structs as well.
912   if (RecordsBeingLaidOut.empty())
913     while (!DeferredRecords.empty())
914       ConvertRecordDeclType(DeferredRecords.pop_back_val());
915 
916   return Ty;
917 }
918 
919 /// getCGRecordLayout - Return record layout info for the given record decl.
920 const CGRecordLayout &
getCGRecordLayout(const RecordDecl * RD)921 CodeGenTypes::getCGRecordLayout(const RecordDecl *RD) {
922   const Type *Key = Context.getTagDeclType(RD).getTypePtr();
923 
924   auto I = CGRecordLayouts.find(Key);
925   if (I != CGRecordLayouts.end())
926     return *I->second;
927   // Compute the type information.
928   ConvertRecordDeclType(RD);
929 
930   // Now try again.
931   I = CGRecordLayouts.find(Key);
932 
933   assert(I != CGRecordLayouts.end() &&
934          "Unable to find record layout information for type");
935   return *I->second;
936 }
937 
isPointerZeroInitializable(QualType T)938 bool CodeGenTypes::isPointerZeroInitializable(QualType T) {
939   assert((T->isAnyPointerType() || T->isBlockPointerType()) && "Invalid type");
940   return isZeroInitializable(T);
941 }
942 
isZeroInitializable(QualType T)943 bool CodeGenTypes::isZeroInitializable(QualType T) {
944   if (T->getAs<PointerType>())
945     return Context.getTargetNullPointerValue(T) == 0;
946 
947   if (const auto *AT = Context.getAsArrayType(T)) {
948     if (isa<IncompleteArrayType>(AT))
949       return true;
950     if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
951       if (Context.getConstantArrayElementCount(CAT) == 0)
952         return true;
953     T = Context.getBaseElementType(T);
954   }
955 
956   // Records are non-zero-initializable if they contain any
957   // non-zero-initializable subobjects.
958   if (const RecordType *RT = T->getAs<RecordType>()) {
959     const RecordDecl *RD = RT->getDecl();
960     return isZeroInitializable(RD);
961   }
962 
963   // We have to ask the ABI about member pointers.
964   if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
965     return getCXXABI().isZeroInitializable(MPT);
966 
967   // Everything else is okay.
968   return true;
969 }
970 
isZeroInitializable(const RecordDecl * RD)971 bool CodeGenTypes::isZeroInitializable(const RecordDecl *RD) {
972   return getCGRecordLayout(RD).isZeroInitializable();
973 }
974