26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/Sequence.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/GlobalVariable.h" 32 using namespace clang;
33 using namespace CodeGen;
40 class ConstExprEmitter;
42 struct ConstantAggregateBuilderUtils {
45 ConstantAggregateBuilderUtils(
CodeGenModule &CGM) : CGM(CGM) {}
47 CharUnits getAlignment(
const llvm::Constant *C)
const {
56 CharUnits getSize(
const llvm::Constant *C)
const {
57 return getSize(C->getType());
60 llvm::Constant *getPadding(
CharUnits PadSize)
const {
63 Ty = llvm::ArrayType::get(Ty, PadSize.
getQuantity());
64 return llvm::UndefValue::get(Ty);
67 llvm::Constant *getZeroes(
CharUnits ZeroSize)
const {
69 return llvm::ConstantAggregateZero::get(Ty);
75 class ConstantAggregateBuilder :
private ConstantAggregateBuilderUtils {
94 bool NaturalLayout =
true;
104 bool AllowOversized);
108 : ConstantAggregateBuilderUtils(CGM) {}
118 bool addBits(
llvm::APInt Bits, uint64_t OffsetInBits,
bool AllowOverwrite);
129 llvm::Constant *build(
llvm::Type *DesiredTy,
bool AllowOversized)
const {
131 NaturalLayout, DesiredTy, AllowOversized);
135 template<
typename Container,
typename Range = std::initializer_list<
136 typename Container::value_type>>
137 static void replace(Container &C,
size_t BeginOff,
size_t EndOff, Range Vals) {
138 assert(BeginOff <= EndOff &&
"invalid replacement range");
139 llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
142 bool ConstantAggregateBuilder::add(llvm::Constant *C,
CharUnits Offset,
143 bool AllowOverwrite) {
145 if (Offset >= Size) {
149 NaturalLayout =
false;
150 else if (AlignedSize < Offset) {
151 Elems.push_back(getPadding(Offset - Size));
152 Offsets.push_back(Size);
155 Offsets.push_back(Offset);
156 Size = Offset + getSize(C);
162 if (!FirstElemToReplace)
167 if (!LastElemToReplace)
170 assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
171 "unexpectedly overwriting field");
173 replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});
174 replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});
175 Size =
std::max(Size, Offset + CSize);
176 NaturalLayout =
false;
180 bool ConstantAggregateBuilder::addBits(
llvm::APInt Bits, uint64_t OffsetInBits,
181 bool AllowOverwrite) {
187 unsigned OffsetWithinChar = OffsetInBits % CharWidth;
195 unsigned WantedBits =
196 std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);
201 if (BitsThisChar.getBitWidth() < CharWidth)
202 BitsThisChar = BitsThisChar.zext(CharWidth);
206 int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
208 BitsThisChar.lshrInPlace(Shift);
210 BitsThisChar = BitsThisChar.shl(-Shift);
212 BitsThisChar = BitsThisChar.shl(OffsetWithinChar);
214 if (BitsThisChar.getBitWidth() > CharWidth)
215 BitsThisChar = BitsThisChar.trunc(CharWidth);
217 if (WantedBits == CharWidth) {
220 OffsetInChars, AllowOverwrite);
226 if (!FirstElemToUpdate)
230 if (!LastElemToUpdate)
232 assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
233 "should have at most one element covering one byte");
238 UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,
239 CharWidth - OffsetWithinChar);
241 UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);
242 BitsThisChar &= UpdateMask;
244 if (*FirstElemToUpdate == *LastElemToUpdate ||
245 Elems[*FirstElemToUpdate]->isNullValue() ||
246 isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) {
249 OffsetInChars,
true);
251 llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
254 auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);
259 assert(CI->getBitWidth() == CharWidth &&
"splitAt failed");
260 assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
261 "unexpectedly overwriting bitfield");
262 BitsThisChar |= (CI->getValue() & ~UpdateMask);
263 ToUpdate = llvm::ConstantInt::get(CGM.
getLLVMContext(), BitsThisChar);
268 if (WantedBits == Bits.getBitWidth())
273 Bits.lshrInPlace(WantedBits);
274 Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);
277 OffsetWithinChar = 0;
289 return Offsets.size();
292 auto FirstAfterPos = llvm::upper_bound(Offsets, Pos);
293 if (FirstAfterPos == Offsets.begin())
297 size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
298 if (Offsets[LastAtOrBeforePosIndex] == Pos)
299 return LastAtOrBeforePosIndex;
302 if (Offsets[LastAtOrBeforePosIndex] +
303 getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)
304 return LastAtOrBeforePosIndex + 1;
307 if (!split(LastAtOrBeforePosIndex, Pos))
315 bool ConstantAggregateBuilder::split(
size_t Index,
CharUnits Hint) {
316 NaturalLayout =
false;
317 llvm::Constant *C = Elems[Index];
320 if (
auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {
321 replace(Elems, Index, Index + 1,
322 llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
323 [&](
unsigned Op) {
return CA->getOperand(Op); }));
324 if (
auto *Seq = dyn_cast<llvm::SequentialType>(CA->getType())) {
326 CharUnits ElemSize = getSize(Seq->getElementType());
328 Offsets, Index, Index + 1,
329 llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
330 [&](
unsigned Op) {
return Offset + Op * ElemSize; }));
333 auto *ST = cast<llvm::StructType>(CA->getType());
334 const llvm::StructLayout *Layout =
336 replace(Offsets, Index, Index + 1,
338 llvm::seq(0u, CA->getNumOperands()), [&](
unsigned Op) {
340 Layout->getElementOffset(Op));
346 if (
auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {
348 CharUnits ElemSize = getSize(CDS->getElementType());
349 replace(Elems, Index, Index + 1,
350 llvm::map_range(llvm::seq(0u, CDS->getNumElements()),
352 return CDS->getElementAsConstant(Elem);
354 replace(Offsets, Index, Index + 1,
356 llvm::seq(0u, CDS->getNumElements()),
357 [&](
unsigned Elem) {
return Offset + Elem * ElemSize; }));
361 if (isa<llvm::ConstantAggregateZero>(C)) {
363 assert(Hint > Offset && Hint < Offset + ElemSize &&
"nothing to split");
364 replace(Elems, Index, Index + 1,
365 {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});
366 replace(Offsets, Index, Index + 1, {
Offset, Hint});
370 if (isa<llvm::UndefValue>(C)) {
371 replace(Elems, Index, Index + 1, {});
372 replace(Offsets, Index, Index + 1, {});
383 static llvm::Constant *
384 EmitArrayConstant(
CodeGenModule &CGM, llvm::ArrayType *DesiredType,
385 llvm::Type *CommonElementType,
unsigned ArrayBound,
387 llvm::Constant *Filler);
389 llvm::Constant *ConstantAggregateBuilder::buildFrom(
392 bool NaturalLayout,
llvm::Type *DesiredTy,
bool AllowOversized) {
393 ConstantAggregateBuilderUtils Utils(CGM);
396 return llvm::UndefValue::get(DesiredTy);
398 auto Offset = [&](
size_t I) {
return Offsets[I] - StartOffset; };
402 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {
403 assert(!AllowOversized &&
"oversized array emission not supported");
405 bool CanEmitArray =
true;
407 llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);
408 CharUnits ElemSize = Utils.getSize(ATy->getElementType());
410 for (
size_t I = 0; I != Elems.size(); ++I) {
412 if (Elems[I]->isNullValue())
416 if (Elems[I]->getType() != CommonType ||
417 Offset(I) % ElemSize != 0) {
418 CanEmitArray =
false;
421 ArrayElements.resize(
Offset(I) / ElemSize + 1, Filler);
422 ArrayElements.back() = Elems[I];
426 return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),
427 ArrayElements, Filler);
433 CharUnits DesiredSize = Utils.getSize(DesiredTy);
435 for (llvm::Constant *C : Elems)
436 Align =
std::max(Align, Utils.getAlignment(C));
442 if ((DesiredSize < AlignedSize && !AllowOversized) ||
443 DesiredSize.alignTo(Align) != DesiredSize) {
445 NaturalLayout =
false;
447 }
else if (DesiredSize > AlignedSize) {
449 UnpackedElemStorage.assign(Elems.begin(), Elems.end());
450 UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
451 UnpackedElems = UnpackedElemStorage;
458 if (!NaturalLayout) {
460 for (
size_t I = 0; I != Elems.size(); ++I) {
461 CharUnits Align = Utils.getAlignment(Elems[I]);
464 assert(DesiredOffset >= SizeSoFar &&
"elements out of order");
466 if (DesiredOffset != NaturalOffset)
468 if (DesiredOffset != SizeSoFar)
469 PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
470 PackedElems.push_back(Elems[I]);
471 SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
476 assert((SizeSoFar <= DesiredSize || AllowOversized) &&
477 "requested size is too small for contents");
478 if (SizeSoFar < DesiredSize)
479 PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
483 llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
484 CGM.
getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);
488 if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
489 if (DesiredSTy->isLayoutIdentical(STy))
493 return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);
496 void ConstantAggregateBuilder::condense(
CharUnits Offset,
501 if (!FirstElemToReplace)
503 size_t First = *FirstElemToReplace;
506 if (!LastElemToReplace)
508 size_t Last = *LastElemToReplace;
510 size_t Length = Last - First;
514 if (Length == 1 && Offsets[First] == Offset &&
515 getSize(Elems[First]) == Size) {
518 auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
519 if (STy && STy->getNumElements() == 1 &&
520 STy->getElementType(0) == Elems[First]->getType())
521 Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
525 llvm::Constant *Replacement = buildFrom(
526 CGM, makeArrayRef(Elems).slice(First, Length),
527 makeArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
528 false, DesiredTy,
false);
529 replace(Elems, First, Last, {Replacement});
530 replace(Offsets, First, Last, {Offset});
537 class ConstStructBuilder {
540 ConstantAggregateBuilder &Builder;
554 ConstantAggregateBuilder &Builder,
CharUnits StartOffset)
555 : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
556 StartOffset(StartOffset) {}
558 bool AppendField(
const FieldDecl *Field, uint64_t FieldOffset,
559 llvm::Constant *InitExpr,
bool AllowOverwrite =
false);
561 bool AppendBytes(
CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
562 bool AllowOverwrite =
false);
564 bool AppendBitField(
const FieldDecl *Field, uint64_t FieldOffset,
565 llvm::ConstantInt *InitExpr,
bool AllowOverwrite =
false);
570 llvm::Constant *Finalize(
QualType Ty);
573 bool ConstStructBuilder::AppendField(
574 const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
575 bool AllowOverwrite) {
580 return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
583 bool ConstStructBuilder::AppendBytes(
CharUnits FieldOffsetInChars,
584 llvm::Constant *InitCst,
585 bool AllowOverwrite) {
586 return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
589 bool ConstStructBuilder::AppendBitField(
590 const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
591 bool AllowOverwrite) {
599 if (FieldSize > FieldValue.getBitWidth())
600 FieldValue = FieldValue.zext(FieldSize);
603 if (FieldSize < FieldValue.getBitWidth())
604 FieldValue = FieldValue.trunc(FieldSize);
606 return Builder.addBits(FieldValue,
612 ConstantAggregateBuilder &
Const,
616 return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
621 QualType ElemType = CAT->getElementType();
625 llvm::Constant *FillC =
nullptr;
627 if (!isa<NoInitExpr>(Filler)) {
634 unsigned NumElementsToUpdate =
635 FillC ? CAT->getSize().getZExtValue() : Updater->
getNumInits();
636 for (
unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
637 Expr *Init =
nullptr;
638 if (I < Updater->getNumInits())
641 if (!Init && FillC) {
642 if (!Const.add(FillC, Offset,
true))
644 }
else if (!Init || isa<NoInitExpr>(Init)) {
646 }
else if (
InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) {
647 if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
651 Const.condense(Offset, ElemTy);
654 if (!Const.add(Val, Offset,
true))
662 bool ConstStructBuilder::Build(
InitListExpr *ILE,
bool AllowOverwrite) {
666 unsigned FieldNo = -1;
667 unsigned ElementNo = 0;
672 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
673 if (CXXRD->getNumBases())
690 Expr *Init =
nullptr;
691 if (ElementNo < ILE->getNumInits())
692 Init = ILE->
getInit(ElementNo++);
693 if (Init && isa<NoInitExpr>(Init))
699 if (AllowOverwrite &&
701 if (
auto *SubILE = dyn_cast<InitListExpr>(Init)) {
704 if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
709 Builder.condense(StartOffset + Offset,
715 llvm::Constant *EltInit =
728 if (Field->
hasAttr<NoUniqueAddressAttr>())
729 AllowOverwrite =
true;
732 if (
auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
750 : Decl(Decl), Offset(Offset), Index(Index) {
757 bool operator<(
const BaseInfo &O)
const {
return Offset < O.Offset; }
769 if (CD->isDynamicClass() && !IsPrimaryBase) {
770 llvm::Constant *VTableAddressPoint =
773 if (!AppendBytes(Offset, VTableAddressPoint))
780 Bases.reserve(CD->getNumBases());
783 BaseEnd = CD->bases_end();
Base != BaseEnd; ++
Base, ++BaseNo) {
784 assert(!
Base->isVirtual() &&
"should not have virtual bases here");
787 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
789 llvm::stable_sort(Bases);
791 for (
unsigned I = 0, N = Bases.size(); I != N; ++I) {
792 BaseInfo &
Base = Bases[I];
795 Build(Val.
getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
796 VTableClass, Offset + Base.Offset);
800 unsigned FieldNo = 0;
803 bool AllowOverwrite =
false;
805 FieldEnd = RD->
field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
817 llvm::Constant *EltInit =
824 if (!AppendField(*Field, Layout.
getFieldOffset(FieldNo) + OffsetBits,
825 EltInit, AllowOverwrite))
829 if (Field->
hasAttr<NoUniqueAddressAttr>())
830 AllowOverwrite =
true;
833 if (!AppendBitField(*Field, Layout.
getFieldOffset(FieldNo) + OffsetBits,
834 cast<llvm::ConstantInt>(EltInit), AllowOverwrite))
842 llvm::Constant *ConstStructBuilder::Finalize(
QualType Type) {
848 llvm::Constant *ConstStructBuilder::BuildStruct(
ConstantEmitter &Emitter,
851 ConstantAggregateBuilder
Const(Emitter.
CGM);
854 if (!Builder.Build(ILE,
false))
857 return Builder.Finalize(ValTy);
860 llvm::Constant *ConstStructBuilder::BuildStruct(
ConstantEmitter &Emitter,
863 ConstantAggregateBuilder
Const(Emitter.
CGM);
871 return Builder.Finalize(ValTy);
875 ConstantAggregateBuilder &Const,
877 return ConstStructBuilder(Emitter, Const, Offset)
878 .Build(Updater,
true);
889 if (llvm::GlobalVariable *Addr =
896 llvm::Constant *C = emitter.tryEmitForInitializer(E->
getInitializer(),
900 "file-scope compound literal did not have constant initializer!");
904 auto GV =
new llvm::GlobalVariable(CGM.
getModule(), C->getType(),
907 C,
".compoundliteral",
nullptr,
908 llvm::GlobalVariable::NotThreadLocal,
910 emitter.finalize(GV);
916 static llvm::Constant *
917 EmitArrayConstant(
CodeGenModule &CGM, llvm::ArrayType *DesiredType,
918 llvm::Type *CommonElementType,
unsigned ArrayBound,
920 llvm::Constant *Filler) {
922 unsigned NonzeroLength = ArrayBound;
923 if (Elements.size() < NonzeroLength && Filler->isNullValue())
924 NonzeroLength = Elements.size();
925 if (NonzeroLength == Elements.size()) {
926 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
930 if (NonzeroLength == 0)
931 return llvm::ConstantAggregateZero::get(DesiredType);
934 unsigned TrailingZeroes = ArrayBound - NonzeroLength;
935 if (TrailingZeroes >= 8) {
936 assert(Elements.size() >= NonzeroLength &&
937 "missing initializer for non-zero element");
941 if (CommonElementType && NonzeroLength >= 8) {
942 llvm::Constant *Initial = llvm::ConstantArray::get(
943 llvm::ArrayType::get(CommonElementType, NonzeroLength),
944 makeArrayRef(Elements).take_front(NonzeroLength));
946 Elements[0] = Initial;
948 Elements.resize(NonzeroLength + 1);
952 CommonElementType ? CommonElementType : DesiredType->getElementType();
953 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
954 Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
955 CommonElementType =
nullptr;
956 }
else if (Elements.size() != ArrayBound) {
958 Elements.resize(ArrayBound, Filler);
959 if (Filler->getType() != CommonElementType)
960 CommonElementType =
nullptr;
964 if (CommonElementType)
965 return llvm::ConstantArray::get(
966 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
970 Types.reserve(Elements.size());
971 for (llvm::Constant *Elt : Elements)
972 Types.push_back(Elt->getType());
973 llvm::StructType *SType =
975 return llvm::ConstantStruct::get(SType, Elements);
984 class ConstExprEmitter :
985 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
988 llvm::LLVMContext &VMContext;
991 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
1030 if (
const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
1038 "Destination type is not union type!");
1043 if (!C)
return nullptr;
1045 auto destTy = ConvertType(destType);
1046 if (C->getType() == destTy)
return C;
1053 Types.push_back(C->getType());
1054 unsigned CurSize = CGM.
getDataLayout().getTypeAllocSize(C->getType());
1055 unsigned TotalSize = CGM.
getDataLayout().getTypeAllocSize(destTy);
1057 assert(CurSize <= TotalSize &&
"Union size mismatch!");
1058 if (
unsigned NumPadBytes = TotalSize - CurSize) {
1060 if (NumPadBytes > 1)
1061 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
1063 Elts.push_back(llvm::UndefValue::get(Ty));
1064 Types.push_back(Ty);
1067 llvm::StructType *STy = llvm::StructType::get(VMContext, Types,
false);
1068 return llvm::ConstantStruct::get(STy, Elts);
1071 case CK_AddressSpaceConversion: {
1073 if (!C)
return nullptr;
1081 case CK_LValueToRValue:
1082 case CK_AtomicToNonAtomic:
1083 case CK_NonAtomicToAtomic:
1085 case CK_ConstructorConversion:
1086 return Visit(subExpr, destType);
1088 case CK_IntToOCLSampler:
1089 llvm_unreachable(
"global sampler variables are not generated");
1091 case CK_Dependent: llvm_unreachable(
"saw dependent cast!");
1093 case CK_BuiltinFnToFnPtr:
1094 llvm_unreachable(
"builtin functions are handled elsewhere");
1096 case CK_ReinterpretMemberPointer:
1097 case CK_DerivedToBaseMemberPointer:
1098 case CK_BaseToDerivedMemberPointer: {
1100 if (!C)
return nullptr;
1105 case CK_ObjCObjectLValueCast:
1106 case CK_ARCProduceObject:
1107 case CK_ARCConsumeObject:
1108 case CK_ARCReclaimReturnedObject:
1109 case CK_ARCExtendBlockObject:
1110 case CK_CopyAndAutoreleaseBlockObject:
1118 case CK_LValueBitCast:
1119 case CK_LValueToRValueBitCast:
1120 case CK_NullToMemberPointer:
1121 case CK_UserDefinedConversion:
1122 case CK_CPointerToObjCPointerCast:
1123 case CK_BlockPointerToObjCPointerCast:
1124 case CK_AnyPointerToBlockPointerCast:
1125 case CK_ArrayToPointerDecay:
1126 case CK_FunctionToPointerDecay:
1127 case CK_BaseToDerived:
1128 case CK_DerivedToBase:
1129 case CK_UncheckedDerivedToBase:
1130 case CK_MemberPointerToBoolean:
1131 case CK_VectorSplat:
1132 case CK_FloatingRealToComplex:
1133 case CK_FloatingComplexToReal:
1134 case CK_FloatingComplexToBoolean:
1135 case CK_FloatingComplexCast:
1136 case CK_FloatingComplexToIntegralComplex:
1137 case CK_IntegralRealToComplex:
1138 case CK_IntegralComplexToReal:
1139 case CK_IntegralComplexToBoolean:
1140 case CK_IntegralComplexCast:
1141 case CK_IntegralComplexToFloatingComplex:
1142 case CK_PointerToIntegral:
1143 case CK_PointerToBoolean:
1144 case CK_NullToPointer:
1145 case CK_IntegralCast:
1146 case CK_BooleanToSignedIntegral:
1147 case CK_IntegralToPointer:
1148 case CK_IntegralToBoolean:
1149 case CK_IntegralToFloating:
1150 case CK_FloatingToIntegral:
1151 case CK_FloatingToBoolean:
1152 case CK_FloatingCast:
1153 case CK_FixedPointCast:
1154 case CK_FixedPointToBoolean:
1155 case CK_FixedPointToIntegral:
1156 case CK_IntegralToFixedPoint:
1157 case CK_ZeroToOCLOpaqueType:
1160 llvm_unreachable(
"Invalid CastKind");
1166 return Visit(DIE->
getExpr(), T);
1182 assert(CAT &&
"can't emit array init for non-constant-bound array");
1184 unsigned NumElements = CAT->getSize().getZExtValue();
1188 unsigned NumInitableElts =
std::min(NumInitElements, NumElements);
1190 QualType EltType = CAT->getElementType();
1193 llvm::Constant *fillC =
nullptr;
1202 if (fillC && fillC->isNullValue())
1203 Elts.reserve(NumInitableElts + 1);
1205 Elts.reserve(NumElements);
1208 for (
unsigned i = 0; i < NumInitableElts; ++i) {
1214 CommonElementType = C->getType();
1215 else if (C->getType() != CommonElementType)
1216 CommonElementType =
nullptr;
1220 llvm::ArrayType *Desired =
1222 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
1227 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
1237 return Visit(ILE->
getInit(0), T);
1240 return EmitArrayInitialization(ILE, T);
1243 return EmitRecordInitialization(ILE, T);
1250 auto C = Visit(E->
getBase(), destType);
1254 ConstantAggregateBuilder
Const(CGM);
1257 if (!EmitDesignatedInitUpdater(Emitter, Const,
CharUnits::Zero(), destType,
1262 bool HasFlexibleArray =
false;
1264 HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
1265 return Const.build(ValTy, HasFlexibleArray);
1275 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1279 if (!RD->hasTrivialDestructor())
1286 assert(E->
getNumArgs() == 1 &&
"trivial ctor with > 1 argument");
1288 "trivial ctor has argument but isn't a copy/move ctor");
1292 "argument to copy ctor is of wrong type");
1294 return Visit(Arg, Ty);
1315 Str.resize(CAT->
getSize().getZExtValue(),
'\0');
1316 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
1331 llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1332 AbstractState saved) {
1333 Abstract = saved.OldValue;
1335 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1336 "created a placeholder while doing an abstract emission?");
1345 auto state = pushAbstract();
1346 auto C = tryEmitPrivateForVarInit(D);
1347 return validateAndPopAbstract(C,
state);
1352 auto state = pushAbstract();
1353 auto C = tryEmitPrivate(E, destType);
1354 return validateAndPopAbstract(C,
state);
1359 auto state = pushAbstract();
1360 auto C = tryEmitPrivate(value, destType);
1361 return validateAndPopAbstract(C,
state);
1366 auto state = pushAbstract();
1367 auto C = tryEmitPrivate(E, destType);
1368 C = validateAndPopAbstract(C,
state);
1371 "internal error: could not emit constant value \"abstractly\"");
1380 auto state = pushAbstract();
1381 auto C = tryEmitPrivate(value, destType);
1382 C = validateAndPopAbstract(C,
state);
1385 "internal error: could not emit constant value \"abstractly\"");
1393 return markIfFailed(tryEmitPrivateForVarInit(D));
1399 initializeNonAbstract(destAddrSpace);
1400 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1406 initializeNonAbstract(destAddrSpace);
1407 auto C = tryEmitPrivateForMemory(value, destType);
1408 assert(C &&
"couldn't emit constant value non-abstractly?");
1413 assert(!Abstract &&
"cannot get current address for abstract constant");
1419 auto global =
new llvm::GlobalVariable(CGM.
getModule(), CGM.
Int8Ty,
true,
1420 llvm::GlobalValue::PrivateLinkage,
1424 llvm::GlobalVariable::NotThreadLocal,
1427 PlaceholderAddresses.push_back(std::make_pair(
nullptr, global));
1433 llvm::GlobalValue *placeholder) {
1434 assert(!PlaceholderAddresses.empty());
1435 assert(PlaceholderAddresses.back().first ==
nullptr);
1436 assert(PlaceholderAddresses.back().second == placeholder);
1437 PlaceholderAddresses.back().first = signal;
1441 struct ReplacePlaceholders {
1445 llvm::Constant *Base;
1449 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1452 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1460 ReplacePlaceholders(
CodeGenModule &CGM, llvm::Constant *base,
1461 ArrayRef<std::pair<llvm::Constant*,
1462 llvm::GlobalVariable*>> addresses)
1463 : CGM(CGM), Base(base),
1464 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1467 void replaceInInitializer(llvm::Constant *init) {
1469 BaseValueTy = init->getType();
1472 Indices.push_back(0);
1473 IndexValues.push_back(
nullptr);
1476 findLocations(init);
1479 assert(IndexValues.size() == Indices.size() &&
"mismatch");
1480 assert(Indices.size() == 1 &&
"didn't pop all indices");
1483 assert(Locations.size() == PlaceholderAddresses.size() &&
1484 "missed a placeholder?");
1490 for (
auto &entry : Locations) {
1491 assert(entry.first->getParent() ==
nullptr &&
"not a placeholder!");
1492 entry.first->replaceAllUsesWith(entry.second);
1493 entry.first->eraseFromParent();
1498 void findLocations(llvm::Constant *init) {
1500 if (
auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1501 for (
unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1502 Indices.push_back(i);
1503 IndexValues.push_back(
nullptr);
1505 findLocations(agg->getOperand(i));
1507 IndexValues.pop_back();
1515 auto it = PlaceholderAddresses.find(init);
1516 if (it != PlaceholderAddresses.end()) {
1517 setLocation(it->second);
1522 if (
auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1523 init =
expr->getOperand(0);
1530 void setLocation(llvm::GlobalVariable *placeholder) {
1531 assert(Locations.find(placeholder) == Locations.end() &&
1532 "already found location for placeholder!");
1537 assert(Indices.size() == IndexValues.size());
1538 for (
size_t i = Indices.size() - 1; i !=
size_t(-1); --i) {
1539 if (IndexValues[i]) {
1541 for (
size_t j = 0; j != i + 1; ++j) {
1542 assert(IndexValues[j] &&
1543 isa<llvm::ConstantInt>(IndexValues[j]) &&
1544 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1551 IndexValues[i] = llvm::ConstantInt::get(CGM.
Int32Ty, Indices[i]);
1556 llvm::Constant *location =
1557 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1559 location = llvm::ConstantExpr::getBitCast(location,
1560 placeholder->getType());
1562 Locations.insert({placeholder, location});
1568 assert(InitializedNonAbstract &&
1569 "finalizing emitter that was used for abstract emission?");
1570 assert(!Finalized &&
"finalizing emitter multiple times");
1571 assert(global->getInitializer());
1576 if (!PlaceholderAddresses.empty()) {
1577 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1578 .replaceInInitializer(global->getInitializer());
1579 PlaceholderAddresses.clear();
1584 assert((!InitializedNonAbstract || Finalized || Failed) &&
1585 "not finalized after being initialized for non-abstract emission");
1586 assert(PlaceholderAddresses.empty() &&
"unhandled placeholders");
1605 dyn_cast_or_null<CXXConstructExpr>(D.
getInit())) {
1610 InConstantContext =
true;
1618 return tryEmitPrivateForMemory(*value, destType);
1631 assert(E &&
"No initializer to emit");
1635 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1636 return (C ? emitForMemory(C, destType) :
nullptr);
1642 auto C = tryEmitAbstract(E, nonMemoryDestType);
1643 return (C ? emitForMemory(C, destType) :
nullptr);
1650 auto C = tryEmitAbstract(value, nonMemoryDestType);
1651 return (C ? emitForMemory(C, destType) :
nullptr);
1657 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1658 return (C ? emitForMemory(C, destType) :
nullptr);
1664 auto C = tryEmitPrivate(value, nonMemoryDestType);
1665 return (C ? emitForMemory(C, destType) :
nullptr);
1673 QualType destValueType = AT->getValueType();
1674 C = emitForMemory(CGM, C, destValueType);
1678 if (innerSize == outerSize)
1681 assert(innerSize < outerSize &&
"emitted over-large constant for atomic");
1682 llvm::Constant *elts[] = {
1684 llvm::ConstantAggregateZero::get(
1685 llvm::ArrayType::get(CGM.
Int8Ty, (outerSize - innerSize) / 8))
1687 return llvm::ConstantStruct::getAnon(elts);
1691 if (C->getType()->isIntegerTy(1)) {
1693 return llvm::ConstantExpr::getZExt(C, boolTy);
1703 bool Success =
false;
1712 C = tryEmitPrivate(Result.
Val, destType);
1714 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1720 return getTargetCodeGenInfo().getNullPointer(*
this, T, QT);
1726 struct ConstantLValue {
1727 llvm::Constant *
Value;
1728 bool HasOffsetApplied;
1730 ConstantLValue(llvm::Constant *value,
1731 bool hasOffsetApplied =
false)
1732 :
Value(value), HasOffsetApplied(hasOffsetApplied) {}
1739 class ConstantLValueEmitter :
public ConstStmtVisitor<ConstantLValueEmitter,
1752 : CGM(emitter.
CGM), Emitter(emitter),
Value(value), DestType(destType) {}
1754 llvm::Constant *tryEmit();
1757 llvm::Constant *tryEmitAbsolute(
llvm::Type *destTy);
1760 ConstantLValue VisitStmt(
const Stmt *S) {
return nullptr; }
1761 ConstantLValue VisitConstantExpr(
const ConstantExpr *E);
1769 ConstantLValue VisitCallExpr(
const CallExpr *E);
1770 ConstantLValue VisitBlockExpr(
const BlockExpr *E);
1773 ConstantLValue VisitMaterializeTemporaryExpr(
1776 bool hasNonZeroOffset()
const {
1781 llvm::Constant *getOffset() {
1782 return llvm::ConstantInt::get(CGM.
Int64Ty,
1787 llvm::Constant *applyOffset(llvm::Constant *C) {
1788 if (!hasNonZeroOffset())
1792 unsigned AS = origPtrTy->getPointerAddressSpace();
1794 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1795 C = llvm::ConstantExpr::getGetElementPtr(CGM.
Int8Ty, C, getOffset());
1796 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1803 llvm::Constant *ConstantLValueEmitter::tryEmit() {
1814 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1819 return tryEmitAbsolute(destTy);
1823 ConstantLValue result = tryEmitBase(base);
1826 llvm::Constant *value = result.Value;
1827 if (!value)
return nullptr;
1830 if (!result.HasOffsetApplied) {
1831 value = applyOffset(value);
1836 if (isa<llvm::PointerType>(destTy))
1837 return llvm::ConstantExpr::getPointerCast(value, destTy);
1839 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1845 ConstantLValueEmitter::tryEmitAbsolute(
llvm::Type *destTy) {
1847 auto destPtrTy = cast<llvm::PointerType>(destTy);
1848 if (
Value.isNullPointer()) {
1856 auto intptrTy = CGM.
getDataLayout().getIntPtrType(destPtrTy);
1858 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1860 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1868 if (D->hasAttr<WeakRefAttr>())
1871 if (
auto FD = dyn_cast<FunctionDecl>(D))
1874 if (
auto VD = dyn_cast<VarDecl>(D)) {
1876 if (!VD->hasLocalStorage()) {
1877 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1880 if (VD->isLocalVarDecl()) {
1896 if (TypeInfo->getType() != StdTypeInfoPtrTy)
1897 TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy);
1902 return Visit(base.
get<
const Expr*>());
1906 ConstantLValueEmitter::VisitConstantExpr(
const ConstantExpr *E) {
1912 return tryEmitGlobalCompoundLiteral(CGM, Emitter.
CGF, E);
1916 ConstantLValueEmitter::VisitStringLiteral(
const StringLiteral *E) {
1921 ConstantLValueEmitter::VisitObjCEncodeExpr(
const ObjCEncodeExpr *E) {
1938 ConstantLValueEmitter::VisitObjCBoxedExpr(
const ObjCBoxedExpr *E) {
1940 "this boxed expression can't be emitted as a compile-time constant");
1946 ConstantLValueEmitter::VisitPredefinedExpr(
const PredefinedExpr *E) {
1951 ConstantLValueEmitter::VisitAddrLabelExpr(
const AddrLabelExpr *E) {
1952 assert(Emitter.
CGF &&
"Invalid address of label expression outside function");
1954 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1960 ConstantLValueEmitter::VisitCallExpr(
const CallExpr *E) {
1962 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1963 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1967 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1976 ConstantLValueEmitter::VisitBlockExpr(
const BlockExpr *E) {
1977 StringRef functionName;
1978 if (
auto CGF = Emitter.
CGF)
1979 functionName = CGF->
CurFn->getName();
1981 functionName =
"global";
1987 ConstantLValueEmitter::VisitCXXTypeidExpr(
const CXXTypeidExpr *E) {
1997 ConstantLValueEmitter::VisitCXXUuidofExpr(
const CXXUuidofExpr *E) {
2002 ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
2020 return ConstantLValueEmitter(*
this, Value, DestType).tryEmit();
2035 llvm::StructType *STy =
2036 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
2037 return llvm::ConstantStruct::get(STy, Complex);
2040 const llvm::APFloat &Init = Value.
getFloat();
2041 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
2045 Init.bitcastToAPInt());
2058 llvm::StructType *STy =
2059 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
2060 return llvm::ConstantStruct::get(STy, Complex);
2066 for (
unsigned I = 0; I != NumElts; ++I) {
2073 llvm_unreachable(
"unsupported vector element type");
2075 return llvm::ConstantVector::get(Inits);
2080 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->
getType());
2081 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->
getType());
2082 if (!LHS || !RHS)
return nullptr;
2086 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.
IntPtrTy);
2087 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.
IntPtrTy);
2088 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
2093 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
2097 return ConstStructBuilder::BuildStruct(*
this, Value, DestType);
2105 llvm::Constant *Filler =
nullptr;
2115 if (Filler && Filler->isNullValue())
2116 Elts.reserve(NumInitElts + 1);
2118 Elts.reserve(NumElements);
2121 for (
unsigned I = 0; I < NumInitElts; ++I) {
2122 llvm::Constant *C = tryEmitPrivateForMemory(
2124 if (!C)
return nullptr;
2127 CommonElementType = C->getType();
2128 else if (C->getType() != CommonElementType)
2129 CommonElementType =
nullptr;
2135 if (CAT ==
nullptr && CommonElementType ==
nullptr && !NumInitElts) {
2138 llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
2140 return llvm::ConstantAggregateZero::get(AType);
2143 llvm::ArrayType *Desired =
2145 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
2151 llvm_unreachable(
"Unknown APValue kind");
2156 return EmittedCompoundLiterals.lookup(E);
2161 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2163 assert(Ok &&
"CLE has already been emitted!");
2168 assert(E->
isFileScope() &&
"not a file-scope compound literal expr");
2169 return tryEmitGlobalCompoundLiteral(*
this,
nullptr, E);
2179 if (
const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2180 return getCXXABI().EmitMemberFunctionPointer(method);
2183 uint64_t fieldOffset = getContext().getFieldOffset(decl);
2184 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2185 return getCXXABI().EmitMemberDataPointer(type, chars);
2194 bool asCompleteObject) {
2196 llvm::StructType *structure =
2200 unsigned numElements = structure->getNumElements();
2201 std::vector<llvm::Constant *> elements(numElements);
2206 for (
const auto &I : CXXR->bases()) {
2207 if (I.isVirtual()) {
2214 cast<CXXRecordDecl>(I.getType()->castAs<
RecordType>()->getDecl());
2223 llvm::Type *baseType = structure->getElementType(fieldIndex);
2229 for (
const auto *Field : record->
fields()) {
2242 if (FieldRD->findFirstNamedDataMember())
2248 if (CXXR && asCompleteObject) {
2249 for (
const auto &I : CXXR->vbases()) {
2251 cast<CXXRecordDecl>(I.getType()->castAs<
RecordType>()->getDecl());
2260 if (elements[fieldIndex])
continue;
2262 llvm::Type *baseType = structure->getElementType(fieldIndex);
2268 for (
unsigned i = 0; i != numElements; ++i) {
2270 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2273 return llvm::ConstantStruct::get(structure, elements);
2284 return llvm::Constant::getNullValue(baseType);
2297 return getNullPointer(
2298 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2300 if (getTypes().isZeroInitializable(T))
2301 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2304 llvm::ArrayType *ATy =
2305 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2309 llvm::Constant *Element =
2311 unsigned NumElements = CAT->
getSize().getZExtValue();
2313 return llvm::ConstantArray::get(ATy, Array);
2320 "Should only see pointers to data members here!");
const llvm::DataLayout & getDataLayout() const
const Expr * getSubExpr() const
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Defines the clang::ASTContext interface.
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
CodeGenFunction *const CGF
virtual llvm::Constant * EmitMemberPointer(const APValue &MP, QualType MPT)
Create a member pointer for the given member pointer constant.
PointerType - C99 6.7.5.1 - Pointer Declarators.
A (possibly-)qualified type.
CodeGenTypes & getTypes()
llvm::Constant * emitForInitializer(const APValue &value, LangAS destAddrSpace, QualType destType)
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr *> &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
bool isMemberDataPointerType() const
llvm::APSInt getValue() const
Expr * getResultExpr()
Return the result expression of this controlling expression.
llvm::Constant * getMemberPointerConstant(const UnaryOperator *e)
llvm::LLVMContext & getLLVMContext()
const Expr * getInit(unsigned Init) const
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
Stmt - This represents one statement.
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
bool isRecordType() const
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Decl - This represents one declaration (or definition), e.g.
llvm::Constant * emitForMemory(llvm::Constant *C, QualType T)
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic, and whose semantics are that of the sole contained initializer)?
ParenExpr - This represents a parethesized expression, e.g.
The base class of the type hierarchy.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Represents a call to a C++ constructor.
bool isZero() const
isZero - Test whether the quantity equals zero.
const TargetInfo & getTargetInfo() const
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a C++ constructor within a class.
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
const AddrLabelExpr * getAddrLabelDiffLHS() const
QualType getElementType() const
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
llvm::Constant * tryEmitPrivateForVarInit(const VarDecl &D)
Represents a variable declaration or definition.
CompoundLiteralExpr - [C99 6.5.2.5].
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
APFloat & getComplexFloatReal()
const T * getAs() const
Member-template getAs<specific type>'.
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
QualType getTypeInfoType() const
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
Expr * getExprOperand() const
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
bool isZeroInitializableAsBase() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer when considered as a bas...
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Represents a struct/union/class.
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
bool cleanupsHaveSideEffects() const
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
virtual llvm::Constant * getVTableAddressPointForConstExpr(BaseSubobject Base, const CXXRecordDecl *VTableClass)=0
Get the address point of the vtable for the given base subobject while building a constexpr...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
llvm::Constant * tryEmitAbstractForInitializer(const VarDecl &D)
Try to emit the initializer of the given declaration as an abstract constant.
llvm::IntegerType * Int64Ty
field_range fields() const
Represents a member of a struct/union/class.
StringLiteral * getString()
unsigned getNonVirtualBaseLLVMFieldNo(const CXXRecordDecl *RD) const
bool isReferenceType() const
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
unsigned getArraySize() const
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
__DEVICE__ int max(int __a, int __b)
Symbolic representation of typeid(T) for some type T.
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
bool GE(InterpState &S, CodePtr OpPC)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
Describes an C or C++ initializer list.
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
bool isBitField() const
Determines whether this field is a bitfield.
CharUnits - This is an opaque type for sizes expressed in character units.
APValue Val
Val - This is the value the expression can be folded to.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
llvm::Constant * tryEmitPrivate(const Expr *E, QualType T)
llvm::StructType * getBaseSubobjectLLVMType() const
Return the "base subobject" LLVM type associated with this record.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
ObjCStringLiteral, used for Objective-C string literals i.e.
field_iterator field_begin() const
unsigned getBitWidthValue(const ASTContext &Ctx) const
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
bool Const(InterpState &S, CodePtr OpPC, const T &Arg)
APSInt & getComplexIntReal()
llvm::GlobalValue * getCurrentAddrPrivate()
Get the address of the current location.
virtual llvm::Value * performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, llvm::Value *V, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
Perform address space cast of an expression of pointer type.
bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor)
isTypeConstant - Determine whether an object of this type can be emitted as a constant.
const Expr * getExpr() const
Get the initialization expression that will be used.
APValue & getVectorElt(unsigned I)
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
static CharUnits One()
One - Construct a CharUnits quantity of one.
ConstantAddress getElementBitCast(llvm::Type *ty) const
const TargetCodeGenInfo & getTargetCodeGenInfo()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
APValue & getArrayFiller()
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
llvm::Constant * getNullPointer(llvm::PointerType *T, QualType QT)
Get target specific null pointer.
InitListExpr * getUpdater() const
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
bool hasArrayFiller() const
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
This represents one expression.
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
const T * castAs() const
Member-template castAs<specific type>.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
unsigned getNumInits() const
field_iterator field_end() const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
llvm::IntegerType * Int32Ty
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant)
Returns LLVM linkage for a declarator.
APValue & getStructField(unsigned i)
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
QualType getEncodedType() const
ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr *E)
Get the address of a uuid descriptor .
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
QualType getTypeOperand(ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Represents a reference to a non-type template parameter that has been substituted with a template arg...
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
APSInt & getComplexIntImag()
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
const Expr * getSubExpr() const
ASTContext & getContext() const
const FieldDecl * getUnionField() const
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
The l-value was considered opaque, so the alignment was determined from a type.
APValue & getStructBase(unsigned i)
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S, QualType T, CodeGenModule &CGM)
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
APValue & getArrayInitializedElt(unsigned I)
virtual llvm::Value * EmitMemberPointerConversion(CodeGenFunction &CGF, const CastExpr *E, llvm::Value *Src)
Perform a derived-to-base, base-to-derived, or bitcast member pointer conversion. ...
This object has an indeterminate value (C++ [basic.indet]).
static QualType getNonMemoryType(CodeGenModule &CGM, QualType type)
bool isExpressibleAsConstantInitializer() const
StringLiteral * getFunctionName()
Encodes a location in the source.
const AddrLabelExpr * getAddrLabelDiffRHS() const
LangAS getAddressSpace() const
Return the address space of this type.
virtual ConstantAddress GenerateConstantString(const StringLiteral *)=0
Generate a constant string object.
Expr * getSubExpr() const
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
CastKind getCastKind() const
APValue & getUnionValue()
bool isUnnamedBitfield() const
Determines whether this is an unnamed bitfield.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Represents a static or instance method of a struct/union/class.
const ConstantArrayType * getAsConstantArrayType(QualType T) const
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
llvm::Constant * EmitNullConstantForBase(const CXXRecordDecl *Record)
Return a null constant appropriate for zero-initializing a base class with the given type...
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded...
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
void registerCurrentAddrPrivate(llvm::Constant *signal, llvm::GlobalValue *placeholder)
Register a 'signal' value with the emitter to inform it where to resolve a placeholder.
llvm::GlobalVariable * getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E)
If it's been emitted already, returns the GlobalVariable corresponding to a compound literal...
constexpr XRayInstrMask None
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
ObjCBoxedExpr - used for generalized expression boxing.
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
llvm::Constant * emitNullForMemory(QualType T)
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
bool hasFlexibleArrayMember() const
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
const Expr * getInitializer() const
Represents a C11 generic selection.
AddrLabelExpr - The GNU address of label extension, representing &&label.
const FieldDecl * getTargetUnionField() const
This class organizes the cross-function state that is used while generating LLVM code.
bool isTypeOperand() const
Dataflow Directional Tag Classes.
[C99 6.4.2.2] - A predefined identifier such as func.
EvalResult is a struct with detailed info about an evaluated expression.
const Expr * getInit() const
static llvm::Constant * EmitNullConstantForBase(CodeGenModule &CGM, llvm::Type *baseType, const CXXRecordDecl *base)
Emit the null constant for a base subobject.
llvm::Constant * getPointer() const
llvm::IntegerType * IntPtrTy
unsigned getArrayInitializedElts() const
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
A pointer to member type per C++ 8.3.3 - Pointers to members.
llvm::Module & getModule() const
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
LabelDecl * getLabel() const
llvm::Constant * tryEmitPrivateForMemory(const Expr *E, QualType T)
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
bool HasSideEffects
Whether the evaluated expression has side effects.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
StmtVisitorBase - This class implements a simple visitor for Stmt subclasses.
ObjCEncodeExpr, used for @encode in Objective-C.
const llvm::APInt & getSize() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
Expr * getReplacement() const
Expr * getArg(unsigned Arg)
Return the specified argument.
llvm::StructType * getLLVMType() const
Return the "complete object" LLVM type associated with this record.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E)
Returns a pointer to a constant global variable for the given file-scope compound literal expression...
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Represents a base class of a C++ class.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
A use of a default initializer in a constructor or in aggregate initialization.
void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV)
Notes that CLE's GlobalVariable is GV.
static llvm::Constant * EmitNullConstant(CodeGenModule &CGM, const RecordDecl *record, bool asCompleteObject)
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
ValueKind getKind() const
APFloat & getComplexFloatImag()
Represents a C++ struct/union/class.
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
A specialization of Address that requires the address to be an LLVM Constant.
There is no such object (it's outside its lifetime).
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
unsigned getVirtualBaseIndex(const CXXRecordDecl *base) const
Return the LLVM field index corresponding to the given virtual base.
__DEVICE__ int min(int __a, int __b)
StringLiteral - This represents a string literal expression, e.g.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
void finalize(llvm::GlobalVariable *global)
llvm::Constant * tryEmitAbstract(const Expr *E, QualType T)
Try to emit the result of the given expression as an abstract constant.
static ConstantAddress invalid()
CGCXXABI & getCXXABI() const
llvm::Constant * tryEmitAbstractForMemory(const Expr *E, QualType T)
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
llvm::Constant * GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name)
Gets the address of a block which requires no captures.
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
unsigned getTargetAddressSpace(QualType T) const
bool isZeroSize(const ASTContext &Ctx) const
Determine if this field is a subobject of zero size, that is, either a zero-length bit-field or a fie...
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
const LangOptions & getLangOpts() const
Represents the canonical version of C arrays with a specified constant size.
Defines enum values for all the target-independent builtin functions.
Represents an implicitly-generated value initialization of an object of a given type.
APFixedPoint & getFixedPoint()
CharUnits & getLValueOffset()
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
unsigned getVectorLength() const