#include "CGCXXABI.h"
#include "CGCleanup.h"
#include "CGDebugInfo.h"
#include "CGObjCRuntime.h"
#include "CGOpenMPRuntime.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "ConstantEmitter.h"
#include "TargetInfo.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Expr.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/ADT/APFixedPoint.h"
#include "llvm/ADT/Optional.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/FixedPointBuilder.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicsPowerPC.h"
#include "llvm/IR/MatrixBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/TypeSize.h"
#include <cstdarg>
using namespace clang;
using namespace CodeGen;
using llvm::Value;
namespace {
bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
BinaryOperator::Opcode Opcode, bool Signed,
llvm::APInt &Result) {
bool Overflow = true;
const auto &LHSAP = LHS->getValue();
const auto &RHSAP = RHS->getValue();
if (Opcode == BO_Add) {
Result = Signed ? LHSAP.sadd_ov(RHSAP, Overflow)
: LHSAP.uadd_ov(RHSAP, Overflow);
} else if (Opcode == BO_Sub) {
Result = Signed ? LHSAP.ssub_ov(RHSAP, Overflow)
: LHSAP.usub_ov(RHSAP, Overflow);
} else if (Opcode == BO_Mul) {
Result = Signed ? LHSAP.smul_ov(RHSAP, Overflow)
: LHSAP.umul_ov(RHSAP, Overflow);
} else if (Opcode == BO_Div || Opcode == BO_Rem) {
if (Signed && !RHS->isZero())
Result = LHSAP.sdiv_ov(RHSAP, Overflow);
else
return false;
}
return Overflow;
}
struct BinOpInfo {
Value *LHS;
Value *RHS;
QualType Ty; BinaryOperator::Opcode Opcode; FPOptions FPFeatures;
const Expr *E;
bool mayHaveIntegerOverflow() const {
auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
if (!LHSCI || !RHSCI)
return true;
llvm::APInt Result;
return ::mayHaveIntegerOverflow(
LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
}
bool isDivremOp() const {
return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
Opcode == BO_RemAssign;
}
bool mayHaveIntegerDivisionByZero() const {
if (isDivremOp())
if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
return CI->isZero();
return true;
}
bool mayHaveFloatDivisionByZero() const {
if (isDivremOp())
if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
return CFP->isZero();
return true;
}
bool isFixedPointOp() const {
if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
QualType LHSType = BinOp->getLHS()->getType();
QualType RHSType = BinOp->getRHS()->getType();
return LHSType->isFixedPointType() || RHSType->isFixedPointType();
}
if (const auto *UnOp = dyn_cast<UnaryOperator>(E))
return UnOp->getSubExpr()->getType()->isFixedPointType();
return false;
}
};
static bool MustVisitNullValue(const Expr *E) {
return E->getType()->isNullPtrType();
}
static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
const Expr *E) {
const Expr *Base = E->IgnoreImpCasts();
if (E == Base)
return llvm::None;
QualType BaseTy = Base->getType();
if (!BaseTy->isPromotableIntegerType() ||
Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
return llvm::None;
return BaseTy;
}
static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
return getUnwidenedIntegerType(Ctx, E).has_value();
}
static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
"Expected a unary or binary operator");
if (!Op.mayHaveIntegerOverflow())
return true;
if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
return !UO->canOverflow();
const auto *BO = cast<BinaryOperator>(Op.E);
auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
if (!OptionalLHSTy)
return false;
auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
if (!OptionalRHSTy)
return false;
QualType LHSTy = *OptionalLHSTy;
QualType RHSTy = *OptionalRHSTy;
if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
!LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
return true;
unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
(2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
}
class ScalarExprEmitter
: public StmtVisitor<ScalarExprEmitter, Value*> {
CodeGenFunction &CGF;
CGBuilderTy &Builder;
bool IgnoreResultAssign;
llvm::LLVMContext &VMContext;
public:
ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
: CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
VMContext(cgf.getLLVMContext()) {
}
bool TestAndClearIgnoreResultAssign() {
bool I = IgnoreResultAssign;
IgnoreResultAssign = false;
return I;
}
llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
return CGF.EmitCheckedLValue(E, TCK);
}
void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
const BinOpInfo &Info);
Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
}
void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
const AlignValueAttr *AVAttr = nullptr;
if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
const ValueDecl *VD = DRE->getDecl();
if (VD->getType()->isReferenceType()) {
if (const auto *TTy =
dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
} else {
if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
return;
AVAttr = VD->getAttr<AlignValueAttr>();
}
}
if (!AVAttr)
if (const auto *TTy =
dyn_cast<TypedefType>(E->getType()))
AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
if (!AVAttr)
return;
Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
}
Value *EmitLoadOfLValue(const Expr *E) {
Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
E->getExprLoc());
EmitLValueAlignmentAssumption(E, V);
return V;
}
Value *EmitConversionToBool(Value *Src, QualType DstTy);
void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
Value *Src, QualType SrcType, QualType DstType,
llvm::Type *DstTy, SourceLocation Loc);
enum ImplicitConversionCheckKind : unsigned char {
ICCK_IntegerTruncation = 0, ICCK_UnsignedIntegerTruncation = 1,
ICCK_SignedIntegerTruncation = 2,
ICCK_IntegerSignChange = 3,
ICCK_SignedIntegerTruncationOrSignChange = 4,
};
void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
QualType DstType, SourceLocation Loc);
void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
QualType DstType, SourceLocation Loc);
struct ScalarConversionOpts {
bool TreatBooleanAsSigned;
bool EmitImplicitIntegerTruncationChecks;
bool EmitImplicitIntegerSignChangeChecks;
ScalarConversionOpts()
: TreatBooleanAsSigned(false),
EmitImplicitIntegerTruncationChecks(false),
EmitImplicitIntegerSignChangeChecks(false) {}
ScalarConversionOpts(clang::SanitizerSet SanOpts)
: TreatBooleanAsSigned(false),
EmitImplicitIntegerTruncationChecks(
SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
EmitImplicitIntegerSignChangeChecks(
SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
};
Value *EmitScalarCast(Value *Src, QualType SrcType, QualType DstType,
llvm::Type *SrcTy, llvm::Type *DstTy,
ScalarConversionOpts Opts);
Value *
EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
SourceLocation Loc,
ScalarConversionOpts Opts = ScalarConversionOpts());
Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
SourceLocation Loc);
Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
QualType SrcTy, QualType DstTy,
SourceLocation Loc);
Value *EmitNullValue(QualType Ty);
Value *EmitFloatToBoolConversion(Value *V) {
llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
return Builder.CreateFCmpUNE(V, Zero, "tobool");
}
Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
return Builder.CreateICmpNE(V, Zero, "tobool");
}
Value *EmitIntToBoolConversion(Value *V) {
if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
Value *Result = ZI->getOperand(0);
if (ZI->use_empty())
ZI->eraseFromParent();
return Result;
}
}
return Builder.CreateIsNotNull(V, "tobool");
}
Value *Visit(Expr *E) {
ApplyDebugLocation DL(CGF, E);
return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
}
Value *VisitStmt(Stmt *S) {
S->dump(llvm::errs(), CGF.getContext());
llvm_unreachable("Stmt can't have complex result type!");
}
Value *VisitExpr(Expr *S);
Value *VisitConstantExpr(ConstantExpr *E) {
if (E->getType()->isVoidType())
return nullptr;
if (Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
if (E->isGLValue())
return CGF.Builder.CreateLoad(Address(
Result, CGF.ConvertTypeForMem(E->getType()),
CGF.getContext().getTypeAlignInChars(E->getType())));
return Result;
}
return Visit(E->getSubExpr());
}
Value *VisitParenExpr(ParenExpr *PE) {
return Visit(PE->getSubExpr());
}
Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
return Visit(E->getReplacement());
}
Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
return Visit(GE->getResultExpr());
}
Value *VisitCoawaitExpr(CoawaitExpr *S) {
return CGF.EmitCoawaitExpr(*S).getScalarVal();
}
Value *VisitCoyieldExpr(CoyieldExpr *S) {
return CGF.EmitCoyieldExpr(*S).getScalarVal();
}
Value *VisitUnaryCoawait(const UnaryOperator *E) {
return Visit(E->getSubExpr());
}
Value *VisitIntegerLiteral(const IntegerLiteral *E) {
return Builder.getInt(E->getValue());
}
Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
return Builder.getInt(E->getValue());
}
Value *VisitFloatingLiteral(const FloatingLiteral *E) {
return llvm::ConstantFP::get(VMContext, E->getValue());
}
Value *VisitCharacterLiteral(const CharacterLiteral *E) {
return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
}
Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
}
Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
}
Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
return EmitNullValue(E->getType());
}
Value *VisitGNUNullExpr(const GNUNullExpr *E) {
return EmitNullValue(E->getType());
}
Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
return Builder.CreateBitCast(V, ConvertType(E->getType()));
}
Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
}
Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
return CGF.EmitPseudoObjectRValue(E).getScalarVal();
}
Value *VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E);
Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
if (E->isGLValue())
return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
E->getExprLoc());
return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
}
Value *VisitDeclRefExpr(DeclRefExpr *E) {
if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
return CGF.emitScalarConstant(Constant, E);
return EmitLoadOfLValue(E);
}
Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
return CGF.EmitObjCSelectorExpr(E);
}
Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
return CGF.EmitObjCProtocolExpr(E);
}
Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
return EmitLoadOfLValue(E);
}
Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
if (E->getMethodDecl() &&
E->getMethodDecl()->getReturnType()->isReferenceType())
return EmitLoadOfLValue(E);
return CGF.EmitObjCMessageExpr(E).getScalarVal();
}
Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
LValue LV = CGF.EmitObjCIsaExpr(E);
Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
return V;
}
Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
VersionTuple Version = E->getVersion();
if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
return CGF.EmitBuiltinAvailable(Version);
}
Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E);
Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
Value *VisitMemberExpr(MemberExpr *E);
Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
return EmitLoadOfLValue(E);
}
Value *VisitInitListExpr(InitListExpr *E);
Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
assert(CGF.getArrayInitIndex() &&
"ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
return CGF.getArrayInitIndex();
}
Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
return EmitNullValue(E->getType());
}
Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
CGF.CGM.EmitExplicitCastExprType(E, &CGF);
return VisitCastExpr(E);
}
Value *VisitCastExpr(CastExpr *E);
Value *VisitCallExpr(const CallExpr *E) {
if (E->getCallReturnType(CGF.getContext())->isReferenceType())
return EmitLoadOfLValue(E);
Value *V = CGF.EmitCallExpr(E).getScalarVal();
EmitLValueAlignmentAssumption(E, V);
return V;
}
Value *VisitStmtExpr(const StmtExpr *E);
Value *VisitUnaryPostDec(const UnaryOperator *E) {
LValue LV = EmitLValue(E->getSubExpr());
return EmitScalarPrePostIncDec(E, LV, false, false);
}
Value *VisitUnaryPostInc(const UnaryOperator *E) {
LValue LV = EmitLValue(E->getSubExpr());
return EmitScalarPrePostIncDec(E, LV, true, false);
}
Value *VisitUnaryPreDec(const UnaryOperator *E) {
LValue LV = EmitLValue(E->getSubExpr());
return EmitScalarPrePostIncDec(E, LV, false, true);
}
Value *VisitUnaryPreInc(const UnaryOperator *E) {
LValue LV = EmitLValue(E->getSubExpr());
return EmitScalarPrePostIncDec(E, LV, true, true);
}
llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
llvm::Value *InVal,
bool IsInc);
llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
bool isInc, bool isPre);
Value *VisitUnaryAddrOf(const UnaryOperator *E) {
if (isa<MemberPointerType>(E->getType())) return CGF.CGM.getMemberPointerConstant(E);
return EmitLValue(E->getSubExpr()).getPointer(CGF);
}
Value *VisitUnaryDeref(const UnaryOperator *E) {
if (E->getType()->isVoidType())
return Visit(E->getSubExpr()); return EmitLoadOfLValue(E);
}
Value *VisitUnaryPlus(const UnaryOperator *E) {
TestAndClearIgnoreResultAssign();
return Visit(E->getSubExpr());
}
Value *VisitUnaryMinus (const UnaryOperator *E);
Value *VisitUnaryNot (const UnaryOperator *E);
Value *VisitUnaryLNot (const UnaryOperator *E);
Value *VisitUnaryReal (const UnaryOperator *E);
Value *VisitUnaryImag (const UnaryOperator *E);
Value *VisitUnaryExtension(const UnaryOperator *E) {
return Visit(E->getSubExpr());
}
Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
return EmitLoadOfLValue(E);
}
Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
auto &Ctx = CGF.getContext();
APValue Evaluated =
SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
return ConstantEmitter(CGF).emitAbstract(SLE->getLocation(), Evaluated,
SLE->getType());
}
Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
return Visit(DAE->getExpr());
}
Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
return Visit(DIE->getExpr());
}
Value *VisitCXXThisExpr(CXXThisExpr *TE) {
return CGF.LoadCXXThis();
}
Value *VisitExprWithCleanups(ExprWithCleanups *E);
Value *VisitCXXNewExpr(const CXXNewExpr *E) {
return CGF.EmitCXXNewExpr(E);
}
Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
CGF.EmitCXXDeleteExpr(E);
return nullptr;
}
Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
}
Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
return Builder.getInt1(E->isSatisfied());
}
Value *VisitRequiresExpr(const RequiresExpr *E) {
return Builder.getInt1(E->isSatisfied());
}
Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
}
Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
}
Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
CGF.EmitScalarExpr(E->getBase());
return nullptr;
}
Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
return EmitNullValue(E->getType());
}
Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
CGF.EmitCXXThrowExpr(E);
return nullptr;
}
Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
return Builder.getInt1(E->getValue());
}
Value *EmitMul(const BinOpInfo &Ops) {
if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
case LangOptions::SOB_Defined:
return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
case LangOptions::SOB_Undefined:
if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
LLVM_FALLTHROUGH;
case LangOptions::SOB_Trapping:
if (CanElideOverflowCheck(CGF.getContext(), Ops))
return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
return EmitOverflowCheckedBinOp(Ops);
}
}
if (Ops.Ty->isConstantMatrixType()) {
llvm::MatrixBuilder MB(Builder);
auto *BO = cast<BinaryOperator>(Ops.E);
auto *LHSMatTy = dyn_cast<ConstantMatrixType>(
BO->getLHS()->getType().getCanonicalType());
auto *RHSMatTy = dyn_cast<ConstantMatrixType>(
BO->getRHS()->getType().getCanonicalType());
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
if (LHSMatTy && RHSMatTy)
return MB.CreateMatrixMultiply(Ops.LHS, Ops.RHS, LHSMatTy->getNumRows(),
LHSMatTy->getNumColumns(),
RHSMatTy->getNumColumns());
return MB.CreateScalarMultiply(Ops.LHS, Ops.RHS);
}
if (Ops.Ty->isUnsignedIntegerType() &&
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
!CanElideOverflowCheck(CGF.getContext(), Ops))
return EmitOverflowCheckedBinOp(Ops);
if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
}
if (Ops.isFixedPointOp())
return EmitFixedPointBinOp(Ops);
return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
}
Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
llvm::Value *Zero,bool isDiv);
static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name);
Value *EmitDiv(const BinOpInfo &Ops);
Value *EmitRem(const BinOpInfo &Ops);
Value *EmitAdd(const BinOpInfo &Ops);
Value *EmitSub(const BinOpInfo &Ops);
Value *EmitShl(const BinOpInfo &Ops);
Value *EmitShr(const BinOpInfo &Ops);
Value *EmitAnd(const BinOpInfo &Ops) {
return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
}
Value *EmitXor(const BinOpInfo &Ops) {
return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
}
Value *EmitOr (const BinOpInfo &Ops) {
return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
}
Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
BinOpInfo EmitBinOps(const BinaryOperator *E);
LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Value *&Result);
Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
#define HANDLEBINOP(OP) \
Value *VisitBin ## OP(const BinaryOperator *E) { \
return Emit ## OP(EmitBinOps(E)); \
} \
Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
}
HANDLEBINOP(Mul)
HANDLEBINOP(Div)
HANDLEBINOP(Rem)
HANDLEBINOP(Add)
HANDLEBINOP(Sub)
HANDLEBINOP(Shl)
HANDLEBINOP(Shr)
HANDLEBINOP(And)
HANDLEBINOP(Xor)
HANDLEBINOP(Or)
#undef HANDLEBINOP
Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
llvm::CmpInst::Predicate SICmpOpc,
llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
#define VISITCOMP(CODE, UI, SI, FP, SIG) \
Value *VisitBin##CODE(const BinaryOperator *E) { \
return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
llvm::FCmpInst::FP, SIG); }
VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
#undef VISITCOMP
Value *VisitBinAssign (const BinaryOperator *E);
Value *VisitBinLAnd (const BinaryOperator *E);
Value *VisitBinLOr (const BinaryOperator *E);
Value *VisitBinComma (const BinaryOperator *E);
Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
return Visit(E->getSemanticForm());
}
Value *VisitBlockExpr(const BlockExpr *BE);
Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Value *VisitChooseExpr(ChooseExpr *CE);
Value *VisitVAArgExpr(VAArgExpr *VE);
Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
return CGF.EmitObjCStringLiteral(E);
}
Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
return CGF.EmitObjCBoxedExpr(E);
}
Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
return CGF.EmitObjCArrayLiteral(E);
}
Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
return CGF.EmitObjCDictionaryLiteral(E);
}
Value *VisitAsTypeExpr(AsTypeExpr *CE);
Value *VisitAtomicExpr(AtomicExpr *AE);
};
}
Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
if (SrcType->isRealFloatingType())
return EmitFloatToBoolConversion(Src);
if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
"Unknown scalar type to convert");
if (isa<llvm::IntegerType>(Src->getType()))
return EmitIntToBoolConversion(Src);
assert(isa<llvm::PointerType>(Src->getType()));
return EmitPointerToBoolConversion(Src, SrcType);
}
void ScalarExprEmitter::EmitFloatConversionCheck(
Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
assert(SrcType->isFloatingType() && "not a conversion from floating point");
if (!isa<llvm::IntegerType>(DstTy))
return;
CodeGenFunction::SanitizerScope SanScope(&CGF);
using llvm::APFloat;
using llvm::APSInt;
llvm::Value *Check = nullptr;
const llvm::fltSemantics &SrcSema =
CGF.getContext().getFloatTypeSemantics(OrigSrcType);
unsigned Width = CGF.getContext().getIntWidth(DstType);
bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
APSInt Min = APSInt::getMinValue(Width, Unsigned);
APFloat MinSrc(SrcSema, APFloat::uninitialized);
if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
APFloat::opOverflow)
MinSrc = APFloat::getInf(SrcSema, true);
else
MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
APSInt Max = APSInt::getMaxValue(Width, Unsigned);
APFloat MaxSrc(SrcSema, APFloat::uninitialized);
if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
APFloat::opOverflow)
MaxSrc = APFloat::getInf(SrcSema, false);
else
MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
if (OrigSrcType->isHalfType()) {
const llvm::fltSemantics &Sema =
CGF.getContext().getFloatTypeSemantics(SrcType);
bool IsInexact;
MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
}
llvm::Value *GE =
Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
llvm::Value *LE =
Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
Check = Builder.CreateAnd(GE, LE);
llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
CGF.EmitCheckTypeDescriptor(OrigSrcType),
CGF.EmitCheckTypeDescriptor(DstType)};
CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
}
static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
std::pair<llvm::Value *, SanitizerMask>>
EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
QualType DstType, CGBuilderTy &Builder) {
llvm::Type *SrcTy = Src->getType();
llvm::Type *DstTy = Dst->getType();
(void)DstTy;
assert(Src != Dst);
assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
"non-integer llvm type");
bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
ScalarExprEmitter::ImplicitConversionCheckKind Kind;
SanitizerMask Mask;
if (!SrcSigned && !DstSigned) {
Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
} else {
Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
}
llvm::Value *Check = nullptr;
Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
return std::make_pair(Kind, std::make_pair(Check, Mask));
}
static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
QualType SrcType, QualType DstType) {
return SrcType->isIntegerType() && DstType->isIntegerType();
}
void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
Value *Dst, QualType DstType,
SourceLocation Loc) {
if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
return;
if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
DstType))
return;
unsigned SrcBits = Src->getType()->getScalarSizeInBits();
unsigned DstBits = Dst->getType()->getScalarSizeInBits();
if (SrcBits <= DstBits)
return;
assert(!DstType->isBooleanType() && "we should not get here with booleans.");
bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
(!SrcSigned && DstSigned))
return;
CodeGenFunction::SanitizerScope SanScope(&CGF);
std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
std::pair<llvm::Value *, SanitizerMask>>
Check =
EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
if (!CGF.SanOpts.has(Check.second.second))
return;
llvm::Constant *StaticArgs[] = {
CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
CGF.EmitCheckTypeDescriptor(DstType),
llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
{Src, Dst});
}
static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
std::pair<llvm::Value *, SanitizerMask>>
EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
QualType DstType, CGBuilderTy &Builder) {
llvm::Type *SrcTy = Src->getType();
llvm::Type *DstTy = Dst->getType();
assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
"non-integer llvm type");
bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
(void)SrcSigned; (void)DstSigned; unsigned SrcBits = SrcTy->getScalarSizeInBits();
unsigned DstBits = DstTy->getScalarSizeInBits();
(void)SrcBits; (void)DstBits;
assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
"either the widths should be different, or the signednesses.");
auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
const char *Name) -> Value * {
bool VSigned = VType->isSignedIntegerOrEnumerationType();
llvm::Type *VTy = V->getType();
if (!VSigned) {
return llvm::ConstantInt::getFalse(VTy->getContext());
}
llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
llvm::Twine(Name) + "." + V->getName() +
".negativitycheck");
};
llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
llvm::Value *Check = nullptr;
Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
return std::make_pair(
ScalarExprEmitter::ICCK_IntegerSignChange,
std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
}
void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
Value *Dst, QualType DstType,
SourceLocation Loc) {
if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
return;
llvm::Type *SrcTy = Src->getType();
llvm::Type *DstTy = Dst->getType();
if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
DstType))
return;
bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
unsigned SrcBits = SrcTy->getScalarSizeInBits();
unsigned DstBits = DstTy->getScalarSizeInBits();
if (SrcSigned == DstSigned && SrcBits == DstBits)
return;
if (!SrcSigned && !DstSigned)
return;
if ((DstBits > SrcBits) && DstSigned)
return;
if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
(SrcBits > DstBits) && SrcSigned) {
return;
}
CodeGenFunction::SanitizerScope SanScope(&CGF);
std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
std::pair<llvm::Value *, SanitizerMask>>
Check;
ImplicitConversionCheckKind CheckKind;
llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
CheckKind = Check.first;
Checks.emplace_back(Check.second);
if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
(SrcBits > DstBits) && !SrcSigned && DstSigned) {
Check =
EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
Checks.emplace_back(Check.second);
}
llvm::Constant *StaticArgs[] = {
CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
CGF.EmitCheckTypeDescriptor(DstType),
llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
{Src, Dst});
}
Value *ScalarExprEmitter::EmitScalarCast(Value *Src, QualType SrcType,
QualType DstType, llvm::Type *SrcTy,
llvm::Type *DstTy,
ScalarConversionOpts Opts) {
llvm::Type *SrcElementTy;
llvm::Type *DstElementTy;
QualType SrcElementType;
QualType DstElementType;
if (SrcType->isMatrixType() && DstType->isMatrixType()) {
SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
SrcElementType = SrcType->castAs<MatrixType>()->getElementType();
DstElementType = DstType->castAs<MatrixType>()->getElementType();
} else {
assert(!SrcType->isMatrixType() && !DstType->isMatrixType() &&
"cannot cast between matrix and non-matrix types");
SrcElementTy = SrcTy;
DstElementTy = DstTy;
SrcElementType = SrcType;
DstElementType = DstType;
}
if (isa<llvm::IntegerType>(SrcElementTy)) {
bool InputSigned = SrcElementType->isSignedIntegerOrEnumerationType();
if (SrcElementType->isBooleanType() && Opts.TreatBooleanAsSigned) {
InputSigned = true;
}
if (isa<llvm::IntegerType>(DstElementTy))
return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
if (InputSigned)
return Builder.CreateSIToFP(Src, DstTy, "conv");
return Builder.CreateUIToFP(Src, DstTy, "conv");
}
if (isa<llvm::IntegerType>(DstElementTy)) {
assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion");
bool IsSigned = DstElementType->isSignedIntegerOrEnumerationType();
if (!CGF.CGM.getCodeGenOpts().StrictFloatCastOverflow) {
llvm::Intrinsic::ID IID =
IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat;
return Builder.CreateCall(CGF.CGM.getIntrinsic(IID, {DstTy, SrcTy}), Src);
}
if (IsSigned)
return Builder.CreateFPToSI(Src, DstTy, "conv");
return Builder.CreateFPToUI(Src, DstTy, "conv");
}
if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
return Builder.CreateFPTrunc(Src, DstTy, "conv");
return Builder.CreateFPExt(Src, DstTy, "conv");
}
Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
QualType DstType,
SourceLocation Loc,
ScalarConversionOpts Opts) {
if (SrcType->isFixedPointType()) {
if (DstType->isBooleanType())
return Builder.CreateIsNotNull(Src, "tobool");
if (DstType->isFixedPointType() || DstType->isIntegerType() ||
DstType->isRealFloatingType())
return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
llvm_unreachable(
"Unhandled scalar conversion from a fixed point type to another type.");
} else if (DstType->isFixedPointType()) {
if (SrcType->isIntegerType() || SrcType->isRealFloatingType())
return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
llvm_unreachable(
"Unhandled scalar conversion to a fixed point type from another type.");
}
QualType NoncanonicalSrcType = SrcType;
QualType NoncanonicalDstType = DstType;
SrcType = CGF.getContext().getCanonicalType(SrcType);
DstType = CGF.getContext().getCanonicalType(DstType);
if (SrcType == DstType) return Src;
if (DstType->isVoidType()) return nullptr;
llvm::Value *OrigSrc = Src;
QualType OrigSrcType = SrcType;
llvm::Type *SrcTy = Src->getType();
if (DstType->isBooleanType())
return EmitConversionToBool(Src, SrcType);
llvm::Type *DstTy = ConvertType(DstType);
if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
if (DstTy->isFloatingPointTy()) {
if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
return Builder.CreateCall(
CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
Src);
} else {
if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Src = Builder.CreateCall(
CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
CGF.CGM.FloatTy),
Src);
} else {
Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
}
SrcType = CGF.getContext().FloatTy;
SrcTy = CGF.FloatTy;
}
}
if (SrcTy == DstTy) {
if (Opts.EmitImplicitIntegerSignChangeChecks)
EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
NoncanonicalDstType, Loc);
return Src;
}
if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
if (isa<llvm::PointerType>(SrcTy))
return Builder.CreateBitCast(Src, DstTy, "conv");
assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
llvm::Value* IntResult =
Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
}
if (isa<llvm::PointerType>(SrcTy)) {
assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
return Builder.CreatePtrToInt(Src, DstTy, "conv");
}
if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
SrcType.getTypePtr() &&
"Splatted expr doesn't match with vector element type?");
unsigned NumElements = cast<llvm::FixedVectorType>(DstTy)->getNumElements();
return Builder.CreateVectorSplat(NumElements, Src, "splat");
}
if (SrcType->isMatrixType() && DstType->isMatrixType())
return EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
llvm::TypeSize SrcSize = SrcTy->getPrimitiveSizeInBits();
llvm::TypeSize DstSize = DstTy->getPrimitiveSizeInBits();
if (SrcSize == DstSize)
return Builder.CreateBitCast(Src, DstTy, "conv");
llvm::Type *SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
llvm::Type *DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
(void)DstElementTy;
assert(((SrcElementTy->isIntegerTy() &&
DstElementTy->isIntegerTy()) ||
(SrcElementTy->isFloatingPointTy() &&
DstElementTy->isFloatingPointTy())) &&
"unexpected conversion between a floating-point vector and an "
"integer vector");
if (SrcElementTy->isIntegerTy())
return Builder.CreateIntCast(Src, DstTy, false, "conv");
if (SrcSize > DstSize)
return Builder.CreateFPTrunc(Src, DstTy, "conv");
return Builder.CreateFPExt(Src, DstTy, "conv");
}
Value *Res = nullptr;
llvm::Type *ResTy = DstTy;
if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
OrigSrcType->isFloatingType())
EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
Loc);
if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
if (SrcTy->isFloatingPointTy()) {
if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
return Builder.CreateCall(
CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
return Builder.CreateFPTrunc(Src, DstTy);
}
DstTy = CGF.FloatTy;
}
Res = EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
if (DstTy != ResTy) {
if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
Res = Builder.CreateCall(
CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
Res);
} else {
Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
}
}
if (Opts.EmitImplicitIntegerTruncationChecks)
EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
NoncanonicalDstType, Loc);
if (Opts.EmitImplicitIntegerSignChangeChecks)
EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
NoncanonicalDstType, Loc);
return Res;
}
Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
QualType DstTy,
SourceLocation Loc) {
llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
llvm::Value *Result;
if (SrcTy->isRealFloatingType())
Result = FPBuilder.CreateFloatingToFixed(Src,
CGF.getContext().getFixedPointSemantics(DstTy));
else if (DstTy->isRealFloatingType())
Result = FPBuilder.CreateFixedToFloating(Src,
CGF.getContext().getFixedPointSemantics(SrcTy),
ConvertType(DstTy));
else {
auto SrcFPSema = CGF.getContext().getFixedPointSemantics(SrcTy);
auto DstFPSema = CGF.getContext().getFixedPointSemantics(DstTy);
if (DstTy->isIntegerType())
Result = FPBuilder.CreateFixedToInteger(Src, SrcFPSema,
DstFPSema.getWidth(),
DstFPSema.isSigned());
else if (SrcTy->isIntegerType())
Result = FPBuilder.CreateIntegerToFixed(Src, SrcFPSema.isSigned(),
DstFPSema);
else
Result = FPBuilder.CreateFixedToFixed(Src, SrcFPSema, DstFPSema);
}
return Result;
}
Value *ScalarExprEmitter::EmitComplexToScalarConversion(
CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
SourceLocation Loc) {
SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
if (DstTy->isBooleanType()) {
Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
return Builder.CreateOr(Src.first, Src.second, "tobool");
}
return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
}
Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
}
void ScalarExprEmitter::EmitBinOpCheck(
ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
assert(CGF.IsSanitizerScope);
SanitizerHandler Check;
SmallVector<llvm::Constant *, 4> StaticData;
SmallVector<llvm::Value *, 2> DynamicData;
BinaryOperatorKind Opcode = Info.Opcode;
if (BinaryOperator::isCompoundAssignmentOp(Opcode))
Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
if (UO && UO->getOpcode() == UO_Minus) {
Check = SanitizerHandler::NegateOverflow;
StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
DynamicData.push_back(Info.RHS);
} else {
if (BinaryOperator::isShiftOp(Opcode)) {
Check = SanitizerHandler::ShiftOutOfBounds;
const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
StaticData.push_back(
CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
StaticData.push_back(
CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
} else if (Opcode == BO_Div || Opcode == BO_Rem) {
Check = SanitizerHandler::DivremOverflow;
StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
} else {
switch (Opcode) {
case BO_Add: Check = SanitizerHandler::AddOverflow; break;
case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
default: llvm_unreachable("unexpected opcode for bin op check");
}
StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
}
DynamicData.push_back(Info.LHS);
DynamicData.push_back(Info.RHS);
}
CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
}
Value *ScalarExprEmitter::VisitExpr(Expr *E) {
CGF.ErrorUnsupported(E, "scalar expression");
if (E->getType()->isVoidType())
return nullptr;
return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
}
Value *
ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) {
ASTContext &Context = CGF.getContext();
llvm::Optional<LangAS> GlobalAS =
Context.getTargetInfo().getConstantAddressSpace();
llvm::Constant *GlobalConstStr = Builder.CreateGlobalStringPtr(
E->ComputeName(Context), "__usn_str",
static_cast<unsigned>(GlobalAS.value_or(LangAS::Default)));
unsigned ExprAS = Context.getTargetAddressSpace(E->getType());
if (GlobalConstStr->getType()->getPointerAddressSpace() == ExprAS)
return GlobalConstStr;
llvm::PointerType *PtrTy = cast<llvm::PointerType>(GlobalConstStr->getType());
llvm::PointerType *NewPtrTy =
llvm::PointerType::getWithSamePointeeType(PtrTy, ExprAS);
return Builder.CreateAddrSpaceCast(GlobalConstStr, NewPtrTy, "usn_addr_cast");
}
Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
if (E->getNumSubExprs() == 2) {
Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
Value *Mask;
auto *LTy = cast<llvm::FixedVectorType>(LHS->getType());
unsigned LHSElts = LTy->getNumElements();
Mask = RHS;
auto *MTy = cast<llvm::FixedVectorType>(Mask->getType());
Value *MaskBits =
llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
auto *RTy = llvm::FixedVectorType::get(LTy->getElementType(),
MTy->getNumElements());
Value* NewV = llvm::UndefValue::get(RTy);
for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
}
return NewV;
}
Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
SmallVector<int, 32> Indices;
for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
if (Idx.isSigned() && Idx.isAllOnes())
Indices.push_back(-1);
else
Indices.push_back(Idx.getZExtValue());
}
return Builder.CreateShuffleVector(V1, V2, Indices, "shuffle");
}
Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
QualType SrcType = E->getSrcExpr()->getType(),
DstType = E->getType();
Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
SrcType = CGF.getContext().getCanonicalType(SrcType);
DstType = CGF.getContext().getCanonicalType(DstType);
if (SrcType == DstType) return Src;
assert(SrcType->isVectorType() &&
"ConvertVector source type must be a vector");
assert(DstType->isVectorType() &&
"ConvertVector destination type must be a vector");
llvm::Type *SrcTy = Src->getType();
llvm::Type *DstTy = ConvertType(DstType);
if (SrcTy == DstTy)
return Src;
QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
DstEltType = DstType->castAs<VectorType>()->getElementType();
assert(SrcTy->isVectorTy() &&
"ConvertVector source IR type must be a vector");
assert(DstTy->isVectorTy() &&
"ConvertVector destination IR type must be a vector");
llvm::Type *SrcEltTy = cast<llvm::VectorType>(SrcTy)->getElementType(),
*DstEltTy = cast<llvm::VectorType>(DstTy)->getElementType();
if (DstEltType->isBooleanType()) {
assert((SrcEltTy->isFloatingPointTy() ||
isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
if (SrcEltTy->isFloatingPointTy()) {
return Builder.CreateFCmpUNE(Src, Zero, "tobool");
} else {
return Builder.CreateICmpNE(Src, Zero, "tobool");
}
}
Value *Res = nullptr;
if (isa<llvm::IntegerType>(SrcEltTy)) {
bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
if (isa<llvm::IntegerType>(DstEltTy))
Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
else if (InputSigned)
Res = Builder.CreateSIToFP(Src, DstTy, "conv");
else
Res = Builder.CreateUIToFP(Src, DstTy, "conv");
} else if (isa<llvm::IntegerType>(DstEltTy)) {
assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
if (DstEltType->isSignedIntegerOrEnumerationType())
Res = Builder.CreateFPToSI(Src, DstTy, "conv");
else
Res = Builder.CreateFPToUI(Src, DstTy, "conv");
} else {
assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
"Unknown real conversion");
if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
else
Res = Builder.CreateFPExt(Src, DstTy, "conv");
}
return Res;
}
Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
CGF.EmitIgnoredExpr(E->getBase());
return CGF.emitScalarConstant(Constant, E);
} else {
Expr::EvalResult Result;
if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
llvm::APSInt Value = Result.Val.getInt();
CGF.EmitIgnoredExpr(E->getBase());
return Builder.getInt(Value);
}
}
return EmitLoadOfLValue(E);
}
Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
TestAndClearIgnoreResultAssign();
if (!E->getBase()->getType()->isVectorType() &&
!E->getBase()->getType()->isVLSTBuiltinType())
return EmitLoadOfLValue(E);
Value *Base = Visit(E->getBase());
Value *Idx = Visit(E->getIdx());
QualType IdxTy = E->getIdx()->getType();
if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, true);
return Builder.CreateExtractElement(Base, Idx, "vecext");
}
Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
TestAndClearIgnoreResultAssign();
Value *RowIdx = Visit(E->getRowIdx());
Value *ColumnIdx = Visit(E->getColumnIdx());
const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
unsigned NumRows = MatrixTy->getNumRows();
llvm::MatrixBuilder MB(Builder);
Value *Idx = MB.CreateIndex(RowIdx, ColumnIdx, NumRows);
if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0)
MB.CreateIndexAssumption(Idx, MatrixTy->getNumElementsFlattened());
Value *Matrix = Visit(E->getBase());
return Builder.CreateExtractElement(Matrix, Idx, "matrixext");
}
static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
unsigned Off) {
int MV = SVI->getMaskValue(Idx);
if (MV == -1)
return -1;
return Off + MV;
}
static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) &&
"Index operand too large for shufflevector mask!");
return C->getZExtValue();
}
Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
bool Ignore = TestAndClearIgnoreResultAssign();
(void)Ignore;
assert (Ignore == false && "init list ignored");
unsigned NumInitElements = E->getNumInits();
if (E->hadArrayRangeDesignator())
CGF.ErrorUnsupported(E, "GNU array range designator extension");
llvm::VectorType *VType =
dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
if (!VType) {
if (NumInitElements == 0) {
return EmitNullValue(E->getType());
}
return Visit(E->getInit(0));
}
unsigned ResElts = cast<llvm::FixedVectorType>(VType)->getNumElements();
unsigned CurIdx = 0;
bool VIsUndefShuffle = false;
llvm::Value *V = llvm::UndefValue::get(VType);
for (unsigned i = 0; i != NumInitElements; ++i) {
Expr *IE = E->getInit(i);
Value *Init = Visit(IE);
SmallVector<int, 16> Args;
llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
if (!VVT) {
if (isa<ExtVectorElementExpr>(IE)) {
llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
if (cast<llvm::FixedVectorType>(EI->getVectorOperandType())
->getNumElements() == ResElts) {
llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
Value *LHS = nullptr, *RHS = nullptr;
if (CurIdx == 0) {
Args.push_back(getAsInt32(C, CGF.Int32Ty));
Args.resize(ResElts, -1);
LHS = EI->getVectorOperand();
RHS = V;
VIsUndefShuffle = true;
} else if (VIsUndefShuffle) {
llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
for (unsigned j = 0; j != CurIdx; ++j)
Args.push_back(getMaskElt(SVV, j, 0));
Args.push_back(ResElts + C->getZExtValue());
Args.resize(ResElts, -1);
LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
RHS = EI->getVectorOperand();
VIsUndefShuffle = false;
}
if (!Args.empty()) {
V = Builder.CreateShuffleVector(LHS, RHS, Args);
++CurIdx;
continue;
}
}
}
V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
"vecinit");
VIsUndefShuffle = false;
++CurIdx;
continue;
}
unsigned InitElts = cast<llvm::FixedVectorType>(VVT)->getNumElements();
unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
if (isa<ExtVectorElementExpr>(IE)) {
llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
Value *SVOp = SVI->getOperand(0);
auto *OpTy = cast<llvm::FixedVectorType>(SVOp->getType());
if (OpTy->getNumElements() == ResElts) {
for (unsigned j = 0; j != CurIdx; ++j) {
if (VIsUndefShuffle) {
Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0));
} else {
Args.push_back(j);
}
}
for (unsigned j = 0, je = InitElts; j != je; ++j)
Args.push_back(getMaskElt(SVI, j, Offset));
Args.resize(ResElts, -1);
if (VIsUndefShuffle)
V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
Init = SVOp;
}
}
if (Args.empty()) {
for (unsigned j = 0; j != InitElts; ++j)
Args.push_back(j);
Args.resize(ResElts, -1);
Init = Builder.CreateShuffleVector(Init, Args, "vext");
Args.clear();
for (unsigned j = 0; j != CurIdx; ++j)
Args.push_back(j);
for (unsigned j = 0; j != InitElts; ++j)
Args.push_back(j + Offset);
Args.resize(ResElts, -1);
}
if (CurIdx == 0)
std::swap(V, Init);
V = Builder.CreateShuffleVector(V, Init, Args, "vecinit");
VIsUndefShuffle = isa<llvm::UndefValue>(Init);
CurIdx += InitElts;
}
llvm::Type *EltTy = VType->getElementType();
for (; CurIdx < ResElts; ++CurIdx) {
Value *Idx = Builder.getInt32(CurIdx);
llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
}
return V;
}
bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
const Expr *E = CE->getSubExpr();
if (CE->getCastKind() == CK_UncheckedDerivedToBase)
return false;
if (isa<CXXThisExpr>(E->IgnoreParens())) {
return false;
}
if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
if (ICE->isGLValue())
return false;
}
return true;
}
Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Expr *E = CE->getSubExpr();
QualType DestTy = CE->getType();
CastKind Kind = CE->getCastKind();
bool Ignored = TestAndClearIgnoreResultAssign();
switch (Kind) {
case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
case CK_BuiltinFnToFnPtr:
llvm_unreachable("builtin functions are handled elsewhere");
case CK_LValueBitCast:
case CK_ObjCObjectLValueCast: {
Address Addr = EmitLValue(E).getAddress(CGF);
Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
return EmitLoadOfLValue(LV, CE->getExprLoc());
}
case CK_LValueToRValueBitCast: {
LValue SourceLVal = CGF.EmitLValue(E);
Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF),
CGF.ConvertTypeForMem(DestTy));
LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
return EmitLoadOfLValue(DestLV, CE->getExprLoc());
}
case CK_CPointerToObjCPointerCast:
case CK_BlockPointerToObjCPointerCast:
case CK_AnyPointerToBlockPointerCast:
case CK_BitCast: {
Value *Src = Visit(const_cast<Expr*>(E));
llvm::Type *SrcTy = Src->getType();
llvm::Type *DstTy = ConvertType(DestTy);
if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
llvm_unreachable("wrong cast for pointers in different address spaces"
"(must be an address space cast)!");
}
if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
if (auto *PT = DestTy->getAs<PointerType>()) {
CGF.EmitVTablePtrCheckForCast(
PT->getPointeeType(),
Address(Src,
CGF.ConvertTypeForMem(
E->getType()->castAs<PointerType>()->getPointeeType()),
CGF.getPointerAlign()),
true, CodeGenFunction::CFITCK_UnrelatedCast,
CE->getBeginLoc());
}
}
if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
const QualType SrcType = E->getType();
if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
Src = Builder.CreateLaunderInvariantGroup(Src);
} else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
Src = Builder.CreateStripInvariantGroup(Src);
}
}
if (auto *CI = dyn_cast<llvm::CallBase>(Src)) {
if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE)) {
QualType PointeeType = DestTy->getPointeeType();
if (!PointeeType.isNull())
CGF.getDebugInfo()->addHeapAllocSiteMetadata(CI, PointeeType,
CE->getExprLoc());
}
}
if (const auto *FixedSrc = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
if (const auto *ScalableDst = dyn_cast<llvm::ScalableVectorType>(DstTy)) {
bool NeedsBitCast = false;
auto PredType = llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
llvm::Type *OrigType = DstTy;
if (ScalableDst == PredType &&
FixedSrc->getElementType() == Builder.getInt8Ty()) {
DstTy = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
ScalableDst = cast<llvm::ScalableVectorType>(DstTy);
NeedsBitCast = true;
}
if (FixedSrc->getElementType() == ScalableDst->getElementType()) {
llvm::Value *UndefVec = llvm::UndefValue::get(DstTy);
llvm::Value *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
llvm::Value *Result = Builder.CreateInsertVector(
DstTy, UndefVec, Src, Zero, "castScalableSve");
if (NeedsBitCast)
Result = Builder.CreateBitCast(Result, OrigType);
return Result;
}
}
}
if (const auto *ScalableSrc = dyn_cast<llvm::ScalableVectorType>(SrcTy)) {
if (const auto *FixedDst = dyn_cast<llvm::FixedVectorType>(DstTy)) {
auto PredType = llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
if (ScalableSrc == PredType &&
FixedDst->getElementType() == Builder.getInt8Ty()) {
SrcTy = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
ScalableSrc = cast<llvm::ScalableVectorType>(SrcTy);
Src = Builder.CreateBitCast(Src, SrcTy);
}
if (ScalableSrc->getElementType() == FixedDst->getElementType()) {
llvm::Value *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
return Builder.CreateExtractVector(DstTy, Src, Zero, "castFixedSve");
}
}
}
if ((isa<llvm::FixedVectorType>(SrcTy) &&
isa<llvm::ScalableVectorType>(DstTy)) ||
(isa<llvm::ScalableVectorType>(SrcTy) &&
isa<llvm::FixedVectorType>(DstTy))) {
Address Addr = CGF.CreateDefaultAlignTempAlloca(SrcTy, "saved-value");
LValue LV = CGF.MakeAddrLValue(Addr, E->getType());
CGF.EmitStoreOfScalar(Src, LV);
Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy),
"castFixedSve");
LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
return EmitLoadOfLValue(DestLV, CE->getExprLoc());
}
return Builder.CreateBitCast(Src, DstTy);
}
case CK_AddressSpaceConversion: {
Expr::EvalResult Result;
if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
Result.Val.isNullPointer()) {
if (Result.HasSideEffects)
Visit(E);
return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
ConvertType(DestTy)), DestTy);
}
return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
}
case CK_AtomicToNonAtomic:
case CK_NonAtomicToAtomic:
case CK_UserDefinedConversion:
return Visit(const_cast<Expr*>(E));
case CK_NoOp: {
llvm::Value *V = Visit(const_cast<Expr *>(E));
if (V) {
llvm::Type *T = ConvertType(DestTy);
if (T != V->getType())
V = Builder.CreateBitCast(V, T);
}
return V;
}
case CK_BaseToDerived: {
const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
Address Base = CGF.EmitPointerWithAlignment(E);
Address Derived =
CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
CE->path_begin(), CE->path_end(),
CGF.ShouldNullCheckClassCastValue(CE));
if (CGF.sanitizePerformTypeCheck())
CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
Derived.getPointer(), DestTy->getPointeeType());
if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
CGF.EmitVTablePtrCheckForCast(DestTy->getPointeeType(), Derived,
true,
CodeGenFunction::CFITCK_DerivedCast,
CE->getBeginLoc());
return Derived.getPointer();
}
case CK_UncheckedDerivedToBase:
case CK_DerivedToBase: {
return CGF.EmitPointerWithAlignment(CE).getPointer();
}
case CK_Dynamic: {
Address V = CGF.EmitPointerWithAlignment(E);
const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
return CGF.EmitDynamicCast(V, DCE);
}
case CK_ArrayToPointerDecay:
return CGF.EmitArrayToPointerDecay(E).getPointer();
case CK_FunctionToPointerDecay:
return EmitLValue(E).getPointer(CGF);
case CK_NullToPointer:
if (MustVisitNullValue(E))
CGF.EmitIgnoredExpr(E);
return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
DestTy);
case CK_NullToMemberPointer: {
if (MustVisitNullValue(E))
CGF.EmitIgnoredExpr(E);
const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
}
case CK_ReinterpretMemberPointer:
case CK_BaseToDerivedMemberPointer:
case CK_DerivedToBaseMemberPointer: {
Value *Src = Visit(E);
return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
}
case CK_ARCProduceObject:
return CGF.EmitARCRetainScalarExpr(E);
case CK_ARCConsumeObject:
return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
case CK_ARCReclaimReturnedObject:
return CGF.EmitARCReclaimReturnedObject(E, Ignored);
case CK_ARCExtendBlockObject:
return CGF.EmitARCExtendBlockObject(E);
case CK_CopyAndAutoreleaseBlockObject:
return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
case CK_FloatingRealToComplex:
case CK_FloatingComplexCast:
case CK_IntegralRealToComplex:
case CK_IntegralComplexCast:
case CK_IntegralComplexToFloatingComplex:
case CK_FloatingComplexToIntegralComplex:
case CK_ConstructorConversion:
case CK_ToUnion:
llvm_unreachable("scalar cast to non-scalar value");
case CK_LValueToRValue:
assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
return Visit(const_cast<Expr*>(E));
case CK_IntegralToPointer: {
Value *Src = Visit(const_cast<Expr*>(E));
auto DestLLVMTy = ConvertType(DestTy);
llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
llvm::Value* IntResult =
Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
if (DestTy.mayBeDynamicClass())
IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
}
return IntToPtr;
}
case CK_PointerToIntegral: {
assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
auto *PtrExpr = Visit(E);
if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
const QualType SrcType = E->getType();
if (SrcType.mayBeDynamicClass())
PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
}
return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
}
case CK_ToVoid: {
CGF.EmitIgnoredExpr(E);
return nullptr;
}
case CK_MatrixCast: {
return EmitScalarConversion(Visit(E), E->getType(), DestTy,
CE->getExprLoc());
}
case CK_VectorSplat: {
llvm::Type *DstTy = ConvertType(DestTy);
Value *Elt = Visit(const_cast<Expr *>(E));
llvm::ElementCount NumElements =
cast<llvm::VectorType>(DstTy)->getElementCount();
return Builder.CreateVectorSplat(NumElements, Elt, "splat");
}
case CK_FixedPointCast:
return EmitScalarConversion(Visit(E), E->getType(), DestTy,
CE->getExprLoc());
case CK_FixedPointToBoolean:
assert(E->getType()->isFixedPointType() &&
"Expected src type to be fixed point type");
assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
return EmitScalarConversion(Visit(E), E->getType(), DestTy,
CE->getExprLoc());
case CK_FixedPointToIntegral:
assert(E->getType()->isFixedPointType() &&
"Expected src type to be fixed point type");
assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
return EmitScalarConversion(Visit(E), E->getType(), DestTy,
CE->getExprLoc());
case CK_IntegralToFixedPoint:
assert(E->getType()->isIntegerType() &&
"Expected src type to be an integer");
assert(DestTy->isFixedPointType() &&
"Expected dest type to be fixed point type");
return EmitScalarConversion(Visit(E), E->getType(), DestTy,
CE->getExprLoc());
case CK_IntegralCast: {
ScalarConversionOpts Opts;
if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
if (!ICE->isPartOfExplicitCast())
Opts = ScalarConversionOpts(CGF.SanOpts);
}
return EmitScalarConversion(Visit(E), E->getType(), DestTy,
CE->getExprLoc(), Opts);
}
case CK_IntegralToFloating:
case CK_FloatingToIntegral:
case CK_FloatingCast:
case CK_FixedPointToFloating:
case CK_FloatingToFixedPoint: {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
return EmitScalarConversion(Visit(E), E->getType(), DestTy,
CE->getExprLoc());
}
case CK_BooleanToSignedIntegral: {
ScalarConversionOpts Opts;
Opts.TreatBooleanAsSigned = true;
return EmitScalarConversion(Visit(E), E->getType(), DestTy,
CE->getExprLoc(), Opts);
}
case CK_IntegralToBoolean:
return EmitIntToBoolConversion(Visit(E));
case CK_PointerToBoolean:
return EmitPointerToBoolConversion(Visit(E), E->getType());
case CK_FloatingToBoolean: {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
return EmitFloatToBoolConversion(Visit(E));
}
case CK_MemberPointerToBoolean: {
llvm::Value *MemPtr = Visit(E);
const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
}
case CK_FloatingComplexToReal:
case CK_IntegralComplexToReal:
return CGF.EmitComplexExpr(E, false, true).first;
case CK_FloatingComplexToBoolean:
case CK_IntegralComplexToBoolean: {
CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
return EmitComplexToScalarConversion(V, E->getType(), DestTy,
CE->getExprLoc());
}
case CK_ZeroToOCLOpaqueType: {
assert((DestTy->isEventT() || DestTy->isQueueT() ||
DestTy->isOCLIntelSubgroupAVCType()) &&
"CK_ZeroToOCLEvent cast on non-event type");
return llvm::Constant::getNullValue(ConvertType(DestTy));
}
case CK_IntToOCLSampler:
return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
}
llvm_unreachable("unknown scalar cast");
}
Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
CodeGenFunction::StmtExprEvaluation eval(CGF);
Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
!E->getType()->isVoidType());
if (!RetAlloca.isValid())
return nullptr;
return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
E->getExprLoc());
}
Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
CodeGenFunction::RunCleanupsScope Scope(CGF);
Value *V = Visit(E->getSubExpr());
Scope.ForceCleanup({&V});
return V;
}
static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
llvm::Value *InVal, bool IsInc,
FPOptions FPFeatures) {
BinOpInfo BinOp;
BinOp.LHS = InVal;
BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
BinOp.Ty = E->getType();
BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
BinOp.FPFeatures = FPFeatures;
BinOp.E = E;
return BinOp;
}
llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
llvm::Value *Amount =
llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
StringRef Name = IsInc ? "inc" : "dec";
switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
case LangOptions::SOB_Defined:
return Builder.CreateAdd(InVal, Amount, Name);
case LangOptions::SOB_Undefined:
if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
return Builder.CreateNSWAdd(InVal, Amount, Name);
LLVM_FALLTHROUGH;
case LangOptions::SOB_Trapping:
if (!E->canOverflow())
return Builder.CreateNSWAdd(InVal, Amount, Name);
return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
E, InVal, IsInc, E->getFPFeaturesInEffect(CGF.getLangOpts())));
}
llvm_unreachable("Unknown SignedOverflowBehaviorTy");
}
namespace {
class OMPLastprivateConditionalUpdateRAII {
private:
CodeGenFunction &CGF;
const UnaryOperator *E;
public:
OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
const UnaryOperator *E)
: CGF(CGF), E(E) {}
~OMPLastprivateConditionalUpdateRAII() {
if (CGF.getLangOpts().OpenMP)
CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
CGF, E->getSubExpr());
}
};
}
llvm::Value *
ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
bool isInc, bool isPre) {
OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
QualType type = E->getSubExpr()->getType();
llvm::PHINode *atomicPHI = nullptr;
llvm::Value *value;
llvm::Value *input;
int amount = (isInc ? 1 : -1);
bool isSubtraction = !isInc;
if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
type = atomicTy->getValueType();
if (isInc && type->isBooleanType()) {
llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
if (isPre) {
Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified())
->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
return Builder.getTrue();
}
return Builder.CreateAtomicRMW(
llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True,
llvm::AtomicOrdering::SequentiallyConsistent);
}
if (!type->isBooleanType() && type->isIntegerType() &&
!(type->isUnsignedIntegerType() &&
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
CGF.getLangOpts().getSignedOverflowBehavior() !=
LangOptions::SOB_Trapping) {
llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
llvm::AtomicRMWInst::Sub;
llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
llvm::Instruction::Sub;
llvm::Value *amt = CGF.EmitToMemory(
llvm::ConstantInt::get(ConvertType(type), 1, true), type);
llvm::Value *old =
Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt,
llvm::AtomicOrdering::SequentiallyConsistent);
return isPre ? Builder.CreateBinOp(op, old, amt) : old;
}
value = EmitLoadOfLValue(LV, E->getExprLoc());
input = value;
llvm::BasicBlock *startBB = Builder.GetInsertBlock();
llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
value = CGF.EmitToMemory(value, type);
Builder.CreateBr(opBB);
Builder.SetInsertPoint(opBB);
atomicPHI = Builder.CreatePHI(value->getType(), 2);
atomicPHI->addIncoming(value, startBB);
value = atomicPHI;
} else {
value = EmitLoadOfLValue(LV, E->getExprLoc());
input = value;
}
if (isInc && type->isBooleanType()) {
value = Builder.getTrue();
} else if (type->isIntegerType()) {
QualType promotedType;
bool canPerformLossyDemotionCheck = false;
if (type->isPromotableIntegerType()) {
promotedType = CGF.getContext().getPromotedIntegerType(type);
assert(promotedType != type && "Shouldn't promote to the same type.");
canPerformLossyDemotionCheck = true;
canPerformLossyDemotionCheck &=
CGF.getContext().getCanonicalType(type) !=
CGF.getContext().getCanonicalType(promotedType);
canPerformLossyDemotionCheck &=
PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
type, promotedType);
assert((!canPerformLossyDemotionCheck ||
type->isSignedIntegerOrEnumerationType() ||
promotedType->isSignedIntegerOrEnumerationType() ||
ConvertType(type)->getScalarSizeInBits() ==
ConvertType(promotedType)->getScalarSizeInBits()) &&
"The following check expects that if we do promotion to different "
"underlying canonical type, at least one of the types (either "
"base or promoted) will be signed, or the bitwidths will match.");
}
if (CGF.SanOpts.hasOneOf(
SanitizerKind::ImplicitIntegerArithmeticValueChange) &&
canPerformLossyDemotionCheck) {
value = EmitScalarConversion(value, type, promotedType, E->getExprLoc());
Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(),
ScalarConversionOpts(CGF.SanOpts));
} else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
} else if (E->canOverflow() && type->isUnsignedIntegerType() &&
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
value = EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
E, value, isInc, E->getFPFeaturesInEffect(CGF.getLangOpts())));
} else {
llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
}
} else if (const PointerType *ptr = type->getAs<PointerType>()) {
QualType type = ptr->getPointeeType();
if (const VariableArrayType *vla
= CGF.getContext().getAsVariableArrayType(type)) {
llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
llvm::Type *elemTy = CGF.ConvertTypeForMem(vla->getElementType());
if (CGF.getLangOpts().isSignedOverflowDefined())
value = Builder.CreateGEP(elemTy, value, numElts, "vla.inc");
else
value = CGF.EmitCheckedInBoundsGEP(
elemTy, value, numElts, false, isSubtraction,
E->getExprLoc(), "vla.inc");
} else if (type->isFunctionType()) {
llvm::Value *amt = Builder.getInt32(amount);
value = CGF.EmitCastToVoidPtr(value);
if (CGF.getLangOpts().isSignedOverflowDefined())
value = Builder.CreateGEP(CGF.Int8Ty, value, amt, "incdec.funcptr");
else
value = CGF.EmitCheckedInBoundsGEP(CGF.Int8Ty, value, amt,
false,
isSubtraction, E->getExprLoc(),
"incdec.funcptr");
value = Builder.CreateBitCast(value, input->getType());
} else {
llvm::Value *amt = Builder.getInt32(amount);
llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
if (CGF.getLangOpts().isSignedOverflowDefined())
value = Builder.CreateGEP(elemTy, value, amt, "incdec.ptr");
else
value = CGF.EmitCheckedInBoundsGEP(
elemTy, value, amt, false, isSubtraction,
E->getExprLoc(), "incdec.ptr");
}
} else if (type->isVectorType()) {
if (type->hasIntegerRepresentation()) {
llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
} else {
value = Builder.CreateFAdd(
value,
llvm::ConstantFP::get(value->getType(), amount),
isInc ? "inc" : "dec");
}
} else if (type->isRealFloatingType()) {
llvm::Value *amt;
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
value = Builder.CreateCall(
CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
CGF.CGM.FloatTy),
input, "incdec.conv");
} else {
value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
}
}
if (value->getType()->isFloatTy())
amt = llvm::ConstantFP::get(VMContext,
llvm::APFloat(static_cast<float>(amount)));
else if (value->getType()->isDoubleTy())
amt = llvm::ConstantFP::get(VMContext,
llvm::APFloat(static_cast<double>(amount)));
else {
llvm::APFloat F(static_cast<float>(amount));
bool ignored;
const llvm::fltSemantics *FS;
if (value->getType()->isFP128Ty())
FS = &CGF.getTarget().getFloat128Format();
else if (value->getType()->isHalfTy())
FS = &CGF.getTarget().getHalfFormat();
else if (value->getType()->isPPC_FP128Ty())
FS = &CGF.getTarget().getIbm128Format();
else
FS = &CGF.getTarget().getLongDoubleFormat();
F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
amt = llvm::ConstantFP::get(VMContext, F);
}
value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
value = Builder.CreateCall(
CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
CGF.CGM.FloatTy),
value, "incdec.conv");
} else {
value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
}
}
} else if (type->isFixedPointType()) {
BinOpInfo Info;
Info.E = E;
Info.Ty = E->getType();
Info.Opcode = isInc ? BO_Add : BO_Sub;
Info.LHS = value;
Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
if (type->isSignedFixedPointType()) {
Info.Opcode = isInc ? BO_Sub : BO_Add;
Info.RHS = Builder.CreateNeg(Info.RHS);
}
llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
auto DstSema = CGF.getContext().getFixedPointSemantics(Info.Ty);
Info.RHS = FPBuilder.CreateIntegerToFixed(Info.RHS, true, DstSema);
value = EmitFixedPointBinOp(Info);
} else {
const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
value = CGF.EmitCastToVoidPtr(value);
CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
if (!isInc) size = -size;
llvm::Value *sizeValue =
llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
if (CGF.getLangOpts().isSignedOverflowDefined())
value = Builder.CreateGEP(CGF.Int8Ty, value, sizeValue, "incdec.objptr");
else
value = CGF.EmitCheckedInBoundsGEP(
CGF.Int8Ty, value, sizeValue, false, isSubtraction,
E->getExprLoc(), "incdec.objptr");
value = Builder.CreateBitCast(value, input->getType());
}
if (atomicPHI) {
llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
auto Pair = CGF.EmitAtomicCompareExchange(
LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
llvm::Value *success = Pair.second;
atomicPHI->addIncoming(old, curBlock);
Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
Builder.SetInsertPoint(contBB);
return isPre ? value : input;
}
if (LV.isBitField())
CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
else
CGF.EmitStoreThroughLValue(RValue::get(value), LV);
return isPre ? value : input;
}
Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
TestAndClearIgnoreResultAssign();
Value *Op = Visit(E->getSubExpr());
if (Op->getType()->isFPOrFPVectorTy())
return Builder.CreateFNeg(Op, "fneg");
BinOpInfo BinOp;
BinOp.RHS = Op;
BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
BinOp.Ty = E->getType();
BinOp.Opcode = BO_Sub;
BinOp.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
BinOp.E = E;
return EmitSub(BinOp);
}
Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
TestAndClearIgnoreResultAssign();
Value *Op = Visit(E->getSubExpr());
return Builder.CreateNot(Op, "neg");
}
Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
if (E->getType()->isVectorType() &&
E->getType()->castAs<VectorType>()->getVectorKind() ==
VectorType::GenericVector) {
Value *Oper = Visit(E->getSubExpr());
Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Value *Result;
if (Oper->getType()->isFPOrFPVectorTy()) {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
} else
Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
}
Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
BoolVal = Builder.CreateNot(BoolVal, "lnot");
return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
}
Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
Expr::EvalResult EVResult;
if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
llvm::APSInt Value = EVResult.Val.getInt();
return Builder.getInt(Value);
}
unsigned n = E->getNumComponents();
llvm::Type* ResultType = ConvertType(E->getType());
llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
QualType CurrentType = E->getTypeSourceInfo()->getType();
for (unsigned i = 0; i != n; ++i) {
OffsetOfNode ON = E->getComponent(i);
llvm::Value *Offset = nullptr;
switch (ON.getKind()) {
case OffsetOfNode::Array: {
Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
CurrentType =
CGF.getContext().getAsArrayType(CurrentType)->getElementType();
llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
Offset = Builder.CreateMul(Idx, ElemSize);
break;
}
case OffsetOfNode::Field: {
FieldDecl *MemberDecl = ON.getField();
RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
unsigned i = 0;
for (RecordDecl::field_iterator Field = RD->field_begin(),
FieldEnd = RD->field_end();
Field != FieldEnd; ++Field, ++i) {
if (*Field == MemberDecl)
break;
}
assert(i < RL.getFieldCount() && "offsetof field in wrong type");
int64_t OffsetInt = RL.getFieldOffset(i) /
CGF.getContext().getCharWidth();
Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
CurrentType = MemberDecl->getType();
break;
}
case OffsetOfNode::Identifier:
llvm_unreachable("dependent __builtin_offsetof");
case OffsetOfNode::Base: {
if (ON.getBase()->isVirtual()) {
CGF.ErrorUnsupported(E, "virtual base in offsetof");
continue;
}
RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
CurrentType = ON.getBase()->getType();
auto *BaseRT = CurrentType->castAs<RecordType>();
auto *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
break;
}
}
Result = Builder.CreateAdd(Result, Offset);
}
return Result;
}
Value *
ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
const UnaryExprOrTypeTraitExpr *E) {
QualType TypeToSize = E->getTypeOfArgument();
if (E->getKind() == UETT_SizeOf) {
if (const VariableArrayType *VAT =
CGF.getContext().getAsVariableArrayType(TypeToSize)) {
if (E->isArgumentType()) {
CGF.EmitVariablyModifiedType(TypeToSize);
} else {
CGF.EmitIgnoredExpr(E->getArgumentExpr());
}
auto VlaSize = CGF.getVLASize(VAT);
llvm::Value *size = VlaSize.NumElts;
CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
if (!eltSize.isOne())
size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
return size;
}
} else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
auto Alignment =
CGF.getContext()
.toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
E->getTypeOfArgument()->getPointeeType()))
.getQuantity();
return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
}
return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
}
Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
Expr *Op = E->getSubExpr();
if (Op->getType()->isAnyComplexType()) {
if (E->isGLValue())
return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
E->getExprLoc()).getScalarVal();
return CGF.EmitComplexExpr(Op, false, true).first;
}
return Visit(Op);
}
Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
Expr *Op = E->getSubExpr();
if (Op->getType()->isAnyComplexType()) {
if (Op->isGLValue())
return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
E->getExprLoc()).getScalarVal();
return CGF.EmitComplexExpr(Op, true, false).second;
}
if (Op->isGLValue())
CGF.EmitLValue(Op);
else
CGF.EmitScalarExpr(Op, true);
return llvm::Constant::getNullValue(ConvertType(E->getType()));
}
BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
TestAndClearIgnoreResultAssign();
BinOpInfo Result;
Result.LHS = Visit(E->getLHS());
Result.RHS = Visit(E->getRHS());
Result.Ty = E->getType();
Result.Opcode = E->getOpcode();
Result.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
Result.E = E;
return Result;
}
LValue ScalarExprEmitter::EmitCompoundAssignLValue(
const CompoundAssignOperator *E,
Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Value *&Result) {
QualType LHSTy = E->getLHS()->getType();
BinOpInfo OpInfo;
if (E->getComputationResultType()->isAnyComplexType())
return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
OpInfo.RHS = Visit(E->getRHS());
OpInfo.Ty = E->getComputationResultType();
OpInfo.Opcode = E->getOpcode();
OpInfo.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
OpInfo.E = E;
LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
llvm::PHINode *atomicPHI = nullptr;
if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
QualType type = atomicTy->getValueType();
if (!type->isBooleanType() && type->isIntegerType() &&
!(type->isUnsignedIntegerType() &&
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
CGF.getLangOpts().getSignedOverflowBehavior() !=
LangOptions::SOB_Trapping) {
llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
llvm::Instruction::BinaryOps Op;
switch (OpInfo.Opcode) {
case BO_MulAssign: case BO_DivAssign:
case BO_RemAssign:
case BO_ShlAssign:
case BO_ShrAssign:
break;
case BO_AddAssign:
AtomicOp = llvm::AtomicRMWInst::Add;
Op = llvm::Instruction::Add;
break;
case BO_SubAssign:
AtomicOp = llvm::AtomicRMWInst::Sub;
Op = llvm::Instruction::Sub;
break;
case BO_AndAssign:
AtomicOp = llvm::AtomicRMWInst::And;
Op = llvm::Instruction::And;
break;
case BO_XorAssign:
AtomicOp = llvm::AtomicRMWInst::Xor;
Op = llvm::Instruction::Xor;
break;
case BO_OrAssign:
AtomicOp = llvm::AtomicRMWInst::Or;
Op = llvm::Instruction::Or;
break;
default:
llvm_unreachable("Invalid compound assignment type");
}
if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
llvm::Value *Amt = CGF.EmitToMemory(
EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
E->getExprLoc()),
LHSTy);
Value *OldVal = Builder.CreateAtomicRMW(
AtomicOp, LHSLV.getPointer(CGF), Amt,
llvm::AtomicOrdering::SequentiallyConsistent);
Result = Builder.CreateBinOp(Op, OldVal, Amt);
return LHSLV;
}
}
llvm::BasicBlock *startBB = Builder.GetInsertBlock();
llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
Builder.CreateBr(opBB);
Builder.SetInsertPoint(opBB);
atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
atomicPHI->addIncoming(OpInfo.LHS, startBB);
OpInfo.LHS = atomicPHI;
}
else
OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
SourceLocation Loc = E->getExprLoc();
OpInfo.LHS =
EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
Result = (this->*Func)(OpInfo);
Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
Loc, ScalarConversionOpts(CGF.SanOpts));
if (atomicPHI) {
llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
auto Pair = CGF.EmitAtomicCompareExchange(
LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
llvm::Value *success = Pair.second;
atomicPHI->addIncoming(old, curBlock);
Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
Builder.SetInsertPoint(contBB);
return LHSLV;
}
if (LHSLV.isBitField())
CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
else
CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
if (CGF.getLangOpts().OpenMP)
CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
E->getLHS());
return LHSLV;
}
Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
bool Ignore = TestAndClearIgnoreResultAssign();
Value *RHS = nullptr;
LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
if (Ignore)
return nullptr;
if (!CGF.getLangOpts().CPlusPlus)
return RHS;
if (!LHS.isVolatileQualified())
return RHS;
return EmitLoadOfLValue(LHS, E->getExprLoc());
}
void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
SanitizerKind::IntegerDivideByZero));
}
const auto *BO = cast<BinaryOperator>(Ops.E);
if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
Ops.Ty->hasSignedIntegerRepresentation() &&
!IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
Ops.mayHaveIntegerOverflow()) {
llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
llvm::Value *IntMin =
Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
llvm::Value *NegOne = llvm::Constant::getAllOnesValue(Ty);
llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
Checks.push_back(
std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
}
if (Checks.size() > 0)
EmitBinOpCheck(Checks, Ops);
}
Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
{
CodeGenFunction::SanitizerScope SanScope(&CGF);
if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Ops.Ty->isIntegerType() &&
(Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
} else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
Ops.Ty->isRealFloatingType() &&
Ops.mayHaveFloatDivisionByZero()) {
llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
Ops);
}
}
if (Ops.Ty->isConstantMatrixType()) {
llvm::MatrixBuilder MB(Builder);
auto *BO = cast<BinaryOperator>(Ops.E);
(void)BO;
assert(
isa<ConstantMatrixType>(BO->getLHS()->getType().getCanonicalType()) &&
"first operand must be a matrix");
assert(BO->getRHS()->getType().getCanonicalType()->isArithmeticType() &&
"second operand must be an arithmetic type");
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
return MB.CreateScalarDiv(Ops.LHS, Ops.RHS,
Ops.Ty->hasUnsignedIntegerRepresentation());
}
if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
llvm::Value *Val;
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
if ((CGF.getLangOpts().OpenCL &&
!CGF.CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
(CGF.getLangOpts().HIP && CGF.getLangOpts().CUDAIsDevice &&
!CGF.CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
llvm::Type *ValTy = Val->getType();
if (ValTy->isFloatTy() ||
(isa<llvm::VectorType>(ValTy) &&
cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
CGF.SetFPAccuracy(Val, 2.5);
}
return Val;
}
else if (Ops.isFixedPointOp())
return EmitFixedPointBinOp(Ops);
else if (Ops.Ty->hasUnsignedIntegerRepresentation())
return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
else
return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
}
Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Ops.Ty->isIntegerType() &&
(Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
CodeGenFunction::SanitizerScope SanScope(&CGF);
llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
}
if (Ops.Ty->hasUnsignedIntegerRepresentation())
return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
else
return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
}
Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
unsigned IID;
unsigned OpID = 0;
SanitizerHandler OverflowKind;
bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
switch (Ops.Opcode) {
case BO_Add:
case BO_AddAssign:
OpID = 1;
IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
llvm::Intrinsic::uadd_with_overflow;
OverflowKind = SanitizerHandler::AddOverflow;
break;
case BO_Sub:
case BO_SubAssign:
OpID = 2;
IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
llvm::Intrinsic::usub_with_overflow;
OverflowKind = SanitizerHandler::SubOverflow;
break;
case BO_Mul:
case BO_MulAssign:
OpID = 3;
IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
llvm::Intrinsic::umul_with_overflow;
OverflowKind = SanitizerHandler::MulOverflow;
break;
default:
llvm_unreachable("Unsupported operation for overflow detection");
}
OpID <<= 1;
if (isSigned)
OpID |= 1;
CodeGenFunction::SanitizerScope SanScope(&CGF);
llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
const std::string *handlerName =
&CGF.getLangOpts().OverflowHandler;
if (handlerName->empty()) {
if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
llvm::Value *NotOverflow = Builder.CreateNot(overflow);
SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
: SanitizerKind::UnsignedIntegerOverflow;
EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
} else
CGF.EmitTrapCheck(Builder.CreateNot(overflow), OverflowKind);
return result;
}
llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
llvm::BasicBlock *continueBB =
CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Builder.CreateCondBr(overflow, overflowBB, continueBB);
Builder.SetInsertPoint(overflowBB);
llvm::Type *Int8Ty = CGF.Int8Ty;
llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
llvm::FunctionType *handlerTy =
llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
llvm::FunctionCallee handler =
CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
llvm::Value *handlerArgs[] = {
lhs,
rhs,
Builder.getInt8(OpID),
Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
};
llvm::Value *handlerResult =
CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
handlerResult = Builder.CreateTrunc(handlerResult, opTy);
Builder.CreateBr(continueBB);
Builder.SetInsertPoint(continueBB);
llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
phi->addIncoming(result, initialBB);
phi->addIncoming(handlerResult, overflowBB);
return phi;
}
static Value *emitPointerArithmetic(CodeGenFunction &CGF,
const BinOpInfo &op,
bool isSubtraction) {
const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Value *pointer = op.LHS;
Expr *pointerOperand = expr->getLHS();
Value *index = op.RHS;
Expr *indexOperand = expr->getRHS();
if (!isSubtraction && !pointer->getType()->isPointerTy()) {
std::swap(pointer, index);
std::swap(pointerOperand, indexOperand);
}
bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
auto &DL = CGF.CGM.getDataLayout();
auto PtrTy = cast<llvm::PointerType>(pointer->getType());
if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
op.Opcode,
expr->getLHS(),
expr->getRHS()))
return CGF.Builder.CreateIntToPtr(index, pointer->getType());
if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
"idx.ext");
}
if (isSubtraction)
index = CGF.Builder.CreateNeg(index, "idx.neg");
if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
false);
const PointerType *pointerType
= pointerOperand->getType()->getAs<PointerType>();
if (!pointerType) {
QualType objectType = pointerOperand->getType()
->castAs<ObjCObjectPointerType>()
->getPointeeType();
llvm::Value *objectSize
= CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
index = CGF.Builder.CreateMul(index, objectSize);
Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
result = CGF.Builder.CreateGEP(CGF.Int8Ty, result, index, "add.ptr");
return CGF.Builder.CreateBitCast(result, pointer->getType());
}
QualType elementType = pointerType->getPointeeType();
if (const VariableArrayType *vla
= CGF.getContext().getAsVariableArrayType(elementType)) {
llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
llvm::Type *elemTy = CGF.ConvertTypeForMem(vla->getElementType());
if (CGF.getLangOpts().isSignedOverflowDefined()) {
index = CGF.Builder.CreateMul(index, numElements, "vla.index");
pointer = CGF.Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
} else {
index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
pointer = CGF.EmitCheckedInBoundsGEP(
elemTy, pointer, index, isSigned, isSubtraction, op.E->getExprLoc(),
"add.ptr");
}
return pointer;
}
if (elementType->isVoidType() || elementType->isFunctionType()) {
Value *result = CGF.EmitCastToVoidPtr(pointer);
result = CGF.Builder.CreateGEP(CGF.Int8Ty, result, index, "add.ptr");
return CGF.Builder.CreateBitCast(result, pointer->getType());
}
llvm::Type *elemTy = CGF.ConvertTypeForMem(elementType);
if (CGF.getLangOpts().isSignedOverflowDefined())
return CGF.Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
return CGF.EmitCheckedInBoundsGEP(
elemTy, pointer, index, isSigned, isSubtraction, op.E->getExprLoc(),
"add.ptr");
}
static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
const CodeGenFunction &CGF, CGBuilderTy &Builder,
bool negMul, bool negAdd) {
assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Value *MulOp0 = MulOp->getOperand(0);
Value *MulOp1 = MulOp->getOperand(1);
if (negMul)
MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
if (negAdd)
Addend = Builder.CreateFNeg(Addend, "neg");
Value *FMulAdd = nullptr;
if (Builder.getIsFPConstrained()) {
assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
"Only constrained operation should be created when Builder is in FP "
"constrained mode");
FMulAdd = Builder.CreateConstrainedFPCall(
CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
Addend->getType()),
{MulOp0, MulOp1, Addend});
} else {
FMulAdd = Builder.CreateCall(
CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
{MulOp0, MulOp1, Addend});
}
MulOp->eraseFromParent();
return FMulAdd;
}
static Value* tryEmitFMulAdd(const BinOpInfo &op,
const CodeGenFunction &CGF, CGBuilderTy &Builder,
bool isSub=false) {
assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
"Only fadd/fsub can be the root of an fmuladd.");
if (!op.FPFeatures.allowFPContractWithinStatement())
return nullptr;
if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
LHSBinOp->use_empty())
return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
}
if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
RHSBinOp->use_empty())
return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
}
if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) {
if (LHSBinOp->getIntrinsicID() ==
llvm::Intrinsic::experimental_constrained_fmul &&
LHSBinOp->use_empty())
return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
}
if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) {
if (RHSBinOp->getIntrinsicID() ==
llvm::Intrinsic::experimental_constrained_fmul &&
RHSBinOp->use_empty())
return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
}
return nullptr;
}
Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
if (op.LHS->getType()->isPointerTy() ||
op.RHS->getType()->isPointerTy())
return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
if (op.Ty->isSignedIntegerOrEnumerationType()) {
switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
case LangOptions::SOB_Defined:
return Builder.CreateAdd(op.LHS, op.RHS, "add");
case LangOptions::SOB_Undefined:
if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
LLVM_FALLTHROUGH;
case LangOptions::SOB_Trapping:
if (CanElideOverflowCheck(CGF.getContext(), op))
return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
return EmitOverflowCheckedBinOp(op);
}
}
if (op.Ty->isConstantMatrixType()) {
llvm::MatrixBuilder MB(Builder);
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
return MB.CreateAdd(op.LHS, op.RHS);
}
if (op.Ty->isUnsignedIntegerType() &&
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
!CanElideOverflowCheck(CGF.getContext(), op))
return EmitOverflowCheckedBinOp(op);
if (op.LHS->getType()->isFPOrFPVectorTy()) {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
return FMulAdd;
return Builder.CreateFAdd(op.LHS, op.RHS, "add");
}
if (op.isFixedPointOp())
return EmitFixedPointBinOp(op);
return Builder.CreateAdd(op.LHS, op.RHS, "add");
}
Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
using llvm::APSInt;
using llvm::ConstantInt;
QualType ResultTy = op.Ty;
QualType LHSTy, RHSTy;
if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
RHSTy = BinOp->getRHS()->getType();
if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
LHSTy = CAO->getComputationLHSType();
ResultTy = CAO->getComputationResultType();
} else
LHSTy = BinOp->getLHS()->getType();
} else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
LHSTy = UnOp->getSubExpr()->getType();
RHSTy = UnOp->getSubExpr()->getType();
}
ASTContext &Ctx = CGF.getContext();
Value *LHS = op.LHS;
Value *RHS = op.RHS;
auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
Value *Result;
llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
switch (op.Opcode) {
case BO_AddAssign:
case BO_Add:
Result = FPBuilder.CreateAdd(LHS, LHSFixedSema, RHS, RHSFixedSema);
break;
case BO_SubAssign:
case BO_Sub:
Result = FPBuilder.CreateSub(LHS, LHSFixedSema, RHS, RHSFixedSema);
break;
case BO_MulAssign:
case BO_Mul:
Result = FPBuilder.CreateMul(LHS, LHSFixedSema, RHS, RHSFixedSema);
break;
case BO_DivAssign:
case BO_Div:
Result = FPBuilder.CreateDiv(LHS, LHSFixedSema, RHS, RHSFixedSema);
break;
case BO_ShlAssign:
case BO_Shl:
Result = FPBuilder.CreateShl(LHS, LHSFixedSema, RHS);
break;
case BO_ShrAssign:
case BO_Shr:
Result = FPBuilder.CreateShr(LHS, LHSFixedSema, RHS);
break;
case BO_LT:
return FPBuilder.CreateLT(LHS, LHSFixedSema, RHS, RHSFixedSema);
case BO_GT:
return FPBuilder.CreateGT(LHS, LHSFixedSema, RHS, RHSFixedSema);
case BO_LE:
return FPBuilder.CreateLE(LHS, LHSFixedSema, RHS, RHSFixedSema);
case BO_GE:
return FPBuilder.CreateGE(LHS, LHSFixedSema, RHS, RHSFixedSema);
case BO_EQ:
return FPBuilder.CreateEQ(LHS, LHSFixedSema, RHS, RHSFixedSema);
case BO_NE:
return FPBuilder.CreateNE(LHS, LHSFixedSema, RHS, RHSFixedSema);
case BO_Cmp:
case BO_LAnd:
case BO_LOr:
llvm_unreachable("Found unimplemented fixed point binary operation");
case BO_PtrMemD:
case BO_PtrMemI:
case BO_Rem:
case BO_Xor:
case BO_And:
case BO_Or:
case BO_Assign:
case BO_RemAssign:
case BO_AndAssign:
case BO_XorAssign:
case BO_OrAssign:
case BO_Comma:
llvm_unreachable("Found unsupported binary operation for fixed point types.");
}
bool IsShift = BinaryOperator::isShiftOp(op.Opcode) ||
BinaryOperator::isShiftAssignOp(op.Opcode);
return FPBuilder.CreateFixedToFixed(Result, IsShift ? LHSFixedSema
: CommonFixedSema,
ResultFixedSema);
}
Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
if (!op.LHS->getType()->isPointerTy()) {
if (op.Ty->isSignedIntegerOrEnumerationType()) {
switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
case LangOptions::SOB_Defined:
return Builder.CreateSub(op.LHS, op.RHS, "sub");
case LangOptions::SOB_Undefined:
if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
LLVM_FALLTHROUGH;
case LangOptions::SOB_Trapping:
if (CanElideOverflowCheck(CGF.getContext(), op))
return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
return EmitOverflowCheckedBinOp(op);
}
}
if (op.Ty->isConstantMatrixType()) {
llvm::MatrixBuilder MB(Builder);
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
return MB.CreateSub(op.LHS, op.RHS);
}
if (op.Ty->isUnsignedIntegerType() &&
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
!CanElideOverflowCheck(CGF.getContext(), op))
return EmitOverflowCheckedBinOp(op);
if (op.LHS->getType()->isFPOrFPVectorTy()) {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
return FMulAdd;
return Builder.CreateFSub(op.LHS, op.RHS, "sub");
}
if (op.isFixedPointOp())
return EmitFixedPointBinOp(op);
return Builder.CreateSub(op.LHS, op.RHS, "sub");
}
if (!op.RHS->getType()->isPointerTy())
return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
llvm::Value *LHS
= Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
llvm::Value *RHS
= Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
const BinaryOperator *expr = cast<BinaryOperator>(op.E);
QualType elementType = expr->getLHS()->getType()->getPointeeType();
llvm::Value *divisor = nullptr;
if (const VariableArrayType *vla
= CGF.getContext().getAsVariableArrayType(elementType)) {
auto VlaSize = CGF.getVLASize(vla);
elementType = VlaSize.Type;
divisor = VlaSize.NumElts;
CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
if (!eltSize.isOne())
divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
} else {
CharUnits elementSize;
if (elementType->isVoidType() || elementType->isFunctionType())
elementSize = CharUnits::One();
else
elementSize = CGF.getContext().getTypeSizeInChars(elementType);
if (elementSize.isOne())
return diffInChars;
divisor = CGF.CGM.getSize(elementSize);
}
return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
}
Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
llvm::IntegerType *Ty;
if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
Ty = cast<llvm::IntegerType>(VT->getElementType());
else
Ty = cast<llvm::IntegerType>(LHS->getType());
return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
}
Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
const Twine &Name) {
llvm::IntegerType *Ty;
if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
Ty = cast<llvm::IntegerType>(VT->getElementType());
else
Ty = cast<llvm::IntegerType>(LHS->getType());
if (llvm::isPowerOf2_64(Ty->getBitWidth()))
return Builder.CreateAnd(RHS, GetWidthMinusOneValue(LHS, RHS), Name);
return Builder.CreateURem(
RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name);
}
Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
if (Ops.isFixedPointOp())
return EmitFixedPointBinOp(Ops);
Value *RHS = Ops.RHS;
if (Ops.LHS->getType() != RHS->getType())
RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
bool SanitizeSignedBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
Ops.Ty->hasSignedIntegerRepresentation() &&
!CGF.getLangOpts().isSignedOverflowDefined() &&
!CGF.getLangOpts().CPlusPlus20;
bool SanitizeUnsignedBase =
CGF.SanOpts.has(SanitizerKind::UnsignedShiftBase) &&
Ops.Ty->hasUnsignedIntegerRepresentation();
bool SanitizeBase = SanitizeSignedBase || SanitizeUnsignedBase;
bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
if (CGF.getLangOpts().OpenCL)
RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask");
else if ((SanitizeBase || SanitizeExponent) &&
isa<llvm::IntegerType>(Ops.LHS->getType())) {
CodeGenFunction::SanitizerScope SanScope(&CGF);
SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
if (SanitizeExponent) {
Checks.push_back(
std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
}
if (SanitizeBase) {
llvm::BasicBlock *Orig = Builder.GetInsertBlock();
llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
llvm::Value *PromotedWidthMinusOne =
(RHS == Ops.RHS) ? WidthMinusOne
: GetWidthMinusOneValue(Ops.LHS, RHS);
CGF.EmitBlock(CheckShiftBase);
llvm::Value *BitsShiftedOff = Builder.CreateLShr(
Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
true, true),
"shl.check");
if (SanitizeUnsignedBase || CGF.getLangOpts().CPlusPlus) {
llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
}
llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
CGF.EmitBlock(Cont);
llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
BaseCheck->addIncoming(Builder.getTrue(), Orig);
BaseCheck->addIncoming(ValidBase, CheckShiftBase);
Checks.push_back(std::make_pair(
BaseCheck, SanitizeSignedBase ? SanitizerKind::ShiftBase
: SanitizerKind::UnsignedShiftBase));
}
assert(!Checks.empty());
EmitBinOpCheck(Checks, Ops);
}
return Builder.CreateShl(Ops.LHS, RHS, "shl");
}
Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
if (Ops.isFixedPointOp())
return EmitFixedPointBinOp(Ops);
Value *RHS = Ops.RHS;
if (Ops.LHS->getType() != RHS->getType())
RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
if (CGF.getLangOpts().OpenCL)
RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask");
else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
isa<llvm::IntegerType>(Ops.LHS->getType())) {
CodeGenFunction::SanitizerScope SanScope(&CGF);
llvm::Value *Valid =
Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
}
if (Ops.Ty->hasUnsignedIntegerRepresentation())
return Builder.CreateLShr(Ops.LHS, RHS, "shr");
return Builder.CreateAShr(Ops.LHS, RHS, "shr");
}
enum IntrinsicType { VCMPEQ, VCMPGT };
static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
BuiltinType::Kind ElemKind) {
switch (ElemKind) {
default: llvm_unreachable("unexpected element type");
case BuiltinType::Char_U:
case BuiltinType::UChar:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
case BuiltinType::Char_S:
case BuiltinType::SChar:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
case BuiltinType::UShort:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
case BuiltinType::Short:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
case BuiltinType::UInt:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
case BuiltinType::Int:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
case BuiltinType::ULong:
case BuiltinType::ULongLong:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
case BuiltinType::Long:
case BuiltinType::LongLong:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
case BuiltinType::Float:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
case BuiltinType::Double:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
case BuiltinType::UInt128:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
: llvm::Intrinsic::ppc_altivec_vcmpgtuq_p;
case BuiltinType::Int128:
return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
: llvm::Intrinsic::ppc_altivec_vcmpgtsq_p;
}
}
Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
llvm::CmpInst::Predicate UICmpOpc,
llvm::CmpInst::Predicate SICmpOpc,
llvm::CmpInst::Predicate FCmpOpc,
bool IsSignaling) {
TestAndClearIgnoreResultAssign();
Value *Result;
QualType LHSTy = E->getLHS()->getType();
QualType RHSTy = E->getRHS()->getType();
if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
assert(E->getOpcode() == BO_EQ ||
E->getOpcode() == BO_NE);
Value *LHS = CGF.EmitScalarExpr(E->getLHS());
Value *RHS = CGF.EmitScalarExpr(E->getRHS());
Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
} else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
BinOpInfo BOInfo = EmitBinOps(E);
Value *LHS = BOInfo.LHS;
Value *RHS = BOInfo.RHS;
if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
Value *FirstVecArg = LHS,
*SecondVecArg = RHS;
QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
switch(E->getOpcode()) {
default: llvm_unreachable("is not a comparison operation");
case BO_EQ:
CR6 = CR6_LT;
ID = GetIntrinsic(VCMPEQ, ElementKind);
break;
case BO_NE:
CR6 = CR6_EQ;
ID = GetIntrinsic(VCMPEQ, ElementKind);
break;
case BO_LT:
CR6 = CR6_LT;
ID = GetIntrinsic(VCMPGT, ElementKind);
std::swap(FirstVecArg, SecondVecArg);
break;
case BO_GT:
CR6 = CR6_LT;
ID = GetIntrinsic(VCMPGT, ElementKind);
break;
case BO_LE:
if (ElementKind == BuiltinType::Float) {
CR6 = CR6_LT;
ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
std::swap(FirstVecArg, SecondVecArg);
}
else {
CR6 = CR6_EQ;
ID = GetIntrinsic(VCMPGT, ElementKind);
}
break;
case BO_GE:
if (ElementKind == BuiltinType::Float) {
CR6 = CR6_LT;
ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
}
else {
CR6 = CR6_EQ;
ID = GetIntrinsic(VCMPGT, ElementKind);
std::swap(FirstVecArg, SecondVecArg);
}
break;
}
Value *CR6Param = Builder.getInt32(CR6);
llvm::Function *F = CGF.CGM.getIntrinsic(ID);
Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
if (ResultTy->getBitWidth() > 1 &&
E->getType() == CGF.getContext().BoolTy)
Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
E->getExprLoc());
}
if (BOInfo.isFixedPointOp()) {
Result = EmitFixedPointBinOp(BOInfo);
} else if (LHS->getType()->isFPOrFPVectorTy()) {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
if (!IsSignaling)
Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
else
Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
} else if (LHSTy->hasSignedIntegerRepresentation()) {
Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
} else {
if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
!isa<llvm::ConstantPointerNull>(LHS) &&
!isa<llvm::ConstantPointerNull>(RHS)) {
if (LHSTy.mayBeDynamicClass())
LHS = Builder.CreateStripInvariantGroup(LHS);
if (RHSTy.mayBeDynamicClass())
RHS = Builder.CreateStripInvariantGroup(RHS);
}
Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
}
if (LHSTy->isVectorType())
return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
} else {
CodeGenFunction::ComplexPairTy LHS, RHS;
QualType CETy;
if (auto *CTy = LHSTy->getAs<ComplexType>()) {
LHS = CGF.EmitComplexExpr(E->getLHS());
CETy = CTy->getElementType();
} else {
LHS.first = Visit(E->getLHS());
LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
CETy = LHSTy;
}
if (auto *CTy = RHSTy->getAs<ComplexType>()) {
RHS = CGF.EmitComplexExpr(E->getRHS());
assert(CGF.getContext().hasSameUnqualifiedType(CETy,
CTy->getElementType()) &&
"The element types must always match.");
(void)CTy;
} else {
RHS.first = Visit(E->getRHS());
RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
"The element types must always match.");
}
Value *ResultR, *ResultI;
if (CETy->isRealFloatingType()) {
ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
} else {
ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
}
if (E->getOpcode() == BO_EQ) {
Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
} else {
assert(E->getOpcode() == BO_NE &&
"Complex comparison other than == or != ?");
Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
}
}
return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
E->getExprLoc());
}
Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
bool Ignore = TestAndClearIgnoreResultAssign();
Value *RHS;
LValue LHS;
switch (E->getLHS()->getType().getObjCLifetime()) {
case Qualifiers::OCL_Strong:
std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
break;
case Qualifiers::OCL_Autoreleasing:
std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
break;
case Qualifiers::OCL_ExplicitNone:
std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
break;
case Qualifiers::OCL_Weak:
RHS = Visit(E->getRHS());
LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore);
break;
case Qualifiers::OCL_None:
RHS = Visit(E->getRHS());
LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
if (LHS.isBitField()) {
CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
} else {
CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
}
}
if (Ignore)
return nullptr;
if (!CGF.getLangOpts().CPlusPlus)
return RHS;
if (!LHS.isVolatileQualified())
return RHS;
return EmitLoadOfLValue(LHS, E->getExprLoc());
}
Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
if (E->getType()->isVectorType()) {
CGF.incrementProfileCounter(E);
Value *LHS = Visit(E->getLHS());
Value *RHS = Visit(E->getRHS());
Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
if (LHS->getType()->isFPOrFPVectorTy()) {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
} else {
LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
}
Value *And = Builder.CreateAnd(LHS, RHS);
return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
}
bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
llvm::Type *ResTy = ConvertType(E->getType());
bool LHSCondVal;
if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
if (LHSCondVal) { CGF.incrementProfileCounter(E);
Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
if (InstrumentRegions &&
CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
llvm::BasicBlock *FBlock = CGF.createBasicBlock("land.end");
llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("land.rhscnt");
Builder.CreateCondBr(RHSCond, RHSBlockCnt, FBlock);
CGF.EmitBlock(RHSBlockCnt);
CGF.incrementProfileCounter(E->getRHS());
CGF.EmitBranch(FBlock);
CGF.EmitBlock(FBlock);
}
return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
}
if (!CGF.ContainsLabel(E->getRHS()))
return llvm::Constant::getNullValue(ResTy);
}
llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
CodeGenFunction::ConditionalEvaluation eval(CGF);
CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
CGF.getProfileCount(E->getRHS()));
llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
"", ContBlock);
for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
PI != PE; ++PI)
PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
eval.begin(CGF);
CGF.EmitBlock(RHSBlock);
CGF.incrementProfileCounter(E);
Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
eval.end(CGF);
RHSBlock = Builder.GetInsertBlock();
if (InstrumentRegions &&
CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("land.rhscnt");
Builder.CreateCondBr(RHSCond, RHSBlockCnt, ContBlock);
CGF.EmitBlock(RHSBlockCnt);
CGF.incrementProfileCounter(E->getRHS());
CGF.EmitBranch(ContBlock);
PN->addIncoming(RHSCond, RHSBlockCnt);
}
{
auto NL = ApplyDebugLocation::CreateEmpty(CGF);
CGF.EmitBlock(ContBlock);
}
PN->addIncoming(RHSCond, RHSBlock);
{
auto NL = ApplyDebugLocation::CreateArtificial(CGF);
PN->setDebugLoc(Builder.getCurrentDebugLocation());
}
return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
}
Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
if (E->getType()->isVectorType()) {
CGF.incrementProfileCounter(E);
Value *LHS = Visit(E->getLHS());
Value *RHS = Visit(E->getRHS());
Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
if (LHS->getType()->isFPOrFPVectorTy()) {
CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
} else {
LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
}
Value *Or = Builder.CreateOr(LHS, RHS);
return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
}
bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
llvm::Type *ResTy = ConvertType(E->getType());
bool LHSCondVal;
if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
if (!LHSCondVal) { CGF.incrementProfileCounter(E);
Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
if (InstrumentRegions &&
CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
llvm::BasicBlock *FBlock = CGF.createBasicBlock("lor.end");
llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("lor.rhscnt");
Builder.CreateCondBr(RHSCond, FBlock, RHSBlockCnt);
CGF.EmitBlock(RHSBlockCnt);
CGF.incrementProfileCounter(E->getRHS());
CGF.EmitBranch(FBlock);
CGF.EmitBlock(FBlock);
}
return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
}
if (!CGF.ContainsLabel(E->getRHS()))
return llvm::ConstantInt::get(ResTy, 1);
}
llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
CodeGenFunction::ConditionalEvaluation eval(CGF);
CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
CGF.getCurrentProfileCount() -
CGF.getProfileCount(E->getRHS()));
llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
"", ContBlock);
for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
PI != PE; ++PI)
PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
eval.begin(CGF);
CGF.EmitBlock(RHSBlock);
CGF.incrementProfileCounter(E);
Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
eval.end(CGF);
RHSBlock = Builder.GetInsertBlock();
if (InstrumentRegions &&
CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("lor.rhscnt");
Builder.CreateCondBr(RHSCond, ContBlock, RHSBlockCnt);
CGF.EmitBlock(RHSBlockCnt);
CGF.incrementProfileCounter(E->getRHS());
CGF.EmitBranch(ContBlock);
PN->addIncoming(RHSCond, RHSBlockCnt);
}
CGF.EmitBlock(ContBlock);
PN->addIncoming(RHSCond, RHSBlock);
return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
}
Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
CGF.EmitIgnoredExpr(E->getLHS());
CGF.EnsureInsertPoint();
return Visit(E->getRHS());
}
static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
CodeGenFunction &CGF) {
return E->IgnoreParens()->isEvaluatable(CGF.getContext());
}
Value *ScalarExprEmitter::
VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
TestAndClearIgnoreResultAssign();
CodeGenFunction::OpaqueValueMapping binding(CGF, E);
Expr *condExpr = E->getCond();
Expr *lhsExpr = E->getTrueExpr();
Expr *rhsExpr = E->getFalseExpr();
bool CondExprBool;
if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
Expr *live = lhsExpr, *dead = rhsExpr;
if (!CondExprBool) std::swap(live, dead);
if (!CGF.ContainsLabel(dead)) {
if (CondExprBool)
CGF.incrementProfileCounter(E);
Value *Result = Visit(live);
if (!Result && !E->getType()->isVoidType())
Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
return Result;
}
}
if ((CGF.getLangOpts().OpenCL && condExpr->getType()->isVectorType()) ||
condExpr->getType()->isExtVectorType()) {
CGF.incrementProfileCounter(E);
llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
llvm::Value *LHS = Visit(lhsExpr);
llvm::Value *RHS = Visit(rhsExpr);
llvm::Type *condType = ConvertType(condExpr->getType());
auto *vecTy = cast<llvm::FixedVectorType>(condType);
unsigned numElem = vecTy->getNumElements();
llvm::Type *elemType = vecTy->getElementType();
llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
llvm::Value *tmp = Builder.CreateSExt(
TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext");
llvm::Value *tmp2 = Builder.CreateNot(tmp);
llvm::Value *RHSTmp = RHS;
llvm::Value *LHSTmp = LHS;
bool wasCast = false;
llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
if (rhsVTy->getElementType()->isFloatingPointTy()) {
RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
wasCast = true;
}
llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
if (wasCast)
tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
return tmp5;
}
if (condExpr->getType()->isVectorType() ||
condExpr->getType()->isVLSTBuiltinType()) {
CGF.incrementProfileCounter(E);
llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
llvm::Value *LHS = Visit(lhsExpr);
llvm::Value *RHS = Visit(rhsExpr);
llvm::Type *CondType = ConvertType(condExpr->getType());
auto *VecTy = cast<llvm::VectorType>(CondType);
llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
}
if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
CGF.incrementProfileCounter(E, StepV);
llvm::Value *LHS = Visit(lhsExpr);
llvm::Value *RHS = Visit(rhsExpr);
if (!LHS) {
assert(!RHS && "LHS and RHS types must match");
return nullptr;
}
return Builder.CreateSelect(CondV, LHS, RHS, "cond");
}
llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
CodeGenFunction::ConditionalEvaluation eval(CGF);
CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
CGF.getProfileCount(lhsExpr));
CGF.EmitBlock(LHSBlock);
CGF.incrementProfileCounter(E);
eval.begin(CGF);
Value *LHS = Visit(lhsExpr);
eval.end(CGF);
LHSBlock = Builder.GetInsertBlock();
Builder.CreateBr(ContBlock);
CGF.EmitBlock(RHSBlock);
eval.begin(CGF);
Value *RHS = Visit(rhsExpr);
eval.end(CGF);
RHSBlock = Builder.GetInsertBlock();
CGF.EmitBlock(ContBlock);
if (!LHS)
return RHS;
if (!RHS)
return LHS;
llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
PN->addIncoming(LHS, LHSBlock);
PN->addIncoming(RHS, RHSBlock);
return PN;
}
Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
return Visit(E->getChosenSubExpr());
}
Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
QualType Ty = VE->getType();
if (Ty->isVariablyModifiedType())
CGF.EmitVariablyModifiedType(Ty);
Address ArgValue = Address::invalid();
Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
llvm::Type *ArgTy = ConvertType(VE->getType());
if (!ArgPtr.isValid()) {
CGF.ErrorUnsupported(VE, "va_arg expression");
return llvm::UndefValue::get(ArgTy);
}
llvm::Value *Val = Builder.CreateLoad(ArgPtr);
if (ArgTy != Val->getType()) {
if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
Val = Builder.CreateIntToPtr(Val, ArgTy);
else
Val = Builder.CreateTrunc(Val, ArgTy);
}
return Val;
}
Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
return CGF.EmitBlockLiteral(block);
}
static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
Value *Src, unsigned NumElementsDst) {
static constexpr int Mask[] = {0, 1, 2, -1};
return Builder.CreateShuffleVector(Src,
llvm::makeArrayRef(Mask, NumElementsDst));
}
static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
const llvm::DataLayout &DL,
Value *Src, llvm::Type *DstTy,
StringRef Name = "") {
auto SrcTy = Src->getType();
if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
return Builder.CreateBitCast(Src, DstTy, Name);
if (SrcTy->isPointerTy() && DstTy->isPointerTy())
return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
if (!DstTy->isIntegerTy())
Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
}
if (!SrcTy->isIntegerTy())
Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
return Builder.CreateIntToPtr(Src, DstTy, Name);
}
Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
llvm::Type *DstTy = ConvertType(E->getType());
llvm::Type *SrcTy = Src->getType();
unsigned NumElementsSrc =
isa<llvm::VectorType>(SrcTy)
? cast<llvm::FixedVectorType>(SrcTy)->getNumElements()
: 0;
unsigned NumElementsDst =
isa<llvm::VectorType>(DstTy)
? cast<llvm::FixedVectorType>(DstTy)->getNumElements()
: 0;
if (E->getType()->isExtVectorBoolType())
return CGF.emitBoolVecConversion(Src, NumElementsDst, "astype");
if (NumElementsSrc == 3 && NumElementsDst != 3) {
Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
DstTy);
Src->setName("astype");
return Src;
}
if (NumElementsSrc != 3 && NumElementsDst == 3) {
auto *Vec4Ty = llvm::FixedVectorType::get(
cast<llvm::VectorType>(DstTy)->getElementType(), 4);
Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
Vec4Ty);
Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
Src->setName("astype");
return Src;
}
return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
Src, DstTy, "astype");
}
Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
return CGF.EmitAtomicExpr(E).getScalarVal();
}
Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
assert(E && hasScalarEvaluationKind(E->getType()) &&
"Invalid scalar expression to emit");
return ScalarExprEmitter(*this, IgnoreResultAssign)
.Visit(const_cast<Expr *>(E));
}
Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
QualType DstTy,
SourceLocation Loc) {
assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
"Invalid scalar expression to emit");
return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
}
Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
QualType SrcTy,
QualType DstTy,
SourceLocation Loc) {
assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
"Invalid complex -> scalar conversion");
return ScalarExprEmitter(*this)
.EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
}
llvm::Value *CodeGenFunction::
EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
bool isInc, bool isPre) {
return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
}
LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
Expr *BaseExpr = E->getBase();
Address Addr = Address::invalid();
if (BaseExpr->isPRValue()) {
llvm::Type *BaseTy =
ConvertTypeForMem(BaseExpr->getType()->getPointeeType());
Addr = Address(EmitScalarExpr(BaseExpr), BaseTy, getPointerAlign());
} else {
Addr = EmitLValue(BaseExpr).getAddress(*this);
}
Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
return MakeAddrLValue(Addr, E->getType());
}
LValue CodeGenFunction::EmitCompoundAssignmentLValue(
const CompoundAssignOperator *E) {
ScalarExprEmitter Scalar(*this);
Value *Result = nullptr;
switch (E->getOpcode()) {
#define COMPOUND_OP(Op) \
case BO_##Op##Assign: \
return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Result)
COMPOUND_OP(Mul);
COMPOUND_OP(Div);
COMPOUND_OP(Rem);
COMPOUND_OP(Add);
COMPOUND_OP(Sub);
COMPOUND_OP(Shl);
COMPOUND_OP(Shr);
COMPOUND_OP(And);
COMPOUND_OP(Xor);
COMPOUND_OP(Or);
#undef COMPOUND_OP
case BO_PtrMemD:
case BO_PtrMemI:
case BO_Mul:
case BO_Div:
case BO_Rem:
case BO_Add:
case BO_Sub:
case BO_Shl:
case BO_Shr:
case BO_LT:
case BO_GT:
case BO_LE:
case BO_GE:
case BO_EQ:
case BO_NE:
case BO_Cmp:
case BO_And:
case BO_Xor:
case BO_Or:
case BO_LAnd:
case BO_LOr:
case BO_Assign:
case BO_Comma:
llvm_unreachable("Not valid compound assignment operators");
}
llvm_unreachable("Unhandled compound assignment operator");
}
struct GEPOffsetAndOverflow {
llvm::Value *TotalOffset;
llvm::Value *OffsetOverflows;
};
static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
llvm::LLVMContext &VMContext,
CodeGenModule &CGM,
CGBuilderTy &Builder) {
const auto &DL = CGM.getDataLayout();
llvm::Value *TotalOffset = nullptr;
if (isa<llvm::Constant>(GEPVal)) {
Value *BasePtr_int =
Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
Value *GEPVal_int =
Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
return {TotalOffset, Builder.getFalse()};
}
auto *GEP = cast<llvm::GEPOperator>(GEPVal);
assert(GEP->getPointerOperand() == BasePtr &&
"BasePtr must be the base of the GEP.");
assert(GEP->isInBounds() && "Expected inbounds GEP");
auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
auto *SAddIntrinsic =
CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
auto *SMulIntrinsic =
CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
llvm::Value *OffsetOverflows = Builder.getFalse();
auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
llvm::Value *RHS) -> llvm::Value * {
assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
llvm::APInt N;
bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
true, N);
if (HasOverflow)
OffsetOverflows = Builder.getTrue();
return llvm::ConstantInt::get(VMContext, N);
}
}
auto *ResultAndOverflow = Builder.CreateCall(
(Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
OffsetOverflows = Builder.CreateOr(
Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
return Builder.CreateExtractValue(ResultAndOverflow, 0);
};
for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
GTI != GTE; ++GTI) {
llvm::Value *LocalOffset;
auto *Index = GTI.getOperand();
if (auto *STy = GTI.getStructTypeOrNull()) {
unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
LocalOffset = llvm::ConstantInt::get(
IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
} else {
auto *ElementSize = llvm::ConstantInt::get(
IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, true);
LocalOffset = eval(BO_Mul, ElementSize, IndexS);
}
if (!TotalOffset || TotalOffset == Zero)
TotalOffset = LocalOffset;
else
TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
}
return {TotalOffset, OffsetOverflows};
}
Value *
CodeGenFunction::EmitCheckedInBoundsGEP(llvm::Type *ElemTy, Value *Ptr,
ArrayRef<Value *> IdxList,
bool SignedIndices, bool IsSubtraction,
SourceLocation Loc, const Twine &Name) {
llvm::Type *PtrTy = Ptr->getType();
Value *GEPVal = Builder.CreateInBoundsGEP(ElemTy, Ptr, IdxList, Name);
if (!SanOpts.has(SanitizerKind::PointerOverflow))
return GEPVal;
bool PerformNullCheck = !NullPointerIsDefined(
Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
bool PerformOverflowCheck =
!isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
if (!(PerformNullCheck || PerformOverflowCheck))
return GEPVal;
const auto &DL = CGM.getDataLayout();
SanitizerScope SanScope(this);
llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
GEPOffsetAndOverflow EvaluatedGEP =
EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
"If the offset got constant-folded, we don't expect that there was an "
"overflow.");
auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
return GEPVal;
auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
if (PerformNullCheck) {
auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
auto *Valid =
CGM.getLangOpts().CPlusPlus
? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
: Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
}
if (PerformOverflowCheck) {
llvm::Value *ValidGEP;
auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
if (SignedIndices) {
auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
auto *PosOrZeroOffset =
Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
ValidGEP =
Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
} else if (!IsSubtraction) {
ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
} else {
ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
}
ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
}
assert(!Checks.empty() && "Should have produced some checks.");
llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
return GEPVal;
}