1 //===- Float2Int.cpp - Demote floating point ops to work on integers ------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Float2Int pass, which aims to demote floating
10 // point operations to work on integers, where that is losslessly possible.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "float2int"
16 #include "llvm/Transforms/Scalar/Float2Int.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/APSInt.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/GlobalsModRef.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/InstIterator.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Transforms/Scalar.h"
32 #include <functional> // For std::function
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.
39 // Mappable instructions are those with an integer corrollary that, given
40 // integer domain inputs, produce an integer output; fadd, for example.
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.
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"
53 struct Float2IntLegacyPass
: public FunctionPass
{
54 static char ID
; // Pass identification, replacement for typeid
55 Float2IntLegacyPass() : FunctionPass(ID
) {
56 initializeFloat2IntLegacyPassPass(*PassRegistry::getPassRegistry());
59 bool runOnFunction(Function
&F
) override
{
63 return Impl
.runImpl(F
);
66 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
68 AU
.addPreserved
<GlobalsAAWrapperPass
>();
76 char Float2IntLegacyPass::ID
= 0;
77 INITIALIZE_PASS(Float2IntLegacyPass
, "float2int", "Float to int", false, false)
79 // Given a FCmp predicate, return a matching ICmp predicate if one
80 // exists, otherwise return BAD_ICMP_PREDICATE.
81 static CmpInst::Predicate
mapFCmpPred(CmpInst::Predicate P
) {
83 case CmpInst::FCMP_OEQ
:
84 case CmpInst::FCMP_UEQ
:
85 return CmpInst::ICMP_EQ
;
86 case CmpInst::FCMP_OGT
:
87 case CmpInst::FCMP_UGT
:
88 return CmpInst::ICMP_SGT
;
89 case CmpInst::FCMP_OGE
:
90 case CmpInst::FCMP_UGE
:
91 return CmpInst::ICMP_SGE
;
92 case CmpInst::FCMP_OLT
:
93 case CmpInst::FCMP_ULT
:
94 return CmpInst::ICMP_SLT
;
95 case CmpInst::FCMP_OLE
:
96 case CmpInst::FCMP_ULE
:
97 return CmpInst::ICMP_SLE
;
98 case CmpInst::FCMP_ONE
:
99 case CmpInst::FCMP_UNE
:
100 return CmpInst::ICMP_NE
;
102 return CmpInst::BAD_ICMP_PREDICATE
;
106 // Given a floating point binary operator, return the matching
108 static Instruction::BinaryOps
mapBinOpcode(unsigned Opcode
) {
110 default: llvm_unreachable("Unhandled opcode!");
111 case Instruction::FAdd
: return Instruction::Add
;
112 case Instruction::FSub
: return Instruction::Sub
;
113 case Instruction::FMul
: return Instruction::Mul
;
117 // Find the roots - instructions that convert from the FP domain to
119 void Float2IntPass::findRoots(Function
&F
, SmallPtrSet
<Instruction
*,8> &Roots
) {
120 for (auto &I
: instructions(F
)) {
121 if (isa
<VectorType
>(I
.getType()))
123 switch (I
.getOpcode()) {
125 case Instruction::FPToUI
:
126 case Instruction::FPToSI
:
129 case Instruction::FCmp
:
130 if (mapFCmpPred(cast
<CmpInst
>(&I
)->getPredicate()) !=
131 CmpInst::BAD_ICMP_PREDICATE
)
138 // Helper - mark I as having been traversed, having range R.
139 void Float2IntPass::seen(Instruction
*I
, ConstantRange R
) {
140 LLVM_DEBUG(dbgs() << "F2I: " << *I
<< ":" << R
<< "\n");
141 auto IT
= SeenInsts
.find(I
);
142 if (IT
!= SeenInsts
.end())
143 IT
->second
= std::move(R
);
145 SeenInsts
.insert(std::make_pair(I
, std::move(R
)));
148 // Helper - get a range representing a poison value.
149 ConstantRange
Float2IntPass::badRange() {
150 return ConstantRange::getFull(MaxIntegerBW
+ 1);
152 ConstantRange
Float2IntPass::unknownRange() {
153 return ConstantRange::getEmpty(MaxIntegerBW
+ 1);
155 ConstantRange
Float2IntPass::validateRange(ConstantRange R
) {
156 if (R
.getBitWidth() > MaxIntegerBW
+ 1)
161 // The most obvious way to structure the search is a depth-first, eager
162 // search from each root. However, that require direct recursion and so
163 // can only handle small instruction sequences. Instead, we split the search
164 // up into two phases:
165 // - walkBackwards: A breadth-first walk of the use-def graph starting from
166 // the roots. Populate "SeenInsts" with interesting
167 // instructions and poison values if they're obvious and
168 // cheap to compute. Calculate the equivalance set structure
169 // while we're here too.
170 // - walkForwards: Iterate over SeenInsts in reverse order, so we visit
171 // defs before their uses. Calculate the real range info.
173 // Breadth-first walk of the use-def graph; determine the set of nodes
174 // we care about and eagerly determine if some of them are poisonous.
175 void Float2IntPass::walkBackwards(const SmallPtrSetImpl
<Instruction
*> &Roots
) {
176 std::deque
<Instruction
*> Worklist(Roots
.begin(), Roots
.end());
177 while (!Worklist
.empty()) {
178 Instruction
*I
= Worklist
.back();
181 if (SeenInsts
.find(I
) != SeenInsts
.end())
185 switch (I
->getOpcode()) {
186 // FIXME: Handle select and phi nodes.
188 // Path terminated uncleanly.
192 case Instruction::UIToFP
:
193 case Instruction::SIToFP
: {
194 // Path terminated cleanly - use the type of the integer input to seed
196 unsigned BW
= I
->getOperand(0)->getType()->getPrimitiveSizeInBits();
197 auto Input
= ConstantRange::getFull(BW
);
198 auto CastOp
= (Instruction::CastOps
)I
->getOpcode();
199 seen(I
, validateRange(Input
.castOp(CastOp
, MaxIntegerBW
+1)));
203 case Instruction::FNeg
:
204 case Instruction::FAdd
:
205 case Instruction::FSub
:
206 case Instruction::FMul
:
207 case Instruction::FPToUI
:
208 case Instruction::FPToSI
:
209 case Instruction::FCmp
:
210 seen(I
, unknownRange());
214 for (Value
*O
: I
->operands()) {
215 if (Instruction
*OI
= dyn_cast
<Instruction
>(O
)) {
216 // Unify def-use chains if they interfere.
217 ECs
.unionSets(I
, OI
);
218 if (SeenInsts
.find(I
)->second
!= badRange())
219 Worklist
.push_back(OI
);
220 } else if (!isa
<ConstantFP
>(O
)) {
221 // Not an instruction or ConstantFP? we can't do anything.
228 // Walk forwards down the list of seen instructions, so we visit defs before
230 void Float2IntPass::walkForwards() {
231 for (auto &It
: reverse(SeenInsts
)) {
232 if (It
.second
!= unknownRange())
235 Instruction
*I
= It
.first
;
236 std::function
<ConstantRange(ArrayRef
<ConstantRange
>)> Op
;
237 switch (I
->getOpcode()) {
238 // FIXME: Handle select and phi nodes.
240 case Instruction::UIToFP
:
241 case Instruction::SIToFP
:
242 llvm_unreachable("Should have been handled in walkForwards!");
244 case Instruction::FNeg
:
245 Op
= [](ArrayRef
<ConstantRange
> Ops
) {
246 assert(Ops
.size() == 1 && "FNeg is a unary operator!");
247 unsigned Size
= Ops
[0].getBitWidth();
248 auto Zero
= ConstantRange(APInt::getNullValue(Size
));
249 return Zero
.sub(Ops
[0]);
253 case Instruction::FAdd
:
254 case Instruction::FSub
:
255 case Instruction::FMul
:
256 Op
= [I
](ArrayRef
<ConstantRange
> Ops
) {
257 assert(Ops
.size() == 2 && "its a binary operator!");
258 auto BinOp
= (Instruction::BinaryOps
) I
->getOpcode();
259 return Ops
[0].binaryOp(BinOp
, Ops
[1]);
264 // Root-only instructions - we'll only see these if they're the
265 // first node in a walk.
267 case Instruction::FPToUI
:
268 case Instruction::FPToSI
:
269 Op
= [I
](ArrayRef
<ConstantRange
> Ops
) {
270 assert(Ops
.size() == 1 && "FPTo[US]I is a unary operator!");
271 // Note: We're ignoring the casts output size here as that's what the
273 auto CastOp
= (Instruction::CastOps
)I
->getOpcode();
274 return Ops
[0].castOp(CastOp
, MaxIntegerBW
+1);
278 case Instruction::FCmp
:
279 Op
= [](ArrayRef
<ConstantRange
> Ops
) {
280 assert(Ops
.size() == 2 && "FCmp is a binary operator!");
281 return Ops
[0].unionWith(Ops
[1]);
287 SmallVector
<ConstantRange
,4> OpRanges
;
288 for (Value
*O
: I
->operands()) {
289 if (Instruction
*OI
= dyn_cast
<Instruction
>(O
)) {
290 assert(SeenInsts
.find(OI
) != SeenInsts
.end() &&
291 "def not seen before use!");
292 OpRanges
.push_back(SeenInsts
.find(OI
)->second
);
293 } else if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(O
)) {
294 // Work out if the floating point number can be losslessly represented
296 // APFloat::convertToInteger(&Exact) purports to do what we want, but
297 // the exactness can be too precise. For example, negative zero can
298 // never be exactly converted to an integer.
300 // Instead, we ask APFloat to round itself to an integral value - this
301 // preserves sign-of-zero - then compare the result with the original.
303 const APFloat
&F
= CF
->getValueAPF();
305 // First, weed out obviously incorrect values. Non-finite numbers
306 // can't be represented and neither can negative zero, unless
307 // we're in fast math mode.
309 (F
.isZero() && F
.isNegative() && isa
<FPMathOperator
>(I
) &&
310 !I
->hasNoSignedZeros())) {
317 auto Res
= NewF
.roundToIntegral(APFloat::rmNearestTiesToEven
);
318 if (Res
!= APFloat::opOK
|| NewF
.compare(F
) != APFloat::cmpEqual
) {
323 // OK, it's representable. Now get it.
324 APSInt
Int(MaxIntegerBW
+1, false);
326 CF
->getValueAPF().convertToInteger(Int
,
327 APFloat::rmNearestTiesToEven
,
329 OpRanges
.push_back(ConstantRange(Int
));
331 llvm_unreachable("Should have already marked this as badRange!");
335 // Reduce the operands' ranges to a single range and return.
337 seen(I
, Op(OpRanges
));
341 // If there is a valid transform to be done, do it.
342 bool Float2IntPass::validateAndTransform() {
343 bool MadeChange
= false;
345 // Iterate over every disjoint partition of the def-use graph.
346 for (auto It
= ECs
.begin(), E
= ECs
.end(); It
!= E
; ++It
) {
347 ConstantRange
R(MaxIntegerBW
+ 1, false);
349 Type
*ConvertedToTy
= nullptr;
351 // For every member of the partition, union all the ranges together.
352 for (auto MI
= ECs
.member_begin(It
), ME
= ECs
.member_end();
354 Instruction
*I
= *MI
;
355 auto SeenI
= SeenInsts
.find(I
);
356 if (SeenI
== SeenInsts
.end())
359 R
= R
.unionWith(SeenI
->second
);
360 // We need to ensure I has no users that have not been seen.
361 // If it does, transformation would be illegal.
363 // Don't count the roots, as they terminate the graphs.
364 if (Roots
.count(I
) == 0) {
365 // Set the type of the conversion while we're here.
367 ConvertedToTy
= I
->getType();
368 for (User
*U
: I
->users()) {
369 Instruction
*UI
= dyn_cast
<Instruction
>(U
);
370 if (!UI
|| SeenInsts
.find(UI
) == SeenInsts
.end()) {
371 LLVM_DEBUG(dbgs() << "F2I: Failing because of " << *U
<< "\n");
381 // If the set was empty, or we failed, or the range is poisonous,
383 if (ECs
.member_begin(It
) == ECs
.member_end() || Fail
||
384 R
.isFullSet() || R
.isSignWrappedSet())
386 assert(ConvertedToTy
&& "Must have set the convertedtoty by this point!");
388 // The number of bits required is the maximum of the upper and
389 // lower limits, plus one so it can be signed.
390 unsigned MinBW
= std::max(R
.getLower().getMinSignedBits(),
391 R
.getUpper().getMinSignedBits()) + 1;
392 LLVM_DEBUG(dbgs() << "F2I: MinBitwidth=" << MinBW
<< ", R: " << R
<< "\n");
394 // If we've run off the realms of the exactly representable integers,
395 // the floating point result will differ from an integer approximation.
397 // Do we need more bits than are in the mantissa of the type we converted
398 // to? semanticsPrecision returns the number of mantissa bits plus one
400 unsigned MaxRepresentableBits
401 = APFloat::semanticsPrecision(ConvertedToTy
->getFltSemantics()) - 1;
402 if (MinBW
> MaxRepresentableBits
) {
403 LLVM_DEBUG(dbgs() << "F2I: Value not guaranteed to be representable!\n");
408 dbgs() << "F2I: Value requires more than 64 bits to represent!\n");
412 // OK, R is known to be representable. Now pick a type for it.
413 // FIXME: Pick the smallest legal type that will fit.
414 Type
*Ty
= (MinBW
> 32) ? Type::getInt64Ty(*Ctx
) : Type::getInt32Ty(*Ctx
);
416 for (auto MI
= ECs
.member_begin(It
), ME
= ECs
.member_end();
425 Value
*Float2IntPass::convert(Instruction
*I
, Type
*ToTy
) {
426 if (ConvertedInsts
.find(I
) != ConvertedInsts
.end())
427 // Already converted this instruction.
428 return ConvertedInsts
[I
];
430 SmallVector
<Value
*,4> NewOperands
;
431 for (Value
*V
: I
->operands()) {
432 // Don't recurse if we're an instruction that terminates the path.
433 if (I
->getOpcode() == Instruction::UIToFP
||
434 I
->getOpcode() == Instruction::SIToFP
) {
435 NewOperands
.push_back(V
);
436 } else if (Instruction
*VI
= dyn_cast
<Instruction
>(V
)) {
437 NewOperands
.push_back(convert(VI
, ToTy
));
438 } else if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(V
)) {
439 APSInt
Val(ToTy
->getPrimitiveSizeInBits(), /*isUnsigned=*/false);
441 CF
->getValueAPF().convertToInteger(Val
,
442 APFloat::rmNearestTiesToEven
,
444 NewOperands
.push_back(ConstantInt::get(ToTy
, Val
));
446 llvm_unreachable("Unhandled operand type?");
450 // Now create a new instruction.
452 Value
*NewV
= nullptr;
453 switch (I
->getOpcode()) {
454 default: llvm_unreachable("Unhandled instruction!");
456 case Instruction::FPToUI
:
457 NewV
= IRB
.CreateZExtOrTrunc(NewOperands
[0], I
->getType());
460 case Instruction::FPToSI
:
461 NewV
= IRB
.CreateSExtOrTrunc(NewOperands
[0], I
->getType());
464 case Instruction::FCmp
: {
465 CmpInst::Predicate P
= mapFCmpPred(cast
<CmpInst
>(I
)->getPredicate());
466 assert(P
!= CmpInst::BAD_ICMP_PREDICATE
&& "Unhandled predicate!");
467 NewV
= IRB
.CreateICmp(P
, NewOperands
[0], NewOperands
[1], I
->getName());
471 case Instruction::UIToFP
:
472 NewV
= IRB
.CreateZExtOrTrunc(NewOperands
[0], ToTy
);
475 case Instruction::SIToFP
:
476 NewV
= IRB
.CreateSExtOrTrunc(NewOperands
[0], ToTy
);
479 case Instruction::FNeg
:
480 NewV
= IRB
.CreateNeg(NewOperands
[0], I
->getName());
483 case Instruction::FAdd
:
484 case Instruction::FSub
:
485 case Instruction::FMul
:
486 NewV
= IRB
.CreateBinOp(mapBinOpcode(I
->getOpcode()),
487 NewOperands
[0], NewOperands
[1],
492 // If we're a root instruction, RAUW.
494 I
->replaceAllUsesWith(NewV
);
496 ConvertedInsts
[I
] = NewV
;
500 // Perform dead code elimination on the instructions we just modified.
501 void Float2IntPass::cleanup() {
502 for (auto &I
: reverse(ConvertedInsts
))
503 I
.first
->eraseFromParent();
506 bool Float2IntPass::runImpl(Function
&F
) {
507 LLVM_DEBUG(dbgs() << "F2I: Looking at function " << F
.getName() << "\n");
508 // Clear out all state.
509 ECs
= EquivalenceClasses
<Instruction
*>();
511 ConvertedInsts
.clear();
514 Ctx
= &F
.getParent()->getContext();
518 walkBackwards(Roots
);
521 bool Modified
= validateAndTransform();
528 FunctionPass
*createFloat2IntPass() { return new Float2IntLegacyPass(); }
530 PreservedAnalyses
Float2IntPass::run(Function
&F
, FunctionAnalysisManager
&) {
532 return PreservedAnalyses::all();
534 PreservedAnalyses PA
;
535 PA
.preserveSet
<CFGAnalyses
>();
536 PA
.preserve
<GlobalsAA
>();
539 } // End namespace llvm