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,
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::Constant *
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::Constant *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()) {
754 if (
const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
762 "Destination type is not union type!");
767 if (!C)
return nullptr;
769 auto destTy = ConvertType(destType);
770 if (C->getType() == destTy)
return C;
777 Types.push_back(C->getType());
778 unsigned CurSize = CGM.
getDataLayout().getTypeAllocSize(C->getType());
779 unsigned TotalSize = CGM.
getDataLayout().getTypeAllocSize(destTy);
781 assert(CurSize <= TotalSize &&
"Union size mismatch!");
782 if (
unsigned NumPadBytes = TotalSize - CurSize) {
785 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
787 Elts.push_back(llvm::UndefValue::get(Ty));
791 llvm::StructType *STy = llvm::StructType::get(VMContext, Types,
false);
792 return llvm::ConstantStruct::get(STy, Elts);
795 case CK_AddressSpaceConversion: {
797 if (!C)
return nullptr;
805 case CK_LValueToRValue:
806 case CK_AtomicToNonAtomic:
807 case CK_NonAtomicToAtomic:
809 case CK_ConstructorConversion:
810 return Visit(subExpr, destType);
812 case CK_IntToOCLSampler:
813 llvm_unreachable(
"global sampler variables are not generated");
815 case CK_Dependent: llvm_unreachable(
"saw dependent cast!");
817 case CK_BuiltinFnToFnPtr:
818 llvm_unreachable(
"builtin functions are handled elsewhere");
820 case CK_ReinterpretMemberPointer:
821 case CK_DerivedToBaseMemberPointer:
822 case CK_BaseToDerivedMemberPointer: {
824 if (!C)
return nullptr;
829 case CK_ObjCObjectLValueCast:
830 case CK_ARCProduceObject:
831 case CK_ARCConsumeObject:
832 case CK_ARCReclaimReturnedObject:
833 case CK_ARCExtendBlockObject:
834 case CK_CopyAndAutoreleaseBlockObject:
842 case CK_LValueBitCast:
843 case CK_NullToMemberPointer:
844 case CK_UserDefinedConversion:
845 case CK_CPointerToObjCPointerCast:
846 case CK_BlockPointerToObjCPointerCast:
847 case CK_AnyPointerToBlockPointerCast:
848 case CK_ArrayToPointerDecay:
849 case CK_FunctionToPointerDecay:
850 case CK_BaseToDerived:
851 case CK_DerivedToBase:
852 case CK_UncheckedDerivedToBase:
853 case CK_MemberPointerToBoolean:
855 case CK_FloatingRealToComplex:
856 case CK_FloatingComplexToReal:
857 case CK_FloatingComplexToBoolean:
858 case CK_FloatingComplexCast:
859 case CK_FloatingComplexToIntegralComplex:
860 case CK_IntegralRealToComplex:
861 case CK_IntegralComplexToReal:
862 case CK_IntegralComplexToBoolean:
863 case CK_IntegralComplexCast:
864 case CK_IntegralComplexToFloatingComplex:
865 case CK_PointerToIntegral:
866 case CK_PointerToBoolean:
867 case CK_NullToPointer:
868 case CK_IntegralCast:
869 case CK_BooleanToSignedIntegral:
870 case CK_IntegralToPointer:
871 case CK_IntegralToBoolean:
872 case CK_IntegralToFloating:
873 case CK_FloatingToIntegral:
874 case CK_FloatingToBoolean:
875 case CK_FloatingCast:
876 case CK_FixedPointCast:
877 case CK_FixedPointToBoolean:
878 case CK_ZeroToOCLOpaqueType:
881 llvm_unreachable(
"Invalid CastKind");
885 return Visit(DAE->
getExpr(), T);
891 return Visit(DIE->
getExpr(), T);
907 assert(CAT &&
"can't emit array init for non-constant-bound array");
909 unsigned NumElements = CAT->getSize().getZExtValue();
913 unsigned NumInitableElts =
std::min(NumInitElements, NumElements);
915 QualType EltType = CAT->getElementType();
918 llvm::Constant *fillC =
nullptr;
927 if (fillC && fillC->isNullValue())
928 Elts.reserve(NumInitableElts + 1);
930 Elts.reserve(NumElements);
933 for (
unsigned i = 0; i < NumInitableElts; ++i) {
939 CommonElementType = C->getType();
940 else if (C->getType() != CommonElementType)
941 CommonElementType =
nullptr;
945 return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
950 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
960 return Visit(ILE->
getInit(0), T);
963 return EmitArrayInitialization(ILE, T);
966 return EmitRecordInitialization(ILE, T);
971 llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
975 llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(destType));
976 llvm::Type *ElemType = AType->getElementType();
979 unsigned NumElements = AType->getNumElements();
981 std::vector<llvm::Constant *> Elts;
982 Elts.reserve(NumElements);
984 QualType destElemType = destAT->getElementType();
986 if (
auto DataArray = dyn_cast<llvm::ConstantDataArray>(Base))
987 for (
unsigned i = 0; i != NumElements; ++i)
988 Elts.push_back(DataArray->getElementAsConstant(i));
989 else if (
auto Array = dyn_cast<llvm::ConstantArray>(Base))
990 for (
unsigned i = 0; i != NumElements; ++i)
991 Elts.push_back(Array->getOperand(i));
995 llvm::Constant *fillC =
nullptr;
997 if (!isa<NoInitExpr>(filler))
999 bool RewriteType = (fillC && fillC->getType() != ElemType);
1001 for (
unsigned i = 0; i != NumElements; ++i) {
1002 Expr *Init =
nullptr;
1003 if (i < NumInitElements)
1008 else if (!Init || isa<NoInitExpr>(Init))
1010 else if (
InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1011 Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType);
1017 RewriteType |= (Elts[i]->getType() != ElemType);
1021 std::vector<llvm::Type *> Types;
1022 Types.reserve(NumElements);
1023 for (
unsigned i = 0; i != NumElements; ++i)
1024 Types.push_back(Elts[i]->getType());
1025 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
1027 return llvm::ConstantStruct::get(SType, Elts);
1030 return llvm::ConstantArray::get(AType, Elts);
1034 return ConstStructBuilder::BuildStruct(Emitter,
this, Base, Updater,
1042 auto C = Visit(E->
getBase(), destType);
1043 if (!C)
return nullptr;
1044 return EmitDesignatedInitUpdater(C, E->
getUpdater(), destType);
1058 if (!RD->hasTrivialDestructor())
1065 assert(E->
getNumArgs() == 1 &&
"trivial ctor with > 1 argument");
1067 "trivial ctor has argument but isn't a copy/move ctor");
1071 "argument to copy ctor is of wrong type");
1073 return Visit(Arg, Ty);
1093 Str.resize(CAT->
getSize().getZExtValue(),
'\0');
1094 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
1109 bool ConstStructBuilder::Build(ConstExprEmitter *ExprEmitter,
1110 llvm::Constant *Base,
1112 assert(Base &&
"base expression should not be empty");
1117 const llvm::StructLayout *BaseLayout = CGM.
getDataLayout().getStructLayout(
1118 cast<llvm::StructType>(Base->getType()));
1119 unsigned FieldNo = -1;
1120 unsigned ElementNo = 0;
1125 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1126 if (CXXRD->getNumBases())
1139 llvm::Constant *EltInit = Base->getAggregateElement(ElementNo);
1145 BaseLayout->getElementOffsetInBits(ElementNo))
1150 Expr *Init =
nullptr;
1151 if (ElementNo < Updater->getNumInits())
1152 Init = Updater->
getInit(ElementNo);
1154 if (!Init || isa<NoInitExpr>(Init))
1156 else if (
InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1157 EltInit = ExprEmitter->EmitDesignatedInitUpdater(EltInit, ChildILE,
1169 else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1179 llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1180 AbstractState saved) {
1181 Abstract = saved.OldValue;
1183 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1184 "created a placeholder while doing an abstract emission?");
1193 auto state = pushAbstract();
1194 auto C = tryEmitPrivateForVarInit(D);
1195 return validateAndPopAbstract(C,
state);
1200 auto state = pushAbstract();
1201 auto C = tryEmitPrivate(E, destType);
1202 return validateAndPopAbstract(C,
state);
1207 auto state = pushAbstract();
1208 auto C = tryEmitPrivate(value, destType);
1209 return validateAndPopAbstract(C,
state);
1214 auto state = pushAbstract();
1215 auto C = tryEmitPrivate(E, destType);
1216 C = validateAndPopAbstract(C,
state);
1219 "internal error: could not emit constant value \"abstractly\"");
1228 auto state = pushAbstract();
1229 auto C = tryEmitPrivate(value, destType);
1230 C = validateAndPopAbstract(C,
state);
1233 "internal error: could not emit constant value \"abstractly\"");
1241 return markIfFailed(tryEmitPrivateForVarInit(D));
1247 initializeNonAbstract(destAddrSpace);
1248 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1254 initializeNonAbstract(destAddrSpace);
1255 auto C = tryEmitPrivateForMemory(value, destType);
1256 assert(C &&
"couldn't emit constant value non-abstractly?");
1261 assert(!Abstract &&
"cannot get current address for abstract constant");
1267 auto global =
new llvm::GlobalVariable(CGM.
getModule(), CGM.
Int8Ty,
true,
1268 llvm::GlobalValue::PrivateLinkage,
1272 llvm::GlobalVariable::NotThreadLocal,
1275 PlaceholderAddresses.push_back(std::make_pair(
nullptr, global));
1281 llvm::GlobalValue *placeholder) {
1282 assert(!PlaceholderAddresses.empty());
1283 assert(PlaceholderAddresses.back().first ==
nullptr);
1284 assert(PlaceholderAddresses.back().second == placeholder);
1285 PlaceholderAddresses.back().first = signal;
1289 struct ReplacePlaceholders {
1293 llvm::Constant *
Base;
1297 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1300 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1308 ReplacePlaceholders(
CodeGenModule &CGM, llvm::Constant *base,
1309 ArrayRef<std::pair<llvm::Constant*,
1310 llvm::GlobalVariable*>> addresses)
1311 : CGM(CGM),
Base(base),
1312 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1315 void replaceInInitializer(llvm::Constant *init) {
1317 BaseValueTy = init->getType();
1320 Indices.push_back(0);
1321 IndexValues.push_back(
nullptr);
1324 findLocations(init);
1327 assert(IndexValues.size() == Indices.size() &&
"mismatch");
1328 assert(Indices.size() == 1 &&
"didn't pop all indices");
1331 assert(Locations.size() == PlaceholderAddresses.size() &&
1332 "missed a placeholder?");
1338 for (
auto &entry : Locations) {
1339 assert(entry.first->getParent() ==
nullptr &&
"not a placeholder!");
1340 entry.first->replaceAllUsesWith(entry.second);
1341 entry.first->eraseFromParent();
1346 void findLocations(llvm::Constant *init) {
1348 if (
auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1349 for (
unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1350 Indices.push_back(i);
1351 IndexValues.push_back(
nullptr);
1353 findLocations(agg->getOperand(i));
1355 IndexValues.pop_back();
1363 auto it = PlaceholderAddresses.find(init);
1364 if (it != PlaceholderAddresses.end()) {
1365 setLocation(it->second);
1370 if (
auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1371 init =
expr->getOperand(0);
1378 void setLocation(llvm::GlobalVariable *placeholder) {
1379 assert(Locations.find(placeholder) == Locations.end() &&
1380 "already found location for placeholder!");
1385 assert(Indices.size() == IndexValues.size());
1386 for (
size_t i = Indices.size() - 1; i !=
size_t(-1); --i) {
1387 if (IndexValues[i]) {
1389 for (
size_t j = 0; j != i + 1; ++j) {
1390 assert(IndexValues[j] &&
1391 isa<llvm::ConstantInt>(IndexValues[j]) &&
1392 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1399 IndexValues[i] = llvm::ConstantInt::get(CGM.
Int32Ty, Indices[i]);
1404 llvm::Constant *location =
1405 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1407 location = llvm::ConstantExpr::getBitCast(location,
1408 placeholder->getType());
1410 Locations.insert({placeholder, location});
1416 assert(InitializedNonAbstract &&
1417 "finalizing emitter that was used for abstract emission?");
1418 assert(!Finalized &&
"finalizing emitter multiple times");
1419 assert(global->getInitializer());
1424 if (!PlaceholderAddresses.empty()) {
1425 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1426 .replaceInInitializer(global->getInitializer());
1427 PlaceholderAddresses.clear();
1432 assert((!InitializedNonAbstract || Finalized || Failed) &&
1433 "not finalized after being initialized for non-abstract emission");
1434 assert(PlaceholderAddresses.empty() &&
"unhandled placeholders");
1453 dyn_cast_or_null<CXXConstructExpr>(D.
getInit())) {
1458 InConstantContext =
true;
1466 return tryEmitPrivateForMemory(*value, destType);
1479 assert(E &&
"No initializer to emit");
1483 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1484 return (C ? emitForMemory(C, destType) :
nullptr);
1490 auto C = tryEmitAbstract(E, nonMemoryDestType);
1491 return (C ? emitForMemory(C, destType) :
nullptr);
1498 auto C = tryEmitAbstract(value, nonMemoryDestType);
1499 return (C ? emitForMemory(C, destType) :
nullptr);
1505 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1506 return (C ? emitForMemory(C, destType) :
nullptr);
1512 auto C = tryEmitPrivate(value, nonMemoryDestType);
1513 return (C ? emitForMemory(C, destType) :
nullptr);
1521 QualType destValueType = AT->getValueType();
1522 C = emitForMemory(CGM, C, destValueType);
1526 if (innerSize == outerSize)
1529 assert(innerSize < outerSize &&
"emitted over-large constant for atomic");
1530 llvm::Constant *elts[] = {
1532 llvm::ConstantAggregateZero::get(
1533 llvm::ArrayType::get(CGM.
Int8Ty, (outerSize - innerSize) / 8))
1535 return llvm::ConstantStruct::getAnon(elts);
1539 if (C->getType()->isIntegerTy(1)) {
1541 return llvm::ConstantExpr::getZExt(C, boolTy);
1551 bool Success =
false;
1560 C = tryEmitPrivate(Result.
Val, destType);
1562 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1568 return getTargetCodeGenInfo().getNullPointer(*
this, T, QT);
1574 struct ConstantLValue {
1575 llvm::Constant *
Value;
1576 bool HasOffsetApplied;
1578 ConstantLValue(llvm::Constant *value,
1579 bool hasOffsetApplied =
false)
1580 :
Value(value), HasOffsetApplied(
false) {}
1587 class ConstantLValueEmitter :
public ConstStmtVisitor<ConstantLValueEmitter,
1600 : CGM(emitter.
CGM), Emitter(emitter),
Value(value), DestType(destType) {}
1602 llvm::Constant *tryEmit();
1605 llvm::Constant *tryEmitAbsolute(
llvm::Type *destTy);
1608 ConstantLValue VisitStmt(
const Stmt *S) {
return nullptr; }
1609 ConstantLValue VisitConstantExpr(
const ConstantExpr *E);
1616 ConstantLValue VisitCallExpr(
const CallExpr *E);
1617 ConstantLValue VisitBlockExpr(
const BlockExpr *E);
1620 ConstantLValue VisitMaterializeTemporaryExpr(
1623 bool hasNonZeroOffset()
const {
1628 llvm::Constant *getOffset() {
1629 return llvm::ConstantInt::get(CGM.
Int64Ty,
1634 llvm::Constant *applyOffset(llvm::Constant *C) {
1635 if (!hasNonZeroOffset())
1639 unsigned AS = origPtrTy->getPointerAddressSpace();
1641 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1642 C = llvm::ConstantExpr::getGetElementPtr(CGM.
Int8Ty, C, getOffset());
1643 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1650 llvm::Constant *ConstantLValueEmitter::tryEmit() {
1658 assert(!hasNonZeroOffset() &&
"offset on array initializer");
1660 return ConstExprEmitter(Emitter).Visit(
expr, DestType);
1671 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1676 return tryEmitAbsolute(destTy);
1680 ConstantLValue result = tryEmitBase(base);
1683 llvm::Constant *value = result.Value;
1684 if (!value)
return nullptr;
1687 if (!result.HasOffsetApplied) {
1688 value = applyOffset(value);
1693 if (isa<llvm::PointerType>(destTy))
1694 return llvm::ConstantExpr::getPointerCast(value, destTy);
1696 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1702 ConstantLValueEmitter::tryEmitAbsolute(
llvm::Type *destTy) {
1703 auto offset = getOffset();
1706 if (
auto destPtrTy = cast<llvm::PointerType>(destTy)) {
1707 if (
Value.isNullPointer()) {
1715 auto intptrTy = CGM.
getDataLayout().getIntPtrType(destPtrTy);
1716 llvm::Constant *C = offset;
1717 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1719 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1729 auto C = getOffset();
1730 C = llvm::ConstantExpr::getIntegerCast(C, destTy,
false);
1738 if (D->hasAttr<WeakRefAttr>())
1741 if (
auto FD = dyn_cast<FunctionDecl>(D))
1744 if (
auto VD = dyn_cast<VarDecl>(D)) {
1746 if (!VD->hasLocalStorage()) {
1747 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1750 if (VD->isLocalVarDecl()) {
1761 return Visit(base.
get<
const Expr*>());
1765 ConstantLValueEmitter::VisitConstantExpr(
const ConstantExpr *E) {
1771 return tryEmitGlobalCompoundLiteral(CGM, Emitter.
CGF, E);
1775 ConstantLValueEmitter::VisitStringLiteral(
const StringLiteral *E) {
1780 ConstantLValueEmitter::VisitObjCEncodeExpr(
const ObjCEncodeExpr *E) {
1791 ConstantLValueEmitter::VisitPredefinedExpr(
const PredefinedExpr *E) {
1792 if (
auto CGF = Emitter.
CGF) {
1794 return cast<ConstantAddress>(Res.
getAddress());
1806 ConstantLValueEmitter::VisitAddrLabelExpr(
const AddrLabelExpr *E) {
1807 assert(Emitter.
CGF &&
"Invalid address of label expression outside function");
1809 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1815 ConstantLValueEmitter::VisitCallExpr(
const CallExpr *E) {
1817 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1818 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1822 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1831 ConstantLValueEmitter::VisitBlockExpr(
const BlockExpr *E) {
1832 StringRef functionName;
1833 if (
auto CGF = Emitter.
CGF)
1834 functionName = CGF->
CurFn->getName();
1836 functionName =
"global";
1842 ConstantLValueEmitter::VisitCXXTypeidExpr(
const CXXTypeidExpr *E) {
1852 ConstantLValueEmitter::VisitCXXUuidofExpr(
const CXXUuidofExpr *E) {
1857 ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1871 llvm_unreachable(
"Constant expressions should be initialized.");
1873 return ConstantLValueEmitter(*
this, Value, DestType).tryEmit();
1885 llvm::StructType *STy =
1886 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1887 return llvm::ConstantStruct::get(STy, Complex);
1890 const llvm::APFloat &Init = Value.
getFloat();
1891 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
1895 Init.bitcastToAPInt());
1908 llvm::StructType *STy =
1909 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1910 return llvm::ConstantStruct::get(STy, Complex);
1916 for (
unsigned I = 0; I != NumElts; ++I) {
1923 llvm_unreachable(
"unsupported vector element type");
1925 return llvm::ConstantVector::get(Inits);
1930 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->
getType());
1931 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->
getType());
1932 if (!LHS || !RHS)
return nullptr;
1936 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.
IntPtrTy);
1937 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.
IntPtrTy);
1938 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1943 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1947 return ConstStructBuilder::BuildStruct(*
this, Value, DestType);
1955 llvm::Constant *Filler =
nullptr;
1965 if (Filler && Filler->isNullValue())
1966 Elts.reserve(NumInitElts + 1);
1968 Elts.reserve(NumElements);
1971 for (
unsigned I = 0; I < NumInitElts; ++I) {
1972 llvm::Constant *C = tryEmitPrivateForMemory(
1974 if (!C)
return nullptr;
1977 CommonElementType = C->getType();
1978 else if (C->getType() != CommonElementType)
1979 CommonElementType =
nullptr;
1985 if (CAT ==
nullptr && CommonElementType ==
nullptr && !NumInitElts) {
1988 llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
1990 return llvm::ConstantAggregateZero::get(AType);
1993 return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
1999 llvm_unreachable(
"Unknown APValue kind");
2004 return EmittedCompoundLiterals.lookup(E);
2009 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2011 assert(Ok &&
"CLE has already been emitted!");
2016 assert(E->
isFileScope() &&
"not a file-scope compound literal expr");
2017 return tryEmitGlobalCompoundLiteral(*
this,
nullptr, E);
2027 if (
const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2028 return getCXXABI().EmitMemberFunctionPointer(method);
2031 uint64_t fieldOffset = getContext().getFieldOffset(decl);
2032 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2033 return getCXXABI().EmitMemberDataPointer(type, chars);
2042 bool asCompleteObject) {
2044 llvm::StructType *structure =
2048 unsigned numElements = structure->getNumElements();
2049 std::vector<llvm::Constant *> elements(numElements);
2054 for (
const auto &I : CXXR->bases()) {
2055 if (I.isVirtual()) {
2062 cast<CXXRecordDecl>(I.getType()->castAs<
RecordType>()->getDecl());
2071 llvm::Type *baseType = structure->getElementType(fieldIndex);
2077 for (
const auto *Field : record->
fields()) {
2090 if (FieldRD->findFirstNamedDataMember())
2096 if (CXXR && asCompleteObject) {
2097 for (
const auto &I : CXXR->vbases()) {
2099 cast<CXXRecordDecl>(I.getType()->castAs<
RecordType>()->getDecl());
2108 if (elements[fieldIndex])
continue;
2110 llvm::Type *baseType = structure->getElementType(fieldIndex);
2116 for (
unsigned i = 0; i != numElements; ++i) {
2118 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2121 return llvm::ConstantStruct::get(structure, elements);
2132 return llvm::Constant::getNullValue(baseType);
2145 return getNullPointer(
2146 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2148 if (getTypes().isZeroInitializable(T))
2149 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2152 llvm::ArrayType *ATy =
2153 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2157 llvm::Constant *Element =
2159 unsigned NumElements = CAT->
getSize().getZExtValue();
2161 return llvm::ConstantArray::get(ATy, Array);
2168 "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.
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.
__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 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 ...
IdentKind getIdentKind() const
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.
ConstantExpr - An expression that occurs in a constant context.
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.
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)
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. ...
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...
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
Return the number of arguments to the constructor call.
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