1 //===- Float2Int.cpp - Demote floating point ops to work on integers ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Float2Int pass, which aims to demote floating
11 // point operations to work on integers, where that is losslessly possible.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "float2int"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/EquivalenceClasses.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/IR/ConstantRange.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/InstIterator.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Transforms/Scalar.h"
34 #include <functional> // For std::function
37 // The algorithm is simple. Start at instructions that convert from the
38 // float to the int domain: fptoui, fptosi and fcmp. Walk up the def-use
39 // graph, using an equivalence datastructure to unify graphs that interfere.
41 // Mappable instructions are those with an integer corrollary that, given
42 // integer domain inputs, produce an integer output; fadd, for example.
44 // If a non-mappable instruction is seen, this entire def-use graph is marked
45 // as non-transformable. If we see an instruction that converts from the
46 // integer domain to FP domain (uitofp,sitofp), we terminate our walk.
48 /// The largest integer type worth dealing with.
49 static cl::opt<unsigned>
50 MaxIntegerBW("float2int-max-integer-bw", cl::init(64), cl::Hidden,
51 cl::desc("Max integer bitwidth to consider in float2int"
55 struct Float2Int : public FunctionPass {
56 static char ID; // Pass identification, replacement for typeid
57 Float2Int() : FunctionPass(ID) {
58 initializeFloat2IntPass(*PassRegistry::getPassRegistry());
61 bool runOnFunction(Function &F) override;
62 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 AU.addPreserved<AliasAnalysis>();
67 void findRoots(Function &F, SmallPtrSet<Instruction*,8> &Roots);
68 ConstantRange seen(Instruction *I, ConstantRange R);
69 ConstantRange badRange();
70 ConstantRange unknownRange();
71 ConstantRange validateRange(ConstantRange R);
72 void walkBackwards(const SmallPtrSetImpl<Instruction*> &Roots);
74 bool validateAndTransform();
75 Value *convert(Instruction *I, Type *ToTy);
78 MapVector<Instruction*, ConstantRange > SeenInsts;
79 SmallPtrSet<Instruction*,8> Roots;
80 EquivalenceClasses<Instruction*> ECs;
81 MapVector<Instruction*, Value*> ConvertedInsts;
86 char Float2Int::ID = 0;
87 INITIALIZE_PASS(Float2Int, "float2int", "Float to int", false, false)
89 // Given a FCmp predicate, return a matching ICmp predicate if one
90 // exists, otherwise return BAD_ICMP_PREDICATE.
91 static CmpInst::Predicate mapFCmpPred(CmpInst::Predicate P) {
93 case CmpInst::FCMP_OEQ:
94 case CmpInst::FCMP_UEQ:
95 return CmpInst::ICMP_EQ;
96 case CmpInst::FCMP_OGT:
97 case CmpInst::FCMP_UGT:
98 return CmpInst::ICMP_SGT;
99 case CmpInst::FCMP_OGE:
100 case CmpInst::FCMP_UGE:
101 return CmpInst::ICMP_SGE;
102 case CmpInst::FCMP_OLT:
103 case CmpInst::FCMP_ULT:
104 return CmpInst::ICMP_SLT;
105 case CmpInst::FCMP_OLE:
106 case CmpInst::FCMP_ULE:
107 return CmpInst::ICMP_SLE;
108 case CmpInst::FCMP_ONE:
109 case CmpInst::FCMP_UNE:
110 return CmpInst::ICMP_NE;
112 return CmpInst::BAD_ICMP_PREDICATE;
116 // Given a floating point binary operator, return the matching
118 static Instruction::BinaryOps mapBinOpcode(unsigned Opcode) {
120 default: llvm_unreachable("Unhandled opcode!");
121 case Instruction::FAdd: return Instruction::Add;
122 case Instruction::FSub: return Instruction::Sub;
123 case Instruction::FMul: return Instruction::Mul;
127 // Find the roots - instructions that convert from the FP domain to
129 void Float2Int::findRoots(Function &F, SmallPtrSet<Instruction*,8> &Roots) {
130 for (auto &I : instructions(F)) {
131 switch (I.getOpcode()) {
133 case Instruction::FPToUI:
134 case Instruction::FPToSI:
137 case Instruction::FCmp:
138 if (mapFCmpPred(cast<CmpInst>(&I)->getPredicate()) !=
139 CmpInst::BAD_ICMP_PREDICATE)
146 // Helper - mark I as having been traversed, having range R.
147 ConstantRange Float2Int::seen(Instruction *I, ConstantRange R) {
148 DEBUG(dbgs() << "F2I: " << *I << ":" << R << "\n");
149 if (SeenInsts.find(I) != SeenInsts.end())
150 SeenInsts.find(I)->second = R;
152 SeenInsts.insert(std::make_pair(I, R));
156 // Helper - get a range representing a poison value.
157 ConstantRange Float2Int::badRange() {
158 return ConstantRange(MaxIntegerBW + 1, true);
160 ConstantRange Float2Int::unknownRange() {
161 return ConstantRange(MaxIntegerBW + 1, false);
163 ConstantRange Float2Int::validateRange(ConstantRange R) {
164 if (R.getBitWidth() > MaxIntegerBW + 1)
169 // The most obvious way to structure the search is a depth-first, eager
170 // search from each root. However, that require direct recursion and so
171 // can only handle small instruction sequences. Instead, we split the search
172 // up into two phases:
173 // - walkBackwards: A breadth-first walk of the use-def graph starting from
174 // the roots. Populate "SeenInsts" with interesting
175 // instructions and poison values if they're obvious and
176 // cheap to compute. Calculate the equivalance set structure
177 // while we're here too.
178 // - walkForwards: Iterate over SeenInsts in reverse order, so we visit
179 // defs before their uses. Calculate the real range info.
181 // Breadth-first walk of the use-def graph; determine the set of nodes
182 // we care about and eagerly determine if some of them are poisonous.
183 void Float2Int::walkBackwards(const SmallPtrSetImpl<Instruction*> &Roots) {
184 std::deque<Instruction*> Worklist(Roots.begin(), Roots.end());
185 while (!Worklist.empty()) {
186 Instruction *I = Worklist.back();
189 if (SeenInsts.find(I) != SeenInsts.end())
193 switch (I->getOpcode()) {
194 // FIXME: Handle select and phi nodes.
196 // Path terminated uncleanly.
200 case Instruction::UIToFP: {
201 // Path terminated cleanly.
202 unsigned BW = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
203 APInt Min = APInt::getMinValue(BW).zextOrSelf(MaxIntegerBW+1);
204 APInt Max = APInt::getMaxValue(BW).zextOrSelf(MaxIntegerBW+1);
205 seen(I, validateRange(ConstantRange(Min, Max)));
209 case Instruction::SIToFP: {
210 // Path terminated cleanly.
211 unsigned BW = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
212 APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(MaxIntegerBW+1);
213 APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(MaxIntegerBW+1);
214 seen(I, validateRange(ConstantRange(SMin, SMax)));
218 case Instruction::FAdd:
219 case Instruction::FSub:
220 case Instruction::FMul:
221 case Instruction::FPToUI:
222 case Instruction::FPToSI:
223 case Instruction::FCmp:
224 seen(I, unknownRange());
228 for (Value *O : I->operands()) {
229 if (Instruction *OI = dyn_cast<Instruction>(O)) {
230 // Unify def-use chains if they interfere.
231 ECs.unionSets(I, OI);
232 if (SeenInsts.find(I)->second != badRange())
233 Worklist.push_back(OI);
234 } else if (!isa<ConstantFP>(O)) {
235 // Not an instruction or ConstantFP? we can't do anything.
242 // Walk forwards down the list of seen instructions, so we visit defs before
244 void Float2Int::walkForwards() {
245 for (auto &It : make_range(SeenInsts.rbegin(), SeenInsts.rend())) {
246 if (It.second != unknownRange())
249 Instruction *I = It.first;
250 std::function<ConstantRange(ArrayRef<ConstantRange>)> Op;
251 switch (I->getOpcode()) {
252 // FIXME: Handle select and phi nodes.
254 case Instruction::UIToFP:
255 case Instruction::SIToFP:
256 llvm_unreachable("Should have been handled in walkForwards!");
258 case Instruction::FAdd:
259 Op = [](ArrayRef<ConstantRange> Ops) {
260 assert(Ops.size() == 2 && "FAdd is a binary operator!");
261 return Ops[0].add(Ops[1]);
265 case Instruction::FSub:
266 Op = [](ArrayRef<ConstantRange> Ops) {
267 assert(Ops.size() == 2 && "FSub is a binary operator!");
268 return Ops[0].sub(Ops[1]);
272 case Instruction::FMul:
273 Op = [](ArrayRef<ConstantRange> Ops) {
274 assert(Ops.size() == 2 && "FMul is a binary operator!");
275 return Ops[0].multiply(Ops[1]);
280 // Root-only instructions - we'll only see these if they're the
281 // first node in a walk.
283 case Instruction::FPToUI:
284 case Instruction::FPToSI:
285 Op = [](ArrayRef<ConstantRange> Ops) {
286 assert(Ops.size() == 1 && "FPTo[US]I is a unary operator!");
291 case Instruction::FCmp:
292 Op = [](ArrayRef<ConstantRange> Ops) {
293 assert(Ops.size() == 2 && "FCmp is a binary operator!");
294 return Ops[0].unionWith(Ops[1]);
300 SmallVector<ConstantRange,4> OpRanges;
301 for (Value *O : I->operands()) {
302 if (Instruction *OI = dyn_cast<Instruction>(O)) {
303 assert(SeenInsts.find(OI) != SeenInsts.end() &&
304 "def not seen before use!");
305 OpRanges.push_back(SeenInsts.find(OI)->second);
306 } else if (ConstantFP *CF = dyn_cast<ConstantFP>(O)) {
307 // Work out if the floating point number can be losslessly represented
309 // APFloat::convertToInteger(&Exact) purports to do what we want, but
310 // the exactness can be too precise. For example, negative zero can
311 // never be exactly converted to an integer.
313 // Instead, we ask APFloat to round itself to an integral value - this
314 // preserves sign-of-zero - then compare the result with the original.
316 APFloat F = CF->getValueAPF();
318 // First, weed out obviously incorrect values. Non-finite numbers
319 // can't be represented and neither can negative zero, unless
320 // we're in fast math mode.
322 (F.isZero() && F.isNegative() && isa<FPMathOperator>(I) &&
323 !I->hasNoSignedZeros())) {
330 auto Res = NewF.roundToIntegral(APFloat::rmNearestTiesToEven);
331 if (Res != APFloat::opOK || NewF.compare(F) != APFloat::cmpEqual) {
336 // OK, it's representable. Now get it.
337 APSInt Int(MaxIntegerBW+1, false);
339 CF->getValueAPF().convertToInteger(Int,
340 APFloat::rmNearestTiesToEven,
342 OpRanges.push_back(ConstantRange(Int));
344 llvm_unreachable("Should have already marked this as badRange!");
348 // Reduce the operands' ranges to a single range and return.
350 seen(I, Op(OpRanges));
354 // If there is a valid transform to be done, do it.
355 bool Float2Int::validateAndTransform() {
356 bool MadeChange = false;
358 // Iterate over every disjoint partition of the def-use graph.
359 for (auto It = ECs.begin(), E = ECs.end(); It != E; ++It) {
360 ConstantRange R(MaxIntegerBW + 1, false);
362 Type *ConvertedToTy = nullptr;
364 // For every member of the partition, union all the ranges together.
365 for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
367 Instruction *I = *MI;
368 auto SeenI = SeenInsts.find(I);
369 if (SeenI == SeenInsts.end())
372 R = R.unionWith(SeenI->second);
373 // We need to ensure I has no users that have not been seen.
374 // If it does, transformation would be illegal.
376 // Don't count the roots, as they terminate the graphs.
377 if (Roots.count(I) == 0) {
378 // Set the type of the conversion while we're here.
380 ConvertedToTy = I->getType();
381 for (User *U : I->users()) {
382 Instruction *UI = dyn_cast<Instruction>(U);
383 if (!UI || SeenInsts.find(UI) == SeenInsts.end()) {
384 DEBUG(dbgs() << "F2I: Failing because of " << *U << "\n");
394 // If the set was empty, or we failed, or the range is poisonous,
396 if (ECs.member_begin(It) == ECs.member_end() || Fail ||
397 R.isFullSet() || R.isSignWrappedSet())
399 assert(ConvertedToTy && "Must have set the convertedtoty by this point!");
401 // The number of bits required is the maximum of the upper and
402 // lower limits, plus one so it can be signed.
403 unsigned MinBW = std::max(R.getLower().getMinSignedBits(),
404 R.getUpper().getMinSignedBits()) + 1;
405 DEBUG(dbgs() << "F2I: MinBitwidth=" << MinBW << ", R: " << R << "\n");
407 // If we've run off the realms of the exactly representable integers,
408 // the floating point result will differ from an integer approximation.
410 // Do we need more bits than are in the mantissa of the type we converted
411 // to? semanticsPrecision returns the number of mantissa bits plus one
413 unsigned MaxRepresentableBits
414 = APFloat::semanticsPrecision(ConvertedToTy->getFltSemantics()) - 1;
415 if (MinBW > MaxRepresentableBits) {
416 DEBUG(dbgs() << "F2I: Value not guaranteed to be representable!\n");
420 DEBUG(dbgs() << "F2I: Value requires more than 64 bits to represent!\n");
424 // OK, R is known to be representable. Now pick a type for it.
425 // FIXME: Pick the smallest legal type that will fit.
426 Type *Ty = (MinBW > 32) ? Type::getInt64Ty(*Ctx) : Type::getInt32Ty(*Ctx);
428 for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
437 Value *Float2Int::convert(Instruction *I, Type *ToTy) {
438 if (ConvertedInsts.find(I) != ConvertedInsts.end())
439 // Already converted this instruction.
440 return ConvertedInsts[I];
442 SmallVector<Value*,4> NewOperands;
443 for (Value *V : I->operands()) {
444 // Don't recurse if we're an instruction that terminates the path.
445 if (I->getOpcode() == Instruction::UIToFP ||
446 I->getOpcode() == Instruction::SIToFP) {
447 NewOperands.push_back(V);
448 } else if (Instruction *VI = dyn_cast<Instruction>(V)) {
449 NewOperands.push_back(convert(VI, ToTy));
450 } else if (ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
451 APSInt Val(ToTy->getPrimitiveSizeInBits(), /*IsUnsigned=*/false);
453 CF->getValueAPF().convertToInteger(Val,
454 APFloat::rmNearestTiesToEven,
456 NewOperands.push_back(ConstantInt::get(ToTy, Val));
458 llvm_unreachable("Unhandled operand type?");
462 // Now create a new instruction.
464 Value *NewV = nullptr;
465 switch (I->getOpcode()) {
466 default: llvm_unreachable("Unhandled instruction!");
468 case Instruction::FPToUI:
469 NewV = IRB.CreateZExtOrTrunc(NewOperands[0], I->getType());
472 case Instruction::FPToSI:
473 NewV = IRB.CreateSExtOrTrunc(NewOperands[0], I->getType());
476 case Instruction::FCmp: {
477 CmpInst::Predicate P = mapFCmpPred(cast<CmpInst>(I)->getPredicate());
478 assert(P != CmpInst::BAD_ICMP_PREDICATE && "Unhandled predicate!");
479 NewV = IRB.CreateICmp(P, NewOperands[0], NewOperands[1], I->getName());
483 case Instruction::UIToFP:
484 NewV = IRB.CreateZExtOrTrunc(NewOperands[0], ToTy);
487 case Instruction::SIToFP:
488 NewV = IRB.CreateSExtOrTrunc(NewOperands[0], ToTy);
491 case Instruction::FAdd:
492 case Instruction::FSub:
493 case Instruction::FMul:
494 NewV = IRB.CreateBinOp(mapBinOpcode(I->getOpcode()),
495 NewOperands[0], NewOperands[1],
500 // If we're a root instruction, RAUW.
502 I->replaceAllUsesWith(NewV);
504 ConvertedInsts[I] = NewV;
508 // Perform dead code elimination on the instructions we just modified.
509 void Float2Int::cleanup() {
510 for (auto &I : make_range(ConvertedInsts.rbegin(), ConvertedInsts.rend()))
511 I.first->eraseFromParent();
514 bool Float2Int::runOnFunction(Function &F) {
515 if (skipOptnoneFunction(F))
518 DEBUG(dbgs() << "F2I: Looking at function " << F.getName() << "\n");
519 // Clear out all state.
520 ECs = EquivalenceClasses<Instruction*>();
522 ConvertedInsts.clear();
525 Ctx = &F.getParent()->getContext();
529 walkBackwards(Roots);
532 bool Modified = validateAndTransform();
538 FunctionPass *llvm::createFloat2IntPass() {
539 return new Float2Int();