37#include "llvm/ADT/APFixedPoint.h"
38#include "llvm/ADT/ScopeExit.h"
39#include "llvm/Analysis/ValueTracking.h"
40#include "llvm/IR/Argument.h"
41#include "llvm/IR/CFG.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DerivedTypes.h"
45#include "llvm/IR/FixedPointBuilder.h"
46#include "llvm/IR/Function.h"
47#include "llvm/IR/GEPNoWrapFlags.h"
48#include "llvm/IR/GetElementPtrTypeIterator.h"
49#include "llvm/IR/GlobalVariable.h"
50#include "llvm/IR/Intrinsics.h"
51#include "llvm/IR/IntrinsicsPowerPC.h"
52#include "llvm/IR/IntrinsicsWebAssembly.h"
53#include "llvm/IR/MatrixBuilder.h"
54#include "llvm/IR/Module.h"
55#include "llvm/Support/TypeSize.h"
78bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
83 const auto &LHSAP = LHS->getValue();
84 const auto &RHSAP = RHS->getValue();
85 if (Opcode == BO_Add) {
87 : LHSAP.uadd_ov(RHSAP, Overflow);
88 }
else if (Opcode == BO_Sub) {
90 : LHSAP.usub_ov(RHSAP, Overflow);
91 }
else if (Opcode == BO_Mul) {
93 : LHSAP.umul_ov(RHSAP, Overflow);
94 }
else if (Opcode == BO_Div || Opcode == BO_Rem) {
95 if (
Signed && !RHS->isZero())
96 Result = LHSAP.sdiv_ov(RHSAP, Overflow);
108 FPOptions FPFeatures;
112 bool mayHaveIntegerOverflow()
const {
114 auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
115 auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
116 if (!LHSCI || !RHSCI)
120 return ::mayHaveIntegerOverflow(
125 bool isDivremOp()
const {
131 bool mayHaveIntegerDivisionByZero()
const {
133 if (
auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
139 bool mayHaveFloatDivisionByZero()
const {
141 if (
auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
142 return CFP->isZero();
149 bool isFixedPointOp()
const {
152 if (
const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
153 QualType LHSType = BinOp->getLHS()->getType();
154 QualType RHSType = BinOp->getRHS()->getType();
157 if (
const auto *UnOp = dyn_cast<UnaryOperator>(E))
158 return UnOp->getSubExpr()->getType()->isFixedPointType();
163 bool rhsHasSignedIntegerRepresentation()
const {
164 if (
const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
165 QualType RHSType = BinOp->getRHS()->getType();
172static bool MustVisitNullValue(
const Expr *E) {
182static bool hasBoolConversionSemantics(
QualType T) {
183 if (
const auto *ED =
T->getAsEnumDecl())
184 return ED->isFixed() && ED->getIntegerType()->isBooleanType();
185 return T->isBooleanType();
204static bool IsWidenedIntegerOp(
const ASTContext &Ctx,
const Expr *E) {
214 const OverflowBehaviorType *OBT = Ty->
getAs<OverflowBehaviorType>();
219 switch (OBT->getBehaviorKind()) {
220 case OverflowBehaviorType::OverflowBehaviorKind::Wrap:
222 case OverflowBehaviorType::OverflowBehaviorKind::Trap:
225 llvm_unreachable(
"Unknown OverflowBehaviorKind");
232 switch (CGF.
getLangOpts().getSignedOverflowBehavior()) {
240 llvm_unreachable(
"Unknown SignedOverflowBehaviorTy");
244static bool CanElideOverflowCheck(
ASTContext &Ctx,
const BinOpInfo &Op) {
246 "Expected a unary or binary operator");
250 if (!Op.mayHaveIntegerOverflow())
257 const auto *BO = dyn_cast<BinaryOperator>(Op.E);
258 if (BO && BO->hasExcludedOverflowPattern())
261 if (Op.Ty.isWrapType())
263 if (Op.Ty.isTrapType())
266 if (Op.Ty->isSignedIntegerType() &&
272 if (Op.Ty->isUnsignedIntegerType() &&
297 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
303 unsigned PromotedSize = Ctx.
getTypeSize(Op.E->getType());
304 return (2 * Ctx.
getTypeSize(LHSTy)) < PromotedSize ||
308class ScalarExprEmitter
310 CodeGenFunction &CGF;
311 CGBuilderTy &Builder;
312 bool IgnoreResultAssign;
313 llvm::LLVMContext &VMContext;
316 ScalarExprEmitter(CodeGenFunction &cgf,
bool ira=
false)
317 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
318 VMContext(cgf.getLLVMContext()) {
325 bool TestAndClearIgnoreResultAssign() {
326 bool I = IgnoreResultAssign;
327 IgnoreResultAssign =
false;
331 llvm::Type *ConvertType(QualType
T) {
return CGF.
ConvertType(
T); }
332 LValue EmitLValue(
const Expr *E) {
return CGF.
EmitLValue(E); }
338 ArrayRef<std::pair<Value *, SanitizerKind::SanitizerOrdinal>> Checks,
339 const BinOpInfo &Info);
341 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
345 void EmitLValueAlignmentAssumption(
const Expr *E,
Value *
V) {
346 const AlignValueAttr *AVAttr =
nullptr;
347 if (
const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
348 const ValueDecl *VD = DRE->getDecl();
351 if (
const auto *TTy =
353 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
363 AVAttr = VD->
getAttr<AlignValueAttr>();
368 if (
const auto *TTy = E->
getType()->
getAs<TypedefType>())
369 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
382 Value *EmitLoadOfLValue(
const Expr *E) {
389 EmitLValueAlignmentAssumption(E,
V);
395 Value *EmitConversionToBool(
Value *Src, QualType DstTy);
399 void EmitFloatConversionCheck(
Value *OrigSrc, QualType OrigSrcType,
400 Value *Src, QualType SrcType, QualType DstType,
401 llvm::Type *DstTy, SourceLocation Loc);
406 enum ImplicitConversionCheckKind :
unsigned char {
407 ICCK_IntegerTruncation = 0,
408 ICCK_UnsignedIntegerTruncation = 1,
409 ICCK_SignedIntegerTruncation = 2,
410 ICCK_IntegerSignChange = 3,
411 ICCK_SignedIntegerTruncationOrSignChange = 4,
416 void EmitIntegerTruncationCheck(
Value *Src, QualType SrcType,
Value *Dst,
417 QualType DstType, SourceLocation Loc,
418 bool OBTrapInvolved =
false);
423 void EmitIntegerSignChangeCheck(
Value *Src, QualType SrcType,
Value *Dst,
424 QualType DstType, SourceLocation Loc,
425 bool OBTrapInvolved =
false);
429 struct ScalarConversionOpts {
430 bool TreatBooleanAsSigned;
431 bool EmitImplicitIntegerTruncationChecks;
432 bool EmitImplicitIntegerSignChangeChecks;
434 bool PatternExcluded;
436 ScalarConversionOpts()
437 : TreatBooleanAsSigned(
false),
438 EmitImplicitIntegerTruncationChecks(
false),
439 EmitImplicitIntegerSignChangeChecks(
false), PatternExcluded(
false) {}
441 ScalarConversionOpts(clang::SanitizerSet SanOpts)
442 : TreatBooleanAsSigned(
false),
443 EmitImplicitIntegerTruncationChecks(
444 SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
445 EmitImplicitIntegerSignChangeChecks(
446 SanOpts.
has(SanitizerKind::ImplicitIntegerSignChange)),
447 PatternExcluded(
false) {}
449 Value *EmitScalarCast(
Value *Src, QualType SrcType, QualType DstType,
450 llvm::Type *SrcTy, llvm::Type *DstTy,
451 ScalarConversionOpts Opts);
453 EmitScalarConversion(
Value *Src, QualType SrcTy, QualType DstTy,
455 ScalarConversionOpts Opts = ScalarConversionOpts());
459 Value *EmitFixedPointConversion(
Value *Src, QualType SrcTy, QualType DstTy,
465 QualType SrcTy, QualType DstTy,
469 Value *EmitNullValue(QualType Ty);
474 llvm::Value *
Zero = llvm::Constant::getNullValue(
V->getType());
475 return Builder.CreateFCmpUNE(
V,
Zero,
"tobool");
479 Value *EmitPointerToBoolConversion(
Value *
V, QualType QT) {
482 return Builder.CreateICmpNE(
V,
Zero,
"tobool");
489 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(
V)) {
490 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
496 ZI->eraseFromParent();
501 return Builder.CreateIsNotNull(
V,
"tobool");
508 Value *Visit(Expr *E) {
509 ApplyDebugLocation DL(CGF, E);
510 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
513 Value *VisitStmt(Stmt *S) {
515 llvm_unreachable(
"Stmt can't have complex result type!");
517 Value *VisitExpr(Expr *S);
519 Value *VisitConstantExpr(ConstantExpr *E) {
525 if (
Value *
Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
540 Value *VisitParenExpr(ParenExpr *PE) {
543 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
546 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
547 return Visit(
GE->getResultExpr());
549 Value *VisitCoawaitExpr(CoawaitExpr *S) {
552 Value *VisitCoyieldExpr(CoyieldExpr *S) {
555 Value *VisitUnaryCoawait(
const UnaryOperator *E) {
560 Value *VisitIntegerLiteral(
const IntegerLiteral *E) {
561 return Builder.getInt(E->
getValue());
563 Value *VisitFixedPointLiteral(
const FixedPointLiteral *E) {
564 return Builder.getInt(E->
getValue());
566 Value *VisitFloatingLiteral(
const FloatingLiteral *E) {
567 return llvm::ConstantFP::get(VMContext, E->
getValue());
569 Value *VisitCharacterLiteral(
const CharacterLiteral *E) {
572 return llvm::ConstantInt::get(ConvertType(E->
getType()), E->
getValue(),
575 Value *VisitObjCBoolLiteralExpr(
const ObjCBoolLiteralExpr *E) {
576 return llvm::ConstantInt::get(ConvertType(E->
getType()), E->
getValue());
578 Value *VisitCXXBoolLiteralExpr(
const CXXBoolLiteralExpr *E) {
579 return llvm::ConstantInt::get(ConvertType(E->
getType()), E->
getValue());
581 Value *VisitCXXScalarValueInitExpr(
const CXXScalarValueInitExpr *E) {
585 return EmitNullValue(E->
getType());
587 Value *VisitGNUNullExpr(
const GNUNullExpr *E) {
588 return EmitNullValue(E->
getType());
590 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
591 Value *VisitUnaryExprOrTypeTraitExpr(
const UnaryExprOrTypeTraitExpr *E);
592 Value *VisitAddrLabelExpr(
const AddrLabelExpr *E) {
594 return Builder.CreateBitCast(
V, ConvertType(E->
getType()));
597 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
601 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
605 Value *VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E);
606 Value *VisitEmbedExpr(EmbedExpr *E);
608 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
617 Value *VisitOpenACCAsteriskSizeExpr(OpenACCAsteriskSizeExpr *E) {
618 llvm_unreachable(
"Codegen for this isn't defined/implemented");
622 Value *VisitDeclRefExpr(DeclRefExpr *E) {
625 return EmitLoadOfLValue(E);
628 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
631 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
634 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
635 return EmitLoadOfLValue(E);
637 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
640 return EmitLoadOfLValue(E);
644 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
650 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
656 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
661 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
662 Value *VisitMatrixSingleSubscriptExpr(MatrixSingleSubscriptExpr *E);
663 Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E);
664 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
665 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
666 Value *VisitMemberExpr(MemberExpr *E);
667 Value *VisitExtVectorElementExpr(Expr *E) {
return EmitLoadOfLValue(E); }
668 Value *VisitMatrixElementExpr(Expr *E) {
return EmitLoadOfLValue(E); }
669 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
675 return EmitLoadOfLValue(E);
678 Value *VisitInitListExpr(InitListExpr *E);
680 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
682 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
686 Value *VisitImplicitValueInitExpr(
const ImplicitValueInitExpr *E) {
687 return EmitNullValue(E->
getType());
689 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
691 return VisitCastExpr(E);
695 Value *VisitCallExpr(
const CallExpr *E) {
697 return EmitLoadOfLValue(E);
699 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
703 EmitLValueAlignmentAssumption(E,
V);
707 Value *VisitStmtExpr(
const StmtExpr *E);
710 Value *VisitUnaryPostDec(
const UnaryOperator *E) {
712 return EmitScalarPrePostIncDec(E, LV,
false,
false);
714 Value *VisitUnaryPostInc(
const UnaryOperator *E) {
716 return EmitScalarPrePostIncDec(E, LV,
true,
false);
718 Value *VisitUnaryPreDec(
const UnaryOperator *E) {
720 return EmitScalarPrePostIncDec(E, LV,
false,
true);
722 Value *VisitUnaryPreInc(
const UnaryOperator *E) {
724 return EmitScalarPrePostIncDec(E, LV,
true,
true);
727 llvm::Value *EmitIncDecConsiderOverflowBehavior(
const UnaryOperator *E,
731 llvm::Value *EmitScalarPrePostIncDec(
const UnaryOperator *E, LValue LV,
732 bool isInc,
bool isPre);
735 Value *VisitUnaryAddrOf(
const UnaryOperator *E) {
739 return EmitLValue(E->
getSubExpr()).getPointer(CGF);
741 Value *VisitUnaryDeref(
const UnaryOperator *E) {
744 return EmitLoadOfLValue(E);
747 Value *VisitUnaryPlus(
const UnaryOperator *E,
748 QualType PromotionType = QualType());
749 Value *VisitPlus(
const UnaryOperator *E, QualType PromotionType);
750 Value *VisitUnaryMinus(
const UnaryOperator *E,
751 QualType PromotionType = QualType());
752 Value *VisitMinus(
const UnaryOperator *E, QualType PromotionType);
754 Value *VisitUnaryNot (
const UnaryOperator *E);
755 Value *VisitUnaryLNot (
const UnaryOperator *E);
756 Value *VisitUnaryReal(
const UnaryOperator *E,
757 QualType PromotionType = QualType());
758 Value *VisitReal(
const UnaryOperator *E, QualType PromotionType);
759 Value *VisitUnaryImag(
const UnaryOperator *E,
760 QualType PromotionType = QualType());
761 Value *VisitImag(
const UnaryOperator *E, QualType PromotionType);
762 Value *VisitUnaryExtension(
const UnaryOperator *E) {
767 Value *VisitMaterializeTemporaryExpr(
const MaterializeTemporaryExpr *E) {
768 return EmitLoadOfLValue(E);
770 Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
778 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
779 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
782 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
783 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
786 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
790 Value *VisitExprWithCleanups(ExprWithCleanups *E);
791 Value *VisitCXXNewExpr(
const CXXNewExpr *E) {
794 Value *VisitCXXDeleteExpr(
const CXXDeleteExpr *E) {
799 Value *VisitTypeTraitExpr(
const TypeTraitExpr *E) {
801 return llvm::ConstantInt::get(ConvertType(E->
getType()),
805 return llvm::ConstantInt::get(ConvertType(E->
getType()),
809 Value *VisitConceptSpecializationExpr(
const ConceptSpecializationExpr *E) {
817 Value *VisitArrayTypeTraitExpr(
const ArrayTypeTraitExpr *E) {
818 return llvm::ConstantInt::get(ConvertType(E->
getType()), E->
getValue());
821 Value *VisitExpressionTraitExpr(
const ExpressionTraitExpr *E) {
822 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->
getValue());
825 Value *VisitCXXPseudoDestructorExpr(
const CXXPseudoDestructorExpr *E) {
835 Value *VisitCXXNullPtrLiteralExpr(
const CXXNullPtrLiteralExpr *E) {
836 return EmitNullValue(E->
getType());
839 Value *VisitCXXThrowExpr(
const CXXThrowExpr *E) {
844 Value *VisitCXXNoexceptExpr(
const CXXNoexceptExpr *E) {
845 return Builder.getInt1(E->
getValue());
849 Value *EmitMul(
const BinOpInfo &Ops) {
850 if (Ops.Ty->isSignedIntegerOrEnumerationType() ||
851 Ops.Ty->isUnsignedIntegerType()) {
852 const bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
854 isSigned ? CGF.
SanOpts.
has(SanitizerKind::SignedIntegerOverflow)
855 : CGF.
SanOpts.
has(SanitizerKind::UnsignedIntegerOverflow);
856 switch (getOverflowBehaviorConsideringType(CGF, Ops.Ty)) {
857 case LangOptions::OB_Wrap:
858 return Builder.CreateMul(Ops.LHS, Ops.RHS,
"mul");
859 case LangOptions::OB_SignedAndDefined:
861 return Builder.CreateMul(Ops.LHS, Ops.RHS,
"mul");
863 case LangOptions::OB_Unset:
865 return isSigned ? Builder.CreateNSWMul(Ops.LHS, Ops.RHS,
"mul")
866 : Builder.CreateMul(Ops.LHS, Ops.RHS,
"mul");
868 case LangOptions::OB_Trap:
869 if (CanElideOverflowCheck(CGF.
getContext(), Ops))
870 return isSigned ? Builder.CreateNSWMul(Ops.LHS, Ops.RHS,
"mul")
871 : Builder.CreateMul(Ops.LHS, Ops.RHS,
"mul");
872 return EmitOverflowCheckedBinOp(Ops);
876 if (Ops.Ty->isConstantMatrixType()) {
877 llvm::MatrixBuilder MB(Builder);
881 auto *LHSMatTy = dyn_cast<ConstantMatrixType>(
882 BO->getLHS()->getType().getCanonicalType());
883 auto *RHSMatTy = dyn_cast<ConstantMatrixType>(
884 BO->getRHS()->getType().getCanonicalType());
885 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
887 if (LHSMatTy && RHSMatTy && !CGF.
getLangOpts().HLSL)
888 return MB.CreateMatrixMultiply(Ops.LHS, Ops.RHS, LHSMatTy->getNumRows(),
889 LHSMatTy->getNumColumns(),
890 RHSMatTy->getNumColumns());
891 return MB.CreateScalarMultiply(Ops.LHS, Ops.RHS);
894 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
896 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
897 return Builder.CreateFMul(Ops.LHS, Ops.RHS,
"mul");
899 if (Ops.isFixedPointOp())
900 return EmitFixedPointBinOp(Ops);
901 return Builder.CreateMul(Ops.LHS, Ops.RHS,
"mul");
905 Value *EmitOverflowCheckedBinOp(
const BinOpInfo &Ops);
908 void EmitUndefinedBehaviorIntegerDivAndRemCheck(
const BinOpInfo &Ops,
909 llvm::Value *
Zero,
bool isDiv);
911 static Value *GetMaximumShiftAmount(
Value *LHS,
Value *RHS,
bool RHSIsSigned);
917 Value *EmitDiv(
const BinOpInfo &Ops);
918 Value *EmitRem(
const BinOpInfo &Ops);
919 Value *EmitAdd(
const BinOpInfo &Ops);
920 Value *EmitSub(
const BinOpInfo &Ops);
921 Value *EmitShl(
const BinOpInfo &Ops);
922 Value *EmitShr(
const BinOpInfo &Ops);
923 Value *EmitAnd(
const BinOpInfo &Ops) {
924 return Builder.CreateAnd(Ops.LHS, Ops.RHS,
"and");
926 Value *EmitXor(
const BinOpInfo &Ops) {
927 return Builder.CreateXor(Ops.LHS, Ops.RHS,
"xor");
929 Value *EmitOr (
const BinOpInfo &Ops) {
930 return Builder.CreateOr(Ops.LHS, Ops.RHS,
"or");
934 Value *EmitFixedPointBinOp(
const BinOpInfo &Ops);
936 BinOpInfo EmitBinOps(
const BinaryOperator *E,
937 QualType PromotionTy = QualType());
939 Value *EmitPromotedValue(
Value *result, QualType PromotionType);
940 Value *EmitUnPromotedValue(
Value *result, QualType ExprType);
941 Value *EmitPromoted(
const Expr *E, QualType PromotionType);
943 LValue EmitCompoundAssignLValue(
const CompoundAssignOperator *E,
944 Value *(ScalarExprEmitter::*F)(
const BinOpInfo &),
947 Value *EmitCompoundAssign(
const CompoundAssignOperator *E,
948 Value *(ScalarExprEmitter::*F)(
const BinOpInfo &));
950 QualType getPromotionType(QualType Ty) {
952 if (
auto *CT = Ty->
getAs<ComplexType>()) {
953 QualType ElementType = CT->getElementType();
954 if (ElementType.UseExcessPrecision(Ctx))
959 if (
auto *VT = Ty->
getAs<VectorType>()) {
960 unsigned NumElements = VT->getNumElements();
970#define HANDLEBINOP(OP) \
971 Value *VisitBin##OP(const BinaryOperator *E) { \
972 QualType promotionTy = getPromotionType(E->getType()); \
973 auto result = Emit##OP(EmitBinOps(E, promotionTy)); \
974 if (result && !promotionTy.isNull()) \
975 result = EmitUnPromotedValue(result, E->getType()); \
978 Value *VisitBin##OP##Assign(const CompoundAssignOperator *E) { \
979 ApplyAtomGroup Grp(CGF.getDebugInfo()); \
980 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit##OP); \
996 llvm::CmpInst::Predicate SICmpOpc,
997 llvm::CmpInst::Predicate FCmpOpc,
bool IsSignaling);
998#define VISITCOMP(CODE, UI, SI, FP, SIG) \
999 Value *VisitBin##CODE(const BinaryOperator *E) { \
1000 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
1001 llvm::FCmpInst::FP, SIG); }
1002 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT,
true)
1016 Value *VisitBinPtrMemD(
const Expr *E) {
return EmitLoadOfLValue(E); }
1017 Value *VisitBinPtrMemI(
const Expr *E) {
return EmitLoadOfLValue(E); }
1019 Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
1024 Value *VisitBlockExpr(
const BlockExpr *BE);
1025 Value *VisitAbstractConditionalOperator(
const AbstractConditionalOperator *);
1026 Value *VisitChooseExpr(ChooseExpr *CE);
1027 Value *VisitVAArgExpr(VAArgExpr *VE);
1028 Value *VisitObjCStringLiteral(
const ObjCStringLiteral *E) {
1031 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
1034 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
1037 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
1040 Value *VisitAsTypeExpr(AsTypeExpr *CE);
1041 Value *VisitAtomicExpr(AtomicExpr *AE);
1042 Value *VisitPackIndexingExpr(PackIndexingExpr *E) {
1055 assert(SrcType.
isCanonical() &&
"EmitScalarConversion strips typedefs");
1058 return EmitFloatToBoolConversion(Src);
1060 if (
const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
1064 if (SrcType == CGF.
getContext().AMDGPUFeaturePredicateTy)
1068 "Unknown scalar type to convert");
1071 return EmitIntToBoolConversion(Src);
1074 return EmitPointerToBoolConversion(Src, SrcType);
1077void ScalarExprEmitter::EmitFloatConversionCheck(
1078 Value *OrigSrc, QualType OrigSrcType,
Value *Src, QualType SrcType,
1079 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
1080 assert(SrcType->
isFloatingType() &&
"not a conversion from floating point");
1084 auto CheckOrdinal = SanitizerKind::SO_FloatCastOverflow;
1085 auto CheckHandler = SanitizerHandler::FloatCastOverflow;
1086 SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
1087 using llvm::APFloat;
1090 llvm::Value *Check =
nullptr;
1091 const llvm::fltSemantics &SrcSema =
1101 APFloat MinSrc(SrcSema, APFloat::uninitialized);
1102 if (MinSrc.convertFromAPInt(
Min, !
Unsigned, APFloat::rmTowardZero) &
1103 APFloat::opOverflow)
1106 MinSrc = APFloat::getInf(SrcSema,
true);
1110 MinSrc.subtract(
APFloat(SrcSema, 1), APFloat::rmTowardNegative);
1113 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
1114 if (MaxSrc.convertFromAPInt(
Max, !
Unsigned, APFloat::rmTowardZero) &
1115 APFloat::opOverflow)
1118 MaxSrc = APFloat::getInf(SrcSema,
false);
1122 MaxSrc.add(
APFloat(SrcSema, 1), APFloat::rmTowardPositive);
1127 const llvm::fltSemantics &Sema =
1130 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
1131 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
1135 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
1137 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
1138 Check = Builder.CreateAnd(GE, LE);
1143 CGF.
EmitCheck(std::make_pair(Check, CheckOrdinal), CheckHandler, StaticArgs,
1149static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1150 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1153 llvm::Type *SrcTy = Src->
getType();
1154 llvm::Type *DstTy = Dst->
getType();
1159 assert(SrcTy->getScalarSizeInBits() > Dst->
getType()->getScalarSizeInBits());
1161 "non-integer llvm type");
1168 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
1170 if (!SrcSigned && !DstSigned) {
1171 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1172 Ordinal = SanitizerKind::SO_ImplicitUnsignedIntegerTruncation;
1174 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1175 Ordinal = SanitizerKind::SO_ImplicitSignedIntegerTruncation;
1178 llvm::Value *Check =
nullptr;
1180 Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned,
"anyext");
1182 Check = Builder.CreateICmpEQ(Check, Src,
"truncheck");
1184 return std::make_pair(Kind, std::make_pair(Check, Ordinal));
1192void ScalarExprEmitter::EmitIntegerTruncationCheck(
Value *Src, QualType SrcType,
1193 Value *Dst, QualType DstType,
1195 bool OBTrapInvolved) {
1196 if (!CGF.
SanOpts.
hasOneOf(SanitizerKind::ImplicitIntegerTruncation) &&
1206 unsigned SrcBits = Src->
getType()->getScalarSizeInBits();
1207 unsigned DstBits = Dst->
getType()->getScalarSizeInBits();
1209 if (SrcBits <= DstBits)
1212 assert(!DstType->
isBooleanType() &&
"we should not get here with booleans.");
1219 if (CGF.
SanOpts.
has(SanitizerKind::ImplicitIntegerSignChange) &&
1220 (!SrcSigned && DstSigned))
1223 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1224 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1227 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1232 SanitizerDebugLocation SanScope(
1234 {SanitizerKind::SO_ImplicitUnsignedIntegerTruncation,
1235 SanitizerKind::SO_ImplicitSignedIntegerTruncation},
1251 SanitizerDebugLocation SanScope(&CGF, {Check.second.second}, CheckHandler);
1259 if (
const auto *OBT = DstType->
getAs<OverflowBehaviorType>()) {
1260 if (OBT->isWrapKind())
1263 if (ignoredBySanitizer && !OBTrapInvolved)
1266 llvm::Constant *StaticArgs[] = {
1269 llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first),
1270 llvm::ConstantInt::get(Builder.getInt32Ty(), 0)};
1272 CGF.
EmitCheck(Check.second, CheckHandler, StaticArgs, {Src, Dst});
1279 llvm::Type *VTy =
V->getType();
1282 return llvm::ConstantInt::getFalse(VTy->getContext());
1284 llvm::Constant *
Zero = llvm::ConstantInt::get(VTy, 0);
1285 return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT,
V,
Zero,
1286 llvm::Twine(Name) +
"." +
V->getName() +
1287 ".negativitycheck");
1292static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1293 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1296 llvm::Type *SrcTy = Src->
getType();
1297 llvm::Type *DstTy = Dst->
getType();
1300 "non-integer llvm type");
1306 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1307 unsigned DstBits = DstTy->getScalarSizeInBits();
1311 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1312 "either the widths should be different, or the signednesses.");
1315 llvm::Value *SrcIsNegative =
1318 llvm::Value *DstIsNegative =
1324 llvm::Value *Check =
nullptr;
1325 Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative,
"signchangecheck");
1327 return std::make_pair(
1328 ScalarExprEmitter::ICCK_IntegerSignChange,
1329 std::make_pair(Check, SanitizerKind::SO_ImplicitIntegerSignChange));
1332void ScalarExprEmitter::EmitIntegerSignChangeCheck(
Value *Src, QualType SrcType,
1333 Value *Dst, QualType DstType,
1335 bool OBTrapInvolved) {
1336 if (!CGF.
SanOpts.
has(SanitizerKind::SO_ImplicitIntegerSignChange) &&
1340 llvm::Type *SrcTy = Src->
getType();
1341 llvm::Type *DstTy = Dst->
getType();
1351 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1352 unsigned DstBits = DstTy->getScalarSizeInBits();
1359 if (SrcSigned == DstSigned && SrcBits == DstBits)
1363 if (!SrcSigned && !DstSigned)
1368 if ((DstBits > SrcBits) && DstSigned)
1370 if (CGF.
SanOpts.
has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1371 (SrcBits > DstBits) && SrcSigned) {
1380 if (!OBTrapInvolved) {
1383 SanitizerKind::ImplicitSignedIntegerTruncation, DstType))
1387 SanitizerKind::ImplicitUnsignedIntegerTruncation, DstType))
1392 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1393 SanitizerDebugLocation SanScope(
1395 {SanitizerKind::SO_ImplicitIntegerSignChange,
1396 SanitizerKind::SO_ImplicitUnsignedIntegerTruncation,
1397 SanitizerKind::SO_ImplicitSignedIntegerTruncation},
1400 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1401 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1405 ImplicitConversionCheckKind CheckKind;
1406 llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>,
1413 CheckKind = Check.first;
1414 Checks.emplace_back(Check.second);
1416 if (CGF.
SanOpts.
has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1417 (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1423 CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1424 Checks.emplace_back(Check.second);
1428 if (!CGF.
SanOpts.
has(SanitizerKind::SO_ImplicitIntegerSignChange)) {
1429 if (OBTrapInvolved) {
1430 llvm::Value *Combined = Check.second.first;
1431 for (
const auto &
C : Checks)
1432 Combined = Builder.CreateAnd(Combined,
C.first);
1438 llvm::Constant *StaticArgs[] = {
1441 llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind),
1442 llvm::ConstantInt::get(Builder.getInt32Ty(), 0)};
1444 CGF.
EmitCheck(Checks, CheckHandler, StaticArgs, {Src, Dst});
1449static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1450 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1456 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
1457 if (!SrcSigned && !DstSigned)
1458 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1460 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1462 llvm::Value *Check =
nullptr;
1464 Check = Builder.CreateIntCast(Dst, Src->
getType(), DstSigned,
"bf.anyext");
1466 Check = Builder.CreateICmpEQ(Check, Src,
"bf.truncheck");
1469 return std::make_pair(
1471 std::make_pair(Check, SanitizerKind::SO_ImplicitBitfieldConversion));
1476static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1477 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1481 llvm::Value *SrcIsNegative =
1484 llvm::Value *DstIsNegative =
1490 llvm::Value *Check =
nullptr;
1492 Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative,
"bf.signchangecheck");
1494 return std::make_pair(
1495 ScalarExprEmitter::ICCK_IntegerSignChange,
1496 std::make_pair(Check, SanitizerKind::SO_ImplicitBitfieldConversion));
1504 if (!
SanOpts.has(SanitizerKind::ImplicitBitfieldConversion))
1522 unsigned SrcBits =
ConvertType(SrcType)->getScalarSizeInBits();
1523 unsigned DstBits = Info.
Size;
1528 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1530 this, {SanitizerKind::SO_ImplicitBitfieldConversion}, CheckHandler);
1532 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1533 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1537 bool EmitTruncation = DstBits < SrcBits;
1541 bool EmitTruncationFromUnsignedToSigned =
1542 EmitTruncation && DstSigned && !SrcSigned;
1544 bool SameTypeSameSize = SrcSigned == DstSigned && SrcBits == DstBits;
1545 bool BothUnsigned = !SrcSigned && !DstSigned;
1546 bool LargerSigned = (DstBits > SrcBits) && DstSigned;
1553 bool EmitSignChange = !SameTypeSameSize && !BothUnsigned && !LargerSigned;
1558 else if (EmitSignChange) {
1559 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1560 "either the widths should be different, or the signednesses.");
1566 ScalarExprEmitter::ImplicitConversionCheckKind CheckKind = Check.first;
1567 if (EmitTruncationFromUnsignedToSigned)
1568 CheckKind = ScalarExprEmitter::ICCK_SignedIntegerTruncationOrSignChange;
1570 llvm::Constant *StaticArgs[] = {
1573 llvm::ConstantInt::get(
Builder.getInt8Ty(), CheckKind),
1574 llvm::ConstantInt::get(
Builder.getInt32Ty(), Info.
Size)};
1576 EmitCheck(Check.second, CheckHandler, StaticArgs, {Src, Dst});
1580 QualType DstType, llvm::Type *SrcTy,
1582 ScalarConversionOpts Opts) {
1584 llvm::Type *SrcElementTy;
1585 llvm::Type *DstElementTy;
1595 "cannot cast between matrix and non-matrix types");
1596 SrcElementTy = SrcTy;
1597 DstElementTy = DstTy;
1598 SrcElementType = SrcType;
1599 DstElementType = DstType;
1604 if (SrcElementType->
isBooleanType() && Opts.TreatBooleanAsSigned) {
1609 return Builder.CreateIntCast(Src, DstTy, InputSigned,
"conv");
1611 return Builder.CreateSIToFP(Src, DstTy,
"conv");
1612 return Builder.CreateUIToFP(Src, DstTy,
"conv");
1616 assert(SrcElementTy->isFloatingPointTy() &&
"Unknown real conversion");
1623 llvm::Intrinsic::ID IID =
1624 IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat;
1625 return Builder.CreateCall(CGF.
CGM.
getIntrinsic(IID, {DstTy, SrcTy}), Src);
1629 return Builder.CreateFPToSI(Src, DstTy,
"conv");
1630 return Builder.CreateFPToUI(Src, DstTy,
"conv");
1633 if ((DstElementTy->is16bitFPTy() && SrcElementTy->is16bitFPTy())) {
1634 Value *FloatVal = Builder.CreateFPExt(Src, Builder.getFloatTy(),
"fpext");
1635 return Builder.CreateFPTrunc(FloatVal, DstTy,
"fptrunc");
1637 if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
1638 return Builder.CreateFPTrunc(Src, DstTy,
"conv");
1639 return Builder.CreateFPExt(Src, DstTy,
"conv");
1644Value *ScalarExprEmitter::EmitScalarConversion(
Value *Src, QualType SrcType,
1647 ScalarConversionOpts Opts) {
1656 if (hasBoolConversionSemantics(DstType))
1662 return Builder.CreateIsNotNull(Src,
"tobool");
1665 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1668 "Unhandled scalar conversion from a fixed point type to another type.");
1672 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1675 "Unhandled scalar conversion to a fixed point type from another type.");
1678 QualType NoncanonicalSrcType = SrcType;
1679 QualType NoncanonicalDstType = DstType;
1683 if (SrcType == DstType)
return Src;
1687 llvm::Value *OrigSrc = Src;
1688 QualType OrigSrcType = SrcType;
1689 llvm::Type *SrcTy = Src->
getType();
1692 if (hasBoolConversionSemantics(DstType))
1693 return EmitConversionToBool(Src, SrcType);
1695 llvm::Type *DstTy = ConvertType(DstType);
1704 const auto *DstOBT = NoncanonicalDstType->
getAs<OverflowBehaviorType>();
1705 const auto *SrcOBT = NoncanonicalSrcType->
getAs<OverflowBehaviorType>();
1706 bool OBTrapInvolved =
1707 (DstOBT && DstOBT->isTrapKind()) || (SrcOBT && SrcOBT->isTrapKind());
1708 bool OBWrapInvolved =
1709 (DstOBT && DstOBT->isWrapKind()) || (SrcOBT && SrcOBT->isWrapKind());
1714 if (DstTy->isFloatingPointTy())
1715 return Builder.CreateFPExt(Src, DstTy,
"conv");
1719 Src = Builder.CreateFPExt(Src, CGF.
CGM.
FloatTy,
"conv");
1725 if (SrcTy == DstTy) {
1726 if (Opts.EmitImplicitIntegerSignChangeChecks ||
1727 (OBTrapInvolved && !OBWrapInvolved))
1728 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
1729 NoncanonicalDstType, Loc, OBTrapInvolved);
1737 if (
auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
1742 assert(SrcType->
isIntegerType() &&
"Not ptr->ptr or int->ptr conversion?");
1747 llvm::Value* IntResult =
1748 Builder.CreateIntCast(Src, MiddleTy, InputSigned,
"conv");
1750 return Builder.CreateIntToPtr(IntResult, DstTy,
"conv");
1756 return Builder.CreatePtrToInt(Src, DstTy,
"conv");
1763 assert(DstType->
castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1765 "Splatted expr doesn't match with vector element type?");
1769 return Builder.CreateVectorSplat(NumElements, Src,
"splat");
1773 return EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1777 llvm::TypeSize SrcSize = SrcTy->getPrimitiveSizeInBits();
1778 llvm::TypeSize DstSize = DstTy->getPrimitiveSizeInBits();
1779 if (SrcSize == DstSize)
1780 return Builder.CreateBitCast(Src, DstTy,
"conv");
1793 assert(((SrcElementTy->isIntegerTy() &&
1794 DstElementTy->isIntegerTy()) ||
1795 (SrcElementTy->isFloatingPointTy() &&
1796 DstElementTy->isFloatingPointTy())) &&
1797 "unexpected conversion between a floating-point vector and an "
1801 if (SrcElementTy->isIntegerTy())
1802 return Builder.CreateIntCast(Src, DstTy,
false,
"conv");
1805 if (SrcSize > DstSize)
1806 return Builder.CreateFPTrunc(Src, DstTy,
"conv");
1809 return Builder.CreateFPExt(Src, DstTy,
"conv");
1813 Value *Res =
nullptr;
1814 llvm::Type *ResTy = DstTy;
1821 if (CGF.
SanOpts.
has(SanitizerKind::FloatCastOverflow) &&
1823 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1831 if (SrcTy->isFloatingPointTy())
1832 return Builder.CreateFPTrunc(Src, CGF.
CGM.
HalfTy,
"conv");
1837 Res = EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1839 if (DstTy != ResTy) {
1840 Res = Builder.CreateFPTrunc(Res, CGF.
CGM.
HalfTy,
"conv");
1843 assert(ResTy->isIntegerTy(16) &&
1844 "Only half FP requires extra conversion");
1845 Res = Builder.CreateBitCast(Res, ResTy);
1849 if ((Opts.EmitImplicitIntegerTruncationChecks || OBTrapInvolved) &&
1850 !OBWrapInvolved && !Opts.PatternExcluded)
1851 EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
1852 NoncanonicalDstType, Loc, OBTrapInvolved);
1854 if (Opts.EmitImplicitIntegerSignChangeChecks ||
1855 (OBTrapInvolved && !OBWrapInvolved))
1856 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
1857 NoncanonicalDstType, Loc, OBTrapInvolved);
1862Value *ScalarExprEmitter::EmitFixedPointConversion(
Value *Src, QualType SrcTy,
1864 SourceLocation Loc) {
1865 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
1868 Result = FPBuilder.CreateFloatingToFixed(Src,
1871 Result = FPBuilder.CreateFixedToFloating(Src,
1873 ConvertType(DstTy));
1879 Result = FPBuilder.CreateFixedToInteger(Src, SrcFPSema,
1880 DstFPSema.getWidth(),
1881 DstFPSema.isSigned());
1883 Result = FPBuilder.CreateIntegerToFixed(Src, SrcFPSema.isSigned(),
1886 Result = FPBuilder.CreateFixedToFixed(Src, SrcFPSema, DstFPSema);
1893Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1895 SourceLocation Loc) {
1897 SrcTy = SrcTy->
castAs<ComplexType>()->getElementType();
1900 if (hasBoolConversionSemantics(DstTy)) {
1902 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1903 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
1904 return Builder.CreateOr(Src.first, Src.second,
"tobool");
1911 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1914Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1922void ScalarExprEmitter::EmitBinOpCheck(
1923 ArrayRef<std::pair<Value *, SanitizerKind::SanitizerOrdinal>> Checks,
1924 const BinOpInfo &Info) {
1927 SmallVector<llvm::Constant *, 4> StaticData;
1928 SmallVector<llvm::Value *, 2> DynamicData;
1936 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1937 if (UO && UO->
getOpcode() == UO_Minus) {
1938 Check = SanitizerHandler::NegateOverflow;
1940 DynamicData.push_back(Info.RHS);
1944 Check = SanitizerHandler::ShiftOutOfBounds;
1946 StaticData.push_back(
1948 StaticData.push_back(
1950 }
else if (Opcode == BO_Div || Opcode == BO_Rem) {
1952 Check = SanitizerHandler::DivremOverflow;
1956 int ArithOverflowKind = 0;
1959 Check = SanitizerHandler::AddOverflow;
1960 ArithOverflowKind = diag::UBSanArithKind::Add;
1964 Check = SanitizerHandler::SubOverflow;
1965 ArithOverflowKind = diag::UBSanArithKind::Sub;
1969 Check = SanitizerHandler::MulOverflow;
1970 ArithOverflowKind = diag::UBSanArithKind::Mul;
1974 llvm_unreachable(
"unexpected opcode for bin op check");
1978 SanitizerKind::UnsignedIntegerOverflow) ||
1980 SanitizerKind::SignedIntegerOverflow)) {
1984 << Info.Ty->isSignedIntegerOrEnumerationType() << ArithOverflowKind
1988 DynamicData.push_back(Info.LHS);
1989 DynamicData.push_back(Info.RHS);
1992 CGF.
EmitCheck(Checks, Check, StaticData, DynamicData, &TR);
1999Value *ScalarExprEmitter::VisitExpr(Expr *E) {
2007ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) {
2009 unsigned AddrSpace =
2011 llvm::Constant *GlobalConstStr = Builder.CreateGlobalString(
2015 return Builder.CreatePointerBitCastOrAddrSpaceCast(GlobalConstStr, ExprTy,
2019Value *ScalarExprEmitter::VisitEmbedExpr(EmbedExpr *E) {
2021 auto It = E->
begin();
2022 return Builder.getInt((*It)->getValue());
2025Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
2033 unsigned LHSElts = LTy->getNumElements();
2041 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
2042 Mask = Builder.CreateAnd(Mask, MaskBits,
"mask");
2050 auto *RTy = llvm::FixedVectorType::get(LTy->getElementType(),
2051 MTy->getNumElements());
2052 Value* NewV = llvm::PoisonValue::get(RTy);
2053 for (
unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
2054 Value *IIndx = llvm::ConstantInt::get(CGF.
SizeTy, i);
2055 Value *Indx = Builder.CreateExtractElement(Mask, IIndx,
"shuf_idx");
2057 Value *VExt = Builder.CreateExtractElement(LHS, Indx,
"shuf_elt");
2058 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx,
"shuf_ins");
2066 SmallVector<int, 32> Indices;
2070 if (Idx.isSigned() && Idx.isAllOnes())
2071 Indices.push_back(-1);
2073 Indices.push_back(Idx.getZExtValue());
2076 return Builder.CreateShuffleVector(V1, V2, Indices,
"shuffle");
2079Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
2087 if (SrcType == DstType)
return Src;
2090 "ConvertVector source type must be a vector");
2092 "ConvertVector destination type must be a vector");
2094 llvm::Type *SrcTy = Src->
getType();
2095 llvm::Type *DstTy = ConvertType(DstType);
2101 QualType SrcEltType = SrcType->
castAs<VectorType>()->getElementType(),
2102 DstEltType = DstType->
castAs<VectorType>()->getElementType();
2104 assert(SrcTy->isVectorTy() &&
2105 "ConvertVector source IR type must be a vector");
2106 assert(DstTy->isVectorTy() &&
2107 "ConvertVector destination IR type must be a vector");
2112 if (DstEltType->isBooleanType()) {
2113 assert((SrcEltTy->isFloatingPointTy() ||
2116 llvm::Value *
Zero = llvm::Constant::getNullValue(SrcTy);
2117 if (SrcEltTy->isFloatingPointTy()) {
2118 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2119 return Builder.CreateFCmpUNE(Src,
Zero,
"tobool");
2121 return Builder.CreateICmpNE(Src,
Zero,
"tobool");
2126 Value *Res =
nullptr;
2131 Res = Builder.CreateIntCast(Src, DstTy, InputSigned,
"conv");
2133 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2135 Res = Builder.CreateSIToFP(Src, DstTy,
"conv");
2137 Res = Builder.CreateUIToFP(Src, DstTy,
"conv");
2140 assert(SrcEltTy->isFloatingPointTy() &&
"Unknown real conversion");
2141 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2142 if (DstEltType->isSignedIntegerOrEnumerationType())
2143 Res = Builder.CreateFPToSI(Src, DstTy,
"conv");
2145 Res = Builder.CreateFPToUI(Src, DstTy,
"conv");
2147 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
2148 "Unknown real conversion");
2149 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2150 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
2151 Res = Builder.CreateFPTrunc(Src, DstTy,
"conv");
2153 Res = Builder.CreateFPExt(Src, DstTy,
"conv");
2159Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
2168 return Builder.getInt(
Value);
2172 llvm::Value *
Result = EmitLoadOfLValue(E);
2178 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(
Result)) {
2179 if (llvm::GetElementPtrInst *GEP =
2180 dyn_cast<llvm::GetElementPtrInst>(
Load->getPointerOperand())) {
2181 if (llvm::Instruction *
Pointer =
2182 dyn_cast<llvm::Instruction>(GEP->getPointerOperand())) {
2194Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
2195 TestAndClearIgnoreResultAssign();
2203 return EmitLoadOfLValue(E);
2211 if (CGF.
SanOpts.
has(SanitizerKind::ArrayBounds))
2214 Value *
Ret = Builder.CreateExtractElement(Base, Idx,
"vecext");
2218 Ret = Builder.CreateInsertElement(
2219 llvm::PoisonValue::get(llvm::FixedVectorType::get(CGF.
Int8Ty, 1)), Ret,
2225Value *ScalarExprEmitter::VisitMatrixSingleSubscriptExpr(
2226 MatrixSingleSubscriptExpr *E) {
2227 TestAndClearIgnoreResultAssign();
2230 unsigned NumRows = MatrixTy->getNumRows();
2231 unsigned NumColumns = MatrixTy->getNumColumns();
2235 llvm::MatrixBuilder MB(Builder);
2239 MB.CreateIndexAssumption(RowIdx, NumRows);
2242 llvm::Type *ElemTy = CGF.
ConvertType(MatrixTy->getElementType());
2243 auto *ResultTy = llvm::FixedVectorType::get(ElemTy, NumColumns);
2244 Value *RowVec = llvm::PoisonValue::get(ResultTy);
2246 for (
unsigned Col = 0; Col != NumColumns; ++Col) {
2247 Value *ColVal = llvm::ConstantInt::get(RowIdx->
getType(), Col);
2248 Value *EltIdx = MB.CreateIndex(RowIdx, ColVal, NumRows, NumColumns,
2249 false,
"matrix_row_idx");
2251 Builder.CreateExtractElement(FlatMatrix, EltIdx,
"matrix_elem");
2252 Value *Lane = llvm::ConstantInt::get(Builder.getInt32Ty(), Col);
2253 RowVec = Builder.CreateInsertElement(RowVec, Elt, Lane,
"matrix_row_ins");
2259Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
2260 TestAndClearIgnoreResultAssign();
2268 llvm::MatrixBuilder MB(Builder);
2270 unsigned NumCols = MatrixTy->getNumColumns();
2271 unsigned NumRows = MatrixTy->getNumRows();
2272 bool IsMatrixRowMajor =
2276 MB.CreateIndex(RowIdx, ColumnIdx, NumRows, NumCols, IsMatrixRowMajor);
2279 MB.CreateIndexAssumption(Idx, MatrixTy->getNumElementsFlattened());
2284 return Builder.CreateExtractElement(Matrix, Idx,
"matrixext");
2289 int MV = SVI->getMaskValue(Idx);
2296 assert(llvm::ConstantInt::isValueValidForType(I32Ty,
C->getZExtValue()) &&
2297 "Index operand too large for shufflevector mask!");
2298 return C->getZExtValue();
2301Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
2302 bool Ignore = TestAndClearIgnoreResultAssign();
2305 assert((Ignore ==
false ||
2307 "init list ignored");
2324 llvm::VectorType *VType =
2325 dyn_cast<llvm::VectorType>(ConvertType(E->
getType()));
2328 if (NumInitElements == 0) {
2330 return EmitNullValue(E->
getType());
2337 if (NumInitElements == 0) {
2339 return EmitNullValue(E->
getType());
2342 if (NumInitElements == 1) {
2343 Expr *InitVector = E->
getInit(0);
2348 return Visit(InitVector);
2351 llvm_unreachable(
"Unexpected initialization of a scalable vector!");
2358 const ConstantMatrixType *ColMajorMT =
2366 unsigned CurIdx = 0;
2367 bool VIsPoisonShuffle =
false;
2368 llvm::Value *
V = llvm::PoisonValue::get(VType);
2369 for (
unsigned i = 0; i != NumInitElements; ++i) {
2372 SmallVector<int, 16> Args;
2374 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(
Init->getType());
2384 ->getNumElements() == ResElts) {
2386 Value *LHS =
nullptr, *RHS =
nullptr;
2391 Args.resize(ResElts, -1);
2393 LHS = EI->getVectorOperand();
2395 VIsPoisonShuffle =
true;
2396 }
else if (VIsPoisonShuffle) {
2399 for (
unsigned j = 0; j != CurIdx; ++j)
2401 Args.push_back(ResElts +
C->getZExtValue());
2402 Args.resize(ResElts, -1);
2405 RHS = EI->getVectorOperand();
2406 VIsPoisonShuffle =
false;
2408 if (!Args.empty()) {
2409 V = Builder.CreateShuffleVector(LHS, RHS, Args);
2415 unsigned InsertIdx =
2419 V = Builder.CreateInsertElement(
V,
Init, Builder.getInt32(InsertIdx),
2421 VIsPoisonShuffle =
false;
2431 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
2434 Value *SVOp = SVI->getOperand(0);
2437 if (OpTy->getNumElements() == ResElts) {
2438 for (
unsigned j = 0; j != CurIdx; ++j) {
2441 if (VIsPoisonShuffle) {
2447 for (
unsigned j = 0, je = InitElts; j != je; ++j)
2449 Args.resize(ResElts, -1);
2451 if (VIsPoisonShuffle)
2461 for (
unsigned j = 0; j != InitElts; ++j)
2463 Args.resize(ResElts, -1);
2464 Init = Builder.CreateShuffleVector(
Init, Args,
"vext");
2467 for (
unsigned j = 0; j != CurIdx; ++j)
2469 for (
unsigned j = 0; j != InitElts; ++j)
2470 Args.push_back(j + Offset);
2471 Args.resize(ResElts, -1);
2478 V = Builder.CreateShuffleVector(
V,
Init, Args,
"vecinit");
2485 llvm::Type *EltTy = VType->getElementType();
2488 for (; CurIdx < ResElts; ++CurIdx) {
2489 unsigned InsertIdx =
2492 Value *Idx = Builder.getInt32(InsertIdx);
2493 llvm::Value *
Init = llvm::Constant::getNullValue(EltTy);
2494 V = Builder.CreateInsertElement(
V,
Init, Idx,
"vecinit");
2507 if (
const auto *UO = dyn_cast<UnaryOperator>(E))
2511 if (
const auto *DRE = dyn_cast<DeclRefExpr>(E))
2514 if (
const auto *ME = dyn_cast<MemberExpr>(E)) {
2533 if (
const auto *UO = dyn_cast<UnaryOperator>(E))
2537 if (
const auto *CE = dyn_cast<CastExpr>(E))
2538 if (CE->getCastKind() == CK_FunctionToPointerDecay ||
2539 CE->getCastKind() == CK_ArrayToPointerDecay)
2550 if (CE->
getCastKind() == CK_UncheckedDerivedToBase)
2560 if (ICE->isGLValue())
2567template <
typename GetElementTy>
2570 unsigned NumSrcElements,
2573 assert(NumSrcElements >= VecTy->getNumElements() &&
2574 "Flattened type on RHS must have the same number or more elements "
2575 "than vector on LHS.");
2577 for (
unsigned I = 0, E = VecTy->getNumElements(); I < E; ++I) {
2578 auto [Element, ElementTy] = GetElement(I);
2580 VecTy->getElementType(), Loc);
2581 V = CGF.
Builder.CreateInsertElement(
V, Cast, I);
2594 CGF, DestTy, LoadList.size(),
2596 RValue RVal = CGF.EmitLoadOfLValue(LoadList[I], Loc);
2597 assert(RVal.isScalar() &&
2598 "All flattened source values should be scalars.");
2599 return std::pair(RVal.getScalarVal(), LoadList[I].getType());
2604 assert(LoadList.size() >= MatTy->getNumElementsFlattened() &&
2605 "Flattened type on RHS must have the same number or more elements "
2606 "than vector on LHS.");
2608 llvm::Value *
V = llvm::PoisonValue::get(CGF.
ConvertType(DestTy));
2610 for (
unsigned Row = 0, RE = MatTy->getNumRows(); Row < RE; Row++) {
2611 for (
unsigned Col = 0, CE = MatTy->getNumColumns(); Col < CE; Col++) {
2614 unsigned LoadIdx = MatTy->getRowMajorFlattenedIndex(Row, Col);
2617 "All flattened source values should be scalars.");
2620 MatTy->getElementType(), Loc);
2621 unsigned MatrixIdx = MatTy->getColumnMajorFlattenedIndex(Row, Col);
2622 V = CGF.
Builder.CreateInsertElement(
V, Cast, MatrixIdx);
2629 "Destination type must be a vector, matrix, or builtin type.");
2631 assert(RVal.
isScalar() &&
"All flattened source values should be scalars.");
2640 llvm::scope_exit RestoreCurCast(
2641 [
this, Prev = CGF.
CurCast] { CGF.CurCast = Prev; });
2645 QualType DestTy = CE->
getType();
2647 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, CE);
2651 bool Ignored = TestAndClearIgnoreResultAssign();
2657 case CK_Dependent: llvm_unreachable(
"dependent cast kind in IR gen!");
2658 case CK_BuiltinFnToFnPtr:
2659 llvm_unreachable(
"builtin functions are handled elsewhere");
2661 case CK_LValueBitCast:
2662 case CK_ObjCObjectLValueCast: {
2666 return EmitLoadOfLValue(LV, CE->
getExprLoc());
2669 case CK_LValueToRValueBitCast: {
2675 return EmitLoadOfLValue(DestLV, CE->
getExprLoc());
2678 case CK_CPointerToObjCPointerCast:
2679 case CK_BlockPointerToObjCPointerCast:
2680 case CK_AnyPointerToBlockPointerCast:
2682 Value *Src = Visit(E);
2683 llvm::Type *SrcTy = Src->
getType();
2684 llvm::Type *DstTy = ConvertType(DestTy);
2695 if (
auto A = dyn_cast<llvm::Argument>(Src); A && A->hasStructRetAttr())
2709 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
2710 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
2715 (!SrcTy->isPtrOrPtrVectorTy() || !DstTy->isPtrOrPtrVectorTy() ||
2716 SrcTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace()) &&
2717 "Address-space cast must be used to convert address spaces");
2719 if (CGF.
SanOpts.
has(SanitizerKind::CFIUnrelatedCast)) {
2720 if (
auto *PT = DestTy->
getAs<PointerType>()) {
2722 PT->getPointeeType(),
2733 const QualType SrcType = E->
getType();
2738 Src = Builder.CreateLaunderInvariantGroup(Src);
2743 if (
auto *CI = dyn_cast<llvm::CallBase>(Src)) {
2747 if (!PointeeType.
isNull())
2756 if (
auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
2757 if (
auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(DstTy)) {
2760 if (ScalableDstTy->getElementType()->isIntegerTy(1) &&
2761 FixedSrcTy->getElementType()->isIntegerTy(8)) {
2762 ScalableDstTy = llvm::ScalableVectorType::get(
2763 FixedSrcTy->getElementType(),
2765 ScalableDstTy->getElementCount().getKnownMinValue(), 8));
2767 if (FixedSrcTy->getElementType() == ScalableDstTy->getElementType()) {
2768 llvm::Value *PoisonVec = llvm::PoisonValue::get(ScalableDstTy);
2769 llvm::Value *
Result = Builder.CreateInsertVector(
2770 ScalableDstTy, PoisonVec, Src,
uint64_t(0),
"cast.scalable");
2772 llvm::VectorType::getWithSizeAndScalar(ScalableDstTy, DstTy));
2773 if (
Result->getType() != ScalableDstTy)
2775 if (
Result->getType() != DstTy)
2785 if (
auto *ScalableSrcTy = dyn_cast<llvm::ScalableVectorType>(SrcTy)) {
2786 if (
auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(DstTy)) {
2789 if (ScalableSrcTy->getElementType()->isIntegerTy(1) &&
2790 FixedDstTy->getElementType()->isIntegerTy(8)) {
2791 if (!ScalableSrcTy->getElementCount().isKnownMultipleOf(8)) {
2792 ScalableSrcTy = llvm::ScalableVectorType::get(
2793 ScalableSrcTy->getElementType(),
2795 ScalableSrcTy->getElementCount().getKnownMinValue()));
2796 llvm::Value *ZeroVec = llvm::Constant::getNullValue(ScalableSrcTy);
2797 Src = Builder.CreateInsertVector(ScalableSrcTy, ZeroVec, Src,
2801 ScalableSrcTy = llvm::ScalableVectorType::get(
2802 FixedDstTy->getElementType(),
2803 ScalableSrcTy->getElementCount().getKnownMinValue() / 8);
2804 Src = Builder.CreateBitCast(Src, ScalableSrcTy);
2806 if (ScalableSrcTy->getElementType() == FixedDstTy->getElementType())
2807 return Builder.CreateExtractVector(DstTy, Src,
uint64_t(0),
2828 return EmitLoadOfLValue(DestLV, CE->
getExprLoc());
2831 llvm::Value *
Result = Builder.CreateBitCast(Src, DstTy);
2834 case CK_AddressSpaceConversion: {
2835 llvm::Type *DestLTy = ConvertType(DestTy);
2838 auto IsWasmFuncref = [](llvm::Type *
T) {
2839 auto *TET = dyn_cast<llvm::TargetExtType>(
T);
2840 return TET && TET->getName() ==
"wasm.funcref";
2842 bool SrcIsFuncref = IsWasmFuncref(ConvertType(E->
getType()));
2843 bool DestIsFuncref = IsWasmFuncref(DestLTy);
2844 if (SrcIsFuncref && DestIsFuncref) {
2849 if (SrcIsFuncref && !DestIsFuncref) {
2853 llvm::Function *ToPtr =
2855 return CGF.
Builder.CreateCall(ToPtr, {Visit(E)});
2857 if (!SrcIsFuncref && DestIsFuncref) {
2860 Expr::EvalResult NullResult;
2865 return llvm::Constant::getNullValue(DestLTy);
2868 llvm::Function *ToFuncref =
2870 return CGF.
Builder.CreateCall(ToFuncref, {Visit(E)});
2874 Result.Val.isNullPointer()) {
2878 if (
Result.HasSideEffects)
2886 case CK_AtomicToNonAtomic:
2887 case CK_NonAtomicToAtomic:
2888 case CK_UserDefinedConversion:
2895 case CK_BaseToDerived: {
2897 assert(DerivedClassDecl &&
"BaseToDerived arg isn't a C++ object pointer!");
2911 if (CGF.
SanOpts.
has(SanitizerKind::CFIDerivedCast))
2919 case CK_UncheckedDerivedToBase:
2920 case CK_DerivedToBase: {
2933 case CK_ArrayToPointerDecay:
2936 case CK_FunctionToPointerDecay:
2937 return EmitLValue(E).getPointer(CGF);
2939 case CK_NullToPointer:
2940 if (MustVisitNullValue(E))
2946 case CK_NullToMemberPointer: {
2947 if (MustVisitNullValue(E))
2950 const MemberPointerType *MPT = CE->
getType()->
getAs<MemberPointerType>();
2954 case CK_ReinterpretMemberPointer:
2955 case CK_BaseToDerivedMemberPointer:
2956 case CK_DerivedToBaseMemberPointer: {
2957 Value *Src = Visit(E);
2968 case CK_ARCProduceObject:
2970 case CK_ARCConsumeObject:
2972 case CK_ARCReclaimReturnedObject:
2974 case CK_ARCExtendBlockObject:
2977 case CK_CopyAndAutoreleaseBlockObject:
2980 case CK_FloatingRealToComplex:
2981 case CK_FloatingComplexCast:
2982 case CK_IntegralRealToComplex:
2983 case CK_IntegralComplexCast:
2984 case CK_IntegralComplexToFloatingComplex:
2985 case CK_FloatingComplexToIntegralComplex:
2986 case CK_ConstructorConversion:
2988 case CK_HLSLArrayRValue:
2989 llvm_unreachable(
"scalar cast to non-scalar value");
2991 case CK_LValueToRValue:
2993 assert(E->
isGLValue() &&
"lvalue-to-rvalue applied to r-value!");
2996 case CK_IntegralToPointer: {
2997 Value *Src = Visit(E);
3001 auto DestLLVMTy = ConvertType(DestTy);
3004 llvm::Value* IntResult =
3005 Builder.CreateIntCast(Src, MiddleTy, InputSigned,
"conv");
3007 auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
3013 IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
3019 case CK_PointerToIntegral: {
3020 assert(!DestTy->
isBooleanType() &&
"bool should use PointerToBool");
3023 return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
3029 case CK_MatrixCast: {
3030 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3037 case CK_HLSLAggregateSplatCast:
3038 case CK_VectorSplat: {
3039 llvm::Type *DstTy = ConvertType(DestTy);
3040 Value *Elt = Visit(E);
3042 llvm::ElementCount NumElements =
3044 return Builder.CreateVectorSplat(NumElements, Elt,
"splat");
3047 case CK_FixedPointCast:
3048 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3051 case CK_FixedPointToBoolean:
3053 "Expected src type to be fixed point type");
3054 assert(hasBoolConversionSemantics(DestTy) &&
3055 "Expected dest type to be a boolean type");
3056 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3059 case CK_FixedPointToIntegral:
3061 "Expected src type to be fixed point type");
3062 assert(DestTy->
isIntegerType() &&
"Expected dest type to be an integer");
3063 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3066 case CK_IntegralToFixedPoint:
3068 "Expected src type to be an integer");
3070 "Expected dest type to be fixed point type");
3071 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3074 case CK_IntegralCast: {
3076 QualType SrcElTy = E->
getType()->
castAs<VectorType>()->getElementType();
3077 return Builder.CreateIntCast(Visit(E), ConvertType(DestTy),
3081 ScalarConversionOpts Opts;
3082 if (
auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
3083 if (!ICE->isPartOfExplicitCast())
3084 Opts = ScalarConversionOpts(CGF.
SanOpts);
3086 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3089 case CK_IntegralToFloating: {
3092 QualType SrcElTy = E->
getType()->
castAs<VectorType>()->getElementType();
3094 return Builder.CreateSIToFP(Visit(E), ConvertType(DestTy),
"conv");
3095 return Builder.CreateUIToFP(Visit(E), ConvertType(DestTy),
"conv");
3097 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3098 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3101 case CK_FloatingToIntegral: {
3104 QualType DstElTy = DestTy->
castAs<VectorType>()->getElementType();
3106 return Builder.CreateFPToSI(Visit(E), ConvertType(DestTy),
"conv");
3107 return Builder.CreateFPToUI(Visit(E), ConvertType(DestTy),
"conv");
3109 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3110 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3113 case CK_FloatingCast: {
3116 QualType SrcElTy = E->
getType()->
castAs<VectorType>()->getElementType();
3117 QualType DstElTy = DestTy->
castAs<VectorType>()->getElementType();
3118 if (DstElTy->
castAs<BuiltinType>()->getKind() <
3119 SrcElTy->
castAs<BuiltinType>()->getKind())
3120 return Builder.CreateFPTrunc(Visit(E), ConvertType(DestTy),
"conv");
3121 return Builder.CreateFPExt(Visit(E), ConvertType(DestTy),
"conv");
3123 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3124 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3127 case CK_FixedPointToFloating:
3128 case CK_FloatingToFixedPoint: {
3129 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3130 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3133 case CK_BooleanToSignedIntegral: {
3134 ScalarConversionOpts Opts;
3135 Opts.TreatBooleanAsSigned =
true;
3136 return EmitScalarConversion(Visit(E), E->
getType(), DestTy,
3139 case CK_IntegralToBoolean:
3140 return EmitIntToBoolConversion(Visit(E));
3141 case CK_PointerToBoolean:
3142 return EmitPointerToBoolConversion(Visit(E), E->
getType());
3143 case CK_FloatingToBoolean: {
3144 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3145 return EmitFloatToBoolConversion(Visit(E));
3147 case CK_MemberPointerToBoolean: {
3148 llvm::Value *MemPtr = Visit(E);
3149 const MemberPointerType *MPT = E->
getType()->
getAs<MemberPointerType>();
3153 case CK_FloatingComplexToReal:
3154 case CK_IntegralComplexToReal:
3157 case CK_FloatingComplexToBoolean:
3158 case CK_IntegralComplexToBoolean: {
3162 return EmitComplexToScalarConversion(
V, E->
getType(), DestTy,
3166 case CK_ZeroToOCLOpaqueType: {
3169 "CK_ZeroToOCLEvent cast on non-event type");
3170 return llvm::Constant::getNullValue(ConvertType(DestTy));
3173 case CK_IntToOCLSampler:
3176 case CK_HLSLVectorTruncation: {
3178 "Destination type must be a vector or builtin type.");
3179 Value *Vec = Visit(E);
3180 if (
auto *VecTy = DestTy->
getAs<VectorType>()) {
3181 SmallVector<int> Mask;
3182 unsigned NumElts = VecTy->getNumElements();
3183 for (
unsigned I = 0; I != NumElts; ++I)
3186 return Builder.CreateShuffleVector(Vec, Mask,
"trunc");
3188 llvm::Value *
Zero = llvm::Constant::getNullValue(CGF.
SizeTy);
3189 return Builder.CreateExtractElement(Vec,
Zero,
"cast.vtrunc");
3191 case CK_HLSLMatrixTruncation: {
3193 "Destination type must be a matrix or builtin type.");
3194 Value *Mat = Visit(E);
3195 if (
auto *MatTy = DestTy->
getAs<ConstantMatrixType>()) {
3196 SmallVector<int> Mask(MatTy->getNumElementsFlattened());
3197 unsigned NumCols = MatTy->getNumColumns();
3198 unsigned NumRows = MatTy->getNumRows();
3199 auto *SrcMatTy = E->
getType()->
getAs<ConstantMatrixType>();
3200 assert(SrcMatTy &&
"Source type must be a matrix type.");
3201 assert(NumRows <= SrcMatTy->getNumRows());
3202 assert(NumCols <= SrcMatTy->getNumColumns());
3204 for (
unsigned R = 0;
R < NumRows;
R++)
3205 for (
unsigned C = 0;
C < NumCols;
C++)
3206 Mask[MatTy->getColumnMajorFlattenedIndex(R,
C)] =
3207 SrcMatTy->getColumnMajorFlattenedIndex(R,
C);
3209 return Builder.CreateShuffleVector(Mat, Mask,
"trunc");
3211 llvm::Value *
Zero = llvm::Constant::getNullValue(CGF.
SizeTy);
3212 return Builder.CreateExtractElement(Mat,
Zero,
"cast.mtrunc");
3214 case CK_HLSLElementwiseCast: {
3218 if (
const auto *SrcMatTy = E->
getType()->
getAs<ConstantMatrixType>()) {
3220 "Matrix elementwise cast destination must be a vector");
3221 assert(RV.
isScalar() &&
"Matrix rvalue must have scalar representation");
3224 CGF, DestTy, SrcMatTy->getNumElementsFlattened(),
3226 unsigned Row = I / SrcMatTy->getNumColumns();
3227 unsigned Col = I % SrcMatTy->getNumColumns();
3228 unsigned Idx = SrcMatTy->getColumnMajorFlattenedIndex(Row, Col);
3230 Builder.CreateExtractElement(SrcVal, Idx,
"matrixext");
3231 return std::pair(Element, SrcMatTy->getElementType());
3252 llvm_unreachable(
"unknown scalar cast");
3255Value *ScalarExprEmitter::VisitStmtExpr(
const StmtExpr *E) {
3256 CodeGenFunction::StmtExprEvaluation eval(CGF);
3265Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
3266 CodeGenFunction::RunCleanupsScope Scope(CGF);
3270 Scope.ForceCleanup({&
V});
3279 llvm::Value *InVal,
bool IsInc,
3283 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1,
false);
3285 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
3286 BinOp.FPFeatures = FPFeatures;
3291llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
3292 const UnaryOperator *E, llvm::Value *InVal,
bool IsInc) {
3295 llvm::Value *Amount =
3296 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, !IsInc);
3297 StringRef Name = IsInc ?
"inc" :
"dec";
3301 isSigned ? CGF.
SanOpts.
has(SanitizerKind::SignedIntegerOverflow)
3302 : CGF.
SanOpts.
has(SanitizerKind::UnsignedIntegerOverflow);
3304 switch (getOverflowBehaviorConsideringType(CGF, Ty)) {
3305 case LangOptions::OB_Wrap:
3306 return Builder.CreateAdd(InVal, Amount, Name);
3307 case LangOptions::OB_SignedAndDefined:
3309 return Builder.CreateAdd(InVal, Amount, Name);
3311 case LangOptions::OB_Unset:
3313 return Builder.CreateAdd(InVal, Amount, Name);
3315 return isSigned ? Builder.CreateNSWAdd(InVal, Amount, Name)
3316 : Builder.CreateAdd(InVal, Amount, Name);
3318 case LangOptions::OB_Trap:
3320 return Builder.CreateAdd(InVal, Amount, Name);
3323 if (CanElideOverflowCheck(CGF.
getContext(), Info))
3324 return isSigned ? Builder.CreateNSWAdd(InVal, Amount, Name)
3325 : Builder.CreateAdd(InVal, Amount, Name);
3326 return EmitOverflowCheckedBinOp(Info);
3328 llvm_unreachable(
"Unknown OverflowBehaviorKind");
3333class OMPLastprivateConditionalUpdateRAII {
3335 CodeGenFunction &CGF;
3336 const UnaryOperator *E;
3339 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
3340 const UnaryOperator *E)
3342 ~OMPLastprivateConditionalUpdateRAII() {
3351ScalarExprEmitter::EmitScalarPrePostIncDec(
const UnaryOperator *E, LValue LV,
3352 bool isInc,
bool isPre) {
3354 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
3356 llvm::PHINode *atomicPHI =
nullptr;
3360 QualType SrcType = E->
getType();
3362 int amount = (isInc ? 1 : -1);
3363 bool isSubtraction = !isInc;
3365 if (
const AtomicType *atomicTy =
type->getAs<AtomicType>()) {
3366 type = atomicTy->getValueType();
3367 if (isInc && hasBoolConversionSemantics(
type)) {
3370 Builder.CreateStore(
True, LV.getAddress(), LV.isVolatileQualified())
3371 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
3372 return Builder.getTrue();
3376 return Builder.CreateAtomicRMW(
3377 llvm::AtomicRMWInst::Xchg, LV.getAddress(),
True,
3378 llvm::AtomicOrdering::SequentiallyConsistent);
3383 if (!hasBoolConversionSemantics(
type) &&
type->isIntegerType() &&
3384 !(
type->isUnsignedIntegerType() &&
3385 CGF.
SanOpts.
has(SanitizerKind::UnsignedIntegerOverflow)) &&
3387 LangOptions::SOB_Trapping) {
3388 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
3389 llvm::AtomicRMWInst::Sub;
3390 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
3391 llvm::Instruction::Sub;
3393 llvm::ConstantInt::get(ConvertType(
type), 1,
true),
type);
3395 Builder.CreateAtomicRMW(aop, LV.getAddress(), amt,
3396 llvm::AtomicOrdering::SequentiallyConsistent);
3397 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
3401 if (
type->isFloatingType()) {
3402 llvm::Type *Ty = ConvertType(
type);
3403 if (llvm::has_single_bit(Ty->getScalarSizeInBits())) {
3404 llvm::AtomicRMWInst::BinOp aop =
3405 isInc ? llvm::AtomicRMWInst::FAdd : llvm::AtomicRMWInst::FSub;
3406 llvm::Instruction::BinaryOps op =
3407 isInc ? llvm::Instruction::FAdd : llvm::Instruction::FSub;
3408 llvm::Value *amt = llvm::ConstantFP::get(Ty, 1.0);
3409 llvm::AtomicRMWInst *old =
3411 llvm::AtomicOrdering::SequentiallyConsistent);
3413 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
3416 value = EmitLoadOfLValue(LV, E->
getExprLoc());
3419 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3422 Builder.CreateBr(opBB);
3423 Builder.SetInsertPoint(opBB);
3424 atomicPHI = Builder.CreatePHI(value->getType(), 2);
3425 atomicPHI->addIncoming(value, startBB);
3428 value = EmitLoadOfLValue(LV, E->
getExprLoc());
3439 if (isInc && hasBoolConversionSemantics(
type)) {
3440 value = Builder.getTrue();
3443 }
else if (
type->isIntegerType()) {
3444 QualType promotedType;
3445 bool canPerformLossyDemotionCheck =
false;
3449 assert(promotedType !=
type &&
"Shouldn't promote to the same type.");
3450 canPerformLossyDemotionCheck =
true;
3451 canPerformLossyDemotionCheck &=
3454 canPerformLossyDemotionCheck &=
3456 type, promotedType);
3457 assert((!canPerformLossyDemotionCheck ||
3458 type->isSignedIntegerOrEnumerationType() ||
3460 ConvertType(
type)->getScalarSizeInBits() ==
3461 ConvertType(promotedType)->getScalarSizeInBits()) &&
3462 "The following check expects that if we do promotion to different "
3463 "underlying canonical type, at least one of the types (either "
3464 "base or promoted) will be signed, or the bitwidths will match.");
3467 SanitizerKind::ImplicitIntegerArithmeticValueChange |
3468 SanitizerKind::ImplicitBitfieldConversion) &&
3469 canPerformLossyDemotionCheck) {
3483 value = EmitScalarConversion(value,
type, promotedType, E->
getExprLoc());
3484 Value *amt = llvm::ConstantInt::get(value->getType(), amount,
true);
3485 value = Builder.CreateAdd(value, amt, isInc ?
"inc" :
"dec");
3489 ScalarConversionOpts Opts;
3490 if (!LV.isBitField())
3491 Opts = ScalarConversionOpts(CGF.
SanOpts);
3492 else if (CGF.
SanOpts.
has(SanitizerKind::ImplicitBitfieldConversion)) {
3494 SrcType = promotedType;
3498 value = EmitScalarConversion(value, promotedType,
type, E->
getExprLoc(),
3504 }
else if (
type->isSignedIntegerOrEnumerationType() ||
3505 type->isUnsignedIntegerType()) {
3506 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
3511 llvm::ConstantInt::get(value->getType(), amount, !isInc);
3512 value = Builder.CreateAdd(value, amt, isInc ?
"inc" :
"dec");
3516 }
else if (
const PointerType *ptr =
type->getAs<PointerType>()) {
3517 QualType
type = ptr->getPointeeType();
3520 if (
const VariableArrayType *vla
3523 if (!isInc) numElts = Builder.CreateNSWNeg(numElts,
"vla.negsize");
3526 value = Builder.CreateGEP(elemTy, value, numElts,
"vla.inc");
3529 elemTy, value, numElts,
false, isSubtraction,
3533 }
else if (
type->isFunctionType()) {
3534 llvm::Value *amt = Builder.getInt32(amount);
3537 value = Builder.CreateGEP(CGF.
Int8Ty, value, amt,
"incdec.funcptr");
3541 false, isSubtraction,
3546 llvm::Value *amt = Builder.getInt32(amount);
3549 value = Builder.CreateGEP(elemTy, value, amt,
"incdec.ptr");
3552 elemTy, value, amt,
false, isSubtraction,
3557 }
else if (
type->isVectorType()) {
3558 if (
type->hasIntegerRepresentation()) {
3559 llvm::Value *amt = llvm::ConstantInt::getSigned(value->getType(), amount);
3561 value = Builder.CreateAdd(value, amt, isInc ?
"inc" :
"dec");
3563 value = Builder.CreateFAdd(
3565 llvm::ConstantFP::get(value->getType(), amount),
3566 isInc ?
"inc" :
"dec");
3570 }
else if (
type->isRealFloatingType()) {
3573 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
3577 value = Builder.CreateFPExt(value, CGF.
CGM.
FloatTy,
"incdec.conv");
3579 if (value->getType()->isFloatTy())
3580 amt = llvm::ConstantFP::get(VMContext,
3581 llvm::APFloat(
static_cast<float>(amount)));
3582 else if (value->getType()->isDoubleTy())
3583 amt = llvm::ConstantFP::get(VMContext,
3584 llvm::APFloat(
static_cast<double>(amount)));
3588 llvm::APFloat F(
static_cast<float>(amount));
3590 const llvm::fltSemantics *FS;
3593 if (value->getType()->isFP128Ty())
3595 else if (value->getType()->isHalfTy())
3597 else if (value->getType()->isBFloatTy())
3599 else if (value->getType()->isPPC_FP128Ty())
3603 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
3604 amt = llvm::ConstantFP::get(VMContext, F);
3606 value = Builder.CreateFAdd(value, amt, isInc ?
"inc" :
"dec");
3609 value = Builder.CreateFPTrunc(value, CGF.
CGM.
HalfTy,
"incdec.conv");
3612 }
else if (
type->isFixedPointType()) {
3619 Info.Opcode = isInc ? BO_Add : BO_Sub;
3621 Info.RHS = llvm::ConstantInt::get(value->getType(), 1,
false);
3624 if (
type->isSignedFixedPointType()) {
3625 Info.Opcode = isInc ? BO_Sub : BO_Add;
3626 Info.RHS = Builder.CreateNeg(Info.RHS);
3631 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
3633 Info.RHS = FPBuilder.CreateIntegerToFixed(Info.RHS,
true, DstSema);
3634 value = EmitFixedPointBinOp(Info);
3638 const ObjCObjectPointerType *OPT =
type->castAs<ObjCObjectPointerType>();
3641 if (!isInc) size = -size;
3642 llvm::Value *sizeValue =
3643 llvm::ConstantInt::getSigned(CGF.
SizeTy, size.getQuantity());
3646 value = Builder.CreateGEP(CGF.
Int8Ty, value, sizeValue,
"incdec.objptr");
3649 CGF.
Int8Ty, value, sizeValue,
false, isSubtraction,
3651 value = Builder.CreateBitCast(value, input->getType());
3655 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3660 llvm::Value *
success = Pair.second;
3661 atomicPHI->addIncoming(old, curBlock);
3662 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
3663 Builder.SetInsertPoint(contBB);
3664 return isPre ? value : input;
3668 if (LV.isBitField()) {
3678 return isPre ? value : input;
3682Value *ScalarExprEmitter::VisitUnaryPlus(
const UnaryOperator *E,
3683 QualType PromotionType) {
3684 QualType promotionTy = PromotionType.
isNull()
3687 Value *result = VisitPlus(E, promotionTy);
3688 if (result && !promotionTy.
isNull())
3689 result = EmitUnPromotedValue(result, E->
getType());
3693Value *ScalarExprEmitter::VisitPlus(
const UnaryOperator *E,
3694 QualType PromotionType) {
3696 TestAndClearIgnoreResultAssign();
3697 if (!PromotionType.
isNull())
3702Value *ScalarExprEmitter::VisitUnaryMinus(
const UnaryOperator *E,
3703 QualType PromotionType) {
3704 QualType promotionTy = PromotionType.
isNull()
3707 Value *result = VisitMinus(E, promotionTy);
3708 if (result && !promotionTy.
isNull())
3709 result = EmitUnPromotedValue(result, E->
getType());
3713Value *ScalarExprEmitter::VisitMinus(
const UnaryOperator *E,
3714 QualType PromotionType) {
3715 TestAndClearIgnoreResultAssign();
3717 if (!PromotionType.
isNull())
3723 if (Op->
getType()->isFPOrFPVectorTy()) {
3724 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
3725 return Builder.CreateFNeg(Op,
"fneg");
3731 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
3733 BinOp.Opcode = BO_Sub;
3736 return EmitSub(BinOp);
3739Value *ScalarExprEmitter::VisitUnaryNot(
const UnaryOperator *E) {
3740 TestAndClearIgnoreResultAssign();
3742 return Builder.CreateNot(Op,
"not");
3745Value *ScalarExprEmitter::VisitUnaryLNot(
const UnaryOperator *E) {
3749 VectorKind::Generic) {
3753 if (Oper->
getType()->isFPOrFPVectorTy()) {
3754 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
3756 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper,
Zero,
"cmp");
3758 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper,
Zero,
"cmp");
3759 return Builder.CreateSExt(
Result, ConvertType(E->
getType()),
"sext");
3768 BoolVal = Builder.CreateNot(BoolVal,
"lnot");
3771 return Builder.CreateZExt(BoolVal, ConvertType(E->
getType()),
"lnot.ext");
3774Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
3776 Expr::EvalResult EVResult;
3779 return Builder.getInt(
Value);
3784 llvm::Type* ResultType = ConvertType(E->
getType());
3785 llvm::Value*
Result = llvm::Constant::getNullValue(ResultType);
3787 for (
unsigned i = 0; i != n; ++i) {
3789 llvm::Value *Offset =
nullptr;
3796 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned,
"conv");
3803 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
3807 Offset = Builder.CreateMul(Idx, ElemSize);
3812 FieldDecl *MemberDecl = ON.
getField();
3822 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
3825 CurrentType = MemberDecl->
getType();
3830 llvm_unreachable(
"dependent __builtin_offsetof");
3847 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.
getQuantity());
3859ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
3860 const UnaryExprOrTypeTraitExpr *E) {
3863 Kind == UETT_SizeOf || Kind == UETT_DataSizeOf || Kind == UETT_CountOf) {
3864 if (
const VariableArrayType *VAT =
3869 bool EvaluateExtent =
true;
3870 if (Kind == UETT_CountOf && VAT->getElementType()->isArrayType()) {
3872 !VAT->getSizeExpr()->isIntegerConstantExpr(CGF.
getContext());
3874 if (EvaluateExtent) {
3885 if (Kind == UETT_CountOf)
3894 if (!eltSize.
isOne())
3897 return VlaSize.NumElts;
3900 }
else if (E->
getKind() == UETT_OpenMPRequiredSimdAlign) {
3906 return llvm::ConstantInt::get(CGF.
SizeTy, Alignment);
3907 }
else if (E->
getKind() == UETT_VectorElements) {
3909 return Builder.CreateElementCount(CGF.
SizeTy, VecTy->getElementCount());
3917Value *ScalarExprEmitter::VisitUnaryReal(
const UnaryOperator *E,
3918 QualType PromotionType) {
3919 QualType promotionTy = PromotionType.
isNull()
3922 Value *result = VisitReal(E, promotionTy);
3923 if (result && !promotionTy.
isNull())
3924 result = EmitUnPromotedValue(result, E->
getType());
3928Value *ScalarExprEmitter::VisitReal(
const UnaryOperator *E,
3929 QualType PromotionType) {
3936 if (!PromotionType.
isNull()) {
3938 Op, IgnoreResultAssign,
true);
3953 if (!PromotionType.
isNull())
3958Value *ScalarExprEmitter::VisitUnaryImag(
const UnaryOperator *E,
3959 QualType PromotionType) {
3960 QualType promotionTy = PromotionType.
isNull()
3963 Value *result = VisitImag(E, promotionTy);
3964 if (result && !promotionTy.
isNull())
3965 result = EmitUnPromotedValue(result, E->
getType());
3969Value *ScalarExprEmitter::VisitImag(
const UnaryOperator *E,
3970 QualType PromotionType) {
3977 if (!PromotionType.
isNull()) {
3979 Op,
true, IgnoreResultAssign);
3983 return result.second
3999 else if (!PromotionType.
isNull())
4003 if (!PromotionType.
isNull())
4004 return llvm::Constant::getNullValue(ConvertType(PromotionType));
4005 return llvm::Constant::getNullValue(ConvertType(E->
getType()));
4012Value *ScalarExprEmitter::EmitPromotedValue(
Value *result,
4013 QualType PromotionType) {
4014 return CGF.
Builder.CreateFPExt(result, ConvertType(PromotionType),
"ext");
4017Value *ScalarExprEmitter::EmitUnPromotedValue(
Value *result,
4018 QualType ExprType) {
4019 return CGF.
Builder.CreateFPTrunc(result, ConvertType(ExprType),
"unpromotion");
4022Value *ScalarExprEmitter::EmitPromoted(
const Expr *E, QualType PromotionType) {
4024 if (
auto BO = dyn_cast<BinaryOperator>(E)) {
4026#define HANDLE_BINOP(OP) \
4028 return Emit##OP(EmitBinOps(BO, PromotionType));
4037 }
else if (
auto UO = dyn_cast<UnaryOperator>(E)) {
4040 return VisitImag(UO, PromotionType);
4042 return VisitReal(UO, PromotionType);
4044 return VisitMinus(UO, PromotionType);
4046 return VisitPlus(UO, PromotionType);
4051 auto result = Visit(
const_cast<Expr *
>(E));
4053 if (!PromotionType.
isNull())
4054 return EmitPromotedValue(result, PromotionType);
4056 return EmitUnPromotedValue(result, E->
getType());
4061BinOpInfo ScalarExprEmitter::EmitBinOps(
const BinaryOperator *E,
4062 QualType PromotionType) {
4063 TestAndClearIgnoreResultAssign();
4067 if (!PromotionType.
isNull())
4068 Result.Ty = PromotionType;
4077LValue ScalarExprEmitter::EmitCompoundAssignLValue(
4078 const CompoundAssignOperator *E,
4079 Value *(ScalarExprEmitter::*
Func)(
const BinOpInfo &),
4090 QualType PromotionTypeCR;
4092 if (PromotionTypeCR.
isNull())
4095 QualType PromotionTypeRHS = getPromotionType(E->
getRHS()->
getType());
4096 if (!PromotionTypeRHS.
isNull())
4099 OpInfo.RHS = Visit(E->
getRHS());
4100 OpInfo.Ty = PromotionTypeCR;
4107 llvm::PHINode *atomicPHI =
nullptr;
4108 if (
const AtomicType *atomicTy = LHSTy->
getAs<AtomicType>()) {
4110 QualType AtomicValueTy = atomicTy->getValueType();
4119 bool CanEmitAtomicRMW;
4121 llvm::Type *IRTy = CGF.
ConvertType(AtomicValueTy);
4125 !OpInfo.FPFeatures.isFPConstrained() &&
4127 llvm::isPowerOf2_64(StoreBits);
4133 CGF.
SanOpts.
has(SanitizerKind::UnsignedIntegerOverflow)) &&
4135 LangOptions::SOB_Trapping;
4137 if (CanEmitAtomicRMW) {
4138 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
4139 llvm::Instruction::BinaryOps Op;
4141 switch (OpInfo.Opcode) {
4143 AtomicOp = llvm::AtomicRMWInst::FAdd;
4144 Op = llvm::Instruction::FAdd;
4147 AtomicOp = llvm::AtomicRMWInst::FSub;
4148 Op = llvm::Instruction::FSub;
4154 switch (OpInfo.Opcode) {
4156 case BO_MulAssign:
case BO_DivAssign:
4162 AtomicOp = llvm::AtomicRMWInst::Add;
4163 Op = llvm::Instruction::Add;
4166 AtomicOp = llvm::AtomicRMWInst::Sub;
4167 Op = llvm::Instruction::Sub;
4170 AtomicOp = llvm::AtomicRMWInst::And;
4171 Op = llvm::Instruction::And;
4174 AtomicOp = llvm::AtomicRMWInst::Xor;
4175 Op = llvm::Instruction::Xor;
4178 AtomicOp = llvm::AtomicRMWInst::Or;
4179 Op = llvm::Instruction::Or;
4182 llvm_unreachable(
"Invalid compound assignment type");
4185 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
4187 EmitScalarConversion(OpInfo.RHS, E->
getRHS()->
getType(), LHSTy,
4191 llvm::AtomicRMWInst *OldVal =
4196 Result = Builder.CreateBinOp(Op, OldVal, Amt);
4202 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
4204 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->
getExprLoc());
4205 OpInfo.LHS = CGF.
EmitToMemory(OpInfo.LHS, AtomicValueTy);
4206 Builder.CreateBr(opBB);
4207 Builder.SetInsertPoint(opBB);
4208 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
4209 atomicPHI->addIncoming(OpInfo.LHS, startBB);
4210 OpInfo.LHS = atomicPHI;
4213 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->
getExprLoc());
4215 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
4217 if (!PromotionTypeLHS.
isNull())
4218 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, PromotionTypeLHS,
4221 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
4232 if (LHSLV.isBitField()) {
4234 Result = EmitScalarConversion(
Result, PromotionTypeCR, LHSTy, Loc);
4235 }
else if (
const auto *atomicTy = LHSTy->
getAs<AtomicType>()) {
4237 EmitScalarConversion(
Result, PromotionTypeCR, atomicTy->getValueType(),
4238 Loc, ScalarConversionOpts(CGF.
SanOpts));
4240 Result = EmitScalarConversion(
Result, PromotionTypeCR, LHSTy, Loc,
4241 ScalarConversionOpts(CGF.
SanOpts));
4245 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
4249 llvm::Value *old = CGF.
EmitToMemory(Pair.first.getScalarVal(), LHSTy);
4250 llvm::Value *
success = Pair.second;
4251 atomicPHI->addIncoming(old, curBlock);
4252 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
4253 Builder.SetInsertPoint(contBB);
4261 if (LHSLV.isBitField()) {
4277Value *ScalarExprEmitter::EmitCompoundAssign(
const CompoundAssignOperator *E,
4278 Value *(ScalarExprEmitter::*
Func)(
const BinOpInfo &)) {
4279 bool Ignore = TestAndClearIgnoreResultAssign();
4280 Value *RHS =
nullptr;
4281 LValue LHS = EmitCompoundAssignLValue(E,
Func, RHS);
4292 if (!LHS.isVolatileQualified())
4296 return EmitLoadOfLValue(LHS, E->
getExprLoc());
4299void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
4300 const BinOpInfo &Ops, llvm::Value *
Zero,
bool isDiv) {
4301 SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>, 2>
4304 if (CGF.
SanOpts.
has(SanitizerKind::IntegerDivideByZero)) {
4305 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS,
Zero),
4306 SanitizerKind::SO_IntegerDivideByZero));
4310 if (CGF.
SanOpts.
has(SanitizerKind::SignedIntegerOverflow) &&
4311 Ops.Ty->hasSignedIntegerRepresentation() &&
4313 Ops.mayHaveIntegerOverflow() &&
4315 SanitizerKind::SignedIntegerOverflow, Ops.Ty)) {
4318 llvm::Value *IntMin =
4319 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
4320 llvm::Value *NegOne = llvm::Constant::getAllOnesValue(Ty);
4322 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
4323 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
4324 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp,
"or");
4326 std::make_pair(NotOverflow, SanitizerKind::SO_SignedIntegerOverflow));
4329 if (Checks.size() > 0)
4330 EmitBinOpCheck(Checks, Ops);
4333Value *ScalarExprEmitter::EmitDiv(
const BinOpInfo &Ops) {
4335 SanitizerDebugLocation SanScope(&CGF,
4336 {SanitizerKind::SO_IntegerDivideByZero,
4337 SanitizerKind::SO_SignedIntegerOverflow,
4338 SanitizerKind::SO_FloatDivideByZero},
4339 SanitizerHandler::DivremOverflow);
4340 if ((CGF.
SanOpts.
has(SanitizerKind::IntegerDivideByZero) ||
4341 CGF.
SanOpts.
has(SanitizerKind::SignedIntegerOverflow)) &&
4342 Ops.Ty->isIntegerType() &&
4343 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
4344 llvm::Value *
Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
4345 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops,
Zero,
true);
4346 }
else if (CGF.
SanOpts.
has(SanitizerKind::FloatDivideByZero) &&
4347 Ops.Ty->isRealFloatingType() &&
4348 Ops.mayHaveFloatDivisionByZero()) {
4349 llvm::Value *
Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
4350 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS,
Zero);
4352 std::make_pair(NonZero, SanitizerKind::SO_FloatDivideByZero), Ops);
4357 if (Ops.Ty->isConstantMatrixType() && !Ops.RHS->getType()->isVectorTy()) {
4358 llvm::MatrixBuilder MB(Builder);
4365 "first operand must be a matrix");
4367 "second operand must be an arithmetic type");
4368 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
4369 return MB.CreateScalarDiv(Ops.LHS, Ops.RHS,
4370 Ops.Ty->hasUnsignedIntegerRepresentation());
4373 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
4375 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
4376 Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS,
"div");
4380 else if (Ops.isFixedPointOp())
4381 return EmitFixedPointBinOp(Ops);
4382 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
4383 return Builder.CreateUDiv(Ops.LHS, Ops.RHS,
"div");
4385 return Builder.CreateSDiv(Ops.LHS, Ops.RHS,
"div");
4388Value *ScalarExprEmitter::EmitRem(
const BinOpInfo &Ops) {
4390 if ((CGF.
SanOpts.
has(SanitizerKind::IntegerDivideByZero) ||
4391 CGF.
SanOpts.
has(SanitizerKind::SignedIntegerOverflow)) &&
4392 Ops.Ty->isIntegerType() &&
4393 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
4394 SanitizerDebugLocation SanScope(&CGF,
4395 {SanitizerKind::SO_IntegerDivideByZero,
4396 SanitizerKind::SO_SignedIntegerOverflow},
4397 SanitizerHandler::DivremOverflow);
4398 llvm::Value *
Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
4399 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops,
Zero,
false);
4402 if (Ops.Ty->hasUnsignedIntegerRepresentation())
4403 return Builder.CreateURem(Ops.LHS, Ops.RHS,
"rem");
4405 if (CGF.
getLangOpts().HLSL && Ops.Ty->hasFloatingRepresentation())
4406 return Builder.CreateFRem(Ops.LHS, Ops.RHS,
"rem");
4408 return Builder.CreateSRem(Ops.LHS, Ops.RHS,
"rem");
4411Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(
const BinOpInfo &Ops) {
4416 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
4417 switch (Ops.Opcode) {
4421 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
4422 llvm::Intrinsic::uadd_with_overflow;
4423 OverflowKind = SanitizerHandler::AddOverflow;
4428 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
4429 llvm::Intrinsic::usub_with_overflow;
4430 OverflowKind = SanitizerHandler::SubOverflow;
4435 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
4436 llvm::Intrinsic::umul_with_overflow;
4437 OverflowKind = SanitizerHandler::MulOverflow;
4440 llvm_unreachable(
"Unsupported operation for overflow detection");
4446 SanitizerDebugLocation SanScope(&CGF,
4447 {SanitizerKind::SO_SignedIntegerOverflow,
4448 SanitizerKind::SO_UnsignedIntegerOverflow},
4454 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
4455 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
4456 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
4459 const std::string *handlerName =
4461 if (handlerName->empty()) {
4467 if (CGF.
SanOpts.
has(SanitizerKind::SignedIntegerOverflow)) {
4468 llvm::Value *NotOf = Builder.CreateNot(overflow);
4470 std::make_pair(NotOf, SanitizerKind::SO_SignedIntegerOverflow),
4473 CGF.
EmitTrapCheck(Builder.CreateNot(overflow), OverflowKind);
4476 if (CGF.
SanOpts.
has(SanitizerKind::UnsignedIntegerOverflow)) {
4477 llvm::Value *NotOf = Builder.CreateNot(overflow);
4479 std::make_pair(NotOf, SanitizerKind::SO_UnsignedIntegerOverflow),
4482 CGF.
EmitTrapCheck(Builder.CreateNot(overflow), OverflowKind);
4487 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
4488 llvm::BasicBlock *continueBB =
4492 Builder.CreateCondBr(overflow, overflowBB, continueBB);
4496 Builder.SetInsertPoint(overflowBB);
4502 llvm::FunctionCallee handler =
4507 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.
Int64Ty);
4508 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.
Int64Ty);
4512 llvm::Value *handlerArgs[] = {
4515 Builder.getInt8(OpID),
4518 llvm::Value *handlerResult =
4522 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
4523 Builder.CreateBr(continueBB);
4525 Builder.SetInsertPoint(continueBB);
4526 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
4527 phi->addIncoming(result, initialBB);
4528 phi->addIncoming(handlerResult, overflowBB);
4537 bool isSubtraction) {
4542 Value *pointer = op.LHS;
4543 Expr *pointerOperand =
expr->getLHS();
4545 Expr *indexOperand =
expr->getRHS();
4548 if (!isSubtraction && !pointer->
getType()->isPointerTy()) {
4549 std::swap(pointer,
index);
4550 std::swap(pointerOperand, indexOperand);
4554 index, isSubtraction);
4560 Expr *indexOperand, llvm::Value *
index,
bool isSubtraction) {
4564 auto &DL =
CGM.getDataLayout();
4587 llvm::Value *Ptr =
Builder.CreateIntToPtr(
index, pointer->getType());
4589 !
SanOpts.has(SanitizerKind::PointerOverflow) ||
4590 NullPointerIsDefined(
Builder.GetInsertBlock()->getParent(),
4591 PtrTy->getPointerAddressSpace()))
4594 auto CheckOrdinal = SanitizerKind::SO_PointerOverflow;
4595 auto CheckHandler = SanitizerHandler::PointerOverflow;
4597 llvm::Value *IsZeroIndex =
Builder.CreateIsNull(
index);
4599 llvm::Type *
IntPtrTy = DL.getIntPtrType(PtrTy);
4600 llvm::Value *IntPtr = llvm::Constant::getNullValue(
IntPtrTy);
4602 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
4603 EmitCheck({{IsZeroIndex, CheckOrdinal}}, CheckHandler, StaticArgs,
4608 if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
4619 if (
SanOpts.has(SanitizerKind::ArrayBounds))
4629 llvm::Value *objectSize =
4635 return Builder.CreateBitCast(result, pointer->getType());
4640 getContext().getAsVariableArrayType(elementType)) {
4642 llvm::Value *numElements =
getVLASize(vla).NumElts;
4651 pointer =
Builder.CreateGEP(elemTy, pointer,
index,
"add.ptr");
4671 return Builder.CreateGEP(elemTy, pointer,
index,
"add.ptr");
4684 bool negMul,
bool negAdd) {
4685 Value *MulOp0 = MulOp->getOperand(0);
4686 Value *MulOp1 = MulOp->getOperand(1);
4688 MulOp0 = Builder.CreateFNeg(MulOp0,
"neg");
4690 Addend = Builder.CreateFNeg(Addend,
"neg");
4692 Value *FMulAdd =
nullptr;
4693 if (Builder.getIsFPConstrained()) {
4695 "Only constrained operation should be created when Builder is in FP "
4696 "constrained mode");
4697 FMulAdd = Builder.CreateConstrainedFPCall(
4698 CGF.
CGM.
getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
4700 {MulOp0, MulOp1, Addend});
4702 FMulAdd = Builder.CreateCall(
4704 {MulOp0, MulOp1, Addend});
4706 MulOp->eraseFromParent();
4721 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
4722 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
4723 "Only fadd/fsub can be the root of an fmuladd.");
4726 if (!op.FPFeatures.allowFPContractWithinStatement())
4731 if (op.LHS->getType() != op.RHS->getType())
4734 Value *LHS = op.LHS;
4735 Value *RHS = op.RHS;
4739 bool NegLHS =
false;
4740 if (
auto *LHSUnOp = dyn_cast<llvm::UnaryOperator>(LHS)) {
4741 if (LHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4742 LHSUnOp->use_empty() && LHSUnOp->getOperand(0)->hasOneUse()) {
4743 LHS = LHSUnOp->getOperand(0);
4748 bool NegRHS =
false;
4749 if (
auto *RHSUnOp = dyn_cast<llvm::UnaryOperator>(RHS)) {
4750 if (RHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4751 RHSUnOp->use_empty() && RHSUnOp->getOperand(0)->hasOneUse()) {
4752 RHS = RHSUnOp->getOperand(0);
4760 if (
auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(LHS)) {
4761 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4762 (LHSBinOp->use_empty() || NegLHS)) {
4766 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, NegLHS, isSub);
4769 if (
auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(RHS)) {
4770 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4771 (RHSBinOp->use_empty() || NegRHS)) {
4775 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub ^ NegRHS,
false);
4779 if (
auto *LHSBinOp = dyn_cast<llvm::CallBase>(LHS)) {
4780 if (LHSBinOp->getIntrinsicID() ==
4781 llvm::Intrinsic::experimental_constrained_fmul &&
4782 (LHSBinOp->use_empty() || NegLHS)) {
4786 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, NegLHS, isSub);
4789 if (
auto *RHSBinOp = dyn_cast<llvm::CallBase>(RHS)) {
4790 if (RHSBinOp->getIntrinsicID() ==
4791 llvm::Intrinsic::experimental_constrained_fmul &&
4792 (RHSBinOp->use_empty() || NegRHS)) {
4796 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub ^ NegRHS,
false);
4803Value *ScalarExprEmitter::EmitAdd(
const BinOpInfo &op) {
4804 if (op.LHS->getType()->isPointerTy() ||
4805 op.RHS->getType()->isPointerTy())
4808 if (op.Ty->isSignedIntegerOrEnumerationType() ||
4809 op.Ty->isUnsignedIntegerType()) {
4810 const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType();
4812 isSigned ? CGF.
SanOpts.
has(SanitizerKind::SignedIntegerOverflow)
4813 : CGF.
SanOpts.
has(SanitizerKind::UnsignedIntegerOverflow);
4814 switch (getOverflowBehaviorConsideringType(CGF, op.Ty)) {
4815 case LangOptions::OB_Wrap:
4816 return Builder.CreateAdd(op.LHS, op.RHS,
"add");
4817 case LangOptions::OB_SignedAndDefined:
4819 return Builder.CreateAdd(op.LHS, op.RHS,
"add");
4821 case LangOptions::OB_Unset:
4823 return isSigned ? Builder.CreateNSWAdd(op.LHS, op.RHS,
"add")
4824 : Builder.CreateAdd(op.LHS, op.RHS,
"add");
4826 case LangOptions::OB_Trap:
4827 if (CanElideOverflowCheck(CGF.
getContext(), op))
4828 return isSigned ? Builder.CreateNSWAdd(op.LHS, op.RHS,
"add")
4829 : Builder.CreateAdd(op.LHS, op.RHS,
"add");
4830 return EmitOverflowCheckedBinOp(op);
4835 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4836 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4842 if (op.Ty->isConstantMatrixType()) {
4843 llvm::MatrixBuilder MB(Builder);
4844 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4845 return MB.CreateAdd(op.LHS, op.RHS);
4848 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4849 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4850 return Builder.CreateFAdd(op.LHS, op.RHS,
"add");
4853 if (op.isFixedPointOp())
4854 return EmitFixedPointBinOp(op);
4856 return Builder.CreateAdd(op.LHS, op.RHS,
"add");
4861Value *ScalarExprEmitter::EmitFixedPointBinOp(
const BinOpInfo &op) {
4863 using llvm::ConstantInt;
4869 QualType ResultTy = op.Ty;
4870 QualType LHSTy, RHSTy;
4871 if (
const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
4872 RHSTy = BinOp->getRHS()->getType();
4873 if (
const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
4878 LHSTy = CAO->getComputationLHSType();
4879 ResultTy = CAO->getComputationResultType();
4881 LHSTy = BinOp->getLHS()->getType();
4882 }
else if (
const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
4883 LHSTy = UnOp->getSubExpr()->getType();
4884 RHSTy = UnOp->getSubExpr()->getType();
4887 Value *LHS = op.LHS;
4888 Value *RHS = op.RHS;
4893 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
4897 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
4898 switch (op.Opcode) {
4901 Result = FPBuilder.CreateAdd(LHS, LHSFixedSema, RHS, RHSFixedSema);
4905 Result = FPBuilder.CreateSub(LHS, LHSFixedSema, RHS, RHSFixedSema);
4909 Result = FPBuilder.CreateMul(LHS, LHSFixedSema, RHS, RHSFixedSema);
4913 Result = FPBuilder.CreateDiv(LHS, LHSFixedSema, RHS, RHSFixedSema);
4917 Result = FPBuilder.CreateShl(LHS, LHSFixedSema, RHS);
4921 Result = FPBuilder.CreateShr(LHS, LHSFixedSema, RHS);
4924 return FPBuilder.CreateLT(LHS, LHSFixedSema, RHS, RHSFixedSema);
4926 return FPBuilder.CreateGT(LHS, LHSFixedSema, RHS, RHSFixedSema);
4928 return FPBuilder.CreateLE(LHS, LHSFixedSema, RHS, RHSFixedSema);
4930 return FPBuilder.CreateGE(LHS, LHSFixedSema, RHS, RHSFixedSema);
4935 return FPBuilder.CreateEQ(LHS, LHSFixedSema, RHS, RHSFixedSema);
4937 return FPBuilder.CreateNE(LHS, LHSFixedSema, RHS, RHSFixedSema);
4941 llvm_unreachable(
"Found unimplemented fixed point binary operation");
4954 llvm_unreachable(
"Found unsupported binary operation for fixed point types.");
4960 return FPBuilder.CreateFixedToFixed(
Result, IsShift ? LHSFixedSema
4965Value *ScalarExprEmitter::EmitSub(
const BinOpInfo &op) {
4967 if (!op.LHS->getType()->isPointerTy()) {
4968 if (op.Ty->isSignedIntegerOrEnumerationType() ||
4969 op.Ty->isUnsignedIntegerType()) {
4970 const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType();
4972 isSigned ? CGF.
SanOpts.
has(SanitizerKind::SignedIntegerOverflow)
4973 : CGF.
SanOpts.
has(SanitizerKind::UnsignedIntegerOverflow);
4974 switch (getOverflowBehaviorConsideringType(CGF, op.Ty)) {
4975 case LangOptions::OB_Wrap:
4976 return Builder.CreateSub(op.LHS, op.RHS,
"sub");
4977 case LangOptions::OB_SignedAndDefined:
4979 return Builder.CreateSub(op.LHS, op.RHS,
"sub");
4981 case LangOptions::OB_Unset:
4983 return isSigned ? Builder.CreateNSWSub(op.LHS, op.RHS,
"sub")
4984 : Builder.CreateSub(op.LHS, op.RHS,
"sub");
4986 case LangOptions::OB_Trap:
4987 if (CanElideOverflowCheck(CGF.
getContext(), op))
4988 return isSigned ? Builder.CreateNSWSub(op.LHS, op.RHS,
"sub")
4989 : Builder.CreateSub(op.LHS, op.RHS,
"sub");
4990 return EmitOverflowCheckedBinOp(op);
4995 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4996 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
5002 if (op.Ty->isConstantMatrixType()) {
5003 llvm::MatrixBuilder MB(Builder);
5004 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
5005 return MB.CreateSub(op.LHS, op.RHS);
5008 if (op.LHS->getType()->isFPOrFPVectorTy()) {
5009 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
5010 return Builder.CreateFSub(op.LHS, op.RHS,
"sub");
5013 if (op.isFixedPointOp())
5014 return EmitFixedPointBinOp(op);
5016 return Builder.CreateSub(op.LHS, op.RHS,
"sub");
5021 if (!op.RHS->getType()->isPointerTy())
5031 LHS = Builder.CreatePtrToInt(op.LHS, CGF.
PtrDiffTy,
"sub.ptr.lhs.cast");
5032 RHS = Builder.CreatePtrToInt(op.RHS, CGF.
PtrDiffTy,
"sub.ptr.rhs.cast");
5034 LHS = Builder.CreatePtrToAddr(op.LHS,
"sub.ptr.lhs.cast");
5035 RHS = Builder.CreatePtrToAddr(op.RHS,
"sub.ptr.rhs.cast");
5037 LHS = Builder.CreateZExtOrTrunc(LHS, CGF.
PtrDiffTy,
"sub.ptr.lhs.ext");
5039 RHS = Builder.CreateZExtOrTrunc(RHS, CGF.
PtrDiffTy,
"sub.ptr.lhs.ext");
5041 Value *diffInChars = Builder.CreateSub(LHS, RHS,
"sub.ptr.sub");
5045 QualType elementType =
expr->getLHS()->getType()->getPointeeType();
5047 llvm::Value *divisor =
nullptr;
5050 if (
const VariableArrayType *vla
5053 elementType = VlaSize.Type;
5054 divisor = VlaSize.NumElts;
5058 if (!eltSize.
isOne())
5065 CharUnits elementSize;
5074 if (elementSize.
isOne())
5081 return Builder.CreateSDiv(diffInChars, divisor,
"sub.ptr.div");
5085 return Builder.CreateExactSDiv(diffInChars, divisor,
"sub.ptr.div");
5088Value *ScalarExprEmitter::GetMaximumShiftAmount(
Value *LHS,
Value *RHS,
5090 llvm::IntegerType *Ty;
5091 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->
getType()))
5099 llvm::Type *RHSTy = RHS->
getType();
5100 llvm::APInt RHSMax =
5101 RHSIsSigned ? llvm::APInt::getSignedMaxValue(RHSTy->getScalarSizeInBits())
5102 : llvm::
APInt::getMaxValue(RHSTy->getScalarSizeInBits());
5103 if (RHSMax.ult(Ty->getBitWidth()))
5104 return llvm::ConstantInt::get(RHSTy, RHSMax);
5105 return llvm::ConstantInt::get(RHSTy, Ty->getBitWidth() - 1);
5109 const Twine &Name) {
5110 llvm::IntegerType *Ty;
5111 if (
auto *VT = dyn_cast<llvm::VectorType>(LHS->
getType()))
5116 if (llvm::isPowerOf2_64(Ty->getBitWidth()))
5117 return Builder.CreateAnd(RHS, GetMaximumShiftAmount(LHS, RHS,
false), Name);
5119 return Builder.CreateURem(
5120 RHS, llvm::ConstantInt::get(RHS->
getType(), Ty->getBitWidth()), Name);
5123Value *ScalarExprEmitter::EmitShl(
const BinOpInfo &Ops) {
5125 if (Ops.isFixedPointOp())
5126 return EmitFixedPointBinOp(Ops);
5130 Value *RHS = Ops.RHS;
5131 if (Ops.LHS->getType() != RHS->
getType())
5132 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(),
false,
"sh_prom");
5134 bool SanitizeSignedBase = CGF.
SanOpts.
has(SanitizerKind::ShiftBase) &&
5135 Ops.Ty->hasSignedIntegerRepresentation() &&
5138 bool SanitizeUnsignedBase =
5139 CGF.
SanOpts.
has(SanitizerKind::UnsignedShiftBase) &&
5140 Ops.Ty->hasUnsignedIntegerRepresentation();
5141 bool SanitizeBase = SanitizeSignedBase || SanitizeUnsignedBase;
5142 bool SanitizeExponent = CGF.
SanOpts.
has(SanitizerKind::ShiftExponent);
5145 RHS = ConstrainShiftValue(Ops.LHS, RHS,
"shl.mask");
5146 else if ((SanitizeBase || SanitizeExponent) &&
5148 SmallVector<SanitizerKind::SanitizerOrdinal, 3> Ordinals;
5149 if (SanitizeSignedBase)
5150 Ordinals.push_back(SanitizerKind::SO_ShiftBase);
5151 if (SanitizeUnsignedBase)
5152 Ordinals.push_back(SanitizerKind::SO_UnsignedShiftBase);
5153 if (SanitizeExponent)
5154 Ordinals.push_back(SanitizerKind::SO_ShiftExponent);
5156 SanitizerDebugLocation SanScope(&CGF, Ordinals,
5157 SanitizerHandler::ShiftOutOfBounds);
5158 SmallVector<std::pair<Value *, SanitizerKind::SanitizerOrdinal>, 2> Checks;
5159 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
5160 llvm::Value *WidthMinusOne =
5161 GetMaximumShiftAmount(Ops.LHS, Ops.RHS, RHSIsSigned);
5162 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
5164 if (SanitizeExponent) {
5166 std::make_pair(ValidExponent, SanitizerKind::SO_ShiftExponent));
5173 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
5176 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
5177 llvm::Value *PromotedWidthMinusOne =
5178 (RHS == Ops.RHS) ? WidthMinusOne
5179 : GetMaximumShiftAmount(Ops.LHS, RHS, RHSIsSigned);
5181 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
5182 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS,
"shl.zeros",
5191 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
5192 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
5194 llvm::Value *
Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
5195 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff,
Zero);
5197 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
5198 BaseCheck->addIncoming(Builder.getTrue(), Orig);
5199 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
5200 Checks.push_back(std::make_pair(
5201 BaseCheck, SanitizeSignedBase ? SanitizerKind::SO_ShiftBase
5202 : SanitizerKind::SO_UnsignedShiftBase));
5205 assert(!Checks.empty());
5206 EmitBinOpCheck(Checks, Ops);
5209 return Builder.CreateShl(Ops.LHS, RHS,
"shl");
5212Value *ScalarExprEmitter::EmitShr(
const BinOpInfo &Ops) {
5214 if (Ops.isFixedPointOp())
5215 return EmitFixedPointBinOp(Ops);
5219 Value *RHS = Ops.RHS;
5220 if (Ops.LHS->getType() != RHS->
getType())
5221 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(),
false,
"sh_prom");
5225 RHS = ConstrainShiftValue(Ops.LHS, RHS,
"shr.mask");
5226 else if (CGF.
SanOpts.
has(SanitizerKind::ShiftExponent) &&
5228 SanitizerDebugLocation SanScope(&CGF, {SanitizerKind::SO_ShiftExponent},
5229 SanitizerHandler::ShiftOutOfBounds);
5230 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
5231 llvm::Value *
Valid = Builder.CreateICmpULE(
5232 Ops.RHS, GetMaximumShiftAmount(Ops.LHS, Ops.RHS, RHSIsSigned));
5233 EmitBinOpCheck(std::make_pair(
Valid, SanitizerKind::SO_ShiftExponent), Ops);
5236 if (Ops.Ty->hasUnsignedIntegerRepresentation())
5237 return Builder.CreateLShr(Ops.LHS, RHS,
"shr");
5238 return Builder.CreateAShr(Ops.LHS, RHS,
"shr");
5246 default: llvm_unreachable(
"unexpected element type");
5247 case BuiltinType::Char_U:
5248 case BuiltinType::UChar:
5249 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
5250 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
5251 case BuiltinType::Char_S:
5252 case BuiltinType::SChar:
5253 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
5254 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
5255 case BuiltinType::UShort:
5256 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
5257 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
5258 case BuiltinType::Short:
5259 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
5260 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
5261 case BuiltinType::UInt:
5262 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
5263 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
5264 case BuiltinType::Int:
5265 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
5266 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
5267 case BuiltinType::ULong:
5268 case BuiltinType::ULongLong:
5269 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
5270 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
5271 case BuiltinType::Long:
5272 case BuiltinType::LongLong:
5273 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
5274 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
5275 case BuiltinType::Float:
5276 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
5277 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
5278 case BuiltinType::Double:
5279 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
5280 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
5281 case BuiltinType::UInt128:
5282 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
5283 : llvm::Intrinsic::ppc_altivec_vcmpgtuq_p;
5284 case BuiltinType::Int128:
5285 return (IT ==
VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
5286 : llvm::Intrinsic::ppc_altivec_vcmpgtsq_p;
5290Value *ScalarExprEmitter::EmitCompare(
const BinaryOperator *E,
5291 llvm::CmpInst::Predicate UICmpOpc,
5292 llvm::CmpInst::Predicate SICmpOpc,
5293 llvm::CmpInst::Predicate FCmpOpc,
5295 TestAndClearIgnoreResultAssign();
5299 if (
const MemberPointerType *MPT = LHSTy->
getAs<MemberPointerType>()) {
5305 CGF, LHS, RHS, MPT, E->
getOpcode() == BO_NE);
5307 BinOpInfo BOInfo = EmitBinOps(E);
5308 Value *LHS = BOInfo.LHS;
5309 Value *RHS = BOInfo.RHS;
5315 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
5317 llvm::Intrinsic::ID
ID = llvm::Intrinsic::not_intrinsic;
5320 Value *FirstVecArg = LHS,
5321 *SecondVecArg = RHS;
5323 QualType ElTy = LHSTy->
castAs<VectorType>()->getElementType();
5327 default: llvm_unreachable(
"is not a comparison operation");
5339 std::swap(FirstVecArg, SecondVecArg);
5346 if (ElementKind == BuiltinType::Float) {
5348 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
5349 std::swap(FirstVecArg, SecondVecArg);
5357 if (ElementKind == BuiltinType::Float) {
5359 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
5364 std::swap(FirstVecArg, SecondVecArg);
5369 Value *CR6Param = Builder.getInt32(CR6);
5371 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
5379 if (ResultTy->getBitWidth() > 1 &&
5381 Result = Builder.CreateTrunc(
Result, Builder.getInt1Ty());
5386 if (BOInfo.isFixedPointOp()) {
5387 Result = EmitFixedPointBinOp(BOInfo);
5388 }
else if (LHS->
getType()->isFPOrFPVectorTy()) {
5389 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
5391 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS,
"cmp");
5393 Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS,
"cmp");
5395 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS,
"cmp");
5398 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS,
"cmp");
5404 return Builder.CreateSExt(
Result, ConvertType(E->
getType()),
"sext");
5413 if (
auto *CTy = LHSTy->
getAs<ComplexType>()) {
5415 CETy = CTy->getElementType();
5417 LHS.first = Visit(E->
getLHS());
5418 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
5421 if (
auto *CTy = RHSTy->
getAs<ComplexType>()) {
5424 CTy->getElementType()) &&
5425 "The element types must always match.");
5428 RHS.first = Visit(E->
getRHS());
5429 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
5431 "The element types must always match.");
5434 Value *ResultR, *ResultI;
5438 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first,
"cmp.r");
5439 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second,
"cmp.i");
5443 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first,
"cmp.r");
5444 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second,
"cmp.i");
5448 Result = Builder.CreateAnd(ResultR, ResultI,
"and.ri");
5451 "Complex comparison other than == or != ?");
5452 Result = Builder.CreateOr(ResultR, ResultI,
"or.ri");
5464 if (
auto *ICE = dyn_cast<ImplicitCastExpr>(E->
getRHS())) {
5465 CastKind Kind = ICE->getCastKind();
5466 if (Kind == CK_IntegralCast || Kind == CK_LValueToRValue) {
5467 *SrcType = ICE->getSubExpr()->getType();
5480 bool Ignore = TestAndClearIgnoreResultAssign();
5514 RHS = Visit(E->
getRHS());
5530 RHS = Visit(E->
getRHS());
5570 return EmitLoadOfLValue(LHS, E->
getExprLoc());
5573Value *ScalarExprEmitter::VisitBinLAnd(
const BinaryOperator *E) {
5584 if (LHS->
getType()->isFPOrFPVectorTy()) {
5585 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
5587 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS,
Zero,
"cmp");
5588 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS,
Zero,
"cmp");
5590 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS,
Zero,
"cmp");
5591 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS,
Zero,
"cmp");
5593 Value *
And = Builder.CreateAnd(LHS, RHS);
5594 return Builder.CreateSExt(
And, ConvertType(E->
getType()),
"sext");
5598 llvm::Type *ResTy = ConvertType(E->
getType());
5617 if (InstrumentRegions &&
5621 llvm::BasicBlock *RHSSkip =
5624 Builder.CreateCondBr(RHSCond, RHSBlockCnt, RHSSkip);
5641 return Builder.CreateZExtOrBitCast(RHSCond, ResTy,
"land.ext");
5652 return llvm::Constant::getNullValue(ResTy);
5663 llvm::BasicBlock *LHSFalseBlock =
5666 CodeGenFunction::ConditionalEvaluation eval(CGF);
5681 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
5683 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
5685 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
5694 RHSBlock = Builder.GetInsertBlock();
5699 llvm::BasicBlock *ContIncoming = RHSBlock;
5700 if (InstrumentRegions &&
5704 llvm::BasicBlock *RHSBlockSkip =
5706 Builder.CreateCondBr(RHSCond, RHSBlockCnt, RHSBlockSkip);
5710 PN->addIncoming(RHSCond, RHSBlockCnt);
5715 ContIncoming = RHSBlockSkip;
5726 PN->addIncoming(RHSCond, ContIncoming);
5735 PN->setDebugLoc(Builder.getCurrentDebugLocation());
5739 return Builder.CreateZExtOrBitCast(PN, ResTy,
"land.ext");
5742Value *ScalarExprEmitter::VisitBinLOr(
const BinaryOperator *E) {
5753 if (LHS->
getType()->isFPOrFPVectorTy()) {
5754 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
5756 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS,
Zero,
"cmp");
5757 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS,
Zero,
"cmp");
5759 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS,
Zero,
"cmp");
5760 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS,
Zero,
"cmp");
5762 Value *
Or = Builder.CreateOr(LHS, RHS);
5763 return Builder.CreateSExt(
Or, ConvertType(E->
getType()),
"sext");
5767 llvm::Type *ResTy = ConvertType(E->
getType());
5786 if (InstrumentRegions &&
5790 llvm::BasicBlock *RHSSkip =
5793 Builder.CreateCondBr(RHSCond, RHSSkip, RHSBlockCnt);
5810 return Builder.CreateZExtOrBitCast(RHSCond, ResTy,
"lor.ext");
5821 return llvm::ConstantInt::get(ResTy, 1);
5831 llvm::BasicBlock *LHSTrueBlock =
5834 CodeGenFunction::ConditionalEvaluation eval(CGF);
5850 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
5852 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
5854 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
5866 RHSBlock = Builder.GetInsertBlock();
5871 llvm::BasicBlock *ContIncoming = RHSBlock;
5872 if (InstrumentRegions &&
5876 llvm::BasicBlock *RHSTrueBlock =
5878 Builder.CreateCondBr(RHSCond, RHSTrueBlock, RHSBlockCnt);
5882 PN->addIncoming(RHSCond, RHSBlockCnt);
5887 ContIncoming = RHSTrueBlock;
5894 PN->addIncoming(RHSCond, ContIncoming);
5901 return Builder.CreateZExtOrBitCast(PN, ResTy,
"lor.ext");
5904Value *ScalarExprEmitter::VisitBinComma(
const BinaryOperator *E) {
5907 return Visit(E->
getRHS());
5914Value *ScalarExprEmitter::
5915VisitAbstractConditionalOperator(
const AbstractConditionalOperator *E) {
5916 TestAndClearIgnoreResultAssign();
5919 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
5921 Expr *condExpr = E->
getCond();
5929 Expr *live = lhsExpr, *dead = rhsExpr;
5930 if (!CondExprBool) std::swap(live, dead);
5957 llvm::Value *LHS = Visit(lhsExpr);
5958 llvm::Value *RHS = Visit(rhsExpr);
5960 llvm::Type *condType = ConvertType(condExpr->
getType());
5963 unsigned numElem = vecTy->getNumElements();
5964 llvm::Type *elemType = vecTy->getElementType();
5966 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
5967 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
5968 llvm::Value *tmp = Builder.CreateSExt(
5969 TestMSB, llvm::FixedVectorType::get(elemType, numElem),
"sext");
5970 llvm::Value *tmp2 = Builder.CreateNot(tmp);
5973 llvm::Value *RHSTmp = RHS;
5974 llvm::Value *LHSTmp = LHS;
5975 bool wasCast =
false;
5977 if (rhsVTy->getElementType()->isFloatingPointTy()) {
5978 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
5979 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
5983 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
5984 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
5985 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4,
"cond");
5987 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
5997 llvm::Value *LHS = Visit(lhsExpr);
5998 llvm::Value *RHS = Visit(rhsExpr);
6000 llvm::Type *CondType = ConvertType(condExpr->
getType());
6003 if (VecTy->getElementType()->isIntegerTy(1))
6004 return Builder.CreateSelect(CondV, LHS, RHS,
"vector_select");
6007 llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
6009 CondV = Builder.CreateICmpSLT(CondV, ZeroVec,
"vector_cond");
6011 CondV = Builder.CreateICmpNE(CondV, ZeroVec,
"vector_cond");
6012 return Builder.CreateSelect(CondV, LHS, RHS,
"vector_select");
6024 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.
Int64Ty);
6028 llvm::Value *LHS = Visit(lhsExpr);
6029 llvm::Value *RHS = Visit(rhsExpr);
6032 assert(!RHS &&
"LHS and RHS types must match");
6035 return Builder.CreateSelect(CondV, LHS, RHS,
"cond");
6046 CodeGenFunction::ConditionalEvaluation eval(CGF);
6060 Value *LHS = Visit(lhsExpr);
6063 LHSBlock = Builder.GetInsertBlock();
6064 Builder.CreateBr(ContBlock);
6076 Value *RHS = Visit(rhsExpr);
6079 RHSBlock = Builder.GetInsertBlock();
6089 llvm::PHINode *PN = Builder.CreatePHI(LHS->
getType(), 2,
"cond");
6090 PN->addIncoming(LHS, LHSBlock);
6091 PN->addIncoming(RHS, RHSBlock);
6096Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
6100Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
6102 RValue ArgPtr = CGF.
EmitVAArg(VE, ArgValue);
6107Value *ScalarExprEmitter::VisitBlockExpr(
const BlockExpr *block) {
6113 Value *Src,
unsigned NumElementsDst) {
6114 static constexpr int Mask[] = {0, 1, 2, -1};
6115 return Builder.CreateShuffleVector(Src,
llvm::ArrayRef(Mask, NumElementsDst));
6135 const llvm::DataLayout &DL,
6136 Value *Src, llvm::Type *DstTy,
6137 StringRef Name =
"") {
6141 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
6142 return Builder.CreateBitCast(Src, DstTy, Name);
6145 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
6146 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
6149 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
6151 if (!DstTy->isIntegerTy())
6152 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
6154 return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
6158 if (!SrcTy->isIntegerTy())
6159 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
6161 return Builder.CreateIntToPtr(Src, DstTy, Name);
6164Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
6166 llvm::Type *DstTy = ConvertType(E->
getType());
6168 llvm::Type *SrcTy = Src->
getType();
6169 unsigned NumElementsSrc =
6173 unsigned NumElementsDst =
6184 if (NumElementsSrc == 3 && NumElementsDst != 3) {
6189 Src->setName(
"astype");
6196 if (NumElementsSrc != 3 && NumElementsDst == 3) {
6197 auto *Vec4Ty = llvm::FixedVectorType::get(
6203 Src->setName(
"astype");
6208 Src, DstTy,
"astype");
6211Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
6223 "Invalid scalar expression to emit");
6225 return ScalarExprEmitter(*
this, IgnoreResultAssign)
6226 .Visit(
const_cast<Expr *
>(E));
6235 "Invalid scalar expression to emit");
6236 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
6246 "Invalid complex -> scalar conversion");
6247 return ScalarExprEmitter(*
this)
6248 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
6255 if (!PromotionType.
isNull())
6256 return ScalarExprEmitter(*this).EmitPromoted(E, PromotionType);
6258 return ScalarExprEmitter(*this).Visit(
const_cast<Expr *
>(E));
6264 bool isInc,
bool isPre) {
6265 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
6275 llvm::Type *BaseTy =
6291 ScalarExprEmitter Scalar(*
this);
6294#define COMPOUND_OP(Op) \
6295 case BO_##Op##Assign: \
6296 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
6333 llvm_unreachable(
"Not valid compound assignment operators");
6336 llvm_unreachable(
"Unhandled compound assignment operator");
6357 llvm::Value *TotalOffset =
nullptr;
6359 auto *IntPtrTy = DL.getAddressType(BasePtr->
getType());
6362 auto *
Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
6363 auto *SAddIntrinsic =
6364 CGM.
getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
6365 auto *SMulIntrinsic =
6366 CGM.
getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
6369 llvm::Value *OffsetOverflows = Builder.getFalse();
6373 llvm::Value *RHS) -> llvm::Value * {
6374 assert((Opcode == BO_Add || Opcode == BO_Mul) &&
"Can't eval binop");
6377 if (
auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
6378 if (
auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
6380 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
6383 OffsetOverflows = Builder.getTrue();
6384 return llvm::ConstantInt::get(VMContext, N);
6389 auto *ResultAndOverflow = Builder.CreateCall(
6390 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
6391 OffsetOverflows = Builder.CreateOr(
6392 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
6393 return Builder.CreateExtractValue(ResultAndOverflow, 0);
6397 for (
auto GTI = llvm::gep_type_begin(ElemTy, IdxList),
6398 GTE = llvm::gep_type_end(ElemTy, IdxList);
6399 GTI != GTE; ++GTI) {
6400 llvm::Value *LocalOffset;
6401 auto *Index = GTI.getOperand();
6403 if (
auto *STy = GTI.getStructTypeOrNull()) {
6407 LocalOffset = llvm::ConstantInt::get(
6408 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
6413 llvm::ConstantInt::get(IntPtrTy, GTI.getSequentialElementStride(DL));
6414 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy,
true);
6415 LocalOffset = eval(BO_Mul, ElementSize, IndexS);
6420 if (!TotalOffset || TotalOffset ==
Zero)
6421 TotalOffset = LocalOffset;
6423 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
6426 return {TotalOffset, OffsetOverflows};
6431static llvm::GEPNoWrapFlags
6433 llvm::Type *SrcTy,
bool SignedIndices,
bool IsSubtraction) {
6434 llvm::GEPNoWrapFlags NW;
6435 bool SectionGEP = CGF.
getLangOpts().OpenMPIsTargetDevice &&
6436 SrcTy->isArrayTy() &&
6437 SrcTy->getArrayElementType()->isArrayTy() &&
6440 NW = llvm::GEPNoWrapFlags::inBounds();
6441 if (!SignedIndices && !IsSubtraction)
6442 NW |= llvm::GEPNoWrapFlags::noUnsignedWrap();
6448 ArrayRef<Value *> IdxList,
6449 bool SignedIndices,
bool IsSubtraction,
6450 SourceLocation Loc,
const Twine &Name) {
6451 llvm::Type *PtrTy =
Ptr->getType();
6453 llvm::GEPNoWrapFlags NWFlags =
6456 Value *GEPVal = Builder.CreateGEP(ElemTy, Ptr, IdxList, Name, NWFlags);
6459 if (!SanOpts.has(SanitizerKind::PointerOverflow))
6463 bool PerformNullCheck = !NullPointerIsDefined(
6464 Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
6467 bool PerformOverflowCheck =
6470 if (!(PerformNullCheck || PerformOverflowCheck))
6473 const auto &DL = CGM.getDataLayout();
6475 auto CheckOrdinal = SanitizerKind::SO_PointerOverflow;
6476 auto CheckHandler = SanitizerHandler::PointerOverflow;
6477 SanitizerDebugLocation SanScope(
this, {CheckOrdinal}, CheckHandler);
6478 llvm::Type *IntPtrTy = DL.getAddressType(PtrTy);
6481 Ptr, ElemTy, IdxList, getLLVMContext(), CGM, Builder);
6483 auto *
Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
6493 auto *IntPtr = Builder.CreatePtrToAddr(Ptr);
6494 auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.
TotalOffset);
6496 llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>,
6500 if (PerformNullCheck) {
6508 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
6509 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
6510 auto *
Valid = Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr);
6511 Checks.emplace_back(
Valid, CheckOrdinal);
6514 if (PerformOverflowCheck) {
6519 llvm::Value *ValidGEP;
6520 auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.
OffsetOverflows);
6521 if (SignedIndices) {
6527 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
6528 auto *PosOrZeroOffset =
6530 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
6532 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
6533 }
else if (!IsSubtraction) {
6538 ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
6544 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
6546 ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
6547 Checks.emplace_back(ValidGEP, CheckOrdinal);
6550 assert(!Checks.empty() &&
"Should have produced some checks.");
6552 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
6554 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
6555 EmitCheck(Checks, CheckHandler, StaticArgs, DynamicArgs);
6561 Address
Addr, ArrayRef<Value *> IdxList, llvm::Type *elementType,
6562 bool SignedIndices,
bool IsSubtraction, SourceLocation Loc, CharUnits Align,
6563 const Twine &Name) {
6564 if (!SanOpts.has(SanitizerKind::PointerOverflow)) {
6565 llvm::GEPNoWrapFlags NWFlags =
6567 SignedIndices, IsSubtraction);
6568 return Builder.CreateGEP(
Addr, IdxList, elementType, Align, Name, NWFlags);
6572 EmitCheckedInBoundsGEP(
Addr.getElementType(),
Addr.emitRawPointer(*
this),
6573 IdxList, SignedIndices, IsSubtraction, Loc, Name),
6574 elementType, Align);
Defines the clang::ASTContext interface.
static llvm::Value * EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF, const BinaryOperator *E, llvm::Value *LHS, llvm::Value *RHS, CompareKind Kind, const char *NameSuffix="")
static void EmitHLSLElementwiseCast(CodeGenFunction &CGF, LValue DestVal, LValue SrcVal, SourceLocation Loc)
static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty)
static llvm::Value * EmitIsNegativeTestHelper(Value *V, QualType VType, const char *Name, CGBuilderTy &Builder)
static Value * createCastsForTypeOfSameSize(CGBuilderTy &Builder, const llvm::DataLayout &DL, Value *Src, llvm::Type *DstTy, StringRef Name="")
static bool isLValueKnownNonNull(CodeGenFunction &CGF, const Expr *E)
static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT, BuiltinType::Kind ElemKind)
static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, llvm::Type *ElemTy, ArrayRef< Value * > IdxList, llvm::LLVMContext &VMContext, CodeGenModule &CGM, CGBuilderTy &Builder)
Compute the total offset in bytes that indexing BasePtr with ElemTy and IdxList applies,...
static bool isDeclRefKnownNonNull(CodeGenFunction &CGF, const ValueDecl *D)
static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(QualType SrcType, QualType DstType)
static llvm::GEPNoWrapFlags inBoundsGEPFlags(const CodeGenFunction &CGF, const llvm::Value *Ptr, llvm::Type *SrcTy, bool SignedIndices, bool IsSubtraction)
static std::pair< ScalarExprEmitter::ImplicitConversionCheckKind, std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > EmitBitfieldTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst, QualType DstType, CGBuilderTy &Builder)
static std::pair< ScalarExprEmitter::ImplicitConversionCheckKind, std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > EmitBitfieldSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst, QualType DstType, CGBuilderTy &Builder)
static std::pair< ScalarExprEmitter::ImplicitConversionCheckKind, std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst, QualType DstType, CGBuilderTy &Builder)
static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx, unsigned Off)
static std::pair< ScalarExprEmitter::ImplicitConversionCheckKind, std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst, QualType DstType, CGBuilderTy &Builder)
static Value * ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF, Value *Src, unsigned NumElementsDst)
static Value * EmitHLSLElementwiseCastToVector(CodeGenFunction &CGF, QualType DestTy, unsigned NumSrcElements, GetElementTy GetElement, SourceLocation Loc)
static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E, llvm::Value *InVal, bool IsInc, FPOptions FPFeatures)
static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf, const BinOpInfo &op, bool isSubtraction)
Emit pointer + index arithmetic.
static mlir::Value tryEmitFMulAdd(mlir::Location loc, const BinOpInfo &op, CIRGenBuilderTy &builder, bool isSub=false)
static mlir::Value buildFMulAdd(mlir::Location addLoc, cir::FMulOp mulOp, mlir::Value addend, CIRGenBuilderTy &builder, bool negMul, bool negAdd)
static std::optional< QualType > getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e)
If e is a widened promoted integer, get its base (unpromoted) type.
static uint32_t getBitWidth(const Expr *E)
static Decl::Kind getKind(const Decl *D)
Result
Implement __builtin_bit_cast and related operations.
Defines AST-level helper utilities for matrix types.
static QualType getPointeeType(const MemRegion *R)
This file contains the declaration of TrapReasonBuilder and related classes.
llvm::APInt getValue() const
bool isNullPointer() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType UnsignedCharTy
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
unsigned getTargetAddressSpace(LangAS AS) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
bool isUnaryOverflowPatternExcluded(const UnaryOperator *UO)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
LabelDecl * getLabel() const
uint64_t getValue() const
QualType getElementType() const
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
A builtin binary operation expression such as "x + y" or "x <= y".
static Opcode getOpForCompoundAssignment(Opcode Opc)
bool isCompoundAssignmentOp() const
SourceLocation getExprLoc() const
bool isShiftAssignOp() const
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, const Expr *LHS, const Expr *RHS)
Return true if a binary operator using the specified opcode and operands would match the 'p = (i8*)nu...
BinaryOperatorKind Opcode
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
QualType getType() const
Retrieves the type of the base class.
Expr * getExpr()
Get the initialization expression that will be used.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
path_iterator path_begin()
CastKind getCastKind() const
bool changesVolatileQualification() const
Return.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
static CharUnits One()
Construct a CharUnits quantity of one.
bool isOne() const
Test whether the quantity equals one.
unsigned getValue() const
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
virtual llvm::Constant * EmitNullMemberPointer(const MemberPointerType *MPT)
Create a null member pointer of the given type.
virtual llvm::Value * EmitMemberPointerIsNotNull(CodeGenFunction &CGF, llvm::Value *MemPtr, const MemberPointerType *MPT)
Determine if a member pointer is non-null. Returns an i1.
virtual llvm::Value * EmitMemberPointerComparison(CodeGenFunction &CGF, llvm::Value *L, llvm::Value *R, const MemberPointerType *MPT, bool Inequality)
Emit a comparison between two member pointers. Returns an i1.
virtual llvm::Value * EmitMemberPointerConversion(CodeGenFunction &CGF, const CastExpr *E, llvm::Value *Src)
Perform a derived-to-base, base-to-derived, or bitcast member pointer conversion.
void EmitPseudoVariable(CGBuilderTy &Builder, llvm::Instruction *Value, QualType Ty)
Emit a pseudo variable and debug info for an intermediate value if it does not correspond to a variab...
void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy, SourceLocation Loc)
Add heapallocsite metadata for MSAllocator calls.
void emitInitListOpaqueValues(CodeGenFunction &CGF, InitListExpr *E)
virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF, const Expr *LHS)
Checks if the provided LVal is lastprivate conditional and emits the code to update the value of the ...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
Produce the code for a CK_ARCConsumeObject.
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
CurrentSourceLocExprScope CurSourceLocExprScope
Source location information about the default argument or member initializer expression we're evaluat...
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
llvm::Value * EmitARCReclaimReturnedObject(const Expr *e, bool allowUnsafeClaim)
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
void SetDivFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
llvm::Value * EmitObjCSelectorExpr(const ObjCSelectorExpr *E)
Emit a selector.
SanitizerSet SanOpts
Sanitizers enabled for this function.
@ UseSkipPath
Skip (false)
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
llvm::Value * EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E)
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
const CastExpr * CurCast
If a cast expression is being visited, this holds the current cast's expression.
static bool hasScalarEvaluationKind(QualType T)
llvm::Type * ConvertType(QualType T)
llvm::Value * EmitObjCProtocolExpr(const ObjCProtocolExpr *E)
llvm::Value * EmitPointerAuthQualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType ValueType, Address StorageAddress, bool IsKnownNonNull)
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E)
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
llvm::Value * EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
RValue EmitVAArg(VAArgExpr *VE, Address &VAListAddr, AggValueSlot Slot=AggValueSlot::ignored())
Generate code to get an argument from the passed in pointer and update it accordingly.
llvm::Value * getAsNaturalPointerTo(Address Addr, QualType PointeeType)
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void maybeUpdateMCDCTestVectorBitmap(const Expr *E)
Increment the profiler's counter for the given expression by StepV.
void EmitCXXDeleteExpr(const CXXDeleteExpr *E)
llvm::Value * EmitObjCArrayLiteral(const ObjCArrayLiteral *E)
llvm::Value * EmitPromotedScalarExpr(const Expr *E, QualType PromotionType)
const LangOptions & getLangOpts() const
llvm::Value * EmitARCStoreStrong(LValue lvalue, llvm::Value *value, bool resultIgnored)
Store into a strong object.
bool isPointerKnownNonNull(const Expr *E)
Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue)
void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc)
Given an assignment *LHS = RHS, emit a test that checks if RHS is nonnull, if LHS is marked _Nonnull.
llvm::Value * EmitPointerAuthUnqualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType PointerType, Address StorageAddress, bool IsKnownNonNull)
std::pair< RValue, llvm::Value * > EmitAtomicCompareExchange(LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc, llvm::AtomicOrdering Success=llvm::AtomicOrdering::SequentiallyConsistent, llvm::AtomicOrdering Failure=llvm::AtomicOrdering::SequentiallyConsistent, bool IsWeak=false, AggValueSlot Slot=AggValueSlot::ignored())
Emit a compare-and-exchange op for atomic type.
void EmitVTablePtrCheckForCast(QualType T, Address Derived, bool MayBeNull, CFITypeCheckKind TCK, SourceLocation Loc)
Derived is the presumed address of an object of type T after a cast.
TypeCheckKind
Situations in which we might emit a check for the suitability of a pointer or glvalue.
@ TCK_DowncastPointer
Checking the operand of a static_cast to a derived pointer type.
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_Load
Checking the operand of a load. Must be suitably sized and aligned.
llvm::Value * EmitCXXNewExpr(const CXXNewExpr *E)
bool hasSkipCounter(const Stmt *S) const
void EmitBitfieldConversionCheck(llvm::Value *Src, QualType SrcType, llvm::Value *Dst, QualType DstType, const CGBitFieldInfo &Info, SourceLocation Loc)
Emit a check that an [implicit] conversion of a bitfield.
std::pair< LValue, llvm::Value * > EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored)
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, llvm::Value *&Result)
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
const TargetInfo & getTarget() const
LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E)
llvm::Value * EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty)
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
static bool isInstrumentedCondition(const Expr *C)
isInstrumentedCondition - Determine whether the given condition is an instrumentable condition (i....
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
llvm::Value * EmitObjCBoxedExpr(const ObjCBoxedExpr *E)
EmitObjCBoxedExpr - This routine generates code to call the appropriate expression boxing method.
void EmitBoundsCheck(const Expr *ArrayExpr, const Expr *ArrayExprBase, llvm::Value *Index, QualType IndexType, bool Accessed)
Emit a check that Base points into an array object, which we can access at index Index.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
void maybeResetMCDCCondBitmap(const Expr *E)
Zero-init the MCDC temp value.
RValue EmitCoyieldExpr(const CoyieldExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
CGDebugInfo * getDebugInfo()
llvm::Value * emitScalarConstant(const ConstantEmission &Constant, Expr *E)
llvm::Value * EmitARCRetainScalarExpr(const Expr *expr)
EmitARCRetainScalarExpr - Semantically equivalent to EmitARCRetainObject(e->getType(),...
llvm::Value * EmitBlockLiteral(const BlockExpr *)
Emit block literal.
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val)
Update the MCDC temp value with the condition's evaluated result.
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
ASTContext & getContext() const
llvm::Value * EmitWithOriginalRHSBitfieldAssignment(const BinaryOperator *E, llvm::Value **Previous, QualType *SrcType)
Retrieve the implicit cast expression of the rhs in a binary operator expression by passing pointers ...
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
static const Expr * stripCond(const Expr *C)
Ignore parentheses and logical-NOT to track conditions consistently.
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
EmitCompoundStmt - Emit a compound statement {..} node.
llvm::AtomicRMWInst * emitAtomicRMWInst(llvm::AtomicRMWInst::BinOp Op, Address Addr, llvm::Value *Val, llvm::AtomicOrdering Order=llvm::AtomicOrdering::SequentiallyConsistent, llvm::SyncScope::ID SSID=llvm::SyncScope::System, const AtomicExpr *AE=nullptr)
Emit an atomicrmw instruction, and applying relevant metadata when applicable.
llvm::Value * EmitPointerArithmetic(const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer, Expr *indexOperand, llvm::Value *index, bool isSubtraction)
Emit pointer + index arithmetic.
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.
uint64_t getCurrentProfileCount()
Get the profiler's current count.
llvm::Type * ConvertTypeForMem(QualType T)
RValue EmitAtomicExpr(AtomicExpr *E)
void markStmtMaybeUsed(const Stmt *S)
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
void FlattenAccessAndTypeLValue(LValue LVal, SmallVectorImpl< LValue > &AccessList)
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
RValue EmitCoawaitExpr(const CoawaitExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
llvm::Value * authPointerToPointerCast(llvm::Value *ResultPtr, QualType SourceType, QualType DestType)
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
llvm::Value * EmitCheckedInBoundsGEP(llvm::Type *ElemTy, 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...
llvm::Value * EmitBuiltinAvailable(const VersionTuple &Version)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
llvm::Value * EmitMatrixIndexExpr(const Expr *E)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false, const TrapReason *TR=nullptr)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
llvm::Value * LoadCXXThis()
LoadCXXThis - Load the value of 'this'.
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
llvm::Value * getArrayInitIndex()
Get the index of the current ArrayInitLoopExpr, if any.
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
llvm::Value * EmitObjCStringLiteral(const ObjCStringLiteral *E)
Emits an instance of NSConstantString representing the object.
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr)
Try to emit a reference to the given value without producing it as an l-value.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
llvm::Value * EmitARCExtendBlockObject(const Expr *expr)
void markStmtAsUsed(bool Skipped, const Stmt *S)
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
ComplexPairTy EmitPromotedValue(ComplexPairTy result, QualType PromotionType)
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
bool isMCDCDecisionExpr(const Expr *E) const
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...
LoadedLValueCapture * CurLoadedLValueCapture
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
static bool ShouldNullCheckClassCastValue(const CastExpr *Cast)
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
This class organizes the cross-function state that is used while generating LLVM code.
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
TrapReasonBuilder BuildTrapReason(unsigned DiagID, TrapReason &TR)
Helper function to construct a TrapReasonBuilder.
llvm::Constant * getNullPointer(llvm::PointerType *T, QualType QT)
Get target specific null pointer.
CodeGenTypes & getTypes()
const TargetInfo & getTarget() const
llvm::Constant * getMemberPointerConstant(const UnaryOperator *e)
const llvm::DataLayout & getDataLayout() const
CGCXXABI & getCXXABI() const
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
const CodeGenOptions & getCodeGenOpts() const
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
LValue - This represents an lvalue references.
bool isVolatileQualified() const
const Qualifiers & getQuals() const
Address getAddress() const
const CGBitFieldInfo & getBitFieldInfo() const
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
static RValue get(llvm::Value *V)
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
CompoundAssignOperator - For compound assignments (e.g.
QualType getComputationLHSType() const
QualType getComputationResultType() const
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
APValue getAPValueResult() const
bool hasAPValueResult() const
Represents a concrete matrix type with constant number of rows and columns.
unsigned mapRowMajorToColumnMajorFlattenedIndex(unsigned RowMajorIdx) const
Given a row-major flattened index RowMajorIdx, return the equivalent column-major flattened index.
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
const Expr * getDefaultExpr() const
ChildElementIter< false > begin()
size_t getDataElementCount() const
This represents one expression.
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
llvm::APFloat getValue() const
const Expr * getSubExpr() const
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
unsigned getNumInits() const
bool hadArrayRangeDesignator() const
const Expr * getInit(unsigned Init) const
bool isSignedOverflowDefined() const
std::string OverflowHandler
The name of the handler function to be called when -ftrapv is specified.
Represents a matrix type, as defined in the Matrix Types clang extensions.
VersionTuple getVersion() const
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
SourceLocation getExprLoc() const LLVM_READONLY
const ObjCMethodDecl * getMethodDecl() const
QualType getReturnType() const
Represents a pointer to an Objective C object.
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Expr * getIndexExpr(unsigned Idx)
const OffsetOfNode & getComponent(unsigned Idx) const
TypeSourceInfo * getTypeSourceInfo() const
unsigned getNumComponents() const
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
FieldDecl * getField() const
For a field offsetof node, returns the field.
@ Array
An index into an array.
@ Identifier
A field in a dependent type, known only by its name.
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Kind getKind() const
Determine what kind of offsetof node this is.
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
SourceLocation getExprLoc() const LLVM_READONLY
Expr * getSelectedExpr() const
const Expr * getSubExpr() const
Pointer-authentication qualifiers.
PointerType - C99 6.7.5.1 - Pointer Declarators.
A (possibly-)qualified type.
PointerAuthQualifier getPointerAuth() const
bool mayBeDynamicClass() const
Returns true if it is a class and it might be dynamic.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
QualType getCanonicalType() const
bool UseExcessPrecision(const ASTContext &Ctx)
bool mayBeNotDynamicClass() const
Returns true if it is not a class or if the class might not be dynamic.
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
@ OCL_None
There is no lifetime qualification on this type.
@ OCL_Weak
Reading or writing from this object requires a barrier call.
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
bool isSatisfied() const
Whether or not the requires clause is satisfied.
std::string ComputeName(ASTContext &Context) const
static constexpr SanitizerMask bitPosToMask(const unsigned Pos)
Create a mask with a bit enabled at position Pos.
llvm::APSInt getShuffleMaskIdx(unsigned N) const
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
unsigned getPackLength() const
Retrieve the length of the parameter pack.
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
SourceLocation getLocation() const
Encodes a location in the source.
CompoundStmt * getSubStmt()
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
void dump() const
Dumps the specified AST fragment and all subtrees to llvm::errs().
SourceLocation getBeginLoc() const LLVM_READONLY
Expr * getReplacement() const
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled.
const llvm::fltSemantics & getHalfFormat() const
const llvm::fltSemantics & getBFloat16Format() const
const llvm::fltSemantics & getLongDoubleFormat() const
const llvm::fltSemantics & getFloat128Format() const
const llvm::fltSemantics & getIbm128Format() const
QualType getType() const
Return the type wrapped by this type source info.
bool getBoolValue() const
const APValue & getAPValue() const
bool isStoredAsBoolean() const
bool isBooleanType() const
bool isSignableType(const ASTContext &Ctx) const
bool isMFloat8Type() const
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
CXXRecordDecl * castAsCXXRecordDecl() const
bool isArithmeticType() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isExtVectorType() const
bool isExtVectorBoolType() const
bool isOCLIntelSubgroupAVCType() const
bool isBuiltinType() const
Helper methods to distinguish type categories.
RecordDecl * castAsRecordDecl() const
bool isAnyComplexType() const
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
bool isMatrixType() const
bool isFunctionType() const
bool isVectorType() const
bool isRealFloatingType() const
Floating point categories.
bool isFloatingType() const
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
const T * getAs() const
Member-template getAs<specific type>'.
bool isNullPtrType() const
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
bool isArgumentType() const
UnaryExprOrTypeTrait getKind() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
SourceLocation getExprLoc() const
Expr * getSubExpr() const
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Represents a C array with a specified size that is not an integer-constant-expression.
Represents a GCC generic vector type.
Defines the clang::TargetInfo interface.
const clang::Expr * ExprTy
bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, const ASTContext &Ctx)
Check whether E is cheap enough and side-effect-free enough to evaluate unconditionally instead of co...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::ArgumentAdaptingMatcherFunc< internal::HasMatcher > has
Matches AST nodes that have child AST nodes that match the provided matcher.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
PRESERVE_NONE bool Ret(InterpState &S)
@ Address
A pointer to a ValueDecl.
bool LE(InterpState &S, CodePtr OpPC)
bool Load(InterpState &S, CodePtr OpPC)
bool GE(InterpState &S, CodePtr OpPC)
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
bool isMatrixRowMajor(const LangOptions &LangOpts, QualType T)
Returns true if matrices of T should be laid out in row-major order.
@ Result
The result type of a method or function.
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
CastKind
CastKind - The kind of operation required for a conversion.
U cast(CodeGen::Address addr)
Diagnostic wrappers for TextAPI types for error reporting.
cl::opt< bool > EnableSingleByteCoverage
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
llvm::Value * TotalOffset
llvm::Value * OffsetOverflows
Structure with information about how a bitfield should be accessed.
unsigned Size
The total size of the bit-field, in bits, not including padding.
const Expr * E
The expression whose l-value is recorded.
std::optional< LValue > LV
The recorded l-value, set if E was loaded by ScalarExprEmitter.
llvm::IntegerType * Int64Ty
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::Type * HalfTy
half, bfloat, float, double
llvm::IntegerType * SizeTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::IntegerType * PtrDiffTy
CharUnits getPointerAlign() const
static TBAAAccessInfo getMayAliasInfo()
APValue Val
Val - This is the value the expression can be folded to.
bool HasSideEffects
Whether the evaluated expression has side effects.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.