1 //===- Float2Int.cpp - Demote floating point ops to work on integers ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Float2Int pass, which aims to demote floating
10 // point operations to work on integers, where that is losslessly possible.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/Float2Int.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/InitializePasses.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include <deque>
29 #include <functional> // For std::function
30 
31 #define DEBUG_TYPE "float2int"
32 
33 using namespace llvm;
34 
35 // The algorithm is simple. Start at instructions that convert from the
36 // float to the int domain: fptoui, fptosi and fcmp. Walk up the def-use
37 // graph, using an equivalence datastructure to unify graphs that interfere.
38 //
39 // Mappable instructions are those with an integer corrollary that, given
40 // integer domain inputs, produce an integer output; fadd, for example.
41 //
42 // If a non-mappable instruction is seen, this entire def-use graph is marked
43 // as non-transformable. If we see an instruction that converts from the
44 // integer domain to FP domain (uitofp,sitofp), we terminate our walk.
45 
46 /// The largest integer type worth dealing with.
47 static cl::opt<unsigned>
48 MaxIntegerBW("float2int-max-integer-bw", cl::init(64), cl::Hidden,
49              cl::desc("Max integer bitwidth to consider in float2int"
50                       "(default=64)"));
51 
52 namespace {
53   struct Float2IntLegacyPass : public FunctionPass {
54     static char ID; // Pass identification, replacement for typeid
55     Float2IntLegacyPass() : FunctionPass(ID) {
56       initializeFloat2IntLegacyPassPass(*PassRegistry::getPassRegistry());
57     }
58 
59     bool runOnFunction(Function &F) override {
60       if (skipFunction(F))
61         return false;
62 
63       const DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
64       return Impl.runImpl(F, DT);
65     }
66 
67     void getAnalysisUsage(AnalysisUsage &AU) const override {
68       AU.setPreservesCFG();
69       AU.addRequired<DominatorTreeWrapperPass>();
70       AU.addPreserved<GlobalsAAWrapperPass>();
71     }
72 
73   private:
74     Float2IntPass Impl;
75   };
76 }
77 
78 char Float2IntLegacyPass::ID = 0;
79 INITIALIZE_PASS(Float2IntLegacyPass, "float2int", "Float to int", false, false)
80 
81 // Given a FCmp predicate, return a matching ICmp predicate if one
82 // exists, otherwise return BAD_ICMP_PREDICATE.
83 static CmpInst::Predicate mapFCmpPred(CmpInst::Predicate P) {
84   switch (P) {
85   case CmpInst::FCMP_OEQ:
86   case CmpInst::FCMP_UEQ:
87     return CmpInst::ICMP_EQ;
88   case CmpInst::FCMP_OGT:
89   case CmpInst::FCMP_UGT:
90     return CmpInst::ICMP_SGT;
91   case CmpInst::FCMP_OGE:
92   case CmpInst::FCMP_UGE:
93     return CmpInst::ICMP_SGE;
94   case CmpInst::FCMP_OLT:
95   case CmpInst::FCMP_ULT:
96     return CmpInst::ICMP_SLT;
97   case CmpInst::FCMP_OLE:
98   case CmpInst::FCMP_ULE:
99     return CmpInst::ICMP_SLE;
100   case CmpInst::FCMP_ONE:
101   case CmpInst::FCMP_UNE:
102     return CmpInst::ICMP_NE;
103   default:
104     return CmpInst::BAD_ICMP_PREDICATE;
105   }
106 }
107 
108 // Given a floating point binary operator, return the matching
109 // integer version.
110 static Instruction::BinaryOps mapBinOpcode(unsigned Opcode) {
111   switch (Opcode) {
112   default: llvm_unreachable("Unhandled opcode!");
113   case Instruction::FAdd: return Instruction::Add;
114   case Instruction::FSub: return Instruction::Sub;
115   case Instruction::FMul: return Instruction::Mul;
116   }
117 }
118 
119 // Find the roots - instructions that convert from the FP domain to
120 // integer domain.
121 void Float2IntPass::findRoots(Function &F, const DominatorTree &DT) {
122   for (BasicBlock &BB : F) {
123     // Unreachable code can take on strange forms that we are not prepared to
124     // handle. For example, an instruction may have itself as an operand.
125     if (!DT.isReachableFromEntry(&BB))
126       continue;
127 
128     for (Instruction &I : BB) {
129       if (isa<VectorType>(I.getType()))
130         continue;
131       switch (I.getOpcode()) {
132       default: break;
133       case Instruction::FPToUI:
134       case Instruction::FPToSI:
135         Roots.insert(&I);
136         break;
137       case Instruction::FCmp:
138         if (mapFCmpPred(cast<CmpInst>(&I)->getPredicate()) !=
139             CmpInst::BAD_ICMP_PREDICATE)
140           Roots.insert(&I);
141         break;
142       }
143     }
144   }
145 }
146 
147 // Helper - mark I as having been traversed, having range R.
148 void Float2IntPass::seen(Instruction *I, ConstantRange R) {
149   LLVM_DEBUG(dbgs() << "F2I: " << *I << ":" << R << "\n");
150   auto IT = SeenInsts.find(I);
151   if (IT != SeenInsts.end())
152     IT->second = std::move(R);
153   else
154     SeenInsts.insert(std::make_pair(I, std::move(R)));
155 }
156 
157 // Helper - get a range representing a poison value.
158 ConstantRange Float2IntPass::badRange() {
159   return ConstantRange::getFull(MaxIntegerBW + 1);
160 }
161 ConstantRange Float2IntPass::unknownRange() {
162   return ConstantRange::getEmpty(MaxIntegerBW + 1);
163 }
164 ConstantRange Float2IntPass::validateRange(ConstantRange R) {
165   if (R.getBitWidth() > MaxIntegerBW + 1)
166     return badRange();
167   return R;
168 }
169 
170 // The most obvious way to structure the search is a depth-first, eager
171 // search from each root. However, that require direct recursion and so
172 // can only handle small instruction sequences. Instead, we split the search
173 // up into two phases:
174 //   - walkBackwards:  A breadth-first walk of the use-def graph starting from
175 //                     the roots. Populate "SeenInsts" with interesting
176 //                     instructions and poison values if they're obvious and
177 //                     cheap to compute. Calculate the equivalance set structure
178 //                     while we're here too.
179 //   - walkForwards:  Iterate over SeenInsts in reverse order, so we visit
180 //                     defs before their uses. Calculate the real range info.
181 
182 // Breadth-first walk of the use-def graph; determine the set of nodes
183 // we care about and eagerly determine if some of them are poisonous.
184 void Float2IntPass::walkBackwards() {
185   std::deque<Instruction*> Worklist(Roots.begin(), Roots.end());
186   while (!Worklist.empty()) {
187     Instruction *I = Worklist.back();
188     Worklist.pop_back();
189 
190     if (SeenInsts.find(I) != SeenInsts.end())
191       // Seen already.
192       continue;
193 
194     switch (I->getOpcode()) {
195       // FIXME: Handle select and phi nodes.
196     default:
197       // Path terminated uncleanly.
198       seen(I, badRange());
199       break;
200 
201     case Instruction::UIToFP:
202     case Instruction::SIToFP: {
203       // Path terminated cleanly - use the type of the integer input to seed
204       // the analysis.
205       unsigned BW = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
206       auto Input = ConstantRange::getFull(BW);
207       auto CastOp = (Instruction::CastOps)I->getOpcode();
208       seen(I, validateRange(Input.castOp(CastOp, MaxIntegerBW+1)));
209       continue;
210     }
211 
212     case Instruction::FNeg:
213     case Instruction::FAdd:
214     case Instruction::FSub:
215     case Instruction::FMul:
216     case Instruction::FPToUI:
217     case Instruction::FPToSI:
218     case Instruction::FCmp:
219       seen(I, unknownRange());
220       break;
221     }
222 
223     for (Value *O : I->operands()) {
224       if (Instruction *OI = dyn_cast<Instruction>(O)) {
225         // Unify def-use chains if they interfere.
226         ECs.unionSets(I, OI);
227         if (SeenInsts.find(I)->second != badRange())
228           Worklist.push_back(OI);
229       } else if (!isa<ConstantFP>(O)) {
230         // Not an instruction or ConstantFP? we can't do anything.
231         seen(I, badRange());
232       }
233     }
234   }
235 }
236 
237 // Walk forwards down the list of seen instructions, so we visit defs before
238 // uses.
239 void Float2IntPass::walkForwards() {
240   for (auto &It : reverse(SeenInsts)) {
241     if (It.second != unknownRange())
242       continue;
243 
244     Instruction *I = It.first;
245     std::function<ConstantRange(ArrayRef<ConstantRange>)> Op;
246     switch (I->getOpcode()) {
247       // FIXME: Handle select and phi nodes.
248     default:
249     case Instruction::UIToFP:
250     case Instruction::SIToFP:
251       llvm_unreachable("Should have been handled in walkForwards!");
252 
253     case Instruction::FNeg:
254       Op = [](ArrayRef<ConstantRange> Ops) {
255         assert(Ops.size() == 1 && "FNeg is a unary operator!");
256         unsigned Size = Ops[0].getBitWidth();
257         auto Zero = ConstantRange(APInt::getZero(Size));
258         return Zero.sub(Ops[0]);
259       };
260       break;
261 
262     case Instruction::FAdd:
263     case Instruction::FSub:
264     case Instruction::FMul:
265       Op = [I](ArrayRef<ConstantRange> Ops) {
266         assert(Ops.size() == 2 && "its a binary operator!");
267         auto BinOp = (Instruction::BinaryOps) I->getOpcode();
268         return Ops[0].binaryOp(BinOp, Ops[1]);
269       };
270       break;
271 
272     //
273     // Root-only instructions - we'll only see these if they're the
274     //                          first node in a walk.
275     //
276     case Instruction::FPToUI:
277     case Instruction::FPToSI:
278       Op = [I](ArrayRef<ConstantRange> Ops) {
279         assert(Ops.size() == 1 && "FPTo[US]I is a unary operator!");
280         // Note: We're ignoring the casts output size here as that's what the
281         // caller expects.
282         auto CastOp = (Instruction::CastOps)I->getOpcode();
283         return Ops[0].castOp(CastOp, MaxIntegerBW+1);
284       };
285       break;
286 
287     case Instruction::FCmp:
288       Op = [](ArrayRef<ConstantRange> Ops) {
289         assert(Ops.size() == 2 && "FCmp is a binary operator!");
290         return Ops[0].unionWith(Ops[1]);
291       };
292       break;
293     }
294 
295     bool Abort = false;
296     SmallVector<ConstantRange,4> OpRanges;
297     for (Value *O : I->operands()) {
298       if (Instruction *OI = dyn_cast<Instruction>(O)) {
299         assert(SeenInsts.find(OI) != SeenInsts.end() &&
300                "def not seen before use!");
301         OpRanges.push_back(SeenInsts.find(OI)->second);
302       } else if (ConstantFP *CF = dyn_cast<ConstantFP>(O)) {
303         // Work out if the floating point number can be losslessly represented
304         // as an integer.
305         // APFloat::convertToInteger(&Exact) purports to do what we want, but
306         // the exactness can be too precise. For example, negative zero can
307         // never be exactly converted to an integer.
308         //
309         // Instead, we ask APFloat to round itself to an integral value - this
310         // preserves sign-of-zero - then compare the result with the original.
311         //
312         const APFloat &F = CF->getValueAPF();
313 
314         // First, weed out obviously incorrect values. Non-finite numbers
315         // can't be represented and neither can negative zero, unless
316         // we're in fast math mode.
317         if (!F.isFinite() ||
318             (F.isZero() && F.isNegative() && isa<FPMathOperator>(I) &&
319              !I->hasNoSignedZeros())) {
320           seen(I, badRange());
321           Abort = true;
322           break;
323         }
324 
325         APFloat NewF = F;
326         auto Res = NewF.roundToIntegral(APFloat::rmNearestTiesToEven);
327         if (Res != APFloat::opOK || NewF != F) {
328           seen(I, badRange());
329           Abort = true;
330           break;
331         }
332         // OK, it's representable. Now get it.
333         APSInt Int(MaxIntegerBW+1, false);
334         bool Exact;
335         CF->getValueAPF().convertToInteger(Int,
336                                            APFloat::rmNearestTiesToEven,
337                                            &Exact);
338         OpRanges.push_back(ConstantRange(Int));
339       } else {
340         llvm_unreachable("Should have already marked this as badRange!");
341       }
342     }
343 
344     // Reduce the operands' ranges to a single range and return.
345     if (!Abort)
346       seen(I, Op(OpRanges));
347   }
348 }
349 
350 // If there is a valid transform to be done, do it.
351 bool Float2IntPass::validateAndTransform() {
352   bool MadeChange = false;
353 
354   // Iterate over every disjoint partition of the def-use graph.
355   for (auto It = ECs.begin(), E = ECs.end(); It != E; ++It) {
356     ConstantRange R(MaxIntegerBW + 1, false);
357     bool Fail = false;
358     Type *ConvertedToTy = nullptr;
359 
360     // For every member of the partition, union all the ranges together.
361     for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
362          MI != ME; ++MI) {
363       Instruction *I = *MI;
364       auto SeenI = SeenInsts.find(I);
365       if (SeenI == SeenInsts.end())
366         continue;
367 
368       R = R.unionWith(SeenI->second);
369       // We need to ensure I has no users that have not been seen.
370       // If it does, transformation would be illegal.
371       //
372       // Don't count the roots, as they terminate the graphs.
373       if (!Roots.contains(I)) {
374         // Set the type of the conversion while we're here.
375         if (!ConvertedToTy)
376           ConvertedToTy = I->getType();
377         for (User *U : I->users()) {
378           Instruction *UI = dyn_cast<Instruction>(U);
379           if (!UI || SeenInsts.find(UI) == SeenInsts.end()) {
380             LLVM_DEBUG(dbgs() << "F2I: Failing because of " << *U << "\n");
381             Fail = true;
382             break;
383           }
384         }
385       }
386       if (Fail)
387         break;
388     }
389 
390     // If the set was empty, or we failed, or the range is poisonous,
391     // bail out.
392     if (ECs.member_begin(It) == ECs.member_end() || Fail ||
393         R.isFullSet() || R.isSignWrappedSet())
394       continue;
395     assert(ConvertedToTy && "Must have set the convertedtoty by this point!");
396 
397     // The number of bits required is the maximum of the upper and
398     // lower limits, plus one so it can be signed.
399     unsigned MinBW = std::max(R.getLower().getMinSignedBits(),
400                               R.getUpper().getMinSignedBits()) + 1;
401     LLVM_DEBUG(dbgs() << "F2I: MinBitwidth=" << MinBW << ", R: " << R << "\n");
402 
403     // If we've run off the realms of the exactly representable integers,
404     // the floating point result will differ from an integer approximation.
405 
406     // Do we need more bits than are in the mantissa of the type we converted
407     // to? semanticsPrecision returns the number of mantissa bits plus one
408     // for the sign bit.
409     unsigned MaxRepresentableBits
410       = APFloat::semanticsPrecision(ConvertedToTy->getFltSemantics()) - 1;
411     if (MinBW > MaxRepresentableBits) {
412       LLVM_DEBUG(dbgs() << "F2I: Value not guaranteed to be representable!\n");
413       continue;
414     }
415     if (MinBW > 64) {
416       LLVM_DEBUG(
417           dbgs() << "F2I: Value requires more than 64 bits to represent!\n");
418       continue;
419     }
420 
421     // OK, R is known to be representable. Now pick a type for it.
422     // FIXME: Pick the smallest legal type that will fit.
423     Type *Ty = (MinBW > 32) ? Type::getInt64Ty(*Ctx) : Type::getInt32Ty(*Ctx);
424 
425     for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
426          MI != ME; ++MI)
427       convert(*MI, Ty);
428     MadeChange = true;
429   }
430 
431   return MadeChange;
432 }
433 
434 Value *Float2IntPass::convert(Instruction *I, Type *ToTy) {
435   if (ConvertedInsts.find(I) != ConvertedInsts.end())
436     // Already converted this instruction.
437     return ConvertedInsts[I];
438 
439   SmallVector<Value*,4> NewOperands;
440   for (Value *V : I->operands()) {
441     // Don't recurse if we're an instruction that terminates the path.
442     if (I->getOpcode() == Instruction::UIToFP ||
443         I->getOpcode() == Instruction::SIToFP) {
444       NewOperands.push_back(V);
445     } else if (Instruction *VI = dyn_cast<Instruction>(V)) {
446       NewOperands.push_back(convert(VI, ToTy));
447     } else if (ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
448       APSInt Val(ToTy->getPrimitiveSizeInBits(), /*isUnsigned=*/false);
449       bool Exact;
450       CF->getValueAPF().convertToInteger(Val,
451                                          APFloat::rmNearestTiesToEven,
452                                          &Exact);
453       NewOperands.push_back(ConstantInt::get(ToTy, Val));
454     } else {
455       llvm_unreachable("Unhandled operand type?");
456     }
457   }
458 
459   // Now create a new instruction.
460   IRBuilder<> IRB(I);
461   Value *NewV = nullptr;
462   switch (I->getOpcode()) {
463   default: llvm_unreachable("Unhandled instruction!");
464 
465   case Instruction::FPToUI:
466     NewV = IRB.CreateZExtOrTrunc(NewOperands[0], I->getType());
467     break;
468 
469   case Instruction::FPToSI:
470     NewV = IRB.CreateSExtOrTrunc(NewOperands[0], I->getType());
471     break;
472 
473   case Instruction::FCmp: {
474     CmpInst::Predicate P = mapFCmpPred(cast<CmpInst>(I)->getPredicate());
475     assert(P != CmpInst::BAD_ICMP_PREDICATE && "Unhandled predicate!");
476     NewV = IRB.CreateICmp(P, NewOperands[0], NewOperands[1], I->getName());
477     break;
478   }
479 
480   case Instruction::UIToFP:
481     NewV = IRB.CreateZExtOrTrunc(NewOperands[0], ToTy);
482     break;
483 
484   case Instruction::SIToFP:
485     NewV = IRB.CreateSExtOrTrunc(NewOperands[0], ToTy);
486     break;
487 
488   case Instruction::FNeg:
489     NewV = IRB.CreateNeg(NewOperands[0], I->getName());
490     break;
491 
492   case Instruction::FAdd:
493   case Instruction::FSub:
494   case Instruction::FMul:
495     NewV = IRB.CreateBinOp(mapBinOpcode(I->getOpcode()),
496                            NewOperands[0], NewOperands[1],
497                            I->getName());
498     break;
499   }
500 
501   // If we're a root instruction, RAUW.
502   if (Roots.count(I))
503     I->replaceAllUsesWith(NewV);
504 
505   ConvertedInsts[I] = NewV;
506   return NewV;
507 }
508 
509 // Perform dead code elimination on the instructions we just modified.
510 void Float2IntPass::cleanup() {
511   for (auto &I : reverse(ConvertedInsts))
512     I.first->eraseFromParent();
513 }
514 
515 bool Float2IntPass::runImpl(Function &F, const DominatorTree &DT) {
516   LLVM_DEBUG(dbgs() << "F2I: Looking at function " << F.getName() << "\n");
517   // Clear out all state.
518   ECs = EquivalenceClasses<Instruction*>();
519   SeenInsts.clear();
520   ConvertedInsts.clear();
521   Roots.clear();
522 
523   Ctx = &F.getParent()->getContext();
524 
525   findRoots(F, DT);
526 
527   walkBackwards();
528   walkForwards();
529 
530   bool Modified = validateAndTransform();
531   if (Modified)
532     cleanup();
533   return Modified;
534 }
535 
536 namespace llvm {
537 FunctionPass *createFloat2IntPass() { return new Float2IntLegacyPass(); }
538 
539 PreservedAnalyses Float2IntPass::run(Function &F, FunctionAnalysisManager &AM) {
540   const DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
541   if (!runImpl(F, DT))
542     return PreservedAnalyses::all();
543 
544   PreservedAnalyses PA;
545   PA.preserveSet<CFGAnalyses>();
546   return PA;
547 }
548 } // End namespace llvm
549