Index: include/llvm/Analysis/ConstantFolding.h =================================================================== --- include/llvm/Analysis/ConstantFolding.h +++ include/llvm/Analysis/ConstantFolding.h @@ -55,6 +55,19 @@ const DataLayout &DL, const TargetLibraryInfo *TLI = nullptr); +/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the +/// specified operands. If successful, the constant result is returned, if not, +/// null is returned. Note that this function can fail when attempting to +/// fold instructions like loads and stores, which have no constant expression +/// form. +/// +/// This function doesn't work for compares (use ConstantFoldCompareInstOperands +/// for this) and GEPs. +Constant *ConstantFoldInstOperands(unsigned Opcode, Type *DestTy, + ArrayRef Ops, + const DataLayout &DL, + const TargetLibraryInfo *TLI = nullptr); + /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare /// instruction (icmp/fcmp) with the specified operands. If it fails, it /// returns a constant expression of the specified operands. Index: lib/Analysis/ConstantFolding.cpp =================================================================== --- lib/Analysis/ConstantFolding.cpp +++ lib/Analysis/ConstantFolding.cpp @@ -902,12 +902,11 @@ /// folding using this function strips this information. /// static Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, + Type *DestTy, unsigned Opcode, ArrayRef Ops, const DataLayout &DL, const TargetLibraryInfo *TLI) { - Type *DestTy = InstOrCE->getType(); - // Handle easy binops first. if (Instruction::isBinaryOp(Opcode)) return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL); @@ -1040,7 +1039,8 @@ return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1], DL, TLI); - return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI); + return ConstantFoldInstOperandsImpl(CE, CE->getType(), CE->getOpcode(), Ops, + DL, TLI); } Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE, @@ -1054,7 +1054,16 @@ ArrayRef Ops, const DataLayout &DL, const TargetLibraryInfo *TLI) { - return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI); + return ConstantFoldInstOperandsImpl(I, I->getType(), I->getOpcode(), Ops, DL, + TLI); +} + +Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy, + ArrayRef Ops, + const DataLayout &DL, + const TargetLibraryInfo *TLI) { + assert(Opcode != Instruction::GetElementPtr && "Invalid for GEPs"); + return ConstantFoldInstOperandsImpl(nullptr, DestTy, Opcode, Ops, DL, TLI); } Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,