#include "llvm/Transforms/Scalar/Float2Int.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include <deque>
#define DEBUG_TYPE "float2int"
using namespace llvm;
static cl::opt<unsigned>
MaxIntegerBW("float2int-max-integer-bw", cl::init(64), cl::Hidden,
cl::desc("Max integer bitwidth to consider in float2int"
"(default=64)"));
namespace {
struct Float2IntLegacyPass : public FunctionPass {
static char ID; Float2IntLegacyPass() : FunctionPass(ID) {
initializeFloat2IntLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
const DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
return Impl.runImpl(F, DT);
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
}
private:
Float2IntPass Impl;
};
}
char Float2IntLegacyPass::ID = 0;
INITIALIZE_PASS(Float2IntLegacyPass, "float2int", "Float to int", false, false)
static CmpInst::Predicate mapFCmpPred(CmpInst::Predicate P) {
switch (P) {
case CmpInst::FCMP_OEQ:
case CmpInst::FCMP_UEQ:
return CmpInst::ICMP_EQ;
case CmpInst::FCMP_OGT:
case CmpInst::FCMP_UGT:
return CmpInst::ICMP_SGT;
case CmpInst::FCMP_OGE:
case CmpInst::FCMP_UGE:
return CmpInst::ICMP_SGE;
case CmpInst::FCMP_OLT:
case CmpInst::FCMP_ULT:
return CmpInst::ICMP_SLT;
case CmpInst::FCMP_OLE:
case CmpInst::FCMP_ULE:
return CmpInst::ICMP_SLE;
case CmpInst::FCMP_ONE:
case CmpInst::FCMP_UNE:
return CmpInst::ICMP_NE;
default:
return CmpInst::BAD_ICMP_PREDICATE;
}
}
static Instruction::BinaryOps mapBinOpcode(unsigned Opcode) {
switch (Opcode) {
default: llvm_unreachable("Unhandled opcode!");
case Instruction::FAdd: return Instruction::Add;
case Instruction::FSub: return Instruction::Sub;
case Instruction::FMul: return Instruction::Mul;
}
}
void Float2IntPass::findRoots(Function &F, const DominatorTree &DT) {
for (BasicBlock &BB : F) {
if (!DT.isReachableFromEntry(&BB))
continue;
for (Instruction &I : BB) {
if (isa<VectorType>(I.getType()))
continue;
switch (I.getOpcode()) {
default: break;
case Instruction::FPToUI:
case Instruction::FPToSI:
Roots.insert(&I);
break;
case Instruction::FCmp:
if (mapFCmpPred(cast<CmpInst>(&I)->getPredicate()) !=
CmpInst::BAD_ICMP_PREDICATE)
Roots.insert(&I);
break;
}
}
}
}
void Float2IntPass::seen(Instruction *I, ConstantRange R) {
LLVM_DEBUG(dbgs() << "F2I: " << *I << ":" << R << "\n");
auto IT = SeenInsts.find(I);
if (IT != SeenInsts.end())
IT->second = std::move(R);
else
SeenInsts.insert(std::make_pair(I, std::move(R)));
}
ConstantRange Float2IntPass::badRange() {
return ConstantRange::getFull(MaxIntegerBW + 1);
}
ConstantRange Float2IntPass::unknownRange() {
return ConstantRange::getEmpty(MaxIntegerBW + 1);
}
ConstantRange Float2IntPass::validateRange(ConstantRange R) {
if (R.getBitWidth() > MaxIntegerBW + 1)
return badRange();
return R;
}
void Float2IntPass::walkBackwards() {
std::deque<Instruction*> Worklist(Roots.begin(), Roots.end());
while (!Worklist.empty()) {
Instruction *I = Worklist.back();
Worklist.pop_back();
if (SeenInsts.find(I) != SeenInsts.end())
continue;
switch (I->getOpcode()) {
default:
seen(I, badRange());
break;
case Instruction::UIToFP:
case Instruction::SIToFP: {
unsigned BW = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
auto Input = ConstantRange::getFull(BW);
auto CastOp = (Instruction::CastOps)I->getOpcode();
seen(I, validateRange(Input.castOp(CastOp, MaxIntegerBW+1)));
continue;
}
case Instruction::FNeg:
case Instruction::FAdd:
case Instruction::FSub:
case Instruction::FMul:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::FCmp:
seen(I, unknownRange());
break;
}
for (Value *O : I->operands()) {
if (Instruction *OI = dyn_cast<Instruction>(O)) {
ECs.unionSets(I, OI);
if (SeenInsts.find(I)->second != badRange())
Worklist.push_back(OI);
} else if (!isa<ConstantFP>(O)) {
seen(I, badRange());
}
}
}
}
Optional<ConstantRange> Float2IntPass::calcRange(Instruction *I) {
SmallVector<ConstantRange, 4> OpRanges;
for (Value *O : I->operands()) {
if (Instruction *OI = dyn_cast<Instruction>(O)) {
auto OpIt = SeenInsts.find(OI);
assert(OpIt != SeenInsts.end() && "def not seen before use!");
if (OpIt->second == unknownRange())
return None; OpRanges.push_back(OpIt->second);
} else if (ConstantFP *CF = dyn_cast<ConstantFP>(O)) {
const APFloat &F = CF->getValueAPF();
if (!F.isFinite() ||
(F.isZero() && F.isNegative() && isa<FPMathOperator>(I) &&
!I->hasNoSignedZeros()))
return badRange();
APFloat NewF = F;
auto Res = NewF.roundToIntegral(APFloat::rmNearestTiesToEven);
if (Res != APFloat::opOK || NewF != F)
return badRange();
APSInt Int(MaxIntegerBW+1, false);
bool Exact;
CF->getValueAPF().convertToInteger(Int,
APFloat::rmNearestTiesToEven,
&Exact);
OpRanges.push_back(ConstantRange(Int));
} else {
llvm_unreachable("Should have already marked this as badRange!");
}
}
switch (I->getOpcode()) {
default:
case Instruction::UIToFP:
case Instruction::SIToFP:
llvm_unreachable("Should have been handled in walkForwards!");
case Instruction::FNeg: {
assert(OpRanges.size() == 1 && "FNeg is a unary operator!");
unsigned Size = OpRanges[0].getBitWidth();
auto Zero = ConstantRange(APInt::getZero(Size));
return Zero.sub(OpRanges[0]);
}
case Instruction::FAdd:
case Instruction::FSub:
case Instruction::FMul: {
assert(OpRanges.size() == 2 && "its a binary operator!");
auto BinOp = (Instruction::BinaryOps) I->getOpcode();
return OpRanges[0].binaryOp(BinOp, OpRanges[1]);
}
case Instruction::FPToUI:
case Instruction::FPToSI: {
assert(OpRanges.size() == 1 && "FPTo[US]I is a unary operator!");
auto CastOp = (Instruction::CastOps)I->getOpcode();
return OpRanges[0].castOp(CastOp, MaxIntegerBW+1);
}
case Instruction::FCmp:
assert(OpRanges.size() == 2 && "FCmp is a binary operator!");
return OpRanges[0].unionWith(OpRanges[1]);
}
}
void Float2IntPass::walkForwards() {
std::deque<Instruction *> Worklist;
for (const auto &Pair : SeenInsts)
if (Pair.second == unknownRange())
Worklist.push_back(Pair.first);
while (!Worklist.empty()) {
Instruction *I = Worklist.back();
Worklist.pop_back();
if (Optional<ConstantRange> Range = calcRange(I))
seen(I, *Range);
else
Worklist.push_front(I); }
}
bool Float2IntPass::validateAndTransform() {
bool MadeChange = false;
for (auto It = ECs.begin(), E = ECs.end(); It != E; ++It) {
ConstantRange R(MaxIntegerBW + 1, false);
bool Fail = false;
Type *ConvertedToTy = nullptr;
for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
MI != ME; ++MI) {
Instruction *I = *MI;
auto SeenI = SeenInsts.find(I);
if (SeenI == SeenInsts.end())
continue;
R = R.unionWith(SeenI->second);
if (!Roots.contains(I)) {
if (!ConvertedToTy)
ConvertedToTy = I->getType();
for (User *U : I->users()) {
Instruction *UI = dyn_cast<Instruction>(U);
if (!UI || SeenInsts.find(UI) == SeenInsts.end()) {
LLVM_DEBUG(dbgs() << "F2I: Failing because of " << *U << "\n");
Fail = true;
break;
}
}
}
if (Fail)
break;
}
if (ECs.member_begin(It) == ECs.member_end() || Fail ||
R.isFullSet() || R.isSignWrappedSet())
continue;
assert(ConvertedToTy && "Must have set the convertedtoty by this point!");
unsigned MinBW = std::max(R.getLower().getMinSignedBits(),
R.getUpper().getMinSignedBits()) + 1;
LLVM_DEBUG(dbgs() << "F2I: MinBitwidth=" << MinBW << ", R: " << R << "\n");
unsigned MaxRepresentableBits
= APFloat::semanticsPrecision(ConvertedToTy->getFltSemantics()) - 1;
if (MinBW > MaxRepresentableBits) {
LLVM_DEBUG(dbgs() << "F2I: Value not guaranteed to be representable!\n");
continue;
}
if (MinBW > 64) {
LLVM_DEBUG(
dbgs() << "F2I: Value requires more than 64 bits to represent!\n");
continue;
}
Type *Ty = (MinBW > 32) ? Type::getInt64Ty(*Ctx) : Type::getInt32Ty(*Ctx);
for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
MI != ME; ++MI)
convert(*MI, Ty);
MadeChange = true;
}
return MadeChange;
}
Value *Float2IntPass::convert(Instruction *I, Type *ToTy) {
if (ConvertedInsts.find(I) != ConvertedInsts.end())
return ConvertedInsts[I];
SmallVector<Value*,4> NewOperands;
for (Value *V : I->operands()) {
if (I->getOpcode() == Instruction::UIToFP ||
I->getOpcode() == Instruction::SIToFP) {
NewOperands.push_back(V);
} else if (Instruction *VI = dyn_cast<Instruction>(V)) {
NewOperands.push_back(convert(VI, ToTy));
} else if (ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
APSInt Val(ToTy->getPrimitiveSizeInBits(), false);
bool Exact;
CF->getValueAPF().convertToInteger(Val,
APFloat::rmNearestTiesToEven,
&Exact);
NewOperands.push_back(ConstantInt::get(ToTy, Val));
} else {
llvm_unreachable("Unhandled operand type?");
}
}
IRBuilder<> IRB(I);
Value *NewV = nullptr;
switch (I->getOpcode()) {
default: llvm_unreachable("Unhandled instruction!");
case Instruction::FPToUI:
NewV = IRB.CreateZExtOrTrunc(NewOperands[0], I->getType());
break;
case Instruction::FPToSI:
NewV = IRB.CreateSExtOrTrunc(NewOperands[0], I->getType());
break;
case Instruction::FCmp: {
CmpInst::Predicate P = mapFCmpPred(cast<CmpInst>(I)->getPredicate());
assert(P != CmpInst::BAD_ICMP_PREDICATE && "Unhandled predicate!");
NewV = IRB.CreateICmp(P, NewOperands[0], NewOperands[1], I->getName());
break;
}
case Instruction::UIToFP:
NewV = IRB.CreateZExtOrTrunc(NewOperands[0], ToTy);
break;
case Instruction::SIToFP:
NewV = IRB.CreateSExtOrTrunc(NewOperands[0], ToTy);
break;
case Instruction::FNeg:
NewV = IRB.CreateNeg(NewOperands[0], I->getName());
break;
case Instruction::FAdd:
case Instruction::FSub:
case Instruction::FMul:
NewV = IRB.CreateBinOp(mapBinOpcode(I->getOpcode()),
NewOperands[0], NewOperands[1],
I->getName());
break;
}
if (Roots.count(I))
I->replaceAllUsesWith(NewV);
ConvertedInsts[I] = NewV;
return NewV;
}
void Float2IntPass::cleanup() {
for (auto &I : reverse(ConvertedInsts))
I.first->eraseFromParent();
}
bool Float2IntPass::runImpl(Function &F, const DominatorTree &DT) {
LLVM_DEBUG(dbgs() << "F2I: Looking at function " << F.getName() << "\n");
ECs = EquivalenceClasses<Instruction*>();
SeenInsts.clear();
ConvertedInsts.clear();
Roots.clear();
Ctx = &F.getParent()->getContext();
findRoots(F, DT);
walkBackwards();
walkForwards();
bool Modified = validateAndTransform();
if (Modified)
cleanup();
return Modified;
}
namespace llvm {
FunctionPass *createFloat2IntPass() { return new Float2IntLegacyPass(); }
PreservedAnalyses Float2IntPass::run(Function &F, FunctionAnalysisManager &AM) {
const DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
if (!runImpl(F, DT))
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
return PA;
}
}