29 #include "llvm/ADT/Hashing.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/MDBuilder.h"
35 #include "llvm/Support/ConvertUTF.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Transforms/Utils/SanitizerStats.h"
42 using namespace clang;
43 using namespace CodeGen;
50 unsigned addressSpace =
51 cast<llvm::PointerType>(value->getType())->getAddressSpace();
55 destType = llvm::Type::getInt8PtrTy(
getLLVMContext(), addressSpace);
57 if (value->getType() == destType)
return value;
66 bool CastToDefaultAddrSpace) {
80 Ty->getPointerTo(DestAddrSpace),
true);
94 return Builder.CreateAlloca(Ty, ArraySize, Name);
111 assert(isa<llvm::AllocaInst>(Var.
getPointer()));
124 bool CastToDefaultAddrSpace) {
127 CastToDefaultAddrSpace);
132 bool CastToDefaultAddrSpace) {
134 CastToDefaultAddrSpace);
178 if (!ignoreResult && aggSlot.
isIgnored())
183 llvm_unreachable(
"bad evaluation kind");
224 llvm_unreachable(
"bad evaluation kind");
265 VD && isa<VarDecl>(VD) && VD->
hasAttr<ObjCPreciseLifetimeAttr>();
286 llvm_unreachable(
"temporary cannot have dynamic storage duration");
288 llvm_unreachable(
"unknown storage duration");
296 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
297 if (!ClassDecl->hasTrivialDestructor())
298 ReferenceTemporaryDtor = ClassDecl->getDestructor();
301 if (!ReferenceTemporaryDtor)
308 llvm::Constant *CleanupFn;
309 llvm::Constant *CleanupArg;
312 ReferenceTemporary, E->
getType(),
315 CleanupArg = llvm::Constant::getNullValue(CGF.
Int8PtrTy);
319 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.
getPointer());
334 ReferenceTemporary, E->
getType(),
340 llvm_unreachable(
"temporary cannot have dynamic storage duration");
361 auto AS = AddrSpace.getValue();
362 auto *GV =
new llvm::GlobalVariable(
364 llvm::GlobalValue::PrivateLinkage, Init,
".ref.tmp",
nullptr,
365 llvm::GlobalValue::NotThreadLocal,
368 GV->setAlignment(alignment.getQuantity());
369 llvm::Constant *C = GV;
371 C = TCG.performAddrSpaceCast(
373 GV->getValueType()->getPointerTo(
386 llvm_unreachable(
"temporary can't have dynamic storage duration");
388 llvm_unreachable(
"unknown storage duration");
401 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(Object.
getPointer())) {
402 Object =
Address(llvm::ConstantExpr::getBitCast(Var,
413 if (Var->hasInitializer())
424 default: llvm_unreachable(
"expected scalar or aggregate expression");
446 for (
const auto &Ignored : CommaLHSs)
449 if (
const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
450 if (opaque->getType()->isRecordType()) {
451 assert(Adjustments.empty());
458 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(
460 Object =
Address(llvm::ConstantExpr::getBitCast(
467 if (!Var->hasInitializer()) {
496 for (
unsigned I = Adjustments.size();
I != 0; --
I) {
498 switch (Adjustment.
Kind) {
511 assert(LV.isSimple() &&
512 "materialized temporary field is not a simple lvalue");
513 Object = LV.getAddress();
554 const llvm::Constant *Elts) {
555 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
562 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
564 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
565 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
566 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
567 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
568 return Builder.CreateMul(B1, KMul);
588 if (Ptr->getType()->getPointerAddressSpace())
599 llvm::BasicBlock *Done =
nullptr;
605 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
609 if ((
SanOpts.
has(SanitizerKind::Null) || AllowNullPointers) &&
610 !SkippedChecks.
has(SanitizerKind::Null) && !PtrToAlloca) {
621 if (AllowNullPointers) {
626 Builder.CreateCondBr(IsNonNull, Rest, Done);
629 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
635 !SkippedChecks.
has(SanitizerKind::ObjectSize) &&
649 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
650 llvm::ConstantInt::get(
IntPtrTy, Size));
651 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
654 uint64_t AlignVal = 0;
656 if (SanOpts.has(SanitizerKind::Alignment) &&
657 !SkippedChecks.has(SanitizerKind::Alignment)) {
658 AlignVal = Alignment.getQuantity();
659 if (!Ty->isIncompleteType() && !AlignVal)
660 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
664 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
667 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
669 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
670 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
674 if (Checks.size() > 0) {
677 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
678 llvm::Constant *StaticData[] = {
679 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
680 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
681 llvm::ConstantInt::get(Int8Ty, TCK)};
682 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
694 if (SanOpts.has(SanitizerKind::Vptr) &&
695 !SkippedChecks.has(SanitizerKind::Vptr) &&
696 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
697 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
698 TCK == TCK_UpcastToVirtualBase) &&
699 RD && RD->hasDefinition() && RD->isDynamicClass()) {
706 llvm::raw_svector_ostream Out(MangledName);
707 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
711 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
713 llvm::hash_code TypeHash = hash_value(Out.str());
716 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
717 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
718 Address VPtrAddr(
Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
723 Hash =
Builder.CreateTrunc(Hash, IntPtrTy);
726 const int CacheSize = 128;
727 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
729 "__ubsan_vptr_type_cache");
731 llvm::ConstantInt::get(IntPtrTy,
735 Builder.CreateAlignedLoad(
Builder.CreateInBoundsGEP(Cache, Indices),
743 llvm::Constant *StaticData[] = {
744 EmitCheckSourceLocation(Loc),
745 EmitCheckTypeDescriptor(Ty),
746 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
747 llvm::ConstantInt::get(Int8Ty, TCK)
750 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
751 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
768 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
769 if (CAT->getSize().ugt(1))
771 }
else if (!isa<IncompleteArrayType>(AT))
777 if (
const auto *ME = dyn_cast<MemberExpr>(E)) {
780 if (
const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
783 return ++FI == FD->getParent()->field_end();
785 }
else if (
const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
786 return IRE->getDecl()->getNextIvar() ==
nullptr;
799 return CGF.
Builder.getInt32(VT->getNumElements());
804 if (
const auto *CE = dyn_cast<CastExpr>(Base)) {
805 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
807 IndexedType = CE->getSubExpr()->getType();
809 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT))
810 return CGF.
Builder.getInt(CAT->getSize());
811 else if (
const auto *VAT = dyn_cast<VariableArrayType>(AT))
822 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
823 "should not be called unless adding bounds checks");
835 llvm::Constant *StaticData[] = {
837 EmitCheckTypeDescriptor(IndexedType),
838 EmitCheckTypeDescriptor(IndexType)
841 :
Builder.CreateICmpULE(IndexVal, BoundVal);
842 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
843 SanitizerHandler::OutOfBounds, StaticData, Index);
849 bool isInc,
bool isPre) {
853 if (isa<llvm::IntegerType>(InVal.first->getType())) {
854 uint64_t AmountVal = isInc ? 1 : -1;
855 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal,
true);
858 NextVal =
Builder.CreateAdd(InVal.first, NextVal, isInc ?
"inc" :
"dec");
861 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
864 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
867 NextVal =
Builder.CreateFAdd(InVal.first, NextVal, isInc ?
"inc" :
"dec");
873 EmitStoreOfComplex(IncVal, LV,
false);
877 return isPre ? IncVal : InVal;
887 DI->EmitExplicitCastType(E->
getType());
904 if (
const CastExpr *CE = dyn_cast<CastExpr>(E)) {
905 if (
const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
906 CGM.EmitExplicitCastExprType(ECE,
this);
908 switch (CE->getCastKind()) {
912 if (
auto PtrTy = CE->getSubExpr()->getType()->getAs<
PointerType>()) {
913 if (PtrTy->getPointeeType()->isVoidType())
917 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo);
918 if (BaseInfo) *BaseInfo = InnerInfo;
922 if (isa<ExplicitCastExpr>(CE) &&
925 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
932 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
933 CE->getCastKind() == CK_BitCast) {
935 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.
getPointer(),
937 CodeGenFunction::CFITCK_UnrelatedCast,
941 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
946 case CK_ArrayToPointerDecay:
947 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
950 case CK_UncheckedDerivedToBase:
951 case CK_DerivedToBase: {
952 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
953 auto Derived = CE->getSubExpr()->
getType()->getPointeeCXXRecordDecl();
954 return GetAddressOfBaseClass(Addr, Derived,
955 CE->path_begin(), CE->path_end(),
956 ShouldNullCheckClassCastValue(CE),
969 if (UO->getOpcode() == UO_AddrOf) {
970 LValue LV = EmitLValue(UO->getSubExpr());
979 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo);
980 return Address(EmitScalarExpr(E), Align);
985 return RValue::get(
nullptr);
987 switch (getEvaluationKind(Ty)) {
992 return RValue::getComplex(std::make_pair(U, U));
999 Address DestPtr = CreateMemTemp(Ty,
"undef.agg.tmp");
1000 return RValue::getAggregate(DestPtr);
1004 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1006 llvm_unreachable(
"bad evaluation kind");
1011 ErrorUnsupported(E, Name);
1012 return GetUndefRValue(E->
getType());
1017 ErrorUnsupported(E, Name);
1018 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->
getType()));
1023 bool CodeGenFunction::IsWrappedCXXThis(
const Expr *Obj) {
1025 while (!isa<CXXThisExpr>(Base)) {
1027 if (isa<CXXDynamicCastExpr>(Base))
1030 if (
const auto *CE = dyn_cast<CastExpr>(Base)) {
1031 Base = CE->getSubExpr();
1032 }
else if (
const auto *PE = dyn_cast<ParenExpr>(Base)) {
1033 Base = PE->getSubExpr();
1034 }
else if (
const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1035 if (UO->getOpcode() == UO_Extension)
1036 Base = UO->getSubExpr();
1048 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(
E))
1049 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E),
true);
1054 if (
const auto *ME = dyn_cast<MemberExpr>(E)) {
1055 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1057 SkippedChecks.
set(SanitizerKind::Alignment,
true);
1058 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1059 SkippedChecks.
set(SanitizerKind::Null,
true);
1085 default:
return EmitUnsupportedLValue(E,
"l-value expression");
1087 case Expr::ObjCPropertyRefExprClass:
1088 llvm_unreachable(
"cannot emit a property reference directly");
1090 case Expr::ObjCSelectorExprClass:
1091 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1092 case Expr::ObjCIsaExprClass:
1093 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1094 case Expr::BinaryOperatorClass:
1095 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1096 case Expr::CompoundAssignOperatorClass: {
1099 Ty = AT->getValueType();
1101 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1102 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1104 case Expr::CallExprClass:
1105 case Expr::CXXMemberCallExprClass:
1106 case Expr::CXXOperatorCallExprClass:
1107 case Expr::UserDefinedLiteralClass:
1108 return EmitCallExprLValue(cast<CallExpr>(E));
1109 case Expr::VAArgExprClass:
1110 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1111 case Expr::DeclRefExprClass:
1112 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1113 case Expr::ParenExprClass:
1114 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1115 case Expr::GenericSelectionExprClass:
1116 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1117 case Expr::PredefinedExprClass:
1118 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1119 case Expr::StringLiteralClass:
1120 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1121 case Expr::ObjCEncodeExprClass:
1122 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1123 case Expr::PseudoObjectExprClass:
1124 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1125 case Expr::InitListExprClass:
1126 return EmitInitListLValue(cast<InitListExpr>(E));
1127 case Expr::CXXTemporaryObjectExprClass:
1128 case Expr::CXXConstructExprClass:
1129 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1130 case Expr::CXXBindTemporaryExprClass:
1131 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1132 case Expr::CXXUuidofExprClass:
1133 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1134 case Expr::LambdaExprClass:
1135 return EmitLambdaLValue(cast<LambdaExpr>(E));
1137 case Expr::ExprWithCleanupsClass: {
1138 const auto *cleanups = cast<ExprWithCleanups>(
E);
1139 enterFullExpression(cleanups);
1141 LValue LV = EmitLValue(cleanups->getSubExpr());
1156 case Expr::CXXDefaultArgExprClass:
1157 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1158 case Expr::CXXDefaultInitExprClass: {
1160 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1162 case Expr::CXXTypeidExprClass:
1163 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1165 case Expr::ObjCMessageExprClass:
1166 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1167 case Expr::ObjCIvarRefExprClass:
1168 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1169 case Expr::StmtExprClass:
1170 return EmitStmtExprLValue(cast<StmtExpr>(E));
1171 case Expr::UnaryOperatorClass:
1172 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1173 case Expr::ArraySubscriptExprClass:
1174 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1175 case Expr::OMPArraySectionExprClass:
1176 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1177 case Expr::ExtVectorElementExprClass:
1178 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1179 case Expr::MemberExprClass:
1180 return EmitMemberExpr(cast<MemberExpr>(E));
1181 case Expr::CompoundLiteralExprClass:
1182 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1183 case Expr::ConditionalOperatorClass:
1184 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1185 case Expr::BinaryConditionalOperatorClass:
1186 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1187 case Expr::ChooseExprClass:
1188 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1189 case Expr::OpaqueValueExprClass:
1190 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1191 case Expr::SubstNonTypeTemplateParmExprClass:
1192 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1193 case Expr::ImplicitCastExprClass:
1194 case Expr::CStyleCastExprClass:
1195 case Expr::CXXFunctionalCastExprClass:
1196 case Expr::CXXStaticCastExprClass:
1197 case Expr::CXXDynamicCastExprClass:
1198 case Expr::CXXReinterpretCastExprClass:
1199 case Expr::CXXConstCastExprClass:
1200 case Expr::ObjCBridgedCastExprClass:
1201 return EmitCastLValue(cast<CastExpr>(E));
1203 case Expr::MaterializeTemporaryExprClass:
1204 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1206 case Expr::CoawaitExprClass:
1207 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1208 case Expr::CoyieldExprClass:
1209 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1221 if (!qs.hasConst() || qs.hasVolatile())
return false;
1225 if (
const auto *RT = dyn_cast<RecordType>(type))
1226 if (
const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1227 if (RD->hasMutableFields() || !RD->isTrivial())
1248 if (
const auto *ref = dyn_cast<ReferenceType>(type)) {
1269 if (isa<ParmVarDecl>(value)) {
1271 }
else if (
auto *var = dyn_cast<VarDecl>(value)) {
1273 }
else if (isa<EnumConstantDecl>(value)) {
1281 bool resultIsReference;
1287 resultIsReference =
false;
1288 resultType = refExpr->
getType();
1293 resultIsReference =
true;
1294 resultType = value->
getType();
1306 llvm::Constant *C = CGM.EmitConstantValue(result.
Val, resultType,
this);
1310 if (isa<VarDecl>(value)) {
1311 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1312 EmitDeclRefExprDbgValue(refExpr, result.
Val);
1314 assert(isa<EnumConstantDecl>(value));
1315 EmitDeclRefExprDbgValue(refExpr, result.
Val);
1319 if (resultIsReference)
1320 return ConstantEmission::forReference(C);
1322 return ConstantEmission::forValue(C);
1339 return ET->getDecl()->getIntegerType()->isBooleanType();
1348 llvm::APInt &Min, llvm::APInt &
End,
1349 bool StrictEnums,
bool IsBool) {
1351 bool IsRegularCPlusPlusEnum = CGF.
getLangOpts().CPlusPlus && StrictEnums &&
1353 if (!IsBool && !IsRegularCPlusPlusEnum)
1362 unsigned Bitwidth = LTy->getScalarSizeInBits();
1366 if (NumNegativeBits) {
1367 unsigned NumBits =
std::max(NumNegativeBits, NumPositiveBits + 1);
1368 assert(NumBits <= Bitwidth);
1369 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1372 assert(NumPositiveBits <= Bitwidth);
1373 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1374 Min = llvm::APInt(Bitwidth, 0);
1380 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(
QualType Ty) {
1381 llvm::APInt Min,
End;
1382 if (!
getRangeForType(*
this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1386 llvm::MDBuilder MDHelper(getLLVMContext());
1387 return MDHelper.createRange(Min, End);
1392 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1393 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1394 if (!HasBoolCheck && !HasEnumCheck)
1398 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1399 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1400 bool NeedsEnumCheck = HasEnumCheck && Ty->
getAs<
EnumType>();
1401 if (!NeedsBoolCheck && !NeedsEnumCheck)
1408 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1411 llvm::APInt Min,
End;
1419 Check =
Builder.CreateICmpULE(
1420 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1423 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1425 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1426 Check =
Builder.CreateAnd(Upper, Lower);
1428 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1429 EmitCheckTypeDescriptor(Ty)};
1431 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1432 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1433 StaticArgs, EmitCheckValue(Value));
1441 llvm::MDNode *TBAAInfo,
1443 uint64_t TBAAOffset,
1444 bool isNontemporal) {
1445 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1450 const auto *VTy = cast<llvm::VectorType>(EltTy);
1453 if (VTy->getNumElements() == 3) {
1456 llvm::VectorType *vec4Ty =
1457 llvm::VectorType::get(VTy->getElementType(), 4);
1458 Address Cast =
Builder.CreateElementBitCast(Addr, vec4Ty,
"castToVec4");
1463 V =
Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1464 {0, 1, 2},
"extractVec");
1465 return EmitFromMemory(V, Ty);
1472 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1473 if (Ty->
isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1474 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1477 llvm::LoadInst *Load =
Builder.CreateLoad(Addr, Volatile);
1478 if (isNontemporal) {
1479 llvm::MDNode *
Node = llvm::MDNode::get(
1480 Load->getContext(), llvm::ConstantAsMetadata::get(
Builder.getInt32(1)));
1481 Load->setMetadata(CGM.getModule().getMDKindID(
"nontemporal"),
Node);
1485 llvm::MDNode *TBAA = MayAlias
1486 ? CGM.getTBAAInfo(getContext().CharTy)
1487 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1489 CGM.DecorateInstructionWithTBAA(Load, TBAA, MayAlias);
1492 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1495 }
else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1496 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1497 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1499 return EmitFromMemory(Load, Ty);
1507 if (Value->getType()->isIntegerTy(1))
1508 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty),
"frombool");
1509 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1510 "wrong value rep of bool");
1519 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1520 "wrong value rep of bool");
1521 return Builder.CreateTrunc(Value,
Builder.getInt1Ty(),
"tobool");
1530 llvm::MDNode *TBAAInfo,
1531 bool isInit,
QualType TBAABaseType,
1532 uint64_t TBAAOffset,
1533 bool isNontemporal) {
1535 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1538 llvm::Type *SrcTy = Value->getType();
1539 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
1541 if (VecTy && VecTy->getNumElements() == 3) {
1543 llvm::Constant *Mask[] = {
Builder.getInt32(0),
Builder.getInt32(1),
1545 llvm::UndefValue::get(
Builder.getInt32Ty())};
1546 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1547 Value =
Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1548 MaskV,
"extractVec");
1549 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1552 Addr =
Builder.CreateElementBitCast(Addr, SrcTy,
"storetmp");
1557 Value = EmitToMemory(Value, Ty);
1560 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1562 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1563 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1567 llvm::StoreInst *
Store =
Builder.CreateStore(Value, Addr, Volatile);
1568 if (isNontemporal) {
1569 llvm::MDNode *
Node =
1570 llvm::MDNode::get(Store->getContext(),
1571 llvm::ConstantAsMetadata::get(
Builder.getInt32(1)));
1572 Store->setMetadata(CGM.getModule().getMDKindID(
"nontemporal"),
Node);
1576 llvm::MDNode *TBAA = MayAlias
1577 ? CGM.getTBAAInfo(getContext().CharTy)
1578 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1580 CGM.DecorateInstructionWithTBAA(Store, TBAA, MayAlias);
1599 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*
this,
1604 if (!getLangOpts().ObjCAutoRefCount) {
1605 return RValue::get(EmitARCLoadWeak(LV.
getAddress()));
1610 Object = EmitObjCConsumeObject(LV.
getType(), Object);
1611 return RValue::get(Object);
1618 return RValue::get(EmitLoadOfScalar(LV, Loc));
1631 return EmitLoadOfExtVectorElementLValue(LV);
1635 return EmitLoadOfGlobalRegLValue(LV);
1637 assert(LV.
isBitField() &&
"Unknown LValue type!");
1638 return EmitLoadOfBitfieldLValue(LV, Loc);
1646 llvm::Type *ResLTy = ConvertType(LV.
getType());
1655 Val =
Builder.CreateShl(Val, HighBits,
"bf.shl");
1656 if (Info.
Offset + HighBits)
1657 Val =
Builder.CreateAShr(Val, Info.
Offset + HighBits,
"bf.ashr");
1667 EmitScalarRangeCheck(Val, LV.
getType(), Loc);
1668 return RValue::get(Val);
1683 unsigned InIdx = getAccessedFieldNo(0, Elts);
1684 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1685 return RValue::get(
Builder.CreateExtractElement(Vec, Elt));
1692 for (
unsigned i = 0; i != NumResultElts; ++i)
1693 Mask.push_back(
Builder.getInt32(getAccessedFieldNo(i, Elts)));
1695 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1696 Vec =
Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1698 return RValue::get(Vec);
1706 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1708 Address CastToPointerElement =
1709 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1710 "conv.ptr.element");
1713 unsigned ix = getAccessedFieldNo(0, Elts);
1716 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1717 getContext().getTypeSizeInChars(EQT),
1720 return VectorBasePtrPlusIx;
1726 "Bad type for register variable");
1727 llvm::MDNode *RegName = cast<llvm::MDNode>(
1728 cast<llvm::MetadataAsValue>(LV.
getGlobalReg())->getMetadata());
1731 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.
getType());
1732 llvm::Type *Ty = OrigTy;
1733 if (OrigTy->isPointerTy())
1734 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1735 llvm::Type *Types[] = { Ty };
1737 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1739 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1740 if (OrigTy->isPointerTy())
1741 Call =
Builder.CreateIntToPtr(Call, OrigTy);
1742 return RValue::get(Call);
1766 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1769 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1771 assert(Dst.
isBitField() &&
"Unknown LValue type");
1772 return EmitStoreThroughBitfieldLValue(Src, Dst);
1779 llvm_unreachable(
"present but none");
1802 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.
getType(),
1813 CGM.getObjCRuntime().EmitObjCWeakAssign(*
this, src, LvalueDst);
1823 llvm::Type *ResultType = IntPtrTy;
1826 RHS =
Builder.CreatePtrToInt(RHS, ResultType,
"sub.ptr.rhs.cast");
1829 "sub.ptr.lhs.cast");
1831 CGM.getObjCRuntime().EmitObjCIvarAssign(*
this, src, dst,
1834 CGM.getObjCRuntime().EmitObjCGlobalAssign(*
this, src, LvalueDst,
1838 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*
this, src, LvalueDst);
1842 assert(Src.
isScalar() &&
"Can't emit an agg store with this method");
1846 void CodeGenFunction::EmitStoreThroughBitfieldLValue(
RValue Src,
LValue Dst,
1849 llvm::Type *ResLTy = ConvertTypeForMem(Dst.
getType());
1856 SrcVal =
Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1869 SrcVal =
Builder.CreateAnd(SrcVal,
1885 SrcVal =
Builder.CreateOr(Val, SrcVal,
"bf.set");
1887 assert(Info.
Offset == 0);
1902 ResultVal =
Builder.CreateShl(ResultVal, HighBits,
"bf.result.shl");
1903 ResultVal =
Builder.CreateAShr(ResultVal, HighBits,
"bf.result.ashr");
1909 *Result = EmitFromMemory(ResultVal, Dst.
getType());
1913 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(
RValue Src,
1924 unsigned NumSrcElts = VTy->getNumElements();
1925 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1926 if (NumDstElts == NumSrcElts) {
1931 for (
unsigned i = 0; i != NumSrcElts; ++i)
1932 Mask[getAccessedFieldNo(i, Elts)] =
Builder.getInt32(i);
1934 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1935 Vec =
Builder.CreateShuffleVector(SrcVal,
1936 llvm::UndefValue::get(Vec->getType()),
1938 }
else if (NumDstElts > NumSrcElts) {
1944 for (
unsigned i = 0; i != NumSrcElts; ++i)
1945 ExtMask.push_back(
Builder.getInt32(i));
1946 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1947 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1949 Builder.CreateShuffleVector(SrcVal,
1950 llvm::UndefValue::get(SrcVal->getType()),
1954 for (
unsigned i = 0; i != NumDstElts; ++i)
1955 Mask.push_back(
Builder.getInt32(i));
1960 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1964 for (
unsigned i = 0; i != NumSrcElts; ++i)
1965 Mask[getAccessedFieldNo(i, Elts)] =
Builder.getInt32(i+NumDstElts);
1966 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1967 Vec =
Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1970 llvm_unreachable(
"unexpected shorten vector length");
1974 unsigned InIdx = getAccessedFieldNo(0, Elts);
1975 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1976 Vec =
Builder.CreateInsertElement(Vec, SrcVal, Elt);
1984 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(
RValue Src,
LValue Dst) {
1986 "Bad type for register variable");
1987 llvm::MDNode *RegName = cast<llvm::MDNode>(
1988 cast<llvm::MetadataAsValue>(Dst.
getGlobalReg())->getMetadata());
1989 assert(RegName &&
"Register LValue is not metadata");
1992 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.
getType());
1993 llvm::Type *Ty = OrigTy;
1994 if (OrigTy->isPointerTy())
1995 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1996 llvm::Type *Types[] = { Ty };
1998 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2000 if (OrigTy->isPointerTy())
2001 Value =
Builder.CreatePtrToInt(Value, Ty);
2003 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2011 bool IsMemberAccess=
false) {
2015 if (isa<ObjCIvarRefExpr>(E)) {
2028 auto *Exp = cast<ObjCIvarRefExpr>(
const_cast<Expr *
>(
E));
2034 if (
const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2035 if (
const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2036 if (VD->hasGlobalStorage()) {
2045 if (
const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2050 if (
const auto *Exp = dyn_cast<ParenExpr>(E)) {
2064 if (
const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2069 if (
const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2074 if (
const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2079 if (
const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2084 if (
const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2097 if (
const auto *Exp = dyn_cast<MemberExpr>(E)) {
2109 StringRef
Name = StringRef()) {
2110 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2134 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2150 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2186 if (FD->
hasAttr<WeakRefAttr>()) {
2201 V = llvm::ConstantExpr::getBitCast(V,
2231 AsmLabelAttr *Asm = VD->
getAttr<AsmLabelAttr>();
2232 assert(Asm->getLabel().size() < 64-Name.size() &&
2233 "Register name too big");
2234 Name.append(Asm->getLabel());
2235 llvm::NamedMDNode *M =
2236 CGM.
getModule().getOrInsertNamedMetadata(Name);
2237 if (M->getNumOperands() == 0) {
2240 llvm::Metadata *Ops[] = {Str};
2247 llvm::MetadataAsValue::get(CGM.
getLLVMContext(), M->getOperand(0));
2248 return LValue::MakeGlobalReg(
Address(Ptr, Alignment), VD->
getType());
2255 if (
const auto *VD = dyn_cast<VarDecl>(ND)) {
2258 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2263 const Expr *Init = VD->getAnyInitializer(VD);
2265 VD->isUsableInConstantExpressions(getContext()) &&
2266 VD->checkInitIsICE() &&
2269 LocalDeclMap.count(VD))) {
2270 llvm::Constant *Val =
2271 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(),
this);
2272 assert(Val &&
"failed to emit reference constant expression");
2279 return MakeAddrLValue(
Address(Val, Alignment), T, BaseInfo);
2284 if (
auto *FD = LambdaCaptureFields.lookup(VD))
2286 else if (CapturedStmtInfo) {
2287 auto I = LocalDeclMap.find(VD);
2288 if (
I != LocalDeclMap.end()) {
2290 return EmitLoadOfReferenceLValue(
I->second, RefTy);
2291 return MakeAddrLValue(
I->second, T);
2295 CapturedStmtInfo->getContextValue());
2297 return MakeAddrLValue(
2302 assert(isa<BlockDecl>(CurCodeDecl));
2303 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2305 return MakeAddrLValue(addr, T, BaseInfo);
2312 assert((ND->
isUsed(
false) || !isa<VarDecl>(ND) ||
2314 "Should not use decl without marking it used!");
2316 if (ND->
hasAttr<WeakRefAttr>()) {
2317 const auto *VD = cast<ValueDecl>(ND);
2319 return MakeAddrLValue(Aliasee, T,
2323 if (
const auto *VD = dyn_cast<VarDecl>(ND)) {
2325 if (VD->hasLinkage() || VD->isStaticDataMember())
2328 Address addr = Address::invalid();
2331 auto iter = LocalDeclMap.find(VD);
2332 if (iter != LocalDeclMap.end()) {
2333 addr = iter->second;
2337 }
else if (VD->isStaticLocal()) {
2338 addr =
Address(CGM.getOrCreateStaticVarDecl(
2339 *VD, CGM.getLLVMLinkageVarDefinition(VD,
false)),
2340 getContext().getDeclAlign(VD));
2344 llvm_unreachable(
"DeclRefExpr for Decl not entered in LocalDeclMap?");
2349 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2351 *
this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2356 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2358 addr = emitBlockByrefAddress(addr, VD);
2364 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2367 LV = MakeAddrLValue(addr, T, BaseInfo);
2370 bool isLocalStorage = VD->hasLocalStorage();
2372 bool NonGCable = isLocalStorage &&
2373 !VD->getType()->isReferenceType() &&
2380 bool isImpreciseLifetime =
2381 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2382 if (isImpreciseLifetime)
2388 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2394 if (
const auto *BD = dyn_cast<BindingDecl>(ND))
2395 return EmitLValue(BD->getBinding());
2397 llvm_unreachable(
"Unhandled DeclRefExpr");
2407 default: llvm_unreachable(
"Unknown unary operator lvalue!");
2410 assert(!T.
isNull() &&
"CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2414 LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
2421 if (getLangOpts().ObjC1 &&
2430 assert(LV.
isSimple() &&
"real/imag on non-ordinary l-value");
2453 bool isInc = E->
getOpcode() == UO_PreInc;
2456 EmitComplexPrePostIncDec(E, LV, isInc,
true);
2458 EmitScalarPrePostIncDec(E, LV, isInc,
true);
2465 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2471 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2478 assert(SL !=
nullptr &&
"No StringLiteral name in PredefinedExpr");
2479 StringRef FnName = CurFn->getName();
2480 if (FnName.startswith(
"\01"))
2481 FnName = FnName.substr(1);
2482 StringRef NameItems[] = {
2484 std::string GVName = llvm::join(NameItems, NameItems + 2,
".");
2486 if (
auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2487 std::string
Name = SL->getString();
2488 if (!Name.empty()) {
2489 unsigned Discriminator =
2490 CGM.getCXXABI().getMangleContext().getBlockId(BD,
true);
2492 Name +=
"_" + Twine(Discriminator + 1).str();
2493 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2494 return MakeAddrLValue(C, E->
getType(), BaseInfo);
2496 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2497 return MakeAddrLValue(C, E->
getType(), BaseInfo);
2500 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2501 return MakeAddrLValue(C, E->
getType(), BaseInfo);
2513 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(
QualType T) {
2515 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2518 uint16_t TypeKind = -1;
2523 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2527 TypeInfo = getContext().getTypeSize(T);
2538 llvm::Constant *Components[] = {
2540 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2542 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2544 auto *GV =
new llvm::GlobalVariable(
2545 CGM.getModule(), Descriptor->getType(),
2546 true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2547 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2548 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2551 CGM.setTypeDescriptorInMap(T, GV);
2557 llvm::Type *TargetTy = IntPtrTy;
2561 if (V->getType()->isFloatingPointTy()) {
2562 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2563 if (Bits <= TargetTy->getIntegerBitWidth())
2564 V =
Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2569 if (V->getType()->isIntegerTy() &&
2570 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2571 return Builder.CreateZExt(V, TargetTy);
2574 if (!V->getType()->isPointerTy()) {
2575 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2579 return Builder.CreatePtrToInt(V, TargetTy);
2595 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2599 int PathComponentsToStrip =
2600 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2601 if (PathComponentsToStrip < 0) {
2602 assert(PathComponentsToStrip !=
INT_MIN);
2603 int PathComponentsToKeep = -PathComponentsToStrip;
2604 auto I = llvm::sys::path::rbegin(FilenameString);
2605 auto E = llvm::sys::path::rend(FilenameString);
2606 while (
I != E && --PathComponentsToKeep)
2609 FilenameString = FilenameString.substr(
I - E);
2610 }
else if (PathComponentsToStrip > 0) {
2611 auto I = llvm::sys::path::begin(FilenameString);
2612 auto E = llvm::sys::path::end(FilenameString);
2613 while (
I != E && PathComponentsToStrip--)
2618 FilenameString.substr(
I - llvm::sys::path::begin(FilenameString));
2620 FilenameString = llvm::sys::path::filename(FilenameString);
2623 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString,
".src");
2624 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2625 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2626 Filename = FilenameGV.getPointer();
2630 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2637 return llvm::ConstantStruct::getAnon(Data);
2654 assert(llvm::countPopulation(Kind) == 1);
2656 case SanitizerKind::Vptr:
2657 return CheckRecoverableKind::AlwaysRecoverable;
2658 case SanitizerKind::Return:
2659 case SanitizerKind::Unreachable:
2662 return CheckRecoverableKind::Recoverable;
2667 struct SanitizerHandlerInfo {
2668 char const *
const Name;
2674 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2676 #undef SANITIZER_CHECK
2680 llvm::FunctionType *FnType,
2684 llvm::BasicBlock *ContBB) {
2686 bool NeedsAbortSuffix =
2688 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2689 const StringRef CheckName = CheckInfo.Name;
2690 std::string FnName =
2691 (
"__ubsan_handle_" + CheckName +
2692 (CheckInfo.Version ?
"_v" + llvm::utostr(CheckInfo.Version) :
"") +
2693 (NeedsAbortSuffix ?
"_abort" :
""))
2696 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2698 llvm::AttrBuilder B;
2700 B.addAttribute(llvm::Attribute::NoReturn)
2701 .addAttribute(llvm::Attribute::NoUnwind);
2703 B.addAttribute(llvm::Attribute::UWTable);
2708 llvm::AttributeList::FunctionIndex, B),
2712 HandlerCall->setDoesNotReturn();
2713 CGF.
Builder.CreateUnreachable();
2719 void CodeGenFunction::EmitCheck(
2720 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2723 assert(IsSanitizerScope);
2724 assert(Checked.size() > 0);
2725 assert(CheckHandler >= 0 &&
2726 CheckHandler <
sizeof(SanitizerHandlers) /
sizeof(*SanitizerHandlers));
2727 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2732 for (
int i = 0, n = Checked.size(); i < n; ++i) {
2736 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2738 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2741 Cond = Cond ?
Builder.CreateAnd(Cond, Check) : Check;
2745 EmitTrapCheck(TrapCond);
2746 if (!FatalCond && !RecoverableCond)
2750 if (FatalCond && RecoverableCond)
2751 JointCond =
Builder.CreateAnd(FatalCond, RecoverableCond);
2753 JointCond = FatalCond ? FatalCond : RecoverableCond;
2757 assert(SanOpts.has(Checked[0].second));
2759 for (
int i = 1, n = Checked.size(); i < n; ++i) {
2761 "All recoverable kinds in a single check must be same!");
2762 assert(SanOpts.has(Checked[i].second));
2766 llvm::BasicBlock *Cont = createBasicBlock(
"cont");
2767 llvm::BasicBlock *Handlers = createBasicBlock(
"handler." + CheckName);
2768 llvm::Instruction *Branch =
Builder.CreateCondBr(JointCond, Cont, Handlers);
2771 llvm::MDBuilder MDHelper(getLLVMContext());
2772 llvm::MDNode *
Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2773 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2774 EmitBlock(Handlers);
2781 Args.reserve(DynamicArgs.size() + 1);
2782 ArgTypes.reserve(DynamicArgs.size() + 1);
2785 if (!StaticArgs.empty()) {
2786 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2788 new llvm::GlobalVariable(CGM.getModule(), Info->getType(),
false,
2789 llvm::GlobalVariable::PrivateLinkage, Info);
2790 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2791 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2792 Args.push_back(
Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2793 ArgTypes.push_back(Int8PtrTy);
2796 for (
size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2797 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2798 ArgTypes.push_back(IntPtrTy);
2801 llvm::FunctionType *FnType =
2802 llvm::FunctionType::get(CGM.VoidTy, ArgTypes,
false);
2804 if (!FatalCond || !RecoverableCond) {
2808 (FatalCond !=
nullptr), Cont);
2812 llvm::BasicBlock *NonFatalHandlerBB =
2813 createBasicBlock(
"non_fatal." + CheckName);
2814 llvm::BasicBlock *FatalHandlerBB = createBasicBlock(
"fatal." + CheckName);
2815 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2816 EmitBlock(FatalHandlerBB);
2819 EmitBlock(NonFatalHandlerBB);
2827 void CodeGenFunction::EmitCfiSlowPathCheck(
2830 llvm::BasicBlock *Cont = createBasicBlock(
"cfi.cont");
2832 llvm::BasicBlock *CheckBB = createBasicBlock(
"cfi.slowpath");
2833 llvm::BranchInst *BI =
Builder.CreateCondBr(Cond, Cont, CheckBB);
2835 llvm::MDBuilder MDHelper(getLLVMContext());
2836 llvm::MDNode *
Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2837 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2841 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2843 llvm::CallInst *CheckCall;
2845 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2847 new llvm::GlobalVariable(CGM.getModule(), Info->getType(),
false,
2848 llvm::GlobalVariable::PrivateLinkage, Info);
2849 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2850 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2852 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2853 "__cfi_slowpath_diag",
2854 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2856 CheckCall =
Builder.CreateCall(
2858 {TypeId, Ptr,
Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2860 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2862 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy},
false));
2863 CheckCall =
Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2866 CheckCall->setDoesNotThrow();
2873 void CodeGenFunction::EmitCfiCheckStub() {
2874 llvm::Module *M = &CGM.getModule();
2875 auto &Ctx = M->getContext();
2877 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
false),
2878 llvm::GlobalValue::WeakAnyLinkage,
"__cfi_check", M);
2885 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap),
"", BB);
2896 void CodeGenFunction::EmitCfiCheckFail() {
2903 Args.push_back(&ArgData);
2904 Args.push_back(&ArgAddr);
2907 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2910 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy},
false),
2911 llvm::GlobalValue::WeakODRLinkage,
"__cfi_check_fail", &CGM.getModule());
2914 StartFunction(
GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2918 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData),
false,
2919 CGM.getContext().VoidPtrTy, ArgData.
getLocation());
2921 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr),
false,
2922 CGM.getContext().VoidPtrTy, ArgAddr.
getLocation());
2926 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2927 EmitTrapCheck(DataIsNotNullPtr);
2929 llvm::StructType *SourceLocationTy =
2930 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
2931 llvm::StructType *CfiCheckFailDataTy =
2932 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
2936 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2938 Address CheckKindAddr(V, getIntAlign());
2941 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2942 CGM.getLLVMContext(),
2943 llvm::MDString::get(CGM.getLLVMContext(),
"all-vtables"));
2945 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2946 {Addr, AllVtables}),
2949 const std::pair<int, SanitizerMask> CheckKinds[] = {
2950 {CFITCK_VCall, SanitizerKind::CFIVCall},
2951 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2952 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2953 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2954 {CFITCK_ICall, SanitizerKind::CFIICall}};
2957 for (
auto CheckKindMaskPair : CheckKinds) {
2958 int Kind = CheckKindMaskPair.first;
2961 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
2962 if (CGM.getLangOpts().Sanitize.has(Mask))
2963 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
2964 {Data, Addr, ValidVtable});
2966 EmitTrapCheck(Cond);
2972 CGM.addUsedGlobal(F);
2976 llvm::BasicBlock *Cont = createBasicBlock(
"cont");
2980 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2981 TrapBB = createBasicBlock(
"trap");
2982 Builder.CreateCondBr(Checked, Cont, TrapBB);
2984 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2985 TrapCall->setDoesNotReturn();
2986 TrapCall->setDoesNotThrow();
2989 Builder.CreateCondBr(Checked, Cont, TrapBB);
2996 llvm::CallInst *TrapCall =
Builder.CreateCall(CGM.getIntrinsic(IntrID));
2998 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2999 auto A = llvm::Attribute::get(getLLVMContext(),
"trap-func-name",
3000 CGM.getCodeGenOpts().TrapFuncName);
3001 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
3010 "Array to pointer decay must have array source type!");
3013 LValue LV = EmitLValue(E);
3014 Address Addr = LV.getAddress();
3015 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3019 llvm::Type *NewTy = ConvertType(E->
getType());
3020 Addr =
Builder.CreateElementBitCast(Addr, NewTy);
3025 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3026 "Expected pointer to array");
3031 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3039 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3043 const Expr *SubExpr = CE->getSubExpr();
3056 const llvm::Twine &name =
"arrayidx") {
3059 CodeGenFunction::NotSubtraction, loc,
3062 return CGF.
Builder.CreateGEP(ptr, indices, name);
3071 if (
auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3072 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3094 const llvm::Twine &name =
"arrayidx") {
3097 for (
auto idx : indices.drop_back())
3098 assert(isa<llvm::ConstantInt>(idx) &&
3099 cast<llvm::ConstantInt>(idx)->isZero());
3114 CGF, addr.
getPointer(), indices, inbounds, signedIndices, loc, name);
3115 return Address(eltPtr, eltAlign);
3124 bool SignedIndices =
false;
3125 auto EmitIdxAfterBase = [&, IdxPre](
bool Promote) ->
llvm::Value * {
3128 assert(E->
getRHS() == E->
getIdx() &&
"index was neither LHS nor RHS");
3129 Idx = EmitScalarExpr(E->
getIdx());
3134 SignedIndices |= IdxSigned;
3136 if (SanOpts.has(SanitizerKind::ArrayBounds))
3137 EmitBoundsCheck(E, E->
getBase(), Idx, IdxTy, Accessed);
3140 if (Promote && Idx->getType() != IntPtrTy)
3141 Idx =
Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned,
"idxprom");
3150 !isa<ExtVectorElementExpr>(E->
getBase())) {
3153 auto *Idx = EmitIdxAfterBase(
false);
3154 assert(LHS.
isSimple() &&
"Can only subscript lvalue vectors here!");
3155 return LValue::MakeVectorElt(LHS.
getAddress(), Idx,
3163 if (isa<ExtVectorElementExpr>(E->
getBase())) {
3165 auto *Idx = EmitIdxAfterBase(
true);
3166 Address Addr = EmitExtVectorElementLValue(LV);
3171 return MakeAddrLValue(Addr, EltType, LV.
getBaseInfo());
3175 Address Addr = Address::invalid();
3177 getContext().getAsVariableArrayType(E->
getType())) {
3181 Addr = EmitPointerWithAlignment(E->
getBase(), &BaseInfo);
3182 auto *Idx = EmitIdxAfterBase(
true);
3191 if (getLangOpts().isSignedOverflowDefined()) {
3192 Idx =
Builder.CreateMul(Idx, numElements);
3194 Idx =
Builder.CreateNSWMul(Idx, numElements);
3198 !getLangOpts().isSignedOverflowDefined(),
3205 Addr = EmitPointerWithAlignment(E->
getBase(), &BaseInfo);
3206 auto *Idx = EmitIdxAfterBase(
true);
3208 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3210 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.
getQuantity());
3218 llvm::Type *OrigBaseTy = Addr.
getType();
3219 Addr =
Builder.CreateElementBitCast(Addr, Int8Ty);
3227 Addr =
Address(EltPtr, EltAlign);
3230 Addr =
Builder.CreateBitCast(Addr, OrigBaseTy);
3236 assert(Array->getType()->isArrayType() &&
3237 "Array to pointer decay must have array source type!");
3241 if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3242 ArrayLV = EmitArraySubscriptExpr(ASE,
true);
3244 ArrayLV = EmitLValue(Array);
3245 auto *Idx = EmitIdxAfterBase(
true);
3250 E->
getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3252 BaseInfo = ArrayLV.getBaseInfo();
3255 Addr = EmitPointerWithAlignment(E->
getBase(), &BaseInfo);
3256 auto *Idx = EmitIdxAfterBase(
true);
3258 !getLangOpts().isSignedOverflowDefined(),
3266 if (getLangOpts().ObjC1 &&
3277 bool IsLowerBound) {
3294 "Expected pointer to array");
3311 bool IsLowerBound) {
3319 if (
auto *AT = getContext().getAsArrayType(BaseTy))
3320 ResultExprTy = AT->getElementType();
3330 EmitScalarExpr(LowerBound), IntPtrTy,
3331 LowerBound->getType()->hasSignedIntegerRepresentation());
3333 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3338 auto &C = CGM.getContext();
3340 llvm::APSInt ConstLength;
3343 if (
Length->isIntegerConstantExpr(ConstLength, C)) {
3344 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3348 llvm::APSInt ConstLowerBound(PointerWidthInBits,
false);
3349 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3350 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3351 LowerBound =
nullptr;
3355 else if (!LowerBound)
3358 if (
Length || LowerBound) {
3359 auto *LowerBoundVal =
3362 EmitScalarExpr(LowerBound), IntPtrTy,
3363 LowerBound->getType()->hasSignedIntegerRepresentation())
3364 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3368 EmitScalarExpr(
Length), IntPtrTy,
3369 Length->getType()->hasSignedIntegerRepresentation())
3370 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3371 Idx =
Builder.CreateAdd(LowerBoundVal, LengthVal,
"lb_add_len",
3373 !getLangOpts().isSignedOverflowDefined());
3374 if (
Length && LowerBound) {
3376 Idx, llvm::ConstantInt::get(IntPtrTy, 1),
"idx_sub_1",
3377 false, !getLangOpts().isSignedOverflowDefined());
3380 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3386 if (
auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3387 Length = VAT->getSizeExpr();
3388 if (
Length->isIntegerConstantExpr(ConstLength, C))
3391 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3392 ConstLength = CAT->getSize();
3395 auto *LengthVal =
Builder.CreateIntCast(
3396 EmitScalarExpr(
Length), IntPtrTy,
3397 Length->getType()->hasSignedIntegerRepresentation());
3399 LengthVal, llvm::ConstantInt::get(IntPtrTy, 1),
"len_sub_1",
3400 false, !getLangOpts().isSignedOverflowDefined());
3402 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3404 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3410 Address EltPtr = Address::invalid();
3412 if (
auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3418 VLA->getElementType(), IsLowerBound);
3426 if (getLangOpts().isSignedOverflowDefined())
3427 Idx =
Builder.CreateMul(Idx, NumElements);
3429 Idx =
Builder.CreateNSWMul(Idx, NumElements);
3431 !getLangOpts().isSignedOverflowDefined(),
3438 assert(Array->getType()->isArrayType() &&
3439 "Array to pointer decay must have array source type!");
3443 if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3444 ArrayLV = EmitArraySubscriptExpr(ASE,
true);
3446 ArrayLV = EmitLValue(Array);
3451 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
3453 BaseInfo = ArrayLV.getBaseInfo();
3456 BaseTy, ResultExprTy, IsLowerBound);
3458 !getLangOpts().isSignedOverflowDefined(),
3462 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
3477 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
3478 Base.getQuals().removeObjCGCAttr();
3483 Base = EmitLValue(E->
getBase());
3487 "Result must be a vector");
3492 Builder.CreateStore(Vec, VecMem);
3505 llvm::Constant *CV =
3506 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3510 assert(Base.
isExtVectorElt() &&
"Can only subscript lvalue vec elts here!");
3515 for (
unsigned i = 0, e = Indices.size(); i != e; ++i)
3516 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3517 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3528 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
3531 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3533 SkippedChecks.
set(SanitizerKind::Alignment,
true);
3534 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
3535 SkippedChecks.
set(SanitizerKind::Null,
true);
3538 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
3540 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3543 if (
auto *Field = dyn_cast<FieldDecl>(ND)) {
3544 LValue LV = EmitLValueForField(BaseLV, Field);
3549 if (
auto *VD = dyn_cast<VarDecl>(ND))
3552 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
3555 llvm_unreachable(
"Unhandled member declaration!");
3561 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3562 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->
getParent());
3564 getContext().getTagDeclType(Field->
getParent());
3565 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3566 return EmitLValueForField(LambdaLV, Field);
3586 "LLVM field at index zero had non-zero offset?");
3601 if (RD->isDynamicClass())
3604 for (
const auto &
Base : RD->bases())
3608 for (
const FieldDecl *Field : RD->fields())
3623 if (rec->isUnion() || rec->hasAttr<MayAliasAttr>())
3624 FieldBaseInfo.setMayAlias(
true);
3625 bool mayAlias = FieldBaseInfo.getMayAlias();
3629 CGM.getTypes().getCGRecordLayout(field->
getParent());
3638 llvm::Type *FieldIntTy =
3639 llvm::Type::getIntNTy(getLLVMContext(), Info.
StorageSize);
3641 Addr =
Builder.CreateElementBitCast(Addr, FieldIntTy);
3645 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
3651 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3652 if (rec->isUnion()) {
3658 const auto FieldType = field->
getType();
3659 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3671 llvm::LoadInst *load =
Builder.CreateLoad(addr,
"ref");
3676 if (CGM.shouldUseTBAA()) {
3679 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3681 tbaa = CGM.getTBAAInfo(type);
3683 CGM.DecorateInstructionWithTBAA(load, tbaa);
3690 getNaturalTypeAlignment(type, &FieldBaseInfo,
true);
3691 FieldBaseInfo.setMayAlias(
false);
3692 addr =
Address(load, alignment);
3705 addr =
Builder.CreateElementBitCast(addr,
3706 CGM.getTypes().ConvertTypeForMem(type),
3709 if (field->
hasAttr<AnnotateAttr>())
3710 addr = EmitFieldAnnotations(field, addr);
3712 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
3716 getContext().getASTRecordLayout(field->
getParent());
3722 getContext().getCharWidth());
3733 LV.
setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3744 return EmitLValueForField(Base, Field);
3749 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3757 return MakeAddrLValue(V, FieldType, FieldBaseInfo);
3764 return MakeAddrLValue(GlobalPtr, E->
getType(), BaseInfo);
3768 EmitVariablyModifiedType(E->
getType());
3770 Address DeclPtr = CreateMemTemp(E->
getType(),
".compoundliteral");
3783 return EmitAggExprToLValue(E);
3786 assert(E->
isTransparent() &&
"non-transparent glvalue init list");
3787 return EmitLValue(E->
getInit(0));
3794 const Expr *Operand) {
3795 if (
auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->
IgnoreParens())) {
3807 assert(hasAggregateEvaluationKind(expr->
getType()) &&
3808 "Unexpected conditional operator!");
3809 return EmitAggExprToLValue(expr);
3816 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3818 if (!CondExprBool) std::swap(live, dead);
3820 if (!ContainsLabel(dead)) {
3823 incrementProfileCounter(expr);
3824 return EmitLValue(live);
3828 llvm::BasicBlock *lhsBlock = createBasicBlock(
"cond.true");
3829 llvm::BasicBlock *rhsBlock = createBasicBlock(
"cond.false");
3830 llvm::BasicBlock *contBlock = createBasicBlock(
"cond.end");
3833 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3836 EmitBlock(lhsBlock);
3837 incrementProfileCounter(expr);
3843 if (lhs && !lhs->isSimple())
3844 return EmitUnsupportedLValue(expr,
"conditional operator");
3846 lhsBlock =
Builder.GetInsertBlock();
3851 EmitBlock(rhsBlock);
3856 if (rhs && !rhs->isSimple())
3857 return EmitUnsupportedLValue(expr,
"conditional operator");
3858 rhsBlock =
Builder.GetInsertBlock();
3860 EmitBlock(contBlock);
3863 llvm::PHINode *phi =
Builder.CreatePHI(lhs->getPointer()->getType(),
3865 phi->addIncoming(lhs->getPointer(), lhsBlock);
3866 phi->addIncoming(rhs->getPointer(), rhsBlock);
3867 Address result(phi,
std::min(lhs->getAlignment(), rhs->getAlignment()));
3869 std::max(lhs->getBaseInfo().getAlignmentSource(),
3870 rhs->getBaseInfo().getAlignmentSource());
3871 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3872 rhs->getBaseInfo().getMayAlias();
3873 return MakeAddrLValue(result, expr->
getType(),
3876 assert((lhs || rhs) &&
3877 "both operands of glvalue conditional are throw-expressions?");
3878 return lhs ? *lhs : *rhs;
3893 case CK_ArrayToPointerDecay:
3894 case CK_FunctionToPointerDecay:
3895 case CK_NullToMemberPointer:
3896 case CK_NullToPointer:
3897 case CK_IntegralToPointer:
3898 case CK_PointerToIntegral:
3899 case CK_PointerToBoolean:
3900 case CK_VectorSplat:
3901 case CK_IntegralCast:
3902 case CK_BooleanToSignedIntegral:
3903 case CK_IntegralToBoolean:
3904 case CK_IntegralToFloating:
3905 case CK_FloatingToIntegral:
3906 case CK_FloatingToBoolean:
3907 case CK_FloatingCast:
3908 case CK_FloatingRealToComplex:
3909 case CK_FloatingComplexToReal:
3910 case CK_FloatingComplexToBoolean:
3911 case CK_FloatingComplexCast:
3912 case CK_FloatingComplexToIntegralComplex:
3913 case CK_IntegralRealToComplex:
3914 case CK_IntegralComplexToReal:
3915 case CK_IntegralComplexToBoolean:
3916 case CK_IntegralComplexCast:
3917 case CK_IntegralComplexToFloatingComplex:
3918 case CK_DerivedToBaseMemberPointer:
3919 case CK_BaseToDerivedMemberPointer:
3920 case CK_MemberPointerToBoolean:
3921 case CK_ReinterpretMemberPointer:
3922 case CK_AnyPointerToBlockPointerCast:
3923 case CK_ARCProduceObject:
3924 case CK_ARCConsumeObject:
3925 case CK_ARCReclaimReturnedObject:
3926 case CK_ARCExtendBlockObject:
3927 case CK_CopyAndAutoreleaseBlockObject:
3928 case CK_AddressSpaceConversion:
3929 case CK_IntToOCLSampler:
3930 return EmitUnsupportedLValue(E,
"unexpected cast lvalue");
3933 llvm_unreachable(
"dependent cast kind in IR gen!");
3935 case CK_BuiltinFnToFnPtr:
3936 llvm_unreachable(
"builtin functions are handled elsewhere");
3939 case CK_NonAtomicToAtomic:
3940 case CK_AtomicToNonAtomic:
3941 return EmitAggExprToLValue(E);
3946 const auto *DCE = cast<CXXDynamicCastExpr>(
E);
3947 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->
getType());
3950 case CK_ConstructorConversion:
3951 case CK_UserDefinedConversion:
3952 case CK_CPointerToObjCPointerCast:
3953 case CK_BlockPointerToObjCPointerCast:
3955 case CK_LValueToRValue:
3958 case CK_UncheckedDerivedToBase:
3959 case CK_DerivedToBase: {
3962 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->
getDecl());
3965 Address This = LV.getAddress();
3972 return MakeAddrLValue(Base, E->
getType(), LV.getBaseInfo());
3975 return EmitAggExprToLValue(E);
3976 case CK_BaseToDerived: {
3978 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->
getDecl());
3984 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3990 if (sanitizePerformTypeCheck())
3991 EmitTypeCheck(TCK_DowncastReference, E->
getExprLoc(),
3992 Derived.getPointer(), E->
getType());
3994 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
3995 EmitVTablePtrCheckForCast(E->
getType(), Derived.getPointer(),
3999 return MakeAddrLValue(Derived, E->
getType(), LV.getBaseInfo());
4001 case CK_LValueBitCast: {
4003 const auto *CE = cast<ExplicitCastExpr>(
E);
4005 CGM.EmitExplicitCastExprType(CE,
this);
4008 ConvertType(CE->getTypeAsWritten()));
4010 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4011 EmitVTablePtrCheckForCast(E->
getType(), V.getPointer(),
4017 case CK_ObjCObjectLValueCast: {
4023 case CK_ZeroToOCLQueue:
4024 llvm_unreachable(
"NULL to OpenCL queue lvalue cast is not valid");
4025 case CK_ZeroToOCLEvent:
4026 llvm_unreachable(
"NULL to OpenCL event lvalue cast is not valid");
4029 llvm_unreachable(
"Unhandled lvalue cast kind?");
4033 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4034 return getOpaqueLValueMapping(e);
4041 LValue FieldLV = EmitLValueForField(LV, FD);
4042 switch (getEvaluationKind(FT)) {
4044 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4052 return EmitLoadOfLValue(FieldLV, Loc);
4054 llvm_unreachable(
"bad evaluation kind");
4065 return EmitBlockCallExpr(E, ReturnValue);
4067 if (
const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4068 return EmitCXXMemberCallExpr(CE, ReturnValue);
4070 if (
const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
4071 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4073 if (
const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
4075 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4076 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4101 return CGCallee::forBuiltin(builtinID, FD);
4105 return CGCallee::forDirect(calleePtr, FD);
4112 if (
auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4113 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4114 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4115 return EmitCallee(ICE->getSubExpr());
4119 }
else if (
auto DRE = dyn_cast<DeclRefExpr>(E)) {
4120 if (
auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4123 }
else if (
auto ME = dyn_cast<MemberExpr>(E)) {
4124 if (
auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4125 EmitIgnoredExpr(ME->getBase());
4130 }
else if (
auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4131 return EmitCallee(NTTP->getReplacement());
4134 }
else if (
auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4135 return CGCallee::forPseudoDestructor(PDE);
4142 calleePtr = EmitScalarExpr(E);
4146 calleePtr = EmitLValue(E).getPointer();
4151 CGCallee callee(calleeInfo, calleePtr);
4158 EmitIgnoredExpr(E->
getLHS());
4159 EnsureInsertPoint();
4160 return EmitLValue(E->
getRHS());
4165 return EmitPointerToDataMemberBinaryExpr(E);
4167 assert(E->
getOpcode() == BO_Assign &&
"unexpected binary l-value");
4172 switch (getEvaluationKind(E->
getType())) {
4176 return EmitARCStoreStrong(E,
false).first;
4179 return EmitARCStoreAutoreleasing(E).first;
4192 EmitStoreThroughLValue(RV, LV);
4197 return EmitComplexAssignmentLValue(E);
4200 return EmitAggExprToLValue(E);
4202 llvm_unreachable(
"bad evaluation kind");
4206 RValue RV = EmitCallExpr(E);
4213 "Can't have a scalar return unless the return type is a "
4221 return EmitAggExprToLValue(E);
4226 &&
"binding l-value to type which needs a temporary");
4228 EmitCXXConstructExpr(E, Slot);
4229 return MakeAddrLValue(Slot.getAddress(), E->
getType(),
4235 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->
getType());
4239 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4244 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->
getType(),
4261 EmitLambdaExpr(E, Slot);
4267 RValue RV = EmitObjCMessageExpr(E);
4274 "Can't have a scalar return unless the return type is a "
4282 CGM.getObjCRuntime().GetAddrOfSelector(*
this, E->
getSelector());
4283 return MakeAddrLValue(V, E->
getType(),
4289 return CGM.getObjCRuntime().EmitIvarOffset(*
this, Interface, Ivar);
4295 unsigned CVRQualifiers) {
4296 return CGM.getObjCRuntime().EmitObjCValueForIvar(*
this, ObjectTy, BaseValue,
4297 Ivar, CVRQualifiers);
4307 BaseValue = EmitScalarExpr(BaseExpr);
4311 LValue BaseLV = EmitLValue(BaseExpr);
4313 ObjectTy = BaseExpr->
getType();
4318 EmitLValueForIvar(ObjectTy, BaseValue, E->
getDecl(),
4326 RValue RV = EmitAnyExprToTemp(E);
4337 "Call must have function pointer type!");
4341 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4348 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4349 TargetDecl->hasAttr<TargetAttr>())
4350 checkTargetFeatures(E, FD);
4354 const auto *FnType =
4355 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4359 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4360 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4361 if (llvm::Constant *PrefixSig =
4362 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4364 llvm::Constant *FTRTTIConst =
4365 CGM.GetAddrOfRTTIDescriptor(
QualType(FnType, 0),
true);
4366 llvm::Type *PrefixStructTyElems[] = {
4367 PrefixSig->getType(),
4368 FTRTTIConst->getType()
4370 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4371 CGM.getLLVMContext(), PrefixStructTyElems,
true);
4373 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4376 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4378 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4380 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4383 llvm::BasicBlock *Cont = createBasicBlock(
"cont");
4384 llvm::BasicBlock *TypeCheck = createBasicBlock(
"typecheck");
4385 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4387 EmitBlock(TypeCheck);
4389 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4391 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4393 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4394 llvm::Constant *StaticData[] = {
4396 EmitCheckTypeDescriptor(CalleeType)
4398 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4399 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4408 if (SanOpts.has(SanitizerKind::CFIICall) &&
4409 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4411 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4413 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
QualType(FnType, 0));
4414 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4416 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4419 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4421 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4422 llvm::Constant *StaticData[] = {
4423 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4425 EmitCheckTypeDescriptor(
QualType(FnType, 0)),
4427 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4428 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4429 CastedCallee, StaticData);
4431 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4432 SanitizerHandler::CFICheckFail, StaticData,
4433 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4439 Args.
add(RValue::get(
Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4440 CGM.getContext().VoidPtrTy);
4449 if (
auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4450 if (OCE->isAssignmentOp())
4451 Order = EvaluationOrder::ForceRightToLeft;
4453 switch (OCE->getOperator()) {
4455 case OO_GreaterGreater:
4460 Order = EvaluationOrder::ForceLeftToRight;
4468 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->
arguments(),
4471 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4472 Args, FnType, Chain);
4494 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4495 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4496 CalleeTy = CalleeTy->getPointerTo();
4498 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4499 CalleePtr =
Builder.CreateBitCast(CalleePtr, CalleeTy,
"callee.knr.cast");
4500 Callee.setFunctionPointer(CalleePtr);
4503 return EmitCall(FnInfo, Callee, ReturnValue, Args);
4508 Address BaseAddr = Address::invalid();
4510 BaseAddr = EmitPointerWithAlignment(E->
getLHS());
4512 BaseAddr = EmitLValue(E->
getLHS()).getAddress();
4522 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
4524 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
4532 LValue lvalue = MakeAddrLValue(addr, type,
4534 switch (getEvaluationKind(type)) {
4536 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4540 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4542 llvm_unreachable(
"bad evaluation kind");
4545 void CodeGenFunction::SetFPAccuracy(
llvm::Value *Val,
float Accuracy) {
4546 assert(Val->getType()->isFPOrFPVectorTy());
4547 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4550 llvm::MDBuilder MDHelper(getLLVMContext());
4551 llvm::MDNode *
Node = MDHelper.createFPMath(Accuracy);
4553 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4557 struct LValueOrRValue {
4571 LValueOrRValue result;
4575 const Expr *semantic = *i;
4579 if (
const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4585 if (ov == resultExpr && ov->
isRValue() && !forLValue &&
4586 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4591 opaqueData = OVMA::bind(CGF, ov, LV);
4596 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4599 if (ov == resultExpr) {
4607 opaques.push_back(opaqueData);
4611 }
else if (semantic == resultExpr) {
4624 for (
unsigned i = 0, e = opaques.size(); i != e; ++i)
4625 opaques[i].unbind(CGF);
unsigned getNumElements() const
unsigned getAddressSpace() const
Return the address space of this type.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
ReturnValueSlot - Contains the address where the return value of a function can be stored...
SourceLocation getExprLoc() const LLVM_READONLY
Defines the clang::ASTContext interface.
const Expr * getBase() const
StmtClass getStmtClass() const
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
CastKind getCastKind() const
unsigned getVRQualifiers() const
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
void end(CodeGenFunction &CGF)
Parameter for captured context.
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
PointerType - C99 6.7.5.1 - Pointer Declarators.
A (possibly-)qualified type.
llvm::Value * getPointer() const
CodeGenTypes & getTypes()
unsigned getColumn() const
Return the presumed column number of this location.
llvm::Type * ConvertTypeForMem(QualType T)
const TargetCodeGenInfo & getTargetHooks() const
Expr * getBaseIvarExp() const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
bool isBitField() const
Determines whether this field is a bitfield.
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
llvm::Module & getModule() const
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
AlignmentSource
The source of the alignment of an l-value; an expression of confidence in the alignment actually matc...
llvm::LLVMContext & getLLVMContext()
LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
const TargetInfo & getTarget() const
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
bool isRecordType() const
Decl - This represents one declaration (or definition), e.g.
Address getAddress() const
static void pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, const Expr *E, Address ReferenceTemporary)
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, QualType Type, CharUnits Alignment=CharUnits::Zero(), SanitizerSet SkippedChecks=SanitizerSet())
Emit a check that V is the address of storage of the appropriate size and alignment for an object of ...
void setTBAAInfo(llvm::MDNode *N)
static llvm::Value * emitArraySubscriptGEP(CodeGenFunction &CGF, llvm::Value *ptr, ArrayRef< llvm::Value * > indices, bool inbounds, bool signedIndices, SourceLocation loc, const llvm::Twine &name="arrayidx")
static void emitCheckHandlerCall(CodeGenFunction &CGF, llvm::FunctionType *FnType, ArrayRef< llvm::Value * > FnArgs, SanitizerHandler CheckHandler, CheckRecoverableKind RecoverKind, bool IsFatal, llvm::BasicBlock *ContBB)
const CastExpr * BasePath
const llvm::DataLayout & getDataLayout() const
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
static Destroyer destroyARCStrongPrecise
Expr * getLowerBound()
Get lower bound of array section.
The base class of the type hierarchy.
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, LValue &LV, bool IsMemberAccess=false)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e)
RValue asAggregateRValue() const
std::unique_ptr< llvm::MemoryBuffer > Buffer
Represents an array type, per C99 6.7.5.2 - Array Declarators.
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
static llvm::Value * EmitBitCastOfLValueToProperType(CodeGenFunction &CGF, llvm::Value *V, llvm::Type *IRType, StringRef Name=StringRef())
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
Represents a call to a C++ constructor.
static LValue EmitThreadPrivateVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, llvm::Type *RealVarTy, SourceLocation Loc)
bool isBooleanType() const
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
void ForceCleanup(std::initializer_list< llvm::Value ** > ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, bool forPointeeType=false)
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
const LangOptions & getLangOpts() const
bool isBlockPointerType() const
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
IdentType getIdentType() const
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
static Destroyer destroyARCWeak
void * getAsOpaquePtr() const
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)?
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Objects with "hidden" visibility are not seen by the dynamic linker.
llvm::Type * getElementType() const
Return the type of the values stored in this address.
static bool hasBooleanRepresentation(QualType Ty)
CompoundLiteralExpr - [C99 6.5.2.5].
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
const Expr * getCallee() const
TLSKind getTLSKind() const
ObjCLifetime getObjCLifetime() const
void setTBAAOffset(uint64_t O)
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
Address getVectorAddress() const
SourceLocation getLocation() const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
The collection of all-type qualifiers we support.
llvm::Constant * getPointer() const
RecordDecl - Represents a struct/union/class.
An object to manage conditionally-evaluated expressions.
void setTBAABaseType(QualType T)
bool isVolatileQualified() const
Represents a class type in Objective C.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceLocation getExprLoc() const LLVM_READONLY
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
bool isReferenceType() const
llvm::Constant * getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, bool IsLowerBound=true)
SourceLocation getExprLoc() const LLVM_READONLY
unsigned getCVRQualifiers() const
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, llvm::APInt &Min, llvm::APInt &End, bool StrictEnums, bool IsBool)
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
void setBaseIvarExp(Expr *V)
bool isPseudoDestructor() const
void InitTempAlloca(Address Alloca, llvm::Value *Value)
InitTempAlloca - Provide an initial value for the given alloca which will be observable at all locati...
static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field)
Drill down to the storage of a field without walking into reference types.
static bool isFlexibleArrayMemberExpr(const Expr *E)
Determine whether this expression refers to a flexible array member in a struct.
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
const Expr *const * const_semantics_iterator
void setNonGC(bool Value)
Address CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Describes an C or C++ initializer list.
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
unsigned Size
The total size of the bit-field, in bits.
static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, const PseudoObjectExpr *E, bool forLValue, AggValueSlot slot)
CharUnits getAlignment() const
const LangOptions & getLangOpts() const
Expr * getTrueExpr() const
Address CreateElementBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Cast the element type of the given address to a different type, preserving information like the align...
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.
const Qualifiers & getQuals() const
const ValueDecl * getExtendingDecl() const
Get the declaration which triggered the lifetime-extension of this temporary, if any.
static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, const FunctionDecl *FD)
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
path_iterator path_begin()
const FunctionDecl * getBuiltinDecl() const
void addCVRQualifiers(unsigned mask)
semantics_iterator semantics_end()
A builtin binary operation expression such as "x + y" or "x <= y".
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...
RecordDecl * getDecl() const
static AlignmentSource getFieldAlignmentSource(AlignmentSource Source)
Given that the base address has the given alignment source, what's our confidence in the alignment of...
virtual llvm::Value * EmitMemberPointerIsNotNull(CodeGenFunction &CGF, llvm::Value *MemPtr, const MemberPointerType *MPT)
Determine if a member pointer is non-null. Returns an i1.
#define LIST_SANITIZER_CHECKS
Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, llvm::Value *memberPtr, const MemberPointerType *memberPtrType, LValueBaseInfo *BaseInfo=nullptr)
Emit the address of a field using a member data pointer.
Scope - A scope is a transient data structure that is used while parsing the program.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
void addQualifiers(Qualifiers Q)
Add the qualifiers from the given set to this set.
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
An adjustment to be made to the temporary created when emitting a reference binding, which accesses a particular subobject of that temporary.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
AlignmentSource getAlignmentSource() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Represents binding an expression to a temporary.
CXXTemporary * getTemporary()
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type...
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned getLine() const
Return the presumed line number of this location.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
void setARCPreciseLifetime(ARCPreciseLifetime_t value)
bool isExtVectorElt() const
Represents an ObjC class declaration.
Checking the operand of a cast to a virtual base object.
detail::InMemoryDirectory::const_iterator I
llvm::Value * EmitCheckedInBoundsGEP(llvm::Value *Ptr, ArrayRef< llvm::Value * > IdxList, bool SignedIndices, bool IsSubtraction, SourceLocation Loc, const Twine &Name="")
Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to detect undefined behavior whe...
static CharUnits getArrayElementAlign(CharUnits arrayAlign, llvm::Value *idx, CharUnits eltSize)
void begin(CodeGenFunction &CGF)
void setThreadLocalRef(bool Value)
This object can be modified without requiring retains or releases.
LValue EmitLValueForField(LValue Base, const FieldDecl *Field)
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor)
isTypeConstant - Determine whether an object of this type can be emitted as a constant.
EnumDecl * getDecl() const
OpenMP 4.0 [2.4, Array Sections].
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type...
static CharUnits One()
One - Construct a CharUnits quantity of one.
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Represents a prototype with parameter type info, e.g.
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
const Decl * getCalleeDecl() const
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
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...
static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind)
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType LValType)=0
Emit a reference to a non-local thread_local variable (including triggering the initialization of all...
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
const CXXPseudoDestructorExpr * getPseudoDestructorExpr() const
Address getBitFieldAddress() const
Represents a call to the builtin function __builtin_va_arg.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
bool isFunctionPointerType() const
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
const ObjCMethodDecl * getMethodDecl() const
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
static TypeEvaluationKind getEvaluationKind(QualType T)
hasAggregateLLVMType - Return true if the specified AST type will map into an aggregate LLVM type or ...
llvm::Value * getPointer() const
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
llvm::Function * generateDestroyHelper(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD)
generateDestroyHelper - Generates a helper function which, when invoked, destroys the given object...
Expr - This represents one expression.
CGCXXABI & getCXXABI() const
bool isAnyComplexType() const
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type, where the destination type is an LLVM scalar type.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
const CGCalleeInfo & getAbstractInfo() const
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.
void setObjCArray(bool Value)
bool isAtomicType() const
Represents a C++ destructor within a class.
static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, LValueBaseInfo &BaseInfo, QualType BaseTy, QualType ElTy, bool IsLowerBound)
bool isVariableArrayType() const
static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, llvm::Value *ThisValue)
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp")
CreateAggTemp - Create a temporary memory object for the given aggregate type.
ASTContext & getContext() const
bool isFloatingType() const
ObjCSelectorExpr used for @selector in Objective-C.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
void add(RValue rvalue, QualType type, bool needscopy=false)
static Optional< LValue > EmitLValueOrThrowExpression(CodeGenFunction &CGF, const Expr *Operand)
Emit the operand of a glvalue conditional operator.
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::Constant *Dtor, llvm::Constant *Addr)=0
Emit code to force the execution of a destructor during global teardown.
Selector getSelector() const
llvm::LLVMContext & getLLVMContext()
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Expr * getSubExpr() const
bool isThreadLocalRef() const
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
An expression that sends a message to the given Objective-C object or class.
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Represents an unpacked "presumed" location which can be presented to the user.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Represents a GCC generic vector type.
llvm::Value * EmitCastToVoidPtr(llvm::Value *value)
Emit a cast to void* in the appropriate address space.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=None)
The scope of a CXXDefaultInitExpr.
QualType getElementType() const
ConstantEmissionKind
Can we constant-emit a load of a reference to a variable of the given type? This is different from pr...
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, IsZeroed_t isZeroed=IsNotZeroed)
forAddr - Make a slot for an aggregate value.
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
GlobalDecl - represents a global declaration.
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
Dynamic storage duration.
The l-value was considered opaque, so the alignment was determined from a type.
bool isNontemporal() const
There is no lifetime qualification on this type.
const SanitizerHandlerInfo SanitizerHandlers[]
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
Assigning into this object requires the old value to be released and the new value to be retained...
static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM)
Named Registers are named metadata pointing to the register name which will be read from/written to a...
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
const char * getFilename() const
Return the presumed filename of this location.
llvm::Constant * EmitConstantExpr(const Expr *E, QualType DestType, CodeGenFunction *CGF=nullptr)
Try to emit the given expression as a constant; returns 0 if the expression cannot be emitted as a co...
ASTContext & getContext() const
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup...
static llvm::Constant * EmitFunctionDeclPointer(CodeGenModule &CGM, const FunctionDecl *FD)
Encodes a location in the source.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
QualType getElementType() const
QualType withCVRQualifiers(unsigned CVR) const
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
SourceLocation getExprLoc() const LLVM_READONLY
const CGBitFieldInfo & getBitFieldInfo() const
bool isValid() const
Return true if this is a valid SourceLocation object.
llvm::MDNode * getTBAAInfo() const
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > PL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Checking the operand of a cast to a base object.
A scoped helper to set the current debug location to the specified location or preferred location of ...
llvm::Value * EmitLifetimeStart(uint64_t Size, llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Represents a static or instance method of a struct/union/class.
static bool hasAnyVptr(const QualType Type, const ASTContext &Context)
static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, const Expr *E, const VarDecl *VD)
SanitizerSet SanOpts
Sanitizers enabled for this function.
static QualType getFixedSizeElementType(const ASTContext &ctx, const VariableArrayType *vla)
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
const CodeGenOptions & getCodeGenOpts() const
TypeCheckKind
Situations in which we might emit a check for the suitability of a pointer or glvalue.
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
StringLiteral * getFunctionName()
void setObjCIvar(bool Value)
QualType getReturnType() const
const T * castAs() const
Member-template castAs<specific type>.
All available information about a concrete callee.
unsigned getAddressSpace() const
Return the address space that this address resides in.
bool isVectorType() const
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Assigning into this object requires a lifetime extension.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Address getExtVectorAddress() const
const Expr * getBase() const
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
llvm::Value * getGlobalReg() const
LValueBaseInfo getBaseInfo() const
static Destroyer destroyARCStrongImprecise
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
QualType getPointeeType() const
void setExternallyDestructed(bool destructed=true)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type, returning the result.
decl_iterator - Iterates through the declarations stored within this context.
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
FunctionArgList - Type for representing both the decl and type of parameters to a function...
ast_type_traits::DynTypedNode Node
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
TLS with a dynamic initializer.
CGFunctionInfo - Class to encapsulate the information about a function definition.
CharUnits getAlignment() const
Return the alignment of this pointer.
This class organizes the cross-function state that is used while generating LLVM code.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
[C99 6.4.2.2] - A predefined identifier such as func.
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
EvalResult is a struct with detailed info about an evaluated expression.
Decl * getReferencedDeclOfCallee()
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored...
Address CreateStructGEP(Address Addr, unsigned Index, CharUnits Offset, const llvm::Twine &Name="")
Checking the bound value in a reference binding.
unsigned IsSigned
Whether the bit-field is signed.
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
llvm::IntegerType * IntPtrTy
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
enum clang::SubobjectAdjustment::@36 Kind
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
EnumDecl - Represents an enum.
detail::InMemoryDirectory::const_iterator E
A pointer to member type per C++ 8.3.3 - Pointers to members.
semantics_iterator semantics_begin()
ExplicitCastExpr - An explicit cast written in the source code.
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).
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type. ...
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
const VariableArrayType * getAsVariableArrayType(QualType T) const
static Address createReferenceTemporary(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, const Expr *Inner)
static bool hasAggregateEvaluationKind(QualType T)
llvm::Constant * getExtVectorElts() const
bool HasSideEffects
Whether the evaluated expression has side effects.
llvm::PointerType * getType() const
Return the type of the pointer value.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Complex values, per C99 6.2.5p11.
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
const T * getAs() const
Member-template getAs<specific type>'.
Checking the operand of a static_cast to a derived pointer type.
Expr * getFalseExpr() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
virtual llvm::Optional< unsigned > getConstantAddressSpace() const
Return an AST address space which can be used opportunistically for constant global memory...
QualType getCanonicalType() const
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
static StringRef getIdentTypeName(IdentType IT)
ObjCEncodeExpr, used for @encode in Objective-C.
virtual bool usesThreadWrapperFunction() const =0
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
llvm::PointerType * Int8PtrTy
SourceLocation getLocStart() const LLVM_READONLY
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
bool isFunctionType() const
QualType getTBAABaseType() const
LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy)
static llvm::Value * emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low, llvm::Value *High)
Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
Address getAddress() const
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
Base for LValueReferenceType and RValueReferenceType.
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.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
void setGlobalObjCRef(bool Value)
SourceLocation getExprLoc() const LLVM_READONLY
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type, returning the result.
const Expr * getInitializer() const
unsigned getFieldIndex() const
getFieldIndex - Returns the index of this field within its record, as appropriate for passing to ASTR...
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
QualType getPointeeType() const
ObjCIvarRefExpr - A reference to an ObjC instance variable.
llvm::Value * getVectorIdx() const
Reading or writing from this object requires a barrier call.
void setCurrentStmt(const Stmt *S)
If the execution count for the current statement is known, record that as the current count...
virtual llvm::Value * performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, llvm::Value *V, unsigned SrcAddr, unsigned DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
Perform address space cast of an expression of pointer type.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
static bool isConstantEmittableObjectType(QualType type)
Given an object of the given canonical type, can we safely copy a value out of it based on its initia...
A non-RAII class containing all the information about a bound opaque value.
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum...
Represents a C++ struct/union/class.
bool isObjCStrong() const
BoundNodesTreeBuilder *const Builder
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset...
bool isObjCObjectPointerType() const
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
llvm::Type * ConvertType(QualType T)
static Destroyer destroyCXXObject
A specialization of Address that requires the address to be an LLVM Constant.
ObjCIvarDecl - Represents an ObjC instance variable.
LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo=LValueBaseInfo(AlignmentSource::Type))
static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD)
LValue EmitLValue(const Expr *E)
EmitLValue - Emit code to compute a designator that specifies the location of the expression...
static llvm::Value * getArrayIndexingBound(CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType)
If Base is known to point to the start of an array, return the length of that array.
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
std::pair< llvm::Value *, QualType > getVLASize(const VariableArrayType *vla)
getVLASize - Returns an LLVM value that corresponds to the size, in non-variably-sized elements...
StringLiteral - This represents a string literal expression, e.g.
Full-expression storage duration (for temporaries).
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
const MemberPointerType * MPT
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
unsigned getTargetAddressSpace(QualType T) const
A reference to a declared variable, function, enum, etc.
static RValue get(llvm::Value *V)
static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type)
QualType getElementType() const
SourceLocation getColonLoc() const
unsigned getASTAllocaAddressSpace() const
const Expr * getInit(unsigned Init) const
const Expr * getSubExpr() const
CodeGenTypes & getTypes() const
SourceLocation getLocation() const
LValue - This represents an lvalue references.
bool isGlobalObjCRef() const
NamedDecl - This represents a decl with a name.
Represents a C array with a specified size that is not an integer-constant-expression.
bool isArithmeticType() const
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Automatic storage duration (most local variables).
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
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 ...
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const CXXRecordDecl * DerivedClass
SourceLocation getLocStart() const LLVM_READONLY
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
CallArgList - Type for representing both the value and type of arguments in a call.
uint64_t getTBAAOffset() const
Address CreateMemTemp(QualType T, const Twine &Name="tmp", bool CastToDefaultAddrSpace=true)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignment...
unsigned getBuiltinID() const
Abstract information about a function or function prototype.
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
void mergeForCast(const LValueBaseInfo &Info)
Expr * getLength()
Get length of array section.
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Structure with information about how a bitfield should be accessed.
const RecordDecl * getParent() const
getParent - Returns the parent of this field declaration, which is the struct in which this field is ...
CheckRecoverableKind
Specify under what conditions this check can be recovered.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
Expr * getBase()
An array section can be written only as Base[LowerBound:Length].
bool isPointerType() const
static const Expr * isSimpleArrayDecayOperand(const Expr *E)
isSimpleArrayDecayOperand - If the specified expr is a simple decay from an array to pointer...
static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts)
getAccessedFieldNo - Given an encoded value and a result number, return the input field number being ...