clang  3.8.0
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 
43  I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
44  delete &*I++;
45 }
46 
48  llvm::StructType *Ty,
49  StringRef suffix) {
50  SmallString<256> TypeName;
51  llvm::raw_svector_ostream OS(TypeName);
52  OS << RD->getKindName() << '.';
53 
54  // Name the codegen type after the typedef name
55  // if there is no tag type name available
56  if (RD->getIdentifier()) {
57  // FIXME: We should not have to check for a null decl context here.
58  // Right now we do it because the implicit Obj-C decls don't have one.
59  if (RD->getDeclContext())
60  RD->printQualifiedName(OS);
61  else
62  RD->printName(OS);
63  } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) {
64  // FIXME: We should not have to check for a null decl context here.
65  // Right now we do it because the implicit Obj-C decls don't have one.
66  if (TDD->getDeclContext())
67  TDD->printQualifiedName(OS);
68  else
69  TDD->printName(OS);
70  } else
71  OS << "anon";
72 
73  if (!suffix.empty())
74  OS << suffix;
75 
76  Ty->setName(OS.str());
77 }
78 
79 /// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from
80 /// ConvertType in that it is used to convert to the memory representation for
81 /// a type. For example, the scalar representation for _Bool is i1, but the
82 /// memory representation is usually i8 or i32, depending on the target.
84  llvm::Type *R = ConvertType(T);
85 
86  // If this is a non-bool type, don't map it.
87  if (!R->isIntegerTy(1))
88  return R;
89 
90  // Otherwise, return an integer of the target-specified size.
91  return llvm::IntegerType::get(getLLVMContext(),
92  (unsigned)Context.getTypeSize(T));
93 }
94 
95 
96 /// isRecordLayoutComplete - Return true if the specified type is already
97 /// completely laid out.
99  llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
100  RecordDeclTypes.find(Ty);
101  return I != RecordDeclTypes.end() && !I->second->isOpaque();
102 }
103 
104 static bool
106  llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked);
107 
108 
109 /// isSafeToConvert - Return true if it is safe to convert the specified record
110 /// decl to IR and lay it out, false if doing so would cause us to get into a
111 /// recursive compilation mess.
112 static bool
114  llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
115  // If we have already checked this type (maybe the same type is used by-value
116  // multiple times in multiple structure fields, don't check again.
117  if (!AlreadyChecked.insert(RD).second)
118  return true;
119 
120  const Type *Key = CGT.getContext().getTagDeclType(RD).getTypePtr();
121 
122  // If this type is already laid out, converting it is a noop.
123  if (CGT.isRecordLayoutComplete(Key)) return true;
124 
125  // If this type is currently being laid out, we can't recursively compile it.
126  if (CGT.isRecordBeingLaidOut(Key))
127  return false;
128 
129  // If this type would require laying out bases that are currently being laid
130  // out, don't do it. This includes virtual base classes which get laid out
131  // when a class is translated, even though they aren't embedded by-value into
132  // the class.
133  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
134  for (const auto &I : CRD->bases())
135  if (!isSafeToConvert(I.getType()->getAs<RecordType>()->getDecl(),
136  CGT, AlreadyChecked))
137  return false;
138  }
139 
140  // If this type would require laying out members that are currently being laid
141  // out, don't do it.
142  for (const auto *I : RD->fields())
143  if (!isSafeToConvert(I->getType(), CGT, AlreadyChecked))
144  return false;
145 
146  // If there are no problems, lets do it.
147  return true;
148 }
149 
150 /// isSafeToConvert - Return true if it is safe to convert this field type,
151 /// which requires the structure elements contained by-value to all be
152 /// recursively safe to convert.
153 static bool
155  llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
156  // Strip off atomic type sugar.
157  if (const auto *AT = T->getAs<AtomicType>())
158  T = AT->getValueType();
159 
160  // If this is a record, check it.
161  if (const auto *RT = T->getAs<RecordType>())
162  return isSafeToConvert(RT->getDecl(), CGT, AlreadyChecked);
163 
164  // If this is an array, check the elements, which are embedded inline.
165  if (const auto *AT = CGT.getContext().getAsArrayType(T))
166  return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked);
167 
168  // Otherwise, there is no concern about transforming this. We only care about
169  // things that are contained by-value in a structure that can have another
170  // structure as a member.
171  return true;
172 }
173 
174 
175 /// isSafeToConvert - Return true if it is safe to convert the specified record
176 /// decl to IR and lay it out, false if doing so would cause us to get into a
177 /// recursive compilation mess.
178 static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) {
179  // If no structs are being laid out, we can certainly do this one.
180  if (CGT.noRecordsBeingLaidOut()) return true;
181 
182  llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked;
183  return isSafeToConvert(RD, CGT, AlreadyChecked);
184 }
185 
186 /// isFuncParamTypeConvertible - Return true if the specified type in a
187 /// function parameter or result position can be converted to an IR type at this
188 /// point. This boils down to being whether it is complete, as well as whether
189 /// we've temporarily deferred expanding the type because we're in a recursive
190 /// context.
192  // Some ABIs cannot have their member pointers represented in IR unless
193  // certain circumstances have been reached.
194  if (const auto *MPT = Ty->getAs<MemberPointerType>())
196 
197  // If this isn't a tagged type, we can convert it!
198  const TagType *TT = Ty->getAs<TagType>();
199  if (!TT) return true;
200 
201  // Incomplete types cannot be converted.
202  if (TT->isIncompleteType())
203  return false;
204 
205  // If this is an enum, then it is always safe to convert.
206  const RecordType *RT = dyn_cast<RecordType>(TT);
207  if (!RT) return true;
208 
209  // Otherwise, we have to be careful. If it is a struct that we're in the
210  // process of expanding, then we can't convert the function type. That's ok
211  // though because we must be in a pointer context under the struct, so we can
212  // just convert it to a dummy type.
213  //
214  // We decide this by checking whether ConvertRecordDeclType returns us an
215  // opaque type for a struct that we know is defined.
216  return isSafeToConvert(RT->getDecl(), *this);
217 }
218 
219 
220 /// Code to verify a given function type is complete, i.e. the return type
221 /// and all of the parameter types are complete. Also check to see if we are in
222 /// a RS_StructPointer context, and if so whether any struct types have been
223 /// pended. If so, we don't want to ask the ABI lowering code to handle a type
224 /// that cannot be converted to an IR type.
227  return false;
228 
229  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
230  for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
231  if (!isFuncParamTypeConvertible(FPT->getParamType(i)))
232  return false;
233 
234  return true;
235 }
236 
237 /// UpdateCompletedType - When we find the full definition for a TagDecl,
238 /// replace the 'opaque' type we previously made for it if applicable.
240  // If this is an enum being completed, then we flush all non-struct types from
241  // the cache. This allows function types and other things that may be derived
242  // from the enum to be recomputed.
243  if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) {
244  // Only flush the cache if we've actually already converted this type.
245  if (TypeCache.count(ED->getTypeForDecl())) {
246  // Okay, we formed some types based on this. We speculated that the enum
247  // would be lowered to i32, so we only need to flush the cache if this
248  // didn't happen.
249  if (!ConvertType(ED->getIntegerType())->isIntegerTy(32))
250  TypeCache.clear();
251  }
252  // If necessary, provide the full definition of a type only used with a
253  // declaration so far.
254  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
255  DI->completeType(ED);
256  return;
257  }
258 
259  // If we completed a RecordDecl that we previously used and converted to an
260  // anonymous type, then go ahead and complete it now.
261  const RecordDecl *RD = cast<RecordDecl>(TD);
262  if (RD->isDependentType()) return;
263 
264  // Only complete it if we converted it already. If we haven't converted it
265  // yet, we'll just do it lazily.
266  if (RecordDeclTypes.count(Context.getTagDeclType(RD).getTypePtr()))
268 
269  // If necessary, provide the full definition of a type only used with a
270  // declaration so far.
271  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
272  DI->completeType(RD);
273 }
274 
275 static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
276  const llvm::fltSemantics &format,
277  bool UseNativeHalf = false) {
278  if (&format == &llvm::APFloat::IEEEhalf) {
279  if (UseNativeHalf)
280  return llvm::Type::getHalfTy(VMContext);
281  else
282  return llvm::Type::getInt16Ty(VMContext);
283  }
284  if (&format == &llvm::APFloat::IEEEsingle)
285  return llvm::Type::getFloatTy(VMContext);
286  if (&format == &llvm::APFloat::IEEEdouble)
287  return llvm::Type::getDoubleTy(VMContext);
288  if (&format == &llvm::APFloat::IEEEquad)
289  return llvm::Type::getFP128Ty(VMContext);
290  if (&format == &llvm::APFloat::PPCDoubleDouble)
291  return llvm::Type::getPPC_FP128Ty(VMContext);
292  if (&format == &llvm::APFloat::x87DoubleExtended)
293  return llvm::Type::getX86_FP80Ty(VMContext);
294  llvm_unreachable("Unknown float format!");
295 }
296 
298  const FunctionDecl *FD) {
299  assert(QFT.isCanonical());
300  const Type *Ty = QFT.getTypePtr();
301  const FunctionType *FT = cast<FunctionType>(QFT.getTypePtr());
302  // First, check whether we can build the full function type. If the
303  // function type depends on an incomplete type (e.g. a struct or enum), we
304  // cannot lower the function type.
305  if (!isFuncTypeConvertible(FT)) {
306  // This function's type depends on an incomplete tag type.
307 
308  // Force conversion of all the relevant record types, to make sure
309  // we re-convert the FunctionType when appropriate.
310  if (const RecordType *RT = FT->getReturnType()->getAs<RecordType>())
311  ConvertRecordDeclType(RT->getDecl());
312  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
313  for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
314  if (const RecordType *RT = FPT->getParamType(i)->getAs<RecordType>())
315  ConvertRecordDeclType(RT->getDecl());
316 
317  SkippedLayout = true;
318 
319  // Return a placeholder type.
320  return llvm::StructType::get(getLLVMContext());
321  }
322 
323  // While we're converting the parameter types for a function, we don't want
324  // to recursively convert any pointed-to structs. Converting directly-used
325  // structs is ok though.
326  if (!RecordsBeingLaidOut.insert(Ty).second) {
327  SkippedLayout = true;
328  return llvm::StructType::get(getLLVMContext());
329  }
330 
331  // The function type can be built; call the appropriate routines to
332  // build it.
333  const CGFunctionInfo *FI;
334  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
337  } else {
338  const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
341  }
342 
343  llvm::Type *ResultType = nullptr;
344  // If there is something higher level prodding our CGFunctionInfo, then
345  // don't recurse into it again.
346  if (FunctionsBeingProcessed.count(FI)) {
347 
348  ResultType = llvm::StructType::get(getLLVMContext());
349  SkippedLayout = true;
350  } else {
351 
352  // Otherwise, we're good to go, go ahead and convert it.
353  ResultType = GetFunctionType(*FI);
354  }
355 
356  RecordsBeingLaidOut.erase(Ty);
357 
358  if (SkippedLayout)
359  TypeCache.clear();
360 
361  if (RecordsBeingLaidOut.empty())
362  while (!DeferredRecords.empty())
363  ConvertRecordDeclType(DeferredRecords.pop_back_val());
364  return ResultType;
365 }
366 
367 /// ConvertType - Convert the specified type to its LLVM form.
369  T = Context.getCanonicalType(T);
370 
371  const Type *Ty = T.getTypePtr();
372 
373  // RecordTypes are cached and processed specially.
374  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
375  return ConvertRecordDeclType(RT->getDecl());
376 
377  // See if type is already cached.
379  // If type is found in map then use it. Otherwise, convert type T.
380  if (TCI != TypeCache.end())
381  return TCI->second;
382 
383  // If we don't have it in the cache, convert it now.
384  llvm::Type *ResultType = nullptr;
385  switch (Ty->getTypeClass()) {
386  case Type::Record: // Handled above.
387 #define TYPE(Class, Base)
388 #define ABSTRACT_TYPE(Class, Base)
389 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
390 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
391 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
392 #include "clang/AST/TypeNodes.def"
393  llvm_unreachable("Non-canonical or dependent types aren't possible.");
394 
395  case Type::Builtin: {
396  switch (cast<BuiltinType>(Ty)->getKind()) {
397  case BuiltinType::Void:
398  case BuiltinType::ObjCId:
399  case BuiltinType::ObjCClass:
400  case BuiltinType::ObjCSel:
401  // LLVM void type can only be used as the result of a function call. Just
402  // map to the same as char.
403  ResultType = llvm::Type::getInt8Ty(getLLVMContext());
404  break;
405 
406  case BuiltinType::Bool:
407  // Note that we always return bool as i1 for use as a scalar type.
408  ResultType = llvm::Type::getInt1Ty(getLLVMContext());
409  break;
410 
411  case BuiltinType::Char_S:
412  case BuiltinType::Char_U:
413  case BuiltinType::SChar:
414  case BuiltinType::UChar:
415  case BuiltinType::Short:
416  case BuiltinType::UShort:
417  case BuiltinType::Int:
418  case BuiltinType::UInt:
419  case BuiltinType::Long:
420  case BuiltinType::ULong:
421  case BuiltinType::LongLong:
422  case BuiltinType::ULongLong:
423  case BuiltinType::WChar_S:
424  case BuiltinType::WChar_U:
425  case BuiltinType::Char16:
426  case BuiltinType::Char32:
427  ResultType = llvm::IntegerType::get(getLLVMContext(),
428  static_cast<unsigned>(Context.getTypeSize(T)));
429  break;
430 
431  case BuiltinType::Half:
432  // Half FP can either be storage-only (lowered to i16) or native.
433  ResultType =
435  Context.getLangOpts().NativeHalfType ||
436  Context.getLangOpts().HalfArgsAndReturns);
437  break;
438  case BuiltinType::Float:
439  case BuiltinType::Double:
440  case BuiltinType::LongDouble:
441  ResultType = getTypeForFormat(getLLVMContext(),
442  Context.getFloatTypeSemantics(T),
443  /* UseNativeHalf = */ false);
444  break;
445 
446  case BuiltinType::NullPtr:
447  // Model std::nullptr_t as i8*
448  ResultType = llvm::Type::getInt8PtrTy(getLLVMContext());
449  break;
450 
451  case BuiltinType::UInt128:
452  case BuiltinType::Int128:
453  ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
454  break;
455 
456  case BuiltinType::OCLImage1d:
457  case BuiltinType::OCLImage1dArray:
458  case BuiltinType::OCLImage1dBuffer:
459  case BuiltinType::OCLImage2d:
460  case BuiltinType::OCLImage2dArray:
461  case BuiltinType::OCLImage2dDepth:
462  case BuiltinType::OCLImage2dArrayDepth:
463  case BuiltinType::OCLImage2dMSAA:
464  case BuiltinType::OCLImage2dArrayMSAA:
465  case BuiltinType::OCLImage2dMSAADepth:
466  case BuiltinType::OCLImage2dArrayMSAADepth:
467  case BuiltinType::OCLImage3d:
468  case BuiltinType::OCLSampler:
469  case BuiltinType::OCLEvent:
470  case BuiltinType::OCLClkEvent:
471  case BuiltinType::OCLQueue:
472  case BuiltinType::OCLNDRange:
473  case BuiltinType::OCLReserveID:
474  ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
475  break;
476 
477  case BuiltinType::Dependent:
478 #define BUILTIN_TYPE(Id, SingletonId)
479 #define PLACEHOLDER_TYPE(Id, SingletonId) \
480  case BuiltinType::Id:
481 #include "clang/AST/BuiltinTypes.def"
482  llvm_unreachable("Unexpected placeholder builtin type!");
483  }
484  break;
485  }
486  case Type::Auto:
487  llvm_unreachable("Unexpected undeduced auto type!");
488  case Type::Complex: {
489  llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
490  ResultType = llvm::StructType::get(EltTy, EltTy, nullptr);
491  break;
492  }
493  case Type::LValueReference:
494  case Type::RValueReference: {
495  const ReferenceType *RTy = cast<ReferenceType>(Ty);
496  QualType ETy = RTy->getPointeeType();
497  llvm::Type *PointeeType = ConvertTypeForMem(ETy);
498  unsigned AS = Context.getTargetAddressSpace(ETy);
499  ResultType = llvm::PointerType::get(PointeeType, AS);
500  break;
501  }
502  case Type::Pointer: {
503  const PointerType *PTy = cast<PointerType>(Ty);
504  QualType ETy = PTy->getPointeeType();
505  llvm::Type *PointeeType = ConvertTypeForMem(ETy);
506  if (PointeeType->isVoidTy())
507  PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
508  unsigned AS = Context.getTargetAddressSpace(ETy);
509  ResultType = llvm::PointerType::get(PointeeType, AS);
510  break;
511  }
512 
513  case Type::VariableArray: {
514  const VariableArrayType *A = cast<VariableArrayType>(Ty);
515  assert(A->getIndexTypeCVRQualifiers() == 0 &&
516  "FIXME: We only handle trivial array types so far!");
517  // VLAs resolve to the innermost element type; this matches
518  // the return of alloca, and there isn't any obviously better choice.
519  ResultType = ConvertTypeForMem(A->getElementType());
520  break;
521  }
522  case Type::IncompleteArray: {
523  const IncompleteArrayType *A = cast<IncompleteArrayType>(Ty);
524  assert(A->getIndexTypeCVRQualifiers() == 0 &&
525  "FIXME: We only handle trivial array types so far!");
526  // int X[] -> [0 x int], unless the element type is not sized. If it is
527  // unsized (e.g. an incomplete struct) just use [0 x i8].
528  ResultType = ConvertTypeForMem(A->getElementType());
529  if (!ResultType->isSized()) {
530  SkippedLayout = true;
531  ResultType = llvm::Type::getInt8Ty(getLLVMContext());
532  }
533  ResultType = llvm::ArrayType::get(ResultType, 0);
534  break;
535  }
536  case Type::ConstantArray: {
537  const ConstantArrayType *A = cast<ConstantArrayType>(Ty);
539 
540  // Lower arrays of undefined struct type to arrays of i8 just to have a
541  // concrete type.
542  if (!EltTy->isSized()) {
543  SkippedLayout = true;
544  EltTy = llvm::Type::getInt8Ty(getLLVMContext());
545  }
546 
547  ResultType = llvm::ArrayType::get(EltTy, A->getSize().getZExtValue());
548  break;
549  }
550  case Type::ExtVector:
551  case Type::Vector: {
552  const VectorType *VT = cast<VectorType>(Ty);
553  ResultType = llvm::VectorType::get(ConvertType(VT->getElementType()),
554  VT->getNumElements());
555  break;
556  }
557  case Type::FunctionNoProto:
558  case Type::FunctionProto:
559  ResultType = ConvertFunctionType(T);
560  break;
561  case Type::ObjCObject:
562  ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
563  break;
564 
565  case Type::ObjCInterface: {
566  // Objective-C interfaces are always opaque (outside of the
567  // runtime, which can do whatever it likes); we never refine
568  // these.
569  llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
570  if (!T)
572  ResultType = T;
573  break;
574  }
575 
576  case Type::ObjCObjectPointer: {
577  // Protocol qualifications do not influence the LLVM type, we just return a
578  // pointer to the underlying interface type. We don't need to worry about
579  // recursive conversion.
580  llvm::Type *T =
581  ConvertTypeForMem(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
582  ResultType = T->getPointerTo();
583  break;
584  }
585 
586  case Type::Enum: {
587  const EnumDecl *ED = cast<EnumType>(Ty)->getDecl();
588  if (ED->isCompleteDefinition() || ED->isFixed())
589  return ConvertType(ED->getIntegerType());
590  // Return a placeholder 'i32' type. This can be changed later when the
591  // type is defined (see UpdateCompletedType), but is likely to be the
592  // "right" answer.
593  ResultType = llvm::Type::getInt32Ty(getLLVMContext());
594  break;
595  }
596 
597  case Type::BlockPointer: {
598  const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
599  llvm::Type *PointeeType = ConvertTypeForMem(FTy);
600  unsigned AS = Context.getTargetAddressSpace(FTy);
601  ResultType = llvm::PointerType::get(PointeeType, AS);
602  break;
603  }
604 
605  case Type::MemberPointer: {
606  if (!getCXXABI().isMemberPointerConvertible(cast<MemberPointerType>(Ty)))
608  ResultType =
609  getCXXABI().ConvertMemberPointerType(cast<MemberPointerType>(Ty));
610  break;
611  }
612 
613  case Type::Atomic: {
614  QualType valueType = cast<AtomicType>(Ty)->getValueType();
615  ResultType = ConvertTypeForMem(valueType);
616 
617  // Pad out to the inflated size if necessary.
618  uint64_t valueSize = Context.getTypeSize(valueType);
619  uint64_t atomicSize = Context.getTypeSize(Ty);
620  if (valueSize != atomicSize) {
621  assert(valueSize < atomicSize);
622  llvm::Type *elts[] = {
623  ResultType,
624  llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
625  };
626  ResultType = llvm::StructType::get(getLLVMContext(),
627  llvm::makeArrayRef(elts));
628  }
629  break;
630  }
631  case Type::Pipe: {
632  ResultType = CGM.getOpenCLRuntime().getPipeType();
633  break;
634  }
635  }
636 
637  assert(ResultType && "Didn't convert a type?");
638 
639  TypeCache[Ty] = ResultType;
640  return ResultType;
641 }
642 
644  return isPaddedAtomicType(type->castAs<AtomicType>());
645 }
646 
648  return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
649 }
650 
651 /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
652 llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) {
653  // TagDecl's are not necessarily unique, instead use the (clang)
654  // type connected to the decl.
655  const Type *Key = Context.getTagDeclType(RD).getTypePtr();
656 
657  llvm::StructType *&Entry = RecordDeclTypes[Key];
658 
659  // If we don't have a StructType at all yet, create the forward declaration.
660  if (!Entry) {
662  addRecordTypeName(RD, Entry, "");
663  }
664  llvm::StructType *Ty = Entry;
665 
666  // If this is still a forward declaration, or the LLVM type is already
667  // complete, there's nothing more to do.
668  RD = RD->getDefinition();
669  if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
670  return Ty;
671 
672  // If converting this type would cause us to infinitely loop, don't do it!
673  if (!isSafeToConvert(RD, *this)) {
674  DeferredRecords.push_back(RD);
675  return Ty;
676  }
677 
678  // Okay, this is a definition of a type. Compile the implementation now.
679  bool InsertResult = RecordsBeingLaidOut.insert(Key).second;
680  (void)InsertResult;
681  assert(InsertResult && "Recursively compiling a struct?");
682 
683  // Force conversion of non-virtual base classes recursively.
684  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
685  for (const auto &I : CRD->bases()) {
686  if (I.isVirtual()) continue;
687 
688  ConvertRecordDeclType(I.getType()->getAs<RecordType>()->getDecl());
689  }
690  }
691 
692  // Layout fields.
693  CGRecordLayout *Layout = ComputeRecordLayout(RD, Ty);
694  CGRecordLayouts[Key] = Layout;
695 
696  // We're done laying out this struct.
697  bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult;
698  assert(EraseResult && "struct not in RecordsBeingLaidOut set?");
699 
700  // If this struct blocked a FunctionType conversion, then recompute whatever
701  // was derived from that.
702  // FIXME: This is hugely overconservative.
703  if (SkippedLayout)
704  TypeCache.clear();
705 
706  // If we're done converting the outer-most record, then convert any deferred
707  // structs as well.
708  if (RecordsBeingLaidOut.empty())
709  while (!DeferredRecords.empty())
710  ConvertRecordDeclType(DeferredRecords.pop_back_val());
711 
712  return Ty;
713 }
714 
715 /// getCGRecordLayout - Return record layout info for the given record decl.
716 const CGRecordLayout &
718  const Type *Key = Context.getTagDeclType(RD).getTypePtr();
719 
720  const CGRecordLayout *Layout = CGRecordLayouts.lookup(Key);
721  if (!Layout) {
722  // Compute the type information.
724 
725  // Now try again.
726  Layout = CGRecordLayouts.lookup(Key);
727  }
728 
729  assert(Layout && "Unable to find record layout information for type");
730  return *Layout;
731 }
732 
734  // No need to check for member pointers when not compiling C++.
735  if (!Context.getLangOpts().CPlusPlus)
736  return true;
737 
738  if (const auto *AT = Context.getAsArrayType(T)) {
739  if (isa<IncompleteArrayType>(AT))
740  return true;
741  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
742  if (Context.getConstantArrayElementCount(CAT) == 0)
743  return true;
744  T = Context.getBaseElementType(T);
745  }
746 
747  // Records are non-zero-initializable if they contain any
748  // non-zero-initializable subobjects.
749  if (const RecordType *RT = T->getAs<RecordType>()) {
750  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
751  return isZeroInitializable(RD);
752  }
753 
754  // We have to ask the ABI about member pointers.
755  if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
756  return getCXXABI().isZeroInitializable(MPT);
757 
758  // Everything else is okay.
759  return true;
760 }
761 
764 }
unsigned getNumElements() const
Definition: Type.h:2749
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
Defines the clang::ASTContext interface.
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1483
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2147
A (possibly-)qualified type.
Definition: Type.h:575
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:164
static llvm::Type * getTypeForFormat(llvm::LLVMContext &VMContext, const llvm::fltSemantics &format, bool UseNativeHalf=false)
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3116
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2847
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:140
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...
CGCXXABI & getCXXABI() const
Definition: CodeGenTypes.h:175
ASTContext & getContext() const
Definition: CodeGenTypes.h:172
The base class of the type hierarchy.
Definition: Type.h:1249
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
const llvm::APInt & getSize() const
Definition: Type.h:2495
CGDebugInfo * getModuleDebugInfo()
bool isCanonical() const
Definition: Type.h:5133
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1793
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:51
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3166
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:2465
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:2788
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 ...
const LangOptions & getLangOpts() const
Definition: ASTContext.h:596
QualType getReturnType() const
Definition: Type.h:2977
field_range fields() const
Definition: Decl.h:3295
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
RecordDecl * getDecl() const
Definition: Type.h:3553
TypeClass getTypeClass() const
Definition: Type.h:1501
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1886
detail::InMemoryDirectory::const_iterator I
virtual llvm::Type * ConvertMemberPointerType(const MemberPointerType *MPT)
Find the LLVM type used to represent the given member pointer type.
Definition: CGCXXABI.cpp:72
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:151
Represents a K&R-style 'int foo()' function, which has no information available about its arguments...
Definition: Type.h:3007
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:5003
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3041
ASTContext * Context
virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const
Return whether or not a member pointers type is convertible to an IR type.
Definition: CGCXXABI.h:174
CodeGenTypes(CodeGenModule &cgm)
DeclContext * getDeclContext()
Definition: DeclBase.h:393
Represents a GCC generic vector type.
Definition: Type.h:2724
QualType getElementType() const
Definition: Type.h:2748
RecordDecl * getDefinition() const
getDefinition - Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3285
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:2878
The l-value was considered opaque, so the alignment was determined from a type.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5089
const TemplateArgument * iterator
Definition: Type.h:4070
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2644
void printName(raw_ostream &os) const
Definition: Decl.h:186
Represents a canonical, potentially-qualified type.
Definition: CanonicalType.h:52
llvm::LLVMContext & getLLVMContext()
Definition: CodeGenTypes.h:176
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5706
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:2818
void printQualifiedName(raw_ostream &OS) const
printQualifiedName - Returns human-readable qualified name for declaration, like A::B::i, for i being member of namespace A::B.
Definition: Decl.cpp:1402
QualType getPointeeType() const
Definition: Type.h:2161
bool isRecordBeingLaidOut(const Type *Ty) const
Definition: CodeGenTypes.h:326
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2526
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
static const Type * getElementType(const Expr *BaseExpr)
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1723
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
EnumDecl - Represents an enum.
Definition: Decl.h:2930
detail::InMemoryDirectory::const_iterator E
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2369
bool isZeroInitializable() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1946
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:3544
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5675
llvm::Type * ConvertFunctionType(QualType FT, const FunctionDecl *FD=nullptr)
Converts the GlobalDecl into an llvm::Type.
This class organizes the cross-module state that is used while lowering AST types to LLVM types...
Definition: CodeGenTypes.h:120
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
Definition: Decl.h:3054
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2287
bool isRecordLayoutComplete(const Type *Ty) const
isRecordLayoutComplete - Return true if the specified type is already completely laid out...
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
QualType getPointeeType() const
Definition: Type.h:2308
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
Represents a C array with an unspecified size.
Definition: Type.h:2530
bool isFuncParamTypeConvertible(QualType Ty)
isFuncParamTypeConvertible - Return true if the specified type in a function parameter or result posi...
virtual llvm::Type * getPipeType()
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:772
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2180
QualType getElementType() const
Definition: Type.h:2458
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CGRecordLayout * ComputeRecordLayout(const RecordDecl *D, llvm::StructType *Ty)
Compute a new LLVM record layout object for the given record.
StringRef getKindName() const
Definition: Decl.h:2843
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2575
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
bool noRecordsBeingLaidOut() const
Definition: CodeGenTypes.h:323
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2480
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
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:1293