26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/GlobalVariable.h" 30 using namespace clang;
31 using namespace CodeGen;
38 class ConstExprEmitter;
39 class ConstStructBuilder {
49 ConstExprEmitter *ExprEmitter,
50 llvm::ConstantStruct *
Base,
60 : CGM(emitter.CGM), Emitter(emitter), Packed(
false),
61 NextFieldOffsetInChars(
CharUnits::Zero()),
64 void AppendField(
const FieldDecl *Field, uint64_t FieldOffset,
65 llvm::Constant *InitExpr);
67 void AppendBytes(
CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
69 void AppendBitField(
const FieldDecl *Field, uint64_t FieldOffset,
70 llvm::ConstantInt *InitExpr);
74 void AppendTailPadding(
CharUnits RecordSize);
76 void ConvertStructToPacked();
79 bool Build(ConstExprEmitter *Emitter, llvm::ConstantStruct *
Base,
83 llvm::Constant *Finalize(
QualType Ty);
85 CharUnits getAlignment(
const llvm::Constant *C)
const {
91 CharUnits getSizeInChars(
const llvm::Constant *C)
const {
97 void ConstStructBuilder::
98 AppendField(
const FieldDecl *Field, uint64_t FieldOffset,
99 llvm::Constant *InitCst) {
104 AppendBytes(FieldOffsetInChars, InitCst);
107 void ConstStructBuilder::
108 AppendBytes(
CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
110 assert(NextFieldOffsetInChars <= FieldOffsetInChars
111 &&
"Field offset mismatch!");
113 CharUnits FieldAlignment = getAlignment(InitCst);
116 CharUnits AlignedNextFieldOffsetInChars =
117 NextFieldOffsetInChars.
alignTo(FieldAlignment);
119 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
121 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
123 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
124 "Did not add enough padding!");
126 AlignedNextFieldOffsetInChars =
127 NextFieldOffsetInChars.
alignTo(FieldAlignment);
130 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
131 assert(!Packed &&
"Alignment is wrong even with a packed struct!");
134 ConvertStructToPacked();
137 if (NextFieldOffsetInChars < FieldOffsetInChars) {
139 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
141 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
142 "Did not add enough padding!");
144 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
148 Elements.push_back(InitCst);
149 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
150 getSizeInChars(InitCst);
154 "Packed struct not byte-aligned!");
156 LLVMStructAlignment =
std::max(LLVMStructAlignment, FieldAlignment);
159 void ConstStructBuilder::AppendBitField(
const FieldDecl *Field,
160 uint64_t FieldOffset,
161 llvm::ConstantInt *CI) {
164 uint64_t NextFieldOffsetInBits = Context.
toBits(NextFieldOffsetInChars);
165 if (FieldOffset > NextFieldOffsetInBits) {
168 llvm::alignTo(FieldOffset - NextFieldOffsetInBits,
171 AppendPadding(PadSize);
176 llvm::APInt FieldValue = CI->getValue();
182 if (FieldSize > FieldValue.getBitWidth())
183 FieldValue = FieldValue.zext(FieldSize);
186 if (FieldSize < FieldValue.getBitWidth())
187 FieldValue = FieldValue.trunc(FieldSize);
189 NextFieldOffsetInBits = Context.
toBits(NextFieldOffsetInChars);
190 if (FieldOffset < NextFieldOffsetInBits) {
193 assert(!Elements.empty() &&
"Elements can't be empty!");
195 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
197 bool FitsCompletelyInPreviousByte =
198 BitsInPreviousByte >= FieldValue.getBitWidth();
200 llvm::APInt Tmp = FieldValue;
202 if (!FitsCompletelyInPreviousByte) {
203 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
206 Tmp.lshrInPlace(NewFieldWidth);
207 Tmp = Tmp.trunc(BitsInPreviousByte);
210 FieldValue = FieldValue.trunc(NewFieldWidth);
212 Tmp = Tmp.trunc(BitsInPreviousByte);
215 FieldValue.lshrInPlace(BitsInPreviousByte);
216 FieldValue = FieldValue.trunc(NewFieldWidth);
220 Tmp = Tmp.zext(CharWidth);
222 if (FitsCompletelyInPreviousByte)
223 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
225 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
230 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
231 Tmp |= Val->getValue();
233 assert(isa<llvm::UndefValue>(LastElt));
238 if (!isa<llvm::IntegerType>(LastElt->getType())) {
241 assert(isa<llvm::ArrayType>(LastElt->getType()) &&
242 "Expected array padding of undefs");
243 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
244 assert(AT->getElementType()->isIntegerTy(CharWidth) &&
245 AT->getNumElements() != 0 &&
246 "Expected non-empty array padding of undefs");
255 assert(isa<llvm::UndefValue>(Elements.back()) &&
256 Elements.back()->getType()->isIntegerTy(CharWidth) &&
257 "Padding addition didn't work right");
261 Elements.back() = llvm::ConstantInt::get(CGM.
getLLVMContext(), Tmp);
263 if (FitsCompletelyInPreviousByte)
267 while (FieldValue.getBitWidth() > CharWidth) {
273 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).
trunc(CharWidth);
276 Tmp = FieldValue.trunc(CharWidth);
278 FieldValue.lshrInPlace(CharWidth);
281 Elements.push_back(llvm::ConstantInt::get(CGM.
getLLVMContext(), Tmp));
282 ++NextFieldOffsetInChars;
284 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
287 assert(FieldValue.getBitWidth() > 0 &&
288 "Should have at least one bit left!");
289 assert(FieldValue.getBitWidth() <= CharWidth &&
290 "Should not have more than a byte left!");
292 if (FieldValue.getBitWidth() < CharWidth) {
294 unsigned BitWidth = FieldValue.getBitWidth();
296 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
298 FieldValue = FieldValue.zext(CharWidth);
304 ++NextFieldOffsetInChars;
307 void ConstStructBuilder::AppendPadding(
CharUnits PadSize) {
313 Ty = llvm::ArrayType::get(Ty, PadSize.
getQuantity());
315 llvm::Constant *C = llvm::UndefValue::get(Ty);
316 Elements.push_back(C);
318 "Padding must have 1 byte alignment!");
320 NextFieldOffsetInChars += getSizeInChars(C);
323 void ConstStructBuilder::AppendTailPadding(
CharUnits RecordSize) {
324 assert(NextFieldOffsetInChars <= RecordSize &&
327 AppendPadding(RecordSize - NextFieldOffsetInChars);
330 void ConstStructBuilder::ConvertStructToPacked() {
334 for (
unsigned i = 0, e = Elements.size(); i != e; ++i) {
335 llvm::Constant *C = Elements[i];
340 ElementOffsetInChars.
alignTo(ElementAlign);
342 if (AlignedElementOffsetInChars > ElementOffsetInChars) {
345 AlignedElementOffsetInChars - ElementOffsetInChars;
349 Ty = llvm::ArrayType::get(Ty, NumChars.
getQuantity());
351 llvm::Constant *Padding = llvm::UndefValue::get(Ty);
352 PackedElements.push_back(Padding);
353 ElementOffsetInChars += getSizeInChars(Padding);
356 PackedElements.push_back(C);
357 ElementOffsetInChars += getSizeInChars(C);
360 assert(ElementOffsetInChars == NextFieldOffsetInChars &&
361 "Packing the struct changed its size!");
363 Elements.swap(PackedElements);
372 unsigned FieldNo = 0;
373 unsigned ElementNo = 0;
378 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
379 if (CXXRD->getNumBases())
383 FieldEnd = RD->
field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
394 llvm::Constant *EltInit;
395 if (ElementNo < ILE->getNumInits())
409 if (
auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
425 : Decl(Decl), Offset(Offset), Index(Index) {
432 bool operator<(
const BaseInfo &O)
const {
return Offset < O.Offset; }
444 if (CD->isDynamicClass() && !IsPrimaryBase) {
445 llvm::Constant *VTableAddressPoint =
448 AppendBytes(Offset, VTableAddressPoint);
454 Bases.reserve(CD->getNumBases());
457 BaseEnd = CD->bases_end();
Base != BaseEnd; ++
Base, ++BaseNo) {
458 assert(!
Base->isVirtual() &&
"should not have virtual bases here");
461 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
463 std::stable_sort(Bases.begin(), Bases.end());
465 for (
unsigned I = 0, N = Bases.size(); I != N; ++I) {
466 BaseInfo &
Base = Bases[I];
469 Build(Val.
getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
470 VTableClass, Offset + Base.Offset);
474 unsigned FieldNo = 0;
478 FieldEnd = RD->
field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
490 llvm::Constant *EltInit =
497 AppendField(*Field, Layout.
getFieldOffset(FieldNo) + OffsetBits, EltInit);
500 AppendBitField(*Field, Layout.
getFieldOffset(FieldNo) + OffsetBits,
501 cast<llvm::ConstantInt>(EltInit));
508 llvm::Constant *ConstStructBuilder::Finalize(
QualType Ty) {
514 if (NextFieldOffsetInChars > LayoutSizeInChars) {
518 "Must have flexible array member if struct is bigger than type!");
524 NextFieldOffsetInChars.
alignTo(LLVMStructAlignment);
526 if (LLVMSizeInChars != LayoutSizeInChars)
527 AppendTailPadding(LayoutSizeInChars);
529 LLVMSizeInChars = NextFieldOffsetInChars.
alignTo(LLVMStructAlignment);
532 if (NextFieldOffsetInChars <= LayoutSizeInChars &&
533 LLVMSizeInChars > LayoutSizeInChars) {
534 assert(!Packed &&
"Size mismatch!");
536 ConvertStructToPacked();
537 assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
538 "Converting to packed did not help!");
541 LLVMSizeInChars = NextFieldOffsetInChars.
alignTo(LLVMStructAlignment);
543 assert(LayoutSizeInChars == LLVMSizeInChars &&
544 "Tail padding mismatch!");
549 llvm::StructType *STy =
553 if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
554 if (ValSTy->isLayoutIdentical(STy))
558 llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
560 assert(NextFieldOffsetInChars.alignTo(getAlignment(Result)) ==
561 getSizeInChars(Result) &&
567 llvm::Constant *ConstStructBuilder::BuildStruct(
ConstantEmitter &Emitter,
568 ConstExprEmitter *ExprEmitter,
569 llvm::ConstantStruct *Base,
572 ConstStructBuilder Builder(Emitter);
573 if (!Builder.Build(ExprEmitter, Base, Updater))
575 return Builder.Finalize(ValTy);
578 llvm::Constant *ConstStructBuilder::BuildStruct(
ConstantEmitter &Emitter,
581 ConstStructBuilder Builder(Emitter);
583 if (!Builder.Build(ILE))
586 return Builder.Finalize(ValTy);
589 llvm::Constant *ConstStructBuilder::BuildStruct(
ConstantEmitter &Emitter,
592 ConstStructBuilder Builder(Emitter);
599 return Builder.Finalize(ValTy);
611 if (llvm::GlobalVariable *Addr =
618 llvm::Constant *C = emitter.tryEmitForInitializer(E->
getInitializer(),
622 "file-scope compound literal did not have constant initializer!");
626 auto GV =
new llvm::GlobalVariable(CGM.
getModule(), C->getType(),
629 C,
".compoundliteral",
nullptr,
630 llvm::GlobalVariable::NotThreadLocal,
632 emitter.finalize(GV);
638 static llvm::Constant *
640 llvm::Type *CommonElementType,
unsigned ArrayBound,
642 llvm::Constant *Filler) {
644 unsigned NonzeroLength = ArrayBound;
645 if (Elements.size() < NonzeroLength && Filler->isNullValue())
646 NonzeroLength = Elements.size();
647 if (NonzeroLength == Elements.size()) {
648 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
652 if (NonzeroLength == 0) {
653 return llvm::ConstantAggregateZero::get(
658 unsigned TrailingZeroes = ArrayBound - NonzeroLength;
659 if (TrailingZeroes >= 8) {
660 assert(Elements.size() >= NonzeroLength &&
661 "missing initializer for non-zero element");
665 if (CommonElementType && NonzeroLength >= 8) {
666 llvm::Constant *Initial = llvm::ConstantArray::get(
667 llvm::ArrayType::get(CommonElementType, NonzeroLength),
668 makeArrayRef(Elements).take_front(NonzeroLength));
670 Elements[0] = Initial;
672 Elements.resize(NonzeroLength + 1);
679 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
680 Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
681 CommonElementType =
nullptr;
682 }
else if (Elements.size() != ArrayBound) {
684 Elements.resize(ArrayBound, Filler);
685 if (Filler->getType() != CommonElementType)
686 CommonElementType =
nullptr;
690 if (CommonElementType)
691 return llvm::ConstantArray::get(
692 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
696 Types.reserve(Elements.size());
697 for (llvm::Constant *Elt : Elements)
698 Types.push_back(Elt->getType());
699 llvm::StructType *SType =
701 return llvm::ConstantStruct::get(SType, Elements);
708 class ConstExprEmitter :
709 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
712 llvm::LLVMContext &VMContext;
715 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
750 if (
const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
758 "Destination type is not union type!");
763 if (!C)
return nullptr;
765 auto destTy = ConvertType(destType);
766 if (C->getType() == destTy)
return C;
773 Types.push_back(C->getType());
774 unsigned CurSize = CGM.
getDataLayout().getTypeAllocSize(C->getType());
775 unsigned TotalSize = CGM.
getDataLayout().getTypeAllocSize(destTy);
777 assert(CurSize <= TotalSize &&
"Union size mismatch!");
778 if (
unsigned NumPadBytes = TotalSize - CurSize) {
781 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
783 Elts.push_back(llvm::UndefValue::get(Ty));
787 llvm::StructType *STy = llvm::StructType::get(VMContext, Types,
false);
788 return llvm::ConstantStruct::get(STy, Elts);
791 case CK_AddressSpaceConversion: {
793 if (!C)
return nullptr;
801 case CK_LValueToRValue:
802 case CK_AtomicToNonAtomic:
803 case CK_NonAtomicToAtomic:
805 case CK_ConstructorConversion:
806 return Visit(subExpr, destType);
808 case CK_IntToOCLSampler:
809 llvm_unreachable(
"global sampler variables are not generated");
811 case CK_Dependent: llvm_unreachable(
"saw dependent cast!");
813 case CK_BuiltinFnToFnPtr:
814 llvm_unreachable(
"builtin functions are handled elsewhere");
816 case CK_ReinterpretMemberPointer:
817 case CK_DerivedToBaseMemberPointer:
818 case CK_BaseToDerivedMemberPointer: {
820 if (!C)
return nullptr;
825 case CK_ObjCObjectLValueCast:
826 case CK_ARCProduceObject:
827 case CK_ARCConsumeObject:
828 case CK_ARCReclaimReturnedObject:
829 case CK_ARCExtendBlockObject:
830 case CK_CopyAndAutoreleaseBlockObject:
838 case CK_LValueBitCast:
839 case CK_NullToMemberPointer:
840 case CK_UserDefinedConversion:
841 case CK_CPointerToObjCPointerCast:
842 case CK_BlockPointerToObjCPointerCast:
843 case CK_AnyPointerToBlockPointerCast:
844 case CK_ArrayToPointerDecay:
845 case CK_FunctionToPointerDecay:
846 case CK_BaseToDerived:
847 case CK_DerivedToBase:
848 case CK_UncheckedDerivedToBase:
849 case CK_MemberPointerToBoolean:
851 case CK_FloatingRealToComplex:
852 case CK_FloatingComplexToReal:
853 case CK_FloatingComplexToBoolean:
854 case CK_FloatingComplexCast:
855 case CK_FloatingComplexToIntegralComplex:
856 case CK_IntegralRealToComplex:
857 case CK_IntegralComplexToReal:
858 case CK_IntegralComplexToBoolean:
859 case CK_IntegralComplexCast:
860 case CK_IntegralComplexToFloatingComplex:
861 case CK_PointerToIntegral:
862 case CK_PointerToBoolean:
863 case CK_NullToPointer:
864 case CK_IntegralCast:
865 case CK_BooleanToSignedIntegral:
866 case CK_IntegralToPointer:
867 case CK_IntegralToBoolean:
868 case CK_IntegralToFloating:
869 case CK_FloatingToIntegral:
870 case CK_FloatingToBoolean:
871 case CK_FloatingCast:
872 case CK_ZeroToOCLEvent:
873 case CK_ZeroToOCLQueue:
876 llvm_unreachable(
"Invalid CastKind");
880 return Visit(DAE->
getExpr(), T);
886 return Visit(DIE->
getExpr(), T);
902 assert(CAT &&
"can't emit array init for non-constant-bound array");
904 unsigned NumElements = CAT->getSize().getZExtValue();
908 unsigned NumInitableElts =
std::min(NumInitElements, NumElements);
910 QualType EltType = CAT->getElementType();
913 llvm::Constant *fillC =
nullptr;
922 if (fillC && fillC->isNullValue())
923 Elts.reserve(NumInitableElts + 1);
925 Elts.reserve(NumElements);
928 for (
unsigned i = 0; i < NumInitableElts; ++i) {
934 CommonElementType = C->getType();
935 else if (C->getType() != CommonElementType)
936 CommonElementType =
nullptr;
940 return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
945 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
955 return Visit(ILE->
getInit(0), T);
958 return EmitArrayInitialization(ILE, T);
961 return EmitRecordInitialization(ILE, T);
966 llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
970 llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(destType));
971 llvm::Type *ElemType = AType->getElementType();
974 unsigned NumElements = AType->getNumElements();
976 std::vector<llvm::Constant *> Elts;
977 Elts.reserve(NumElements);
979 QualType destElemType = destAT->getElementType();
981 if (
auto DataArray = dyn_cast<llvm::ConstantDataArray>(Base))
982 for (
unsigned i = 0; i != NumElements; ++i)
983 Elts.push_back(DataArray->getElementAsConstant(i));
984 else if (
auto Array = dyn_cast<llvm::ConstantArray>(Base))
985 for (
unsigned i = 0; i != NumElements; ++i)
986 Elts.push_back(Array->getOperand(i));
990 llvm::Constant *fillC =
nullptr;
992 if (!isa<NoInitExpr>(filler))
994 bool RewriteType = (fillC && fillC->getType() != ElemType);
996 for (
unsigned i = 0; i != NumElements; ++i) {
997 Expr *Init =
nullptr;
998 if (i < NumInitElements)
1003 else if (!Init || isa<NoInitExpr>(Init))
1005 else if (
InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1006 Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType);
1012 RewriteType |= (Elts[i]->getType() != ElemType);
1016 std::vector<llvm::Type *> Types;
1017 Types.reserve(NumElements);
1018 for (
unsigned i = 0; i != NumElements; ++i)
1019 Types.push_back(Elts[i]->getType());
1020 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
1022 return llvm::ConstantStruct::get(SType, Elts);
1025 return llvm::ConstantArray::get(AType, Elts);
1029 return ConstStructBuilder::BuildStruct(Emitter,
this,
1030 dyn_cast<llvm::ConstantStruct>(Base), Updater, destType);
1037 auto C = Visit(E->
getBase(), destType);
1038 if (!C)
return nullptr;
1039 return EmitDesignatedInitUpdater(C, E->
getUpdater(), destType);
1053 if (!RD->hasTrivialDestructor())
1060 assert(E->
getNumArgs() == 1 &&
"trivial ctor with > 1 argument");
1062 "trivial ctor has argument but isn't a copy/move ctor");
1066 "argument to copy ctor is of wrong type");
1068 return Visit(Arg, Ty);
1088 Str.resize(CAT->
getSize().getZExtValue(),
'\0');
1089 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
1104 bool ConstStructBuilder::Build(ConstExprEmitter *ExprEmitter,
1105 llvm::ConstantStruct *Base,
1107 assert(Base &&
"base expression should not be empty");
1112 const llvm::StructLayout *BaseLayout = CGM.
getDataLayout().getStructLayout(
1114 unsigned FieldNo = -1;
1115 unsigned ElementNo = 0;
1120 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1121 if (CXXRD->getNumBases())
1134 llvm::Constant *EltInit = Base->getOperand(ElementNo);
1140 BaseLayout->getElementOffsetInBits(ElementNo))
1145 Expr *Init =
nullptr;
1146 if (ElementNo < Updater->getNumInits())
1147 Init = Updater->
getInit(ElementNo);
1149 if (!Init || isa<NoInitExpr>(Init))
1151 else if (
InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1152 EltInit = ExprEmitter->EmitDesignatedInitUpdater(EltInit, ChildILE,
1164 else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1174 llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1175 AbstractState saved) {
1176 Abstract = saved.OldValue;
1178 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1179 "created a placeholder while doing an abstract emission?");
1188 auto state = pushAbstract();
1189 auto C = tryEmitPrivateForVarInit(D);
1190 return validateAndPopAbstract(C,
state);
1195 auto state = pushAbstract();
1196 auto C = tryEmitPrivate(E, destType);
1197 return validateAndPopAbstract(C,
state);
1202 auto state = pushAbstract();
1203 auto C = tryEmitPrivate(value, destType);
1204 return validateAndPopAbstract(C,
state);
1209 auto state = pushAbstract();
1210 auto C = tryEmitPrivate(E, destType);
1211 C = validateAndPopAbstract(C,
state);
1214 "internal error: could not emit constant value \"abstractly\"");
1223 auto state = pushAbstract();
1224 auto C = tryEmitPrivate(value, destType);
1225 C = validateAndPopAbstract(C,
state);
1228 "internal error: could not emit constant value \"abstractly\"");
1236 return markIfFailed(tryEmitPrivateForVarInit(D));
1242 initializeNonAbstract(destAddrSpace);
1243 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1249 initializeNonAbstract(destAddrSpace);
1250 auto C = tryEmitPrivateForMemory(value, destType);
1251 assert(C &&
"couldn't emit constant value non-abstractly?");
1256 assert(!Abstract &&
"cannot get current address for abstract constant");
1262 auto global =
new llvm::GlobalVariable(CGM.
getModule(), CGM.
Int8Ty,
true,
1263 llvm::GlobalValue::PrivateLinkage,
1267 llvm::GlobalVariable::NotThreadLocal,
1270 PlaceholderAddresses.push_back(std::make_pair(
nullptr, global));
1276 llvm::GlobalValue *placeholder) {
1277 assert(!PlaceholderAddresses.empty());
1278 assert(PlaceholderAddresses.back().first ==
nullptr);
1279 assert(PlaceholderAddresses.back().second == placeholder);
1280 PlaceholderAddresses.back().first = signal;
1284 struct ReplacePlaceholders {
1288 llvm::Constant *
Base;
1292 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1295 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1303 ReplacePlaceholders(
CodeGenModule &CGM, llvm::Constant *base,
1304 ArrayRef<std::pair<llvm::Constant*,
1305 llvm::GlobalVariable*>> addresses)
1306 : CGM(CGM),
Base(base),
1307 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1310 void replaceInInitializer(llvm::Constant *init) {
1312 BaseValueTy = init->getType();
1315 Indices.push_back(0);
1316 IndexValues.push_back(
nullptr);
1319 findLocations(init);
1322 assert(IndexValues.size() == Indices.size() &&
"mismatch");
1323 assert(Indices.size() == 1 &&
"didn't pop all indices");
1326 assert(Locations.size() == PlaceholderAddresses.size() &&
1327 "missed a placeholder?");
1333 for (
auto &entry : Locations) {
1334 assert(entry.first->getParent() ==
nullptr &&
"not a placeholder!");
1335 entry.first->replaceAllUsesWith(entry.second);
1336 entry.first->eraseFromParent();
1341 void findLocations(llvm::Constant *init) {
1343 if (
auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1344 for (
unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1345 Indices.push_back(i);
1346 IndexValues.push_back(
nullptr);
1348 findLocations(agg->getOperand(i));
1350 IndexValues.pop_back();
1358 auto it = PlaceholderAddresses.find(init);
1359 if (it != PlaceholderAddresses.end()) {
1360 setLocation(it->second);
1365 if (
auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1366 init =
expr->getOperand(0);
1373 void setLocation(llvm::GlobalVariable *placeholder) {
1374 assert(Locations.find(placeholder) == Locations.end() &&
1375 "already found location for placeholder!");
1380 assert(Indices.size() == IndexValues.size());
1381 for (
size_t i = Indices.size() - 1; i !=
size_t(-1); --i) {
1382 if (IndexValues[i]) {
1384 for (
size_t j = 0; j != i + 1; ++j) {
1385 assert(IndexValues[j] &&
1386 isa<llvm::ConstantInt>(IndexValues[j]) &&
1387 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1394 IndexValues[i] = llvm::ConstantInt::get(CGM.
Int32Ty, Indices[i]);
1399 llvm::Constant *location =
1400 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1402 location = llvm::ConstantExpr::getBitCast(location,
1403 placeholder->getType());
1405 Locations.insert({placeholder, location});
1411 assert(InitializedNonAbstract &&
1412 "finalizing emitter that was used for abstract emission?");
1413 assert(!Finalized &&
"finalizing emitter multiple times");
1414 assert(global->getInitializer());
1419 if (!PlaceholderAddresses.empty()) {
1420 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1421 .replaceInInitializer(global->getInitializer());
1422 PlaceholderAddresses.clear();
1427 assert((!InitializedNonAbstract || Finalized || Failed) &&
1428 "not finalized after being initialized for non-abstract emission");
1429 assert(PlaceholderAddresses.empty() &&
"unhandled placeholders");
1448 dyn_cast_or_null<CXXConstructExpr>(D.
getInit())) {
1460 return tryEmitPrivateForMemory(*value, destType);
1473 assert(E &&
"No initializer to emit");
1477 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1478 return (C ? emitForMemory(C, destType) :
nullptr);
1484 auto C = tryEmitAbstract(E, nonMemoryDestType);
1485 return (C ? emitForMemory(C, destType) :
nullptr);
1492 auto C = tryEmitAbstract(value, nonMemoryDestType);
1493 return (C ? emitForMemory(C, destType) :
nullptr);
1499 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1500 return (C ? emitForMemory(C, destType) :
nullptr);
1506 auto C = tryEmitPrivate(value, nonMemoryDestType);
1507 return (C ? emitForMemory(C, destType) :
nullptr);
1515 QualType destValueType = AT->getValueType();
1516 C = emitForMemory(CGM, C, destValueType);
1520 if (innerSize == outerSize)
1523 assert(innerSize < outerSize &&
"emitted over-large constant for atomic");
1524 llvm::Constant *elts[] = {
1526 llvm::ConstantAggregateZero::get(
1527 llvm::ArrayType::get(CGM.
Int8Ty, (outerSize - innerSize) / 8))
1529 return llvm::ConstantStruct::getAnon(elts);
1533 if (C->getType()->isIntegerTy(1)) {
1535 return llvm::ConstantExpr::getZExt(C, boolTy);
1545 bool Success =
false;
1554 C = tryEmitPrivate(Result.
Val, destType);
1556 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1562 return getTargetCodeGenInfo().getNullPointer(*
this, T, QT);
1568 struct ConstantLValue {
1569 llvm::Constant *
Value;
1570 bool HasOffsetApplied;
1572 ConstantLValue(llvm::Constant *value,
1573 bool hasOffsetApplied =
false)
1574 :
Value(value), HasOffsetApplied(
false) {}
1581 class ConstantLValueEmitter :
public ConstStmtVisitor<ConstantLValueEmitter,
1594 : CGM(emitter.
CGM), Emitter(emitter),
Value(value), DestType(destType) {}
1596 llvm::Constant *tryEmit();
1599 llvm::Constant *tryEmitAbsolute(
llvm::Type *destTy);
1602 ConstantLValue VisitStmt(
const Stmt *S) {
return nullptr; }
1609 ConstantLValue VisitCallExpr(
const CallExpr *E);
1610 ConstantLValue VisitBlockExpr(
const BlockExpr *E);
1613 ConstantLValue VisitMaterializeTemporaryExpr(
1616 bool hasNonZeroOffset()
const {
1621 llvm::Constant *getOffset() {
1622 return llvm::ConstantInt::get(CGM.
Int64Ty,
1627 llvm::Constant *applyOffset(llvm::Constant *C) {
1628 if (!hasNonZeroOffset())
1632 unsigned AS = origPtrTy->getPointerAddressSpace();
1634 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1635 C = llvm::ConstantExpr::getGetElementPtr(CGM.
Int8Ty, C, getOffset());
1636 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1643 llvm::Constant *ConstantLValueEmitter::tryEmit() {
1651 assert(!hasNonZeroOffset() &&
"offset on array initializer");
1653 return ConstExprEmitter(Emitter).Visit(
expr, DestType);
1664 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1669 return tryEmitAbsolute(destTy);
1673 ConstantLValue result = tryEmitBase(base);
1676 llvm::Constant *value = result.Value;
1677 if (!value)
return nullptr;
1680 if (!result.HasOffsetApplied) {
1681 value = applyOffset(value);
1686 if (isa<llvm::PointerType>(destTy))
1687 return llvm::ConstantExpr::getPointerCast(value, destTy);
1689 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1695 ConstantLValueEmitter::tryEmitAbsolute(
llvm::Type *destTy) {
1696 auto offset = getOffset();
1699 if (
auto destPtrTy = cast<llvm::PointerType>(destTy)) {
1700 if (
Value.isNullPointer()) {
1708 auto intptrTy = CGM.
getDataLayout().getIntPtrType(destPtrTy);
1709 llvm::Constant *C = offset;
1710 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1712 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1722 auto C = getOffset();
1723 C = llvm::ConstantExpr::getIntegerCast(C, destTy,
false);
1731 if (D->hasAttr<WeakRefAttr>())
1734 if (
auto FD = dyn_cast<FunctionDecl>(D))
1737 if (
auto VD = dyn_cast<VarDecl>(D)) {
1739 if (!VD->hasLocalStorage()) {
1740 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1743 if (VD->isLocalVarDecl()) {
1754 return Visit(base.
get<
const Expr*>());
1759 return tryEmitGlobalCompoundLiteral(CGM, Emitter.
CGF, E);
1763 ConstantLValueEmitter::VisitStringLiteral(
const StringLiteral *E) {
1768 ConstantLValueEmitter::VisitObjCEncodeExpr(
const ObjCEncodeExpr *E) {
1779 ConstantLValueEmitter::VisitPredefinedExpr(
const PredefinedExpr *E) {
1780 if (
auto CGF = Emitter.
CGF) {
1782 return cast<ConstantAddress>(Res.
getAddress());
1794 ConstantLValueEmitter::VisitAddrLabelExpr(
const AddrLabelExpr *E) {
1795 assert(Emitter.
CGF &&
"Invalid address of label expression outside function");
1797 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1803 ConstantLValueEmitter::VisitCallExpr(
const CallExpr *E) {
1805 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1806 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1810 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1819 ConstantLValueEmitter::VisitBlockExpr(
const BlockExpr *E) {
1820 StringRef functionName;
1821 if (
auto CGF = Emitter.
CGF)
1822 functionName = CGF->
CurFn->getName();
1824 functionName =
"global";
1830 ConstantLValueEmitter::VisitCXXTypeidExpr(
const CXXTypeidExpr *E) {
1840 ConstantLValueEmitter::VisitCXXUuidofExpr(
const CXXUuidofExpr *E) {
1845 ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1859 llvm_unreachable(
"Constant expressions should be initialized.");
1861 return ConstantLValueEmitter(*
this, Value, DestType).tryEmit();
1873 llvm::StructType *STy =
1874 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1875 return llvm::ConstantStruct::get(STy, Complex);
1878 const llvm::APFloat &Init = Value.
getFloat();
1879 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
1883 Init.bitcastToAPInt());
1896 llvm::StructType *STy =
1897 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1898 return llvm::ConstantStruct::get(STy, Complex);
1904 for (
unsigned I = 0; I != NumElts; ++I) {
1911 llvm_unreachable(
"unsupported vector element type");
1913 return llvm::ConstantVector::get(Inits);
1918 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->
getType());
1919 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->
getType());
1920 if (!LHS || !RHS)
return nullptr;
1924 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.
IntPtrTy);
1925 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.
IntPtrTy);
1926 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1931 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1935 return ConstStructBuilder::BuildStruct(*
this, Value, DestType);
1943 llvm::Constant *Filler =
nullptr;
1953 if (Filler && Filler->isNullValue())
1954 Elts.reserve(NumInitElts + 1);
1956 Elts.reserve(NumElements);
1959 for (
unsigned I = 0; I < NumInitElts; ++I) {
1960 llvm::Constant *C = tryEmitPrivateForMemory(
1962 if (!C)
return nullptr;
1965 CommonElementType = C->getType();
1966 else if (C->getType() != CommonElementType)
1967 CommonElementType =
nullptr;
1971 return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
1977 llvm_unreachable(
"Unknown APValue kind");
1982 return EmittedCompoundLiterals.lookup(E);
1987 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
1989 assert(Ok &&
"CLE has already been emitted!");
1994 assert(E->
isFileScope() &&
"not a file-scope compound literal expr");
1995 return tryEmitGlobalCompoundLiteral(*
this,
nullptr, E);
2005 if (
const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2006 return getCXXABI().EmitMemberFunctionPointer(method);
2009 uint64_t fieldOffset = getContext().getFieldOffset(decl);
2010 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2011 return getCXXABI().EmitMemberDataPointer(type, chars);
2020 bool asCompleteObject) {
2022 llvm::StructType *structure =
2026 unsigned numElements = structure->getNumElements();
2027 std::vector<llvm::Constant *> elements(numElements);
2032 for (
const auto &I : CXXR->bases()) {
2033 if (I.isVirtual()) {
2040 cast<CXXRecordDecl>(I.getType()->castAs<
RecordType>()->getDecl());
2049 llvm::Type *baseType = structure->getElementType(fieldIndex);
2055 for (
const auto *Field : record->
fields()) {
2068 if (FieldRD->findFirstNamedDataMember())
2074 if (CXXR && asCompleteObject) {
2075 for (
const auto &I : CXXR->vbases()) {
2077 cast<CXXRecordDecl>(I.getType()->castAs<
RecordType>()->getDecl());
2086 if (elements[fieldIndex])
continue;
2088 llvm::Type *baseType = structure->getElementType(fieldIndex);
2094 for (
unsigned i = 0; i != numElements; ++i) {
2096 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2099 return llvm::ConstantStruct::get(structure, elements);
2110 return llvm::Constant::getNullValue(baseType);
2123 return getNullPointer(
2124 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2126 if (getTypes().isZeroInitializable(T))
2127 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2130 llvm::ArrayType *ATy =
2131 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2135 llvm::Constant *Element =
2137 unsigned NumElements = CAT->
getSize().getZExtValue();
2139 return llvm::ConstantArray::get(ATy, Array);
2146 "Should only see pointers to data members here!");
const llvm::DataLayout & getDataLayout() 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.
virtual llvm::Constant * EmitMemberPointer(const APValue &MP, QualType MPT)
Create a member pointer for the given member pointer constant.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
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.
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
bool isMemberDataPointerType() const
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.
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 Expr * getResultExpr() const
The generic selection's result expression.
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>'.
unsigned getCharAlign() const
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
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]).
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Address getAddress() const
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
unsigned getArraySize() const
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
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
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::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
IgnoreParenCasts - Ignore parentheses and casts.
ObjCStringLiteral, used for Objective-C string literals i.e.
field_iterator field_begin() const
unsigned getBitWidthValue(const ASTContext &Ctx) const
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
APSInt & getComplexIntReal()
llvm::GlobalValue * getCurrentAddrPrivate()
Get the address of the current location.
A default argument (C++ [dcl.fct.default]).
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
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
const TargetCodeGenInfo & getTargetCodeGenInfo()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
APValue & getArrayFiller()
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.
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 ...
Expr - 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.
RecordDecl * getDecl() const
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.
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
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. ...
static QualType getNonMemoryType(CodeGenModule &CGM, QualType type)
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...
IdentType getIdentType() const
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
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
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating '\0' character...
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.
CharUnits getSize() const
getSize - Get the record size in characters.
[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
const Expr * getExpr() const
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.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
unsigned kind
All of the diagnostics that can be emitted by the frontend.
unsigned getVirtualBaseIndex(const CXXRecordDecl *base) const
Return the LLVM field index corresponding to the given virtual base.
LValue EmitPredefinedLValue(const PredefinedExpr *E)
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
__DEVICE__ int max(int __a, int __b)
llvm::Constant * tryEmitAbstractForMemory(const Expr *E, QualType T)
__DEVICE__ int min(int __a, int __b)
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
LValue - This represents an lvalue references.
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
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
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.
CharUnits & getLValueOffset()
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
unsigned getVectorLength() const