clang  8.0.0svn
CodeGenTypes.cpp
Go to the documentation of this file.
1 //===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the code that handles AST -> LLVM type lowering.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenTypes.h"
15 #include "CGCXXABI.h"
16 #include "CGCall.h"
17 #include "CGOpenCLRuntime.h"
18 #include "CGRecordLayout.h"
19 #include "TargetInfo.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/RecordLayout.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Module.h"
29 using namespace clang;
30 using namespace CodeGen;
31 
33  : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()),
34  Target(cgm.getTarget()), TheCXXABI(cgm.getCXXABI()),
35  TheABIInfo(cgm.getTargetCodeGenInfo().getABIInfo()) {
36  SkippedLayout = false;
37 }
38 
40  llvm::DeleteContainerSeconds(CGRecordLayouts);
41 
42  for (llvm::FoldingSet<CGFunctionInfo>::iterator
43  I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
44  delete &*I++;
45 }
46 
48  return CGM.getCodeGenOpts();
49 }
50 
52  llvm::StructType *Ty,
53  StringRef suffix) {
54  SmallString<256> TypeName;
55  llvm::raw_svector_ostream OS(TypeName);
56  OS << RD->getKindName() << '.';
57 
58  // Name the codegen type after the typedef name
59  // if there is no tag type name available
60  if (RD->getIdentifier()) {
61  // FIXME: We should not have to check for a null decl context here.
62  // Right now we do it because the implicit Obj-C decls don't have one.
63  if (RD->getDeclContext())
64  RD->printQualifiedName(OS);
65  else
66  RD->printName(OS);
67  } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) {
68  // FIXME: We should not have to check for a null decl context here.
69  // Right now we do it because the implicit Obj-C decls don't have one.
70  if (TDD->getDeclContext())
71  TDD->printQualifiedName(OS);
72  else
73  TDD->printName(OS);
74  } else
75  OS << "anon";
76 
77  if (!suffix.empty())
78  OS << suffix;
79 
80  Ty->setName(OS.str());
81 }
82 
83 /// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from
84 /// ConvertType in that it is used to convert to the memory representation for
85 /// a type. For example, the scalar representation for _Bool is i1, but the
86 /// memory representation is usually i8 or i32, depending on the target.
88  llvm::Type *R = ConvertType(T);
89 
90  // If this is a non-bool type, don't map it.
91  if (!R->isIntegerTy(1))
92  return R;
93 
94  // Otherwise, return an integer of the target-specified size.
95  return llvm::IntegerType::get(getLLVMContext(),
96  (unsigned)Context.getTypeSize(T));
97 }
98 
99 
100 /// isRecordLayoutComplete - Return true if the specified type is already
101 /// completely laid out.
103  llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
104  RecordDeclTypes.find(Ty);
105  return I != RecordDeclTypes.end() && !I->second->isOpaque();
106 }
107 
108 static bool
110  llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked);
111 
112 
113 /// isSafeToConvert - Return true if it is safe to convert the specified record
114 /// decl to IR and lay it out, false if doing so would cause us to get into a
115 /// recursive compilation mess.
116 static bool
118  llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
119  // If we have already checked this type (maybe the same type is used by-value
120  // multiple times in multiple structure fields, don't check again.
121  if (!AlreadyChecked.insert(RD).second)
122  return true;
123 
124  const Type *Key = CGT.getContext().getTagDeclType(RD).getTypePtr();
125 
126  // If this type is already laid out, converting it is a noop.
127  if (CGT.isRecordLayoutComplete(Key)) return true;
128 
129  // If this type is currently being laid out, we can't recursively compile it.
130  if (CGT.isRecordBeingLaidOut(Key))
131  return false;
132 
133  // If this type would require laying out bases that are currently being laid
134  // out, don't do it. This includes virtual base classes which get laid out
135  // when a class is translated, even though they aren't embedded by-value into
136  // the class.
137  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
138  for (const auto &I : CRD->bases())
139  if (!isSafeToConvert(I.getType()->getAs<RecordType>()->getDecl(),
140  CGT, AlreadyChecked))
141  return false;
142  }
143 
144  // If this type would require laying out members that are currently being laid
145  // out, don't do it.
146  for (const auto *I : RD->fields())
147  if (!isSafeToConvert(I->getType(), CGT, AlreadyChecked))
148  return false;
149 
150  // If there are no problems, lets do it.
151  return true;
152 }
153 
154 /// isSafeToConvert - Return true if it is safe to convert this field type,
155 /// which requires the structure elements contained by-value to all be
156 /// recursively safe to convert.
157 static bool
159  llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
160  // Strip off atomic type sugar.
161  if (const auto *AT = T->getAs<AtomicType>())
162  T = AT->getValueType();
163 
164  // If this is a record, check it.
165  if (const auto *RT = T->getAs<RecordType>())
166  return isSafeToConvert(RT->getDecl(), CGT, AlreadyChecked);
167 
168  // If this is an array, check the elements, which are embedded inline.
169  if (const auto *AT = CGT.getContext().getAsArrayType(T))
170  return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked);
171 
172  // Otherwise, there is no concern about transforming this. We only care about
173  // things that are contained by-value in a structure that can have another
174  // structure as a member.
175  return true;
176 }
177 
178 
179 /// isSafeToConvert - Return true if it is safe to convert the specified record
180 /// decl to IR and lay it out, false if doing so would cause us to get into a
181 /// recursive compilation mess.
182 static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) {
183  // If no structs are being laid out, we can certainly do this one.
184  if (CGT.noRecordsBeingLaidOut()) return true;
185 
186  llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked;
187  return isSafeToConvert(RD, CGT, AlreadyChecked);
188 }
189 
190 /// isFuncParamTypeConvertible - Return true if the specified type in a
191 /// function parameter or result position can be converted to an IR type at this
192 /// point. This boils down to being whether it is complete, as well as whether
193 /// we've temporarily deferred expanding the type because we're in a recursive
194 /// context.
196  // Some ABIs cannot have their member pointers represented in IR unless
197  // certain circumstances have been reached.
198  if (const auto *MPT = Ty->getAs<MemberPointerType>())
200 
201  // If this isn't a tagged type, we can convert it!
202  const TagType *TT = Ty->getAs<TagType>();
203  if (!TT) return true;
204 
205  // Incomplete types cannot be converted.
206  if (TT->isIncompleteType())
207  return false;
208 
209  // If this is an enum, then it is always safe to convert.
210  const RecordType *RT = dyn_cast<RecordType>(TT);
211  if (!RT) return true;
212 
213  // Otherwise, we have to be careful. If it is a struct that we're in the
214  // process of expanding, then we can't convert the function type. That's ok
215  // though because we must be in a pointer context under the struct, so we can
216  // just convert it to a dummy type.
217  //
218  // We decide this by checking whether ConvertRecordDeclType returns us an
219  // opaque type for a struct that we know is defined.
220  return isSafeToConvert(RT->getDecl(), *this);
221 }
222 
223 
224 /// Code to verify a given function type is complete, i.e. the return type
225 /// and all of the parameter types are complete. Also check to see if we are in
226 /// a RS_StructPointer context, and if so whether any struct types have been
227 /// pended. If so, we don't want to ask the ABI lowering code to handle a type
228 /// that cannot be converted to an IR type.
231  return false;
232 
233  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
234  for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
235  if (!isFuncParamTypeConvertible(FPT->getParamType(i)))
236  return false;
237 
238  return true;
239 }
240 
241 /// UpdateCompletedType - When we find the full definition for a TagDecl,
242 /// replace the 'opaque' type we previously made for it if applicable.
244  // If this is an enum being completed, then we flush all non-struct types from
245  // the cache. This allows function types and other things that may be derived
246  // from the enum to be recomputed.
247  if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) {
248  // Only flush the cache if we've actually already converted this type.
249  if (TypeCache.count(ED->getTypeForDecl())) {
250  // Okay, we formed some types based on this. We speculated that the enum
251  // would be lowered to i32, so we only need to flush the cache if this
252  // didn't happen.
253  if (!ConvertType(ED->getIntegerType())->isIntegerTy(32))
254  TypeCache.clear();
255  }
256  // If necessary, provide the full definition of a type only used with a
257  // declaration so far.
258  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
259  DI->completeType(ED);
260  return;
261  }
262 
263  // If we completed a RecordDecl that we previously used and converted to an
264  // anonymous type, then go ahead and complete it now.
265  const RecordDecl *RD = cast<RecordDecl>(TD);
266  if (RD->isDependentType()) return;
267 
268  // Only complete it if we converted it already. If we haven't converted it
269  // yet, we'll just do it lazily.
270  if (RecordDeclTypes.count(Context.getTagDeclType(RD).getTypePtr()))
272 
273  // If necessary, provide the full definition of a type only used with a
274  // declaration so far.
275  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
276  DI->completeType(RD);
277 }
278 
280  QualType T = Context.getRecordType(RD);
281  T = Context.getCanonicalType(T);
282 
283  const Type *Ty = T.getTypePtr();
284  if (RecordsWithOpaqueMemberPointers.count(Ty)) {
285  TypeCache.clear();
286  RecordsWithOpaqueMemberPointers.clear();
287  }
288 }
289 
290 static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
291  const llvm::fltSemantics &format,
292  bool UseNativeHalf = false) {
293  if (&format == &llvm::APFloat::IEEEhalf()) {
294  if (UseNativeHalf)
295  return llvm::Type::getHalfTy(VMContext);
296  else
297  return llvm::Type::getInt16Ty(VMContext);
298  }
299  if (&format == &llvm::APFloat::IEEEsingle())
300  return llvm::Type::getFloatTy(VMContext);
301  if (&format == &llvm::APFloat::IEEEdouble())
302  return llvm::Type::getDoubleTy(VMContext);
303  if (&format == &llvm::APFloat::IEEEquad())
304  return llvm::Type::getFP128Ty(VMContext);
305  if (&format == &llvm::APFloat::PPCDoubleDouble())
306  return llvm::Type::getPPC_FP128Ty(VMContext);
307  if (&format == &llvm::APFloat::x87DoubleExtended())
308  return llvm::Type::getX86_FP80Ty(VMContext);
309  llvm_unreachable("Unknown float format!");
310 }
311 
313  const FunctionDecl *FD) {
314  assert(QFT.isCanonical());
315  const Type *Ty = QFT.getTypePtr();
316  const FunctionType *FT = cast<FunctionType>(QFT.getTypePtr());
317  // First, check whether we can build the full function type. If the
318  // function type depends on an incomplete type (e.g. a struct or enum), we
319  // cannot lower the function type.
320  if (!isFuncTypeConvertible(FT)) {
321  // This function's type depends on an incomplete tag type.
322 
323  // Force conversion of all the relevant record types, to make sure
324  // we re-convert the FunctionType when appropriate.
325  if (const RecordType *RT = FT->getReturnType()->getAs<RecordType>())
326  ConvertRecordDeclType(RT->getDecl());
327  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
328  for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
329  if (const RecordType *RT = FPT->getParamType(i)->getAs<RecordType>())
330  ConvertRecordDeclType(RT->getDecl());
331 
332  SkippedLayout = true;
333 
334  // Return a placeholder type.
335  return llvm::StructType::get(getLLVMContext());
336  }
337 
338  // While we're converting the parameter types for a function, we don't want
339  // to recursively convert any pointed-to structs. Converting directly-used
340  // structs is ok though.
341  if (!RecordsBeingLaidOut.insert(Ty).second) {
342  SkippedLayout = true;
343  return llvm::StructType::get(getLLVMContext());
344  }
345 
346  // The function type can be built; call the appropriate routines to
347  // build it.
348  const CGFunctionInfo *FI;
349  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
352  } else {
353  const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
356  }
357 
358  llvm::Type *ResultType = nullptr;
359  // If there is something higher level prodding our CGFunctionInfo, then
360  // don't recurse into it again.
361  if (FunctionsBeingProcessed.count(FI)) {
362 
363  ResultType = llvm::StructType::get(getLLVMContext());
364  SkippedLayout = true;
365  } else {
366 
367  // Otherwise, we're good to go, go ahead and convert it.
368  ResultType = GetFunctionType(*FI);
369  }
370 
371  RecordsBeingLaidOut.erase(Ty);
372 
373  if (SkippedLayout)
374  TypeCache.clear();
375 
376  if (RecordsBeingLaidOut.empty())
377  while (!DeferredRecords.empty())
378  ConvertRecordDeclType(DeferredRecords.pop_back_val());
379  return ResultType;
380 }
381 
382 /// ConvertType - Convert the specified type to its LLVM form.
384  T = Context.getCanonicalType(T);
385 
386  const Type *Ty = T.getTypePtr();
387 
388  // RecordTypes are cached and processed specially.
389  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
390  return ConvertRecordDeclType(RT->getDecl());
391 
392  // See if type is already cached.
393  llvm::DenseMap<const Type *, llvm::Type *>::iterator TCI = TypeCache.find(Ty);
394  // If type is found in map then use it. Otherwise, convert type T.
395  if (TCI != TypeCache.end())
396  return TCI->second;
397 
398  // If we don't have it in the cache, convert it now.
399  llvm::Type *ResultType = nullptr;
400  switch (Ty->getTypeClass()) {
401  case Type::Record: // Handled above.
402 #define TYPE(Class, Base)
403 #define ABSTRACT_TYPE(Class, Base)
404 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
405 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
406 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
407 #include "clang/AST/TypeNodes.def"
408  llvm_unreachable("Non-canonical or dependent types aren't possible.");
409 
410  case Type::Builtin: {
411  switch (cast<BuiltinType>(Ty)->getKind()) {
412  case BuiltinType::Void:
413  case BuiltinType::ObjCId:
414  case BuiltinType::ObjCClass:
415  case BuiltinType::ObjCSel:
416  // LLVM void type can only be used as the result of a function call. Just
417  // map to the same as char.
418  ResultType = llvm::Type::getInt8Ty(getLLVMContext());
419  break;
420 
421  case BuiltinType::Bool:
422  // Note that we always return bool as i1 for use as a scalar type.
423  ResultType = llvm::Type::getInt1Ty(getLLVMContext());
424  break;
425 
426  case BuiltinType::Char_S:
427  case BuiltinType::Char_U:
428  case BuiltinType::SChar:
429  case BuiltinType::UChar:
430  case BuiltinType::Short:
431  case BuiltinType::UShort:
432  case BuiltinType::Int:
433  case BuiltinType::UInt:
434  case BuiltinType::Long:
435  case BuiltinType::ULong:
436  case BuiltinType::LongLong:
437  case BuiltinType::ULongLong:
438  case BuiltinType::WChar_S:
439  case BuiltinType::WChar_U:
440  case BuiltinType::Char8:
441  case BuiltinType::Char16:
442  case BuiltinType::Char32:
443  case BuiltinType::ShortAccum:
444  case BuiltinType::Accum:
445  case BuiltinType::LongAccum:
446  case BuiltinType::UShortAccum:
447  case BuiltinType::UAccum:
448  case BuiltinType::ULongAccum:
449  case BuiltinType::ShortFract:
450  case BuiltinType::Fract:
451  case BuiltinType::LongFract:
452  case BuiltinType::UShortFract:
453  case BuiltinType::UFract:
454  case BuiltinType::ULongFract:
455  case BuiltinType::SatShortAccum:
456  case BuiltinType::SatAccum:
457  case BuiltinType::SatLongAccum:
458  case BuiltinType::SatUShortAccum:
459  case BuiltinType::SatUAccum:
460  case BuiltinType::SatULongAccum:
461  case BuiltinType::SatShortFract:
462  case BuiltinType::SatFract:
463  case BuiltinType::SatLongFract:
464  case BuiltinType::SatUShortFract:
465  case BuiltinType::SatUFract:
466  case BuiltinType::SatULongFract:
467  ResultType = llvm::IntegerType::get(getLLVMContext(),
468  static_cast<unsigned>(Context.getTypeSize(T)));
469  break;
470 
471  case BuiltinType::Float16:
472  ResultType =
474  /* UseNativeHalf = */ true);
475  break;
476 
477  case BuiltinType::Half:
478  // Half FP can either be storage-only (lowered to i16) or native.
479  ResultType = getTypeForFormat(
481  Context.getLangOpts().NativeHalfType ||
483  break;
484  case BuiltinType::Float:
485  case BuiltinType::Double:
486  case BuiltinType::LongDouble:
487  case BuiltinType::Float128:
488  ResultType = getTypeForFormat(getLLVMContext(),
489  Context.getFloatTypeSemantics(T),
490  /* UseNativeHalf = */ false);
491  break;
492 
493  case BuiltinType::NullPtr:
494  // Model std::nullptr_t as i8*
495  ResultType = llvm::Type::getInt8PtrTy(getLLVMContext());
496  break;
497 
498  case BuiltinType::UInt128:
499  case BuiltinType::Int128:
500  ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
501  break;
502 
503 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
504  case BuiltinType::Id:
505 #include "clang/Basic/OpenCLImageTypes.def"
506 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
507  case BuiltinType::Id:
508 #include "clang/Basic/OpenCLExtensionTypes.def"
509  case BuiltinType::OCLSampler:
510  case BuiltinType::OCLEvent:
511  case BuiltinType::OCLClkEvent:
512  case BuiltinType::OCLQueue:
513  case BuiltinType::OCLReserveID:
514  ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
515  break;
516 
517  case BuiltinType::Dependent:
518 #define BUILTIN_TYPE(Id, SingletonId)
519 #define PLACEHOLDER_TYPE(Id, SingletonId) \
520  case BuiltinType::Id:
521 #include "clang/AST/BuiltinTypes.def"
522  llvm_unreachable("Unexpected placeholder builtin type!");
523  }
524  break;
525  }
526  case Type::Auto:
527  case Type::DeducedTemplateSpecialization:
528  llvm_unreachable("Unexpected undeduced type!");
529  case Type::Complex: {
530  llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
531  ResultType = llvm::StructType::get(EltTy, EltTy);
532  break;
533  }
534  case Type::LValueReference:
535  case Type::RValueReference: {
536  const ReferenceType *RTy = cast<ReferenceType>(Ty);
537  QualType ETy = RTy->getPointeeType();
538  llvm::Type *PointeeType = ConvertTypeForMem(ETy);
539  unsigned AS = Context.getTargetAddressSpace(ETy);
540  ResultType = llvm::PointerType::get(PointeeType, AS);
541  break;
542  }
543  case Type::Pointer: {
544  const PointerType *PTy = cast<PointerType>(Ty);
545  QualType ETy = PTy->getPointeeType();
546  llvm::Type *PointeeType = ConvertTypeForMem(ETy);
547  if (PointeeType->isVoidTy())
548  PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
549  unsigned AS = Context.getTargetAddressSpace(ETy);
550  ResultType = llvm::PointerType::get(PointeeType, AS);
551  break;
552  }
553 
554  case Type::VariableArray: {
555  const VariableArrayType *A = cast<VariableArrayType>(Ty);
556  assert(A->getIndexTypeCVRQualifiers() == 0 &&
557  "FIXME: We only handle trivial array types so far!");
558  // VLAs resolve to the innermost element type; this matches
559  // the return of alloca, and there isn't any obviously better choice.
560  ResultType = ConvertTypeForMem(A->getElementType());
561  break;
562  }
563  case Type::IncompleteArray: {
564  const IncompleteArrayType *A = cast<IncompleteArrayType>(Ty);
565  assert(A->getIndexTypeCVRQualifiers() == 0 &&
566  "FIXME: We only handle trivial array types so far!");
567  // int X[] -> [0 x int], unless the element type is not sized. If it is
568  // unsized (e.g. an incomplete struct) just use [0 x i8].
569  ResultType = ConvertTypeForMem(A->getElementType());
570  if (!ResultType->isSized()) {
571  SkippedLayout = true;
572  ResultType = llvm::Type::getInt8Ty(getLLVMContext());
573  }
574  ResultType = llvm::ArrayType::get(ResultType, 0);
575  break;
576  }
577  case Type::ConstantArray: {
578  const ConstantArrayType *A = cast<ConstantArrayType>(Ty);
580 
581  // Lower arrays of undefined struct type to arrays of i8 just to have a
582  // concrete type.
583  if (!EltTy->isSized()) {
584  SkippedLayout = true;
585  EltTy = llvm::Type::getInt8Ty(getLLVMContext());
586  }
587 
588  ResultType = llvm::ArrayType::get(EltTy, A->getSize().getZExtValue());
589  break;
590  }
591  case Type::ExtVector:
592  case Type::Vector: {
593  const VectorType *VT = cast<VectorType>(Ty);
594  ResultType = llvm::VectorType::get(ConvertType(VT->getElementType()),
595  VT->getNumElements());
596  break;
597  }
598  case Type::FunctionNoProto:
599  case Type::FunctionProto:
600  ResultType = ConvertFunctionType(T);
601  break;
602  case Type::ObjCObject:
603  ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
604  break;
605 
606  case Type::ObjCInterface: {
607  // Objective-C interfaces are always opaque (outside of the
608  // runtime, which can do whatever it likes); we never refine
609  // these.
610  llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
611  if (!T)
613  ResultType = T;
614  break;
615  }
616 
617  case Type::ObjCObjectPointer: {
618  // Protocol qualifications do not influence the LLVM type, we just return a
619  // pointer to the underlying interface type. We don't need to worry about
620  // recursive conversion.
621  llvm::Type *T =
622  ConvertTypeForMem(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
623  ResultType = T->getPointerTo();
624  break;
625  }
626 
627  case Type::Enum: {
628  const EnumDecl *ED = cast<EnumType>(Ty)->getDecl();
629  if (ED->isCompleteDefinition() || ED->isFixed())
630  return ConvertType(ED->getIntegerType());
631  // Return a placeholder 'i32' type. This can be changed later when the
632  // type is defined (see UpdateCompletedType), but is likely to be the
633  // "right" answer.
634  ResultType = llvm::Type::getInt32Ty(getLLVMContext());
635  break;
636  }
637 
638  case Type::BlockPointer: {
639  const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
640  llvm::Type *PointeeType = ConvertTypeForMem(FTy);
641  unsigned AS = Context.getTargetAddressSpace(FTy);
642  ResultType = llvm::PointerType::get(PointeeType, AS);
643  break;
644  }
645 
646  case Type::MemberPointer: {
647  auto *MPTy = cast<MemberPointerType>(Ty);
648  if (!getCXXABI().isMemberPointerConvertible(MPTy)) {
649  RecordsWithOpaqueMemberPointers.insert(MPTy->getClass());
651  } else {
652  ResultType = getCXXABI().ConvertMemberPointerType(MPTy);
653  }
654  break;
655  }
656 
657  case Type::Atomic: {
658  QualType valueType = cast<AtomicType>(Ty)->getValueType();
659  ResultType = ConvertTypeForMem(valueType);
660 
661  // Pad out to the inflated size if necessary.
662  uint64_t valueSize = Context.getTypeSize(valueType);
663  uint64_t atomicSize = Context.getTypeSize(Ty);
664  if (valueSize != atomicSize) {
665  assert(valueSize < atomicSize);
666  llvm::Type *elts[] = {
667  ResultType,
668  llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
669  };
670  ResultType = llvm::StructType::get(getLLVMContext(),
671  llvm::makeArrayRef(elts));
672  }
673  break;
674  }
675  case Type::Pipe: {
676  ResultType = CGM.getOpenCLRuntime().getPipeType(cast<PipeType>(Ty));
677  break;
678  }
679  }
680 
681  assert(ResultType && "Didn't convert a type?");
682 
683  TypeCache[Ty] = ResultType;
684  return ResultType;
685 }
686 
688  return isPaddedAtomicType(type->castAs<AtomicType>());
689 }
690 
692  return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
693 }
694 
695 /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
696 llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) {
697  // TagDecl's are not necessarily unique, instead use the (clang)
698  // type connected to the decl.
699  const Type *Key = Context.getTagDeclType(RD).getTypePtr();
700 
701  llvm::StructType *&Entry = RecordDeclTypes[Key];
702 
703  // If we don't have a StructType at all yet, create the forward declaration.
704  if (!Entry) {
706  addRecordTypeName(RD, Entry, "");
707  }
708  llvm::StructType *Ty = Entry;
709 
710  // If this is still a forward declaration, or the LLVM type is already
711  // complete, there's nothing more to do.
712  RD = RD->getDefinition();
713  if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
714  return Ty;
715 
716  // If converting this type would cause us to infinitely loop, don't do it!
717  if (!isSafeToConvert(RD, *this)) {
718  DeferredRecords.push_back(RD);
719  return Ty;
720  }
721 
722  // Okay, this is a definition of a type. Compile the implementation now.
723  bool InsertResult = RecordsBeingLaidOut.insert(Key).second;
724  (void)InsertResult;
725  assert(InsertResult && "Recursively compiling a struct?");
726 
727  // Force conversion of non-virtual base classes recursively.
728  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
729  for (const auto &I : CRD->bases()) {
730  if (I.isVirtual()) continue;
731 
732  ConvertRecordDeclType(I.getType()->getAs<RecordType>()->getDecl());
733  }
734  }
735 
736  // Layout fields.
737  CGRecordLayout *Layout = ComputeRecordLayout(RD, Ty);
738  CGRecordLayouts[Key] = Layout;
739 
740  // We're done laying out this struct.
741  bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult;
742  assert(EraseResult && "struct not in RecordsBeingLaidOut set?");
743 
744  // If this struct blocked a FunctionType conversion, then recompute whatever
745  // was derived from that.
746  // FIXME: This is hugely overconservative.
747  if (SkippedLayout)
748  TypeCache.clear();
749 
750  // If we're done converting the outer-most record, then convert any deferred
751  // structs as well.
752  if (RecordsBeingLaidOut.empty())
753  while (!DeferredRecords.empty())
754  ConvertRecordDeclType(DeferredRecords.pop_back_val());
755 
756  return Ty;
757 }
758 
759 /// getCGRecordLayout - Return record layout info for the given record decl.
760 const CGRecordLayout &
762  const Type *Key = Context.getTagDeclType(RD).getTypePtr();
763 
764  const CGRecordLayout *Layout = CGRecordLayouts.lookup(Key);
765  if (!Layout) {
766  // Compute the type information.
768 
769  // Now try again.
770  Layout = CGRecordLayouts.lookup(Key);
771  }
772 
773  assert(Layout && "Unable to find record layout information for type");
774  return *Layout;
775 }
776 
778  assert((T->isAnyPointerType() || T->isBlockPointerType()) && "Invalid type");
779  return isZeroInitializable(T);
780 }
781 
783  if (T->getAs<PointerType>())
784  return Context.getTargetNullPointerValue(T) == 0;
785 
786  if (const auto *AT = Context.getAsArrayType(T)) {
787  if (isa<IncompleteArrayType>(AT))
788  return true;
789  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
790  if (Context.getConstantArrayElementCount(CAT) == 0)
791  return true;
792  T = Context.getBaseElementType(T);
793  }
794 
795  // Records are non-zero-initializable if they contain any
796  // non-zero-initializable subobjects.
797  if (const RecordType *RT = T->getAs<RecordType>()) {
798  const RecordDecl *RD = RT->getDecl();
799  return isZeroInitializable(RD);
800  }
801 
802  // We have to ask the ABI about member pointers.
803  if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
804  return getCXXABI().isZeroInitializable(MPT);
805 
806  // Everything else is okay.
807  return true;
808 }
809 
812 }
bool noRecordsBeingLaidOut() const
Definition: CodeGenTypes.h:370
CGCXXABI & getCXXABI() const
Definition: CodeGenTypes.h:177
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
Defines the clang::ASTContext interface.
Represents a function declaration or definition.
Definition: Decl.h:1732
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2543
QualType getPointeeType() const
Definition: Type.h:2556
A (possibly-)qualified type.
Definition: Type.h:642
bool isBlockPointerType() const
Definition: Type.h:6290
const CodeGenOptions & getCodeGenOpts() const
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the &#39;opaque&#39; type we pr...
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
static llvm::Type * getTypeForFormat(llvm::LLVMContext &VMContext, const llvm::fltSemantics &format, bool UseNativeHalf=false)
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3361
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty, const FunctionDecl *FD)
Arrange the argument and result information for a value of the given freestanding function type...
Definition: CGCall.cpp:187
void addRecordTypeName(const RecordDecl *RD, llvm::StructType *Ty, StringRef suffix)
addRecordTypeName - Compute a name from the given record decl with an optional suffix and name the gi...
bool isRecordBeingLaidOut(const Type *Ty) const
Definition: CodeGenTypes.h:373
The base class of the type hierarchy.
Definition: Type.h:1415
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:689
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:5969
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i...
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
QualType getElementType() const
Definition: Type.h:2853
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3165
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3525
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6716
CGDebugInfo * getModuleDebugInfo()
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:54
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
Represents a struct/union/class.
Definition: Decl.h:3589
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3770
field_range fields() const
Definition: Decl.h:3780
bool isPaddedAtomicType(QualType type)
static bool isSafeToConvert(QualType T, CodeGenTypes &CGT, llvm::SmallPtrSet< const RecordDecl *, 16 > &AlreadyChecked)
isSafeToConvert - Return true if it is safe to convert this field type, which requires the structure ...
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6058
bool isZeroInitializable() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer.
virtual llvm::Type * ConvertMemberPointerType(const MemberPointerType *MPT)
Find the LLVM type used to represent the given member pointer type.
Definition: CGCXXABI.cpp:43
virtual llvm::Type * getPipeType(const PipeType *T, StringRef Name, llvm::Type *&PipeTy)
virtual llvm::Type * convertOpenCLSpecificType(const Type *T)
virtual bool isZeroInitializable(const MemberPointerType *MPT)
Return true if the given member pointer can be zero-initialized (in the C++ sense) with an LLVM zeroi...
Definition: CGCXXABI.cpp:123
Represents a K&R-style &#39;int foo()&#39; function, which has no information available about its arguments...
Definition: Type.h:3649
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3686
bool isPointerZeroInitializable(QualType T)
Check if the pointer type can be zero-initialized (in the C++ sense) with an LLVM zeroinitializer...
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3216
CodeGenTypes(CodeGenModule &cgm)
StringRef getKindName() const
Definition: Decl.h:3235
QualType getPointeeType() const
Definition: Type.h:2700
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6779
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
DeclContext * getDeclContext()
Definition: DeclBase.h:427
const CodeGenOptions & getCodeGenOpts() const
QualType getRecordType(const RecordDecl *Decl) const
Represents a GCC generic vector type.
Definition: Type.h:3174
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition: Decl.cpp:1527
The l-value was considered opaque, so the alignment was determined from a type.
RecordDecl * getDecl() const
Definition: Type.h:4366
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:719
virtual void printName(raw_ostream &os) const
Definition: Decl.cpp:1516
QualType getReturnType() const
Definition: Type.h:3617
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3060
QualType getElementType() const
Definition: Type.h:3209
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Represents a canonical, potentially-qualified type.
Definition: CanonicalType.h:66
bool isRecordLayoutComplete(const Type *Ty) const
isRecordLayoutComplete - Return true if the specified type is already completely laid out...
bool isAnyPointerType() const
Definition: Type.h:6286
llvm::LLVMContext & getLLVMContext()
Definition: CodeGenTypes.h:178
TypeClass getTypeClass() const
Definition: Type.h:1817
bool isCanonical() const
Definition: Type.h:6102
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat &#39;semantics&#39; for the specified scalar floating point type.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2912
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
Dataflow Directional Tag Classes.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const
Return whether or not a member pointers type is convertible to an IR type.
Definition: CGCXXABI.h:186
Represents an enum.
Definition: Decl.h:3322
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2762
llvm::StructType * ConvertRecordDeclType(const RecordDecl *TD)
ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4356
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:2863
llvm::Type * ConvertFunctionType(QualType FT, const FunctionDecl *FD=nullptr)
Converts the GlobalDecl into an llvm::Type.
const llvm::APInt & getSize() const
Definition: Type.h:2896
This class organizes the cross-module state that is used while lowering AST types to LLVM types...
Definition: CodeGenTypes.h:120
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2679
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2069
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2023
ASTContext & getContext() const
Definition: CodeGenTypes.h:174
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2252
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3270
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
Represents a C array with an unspecified size.
Definition: Type.h:2932
bool isFuncParamTypeConvertible(QualType Ty)
isFuncParamTypeConvertible - Return true if the specified type in a function parameter or result posi...
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class...
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3476
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:954
unsigned getNumElements() const
Definition: Type.h:3210
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
CGRecordLayout * ComputeRecordLayout(const RecordDecl *D, llvm::StructType *Ty)
Compute a new LLVM record layout object for the given record.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2977
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2498
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:706
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2878
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1544