LLVM 19.0.0git
Float2Int.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/APSInt.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/Dominators.h"
21#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/Module.h"
24#include "llvm/Support/Debug.h"
26#include <deque>
27
28#define DEBUG_TYPE "float2int"
29
30using namespace llvm;
31
32// The algorithm is simple. Start at instructions that convert from the
33// float to the int domain: fptoui, fptosi and fcmp. Walk up the def-use
34// graph, using an equivalence datastructure to unify graphs that interfere.
35//
36// Mappable instructions are those with an integer corrollary that, given
37// integer domain inputs, produce an integer output; fadd, for example.
38//
39// If a non-mappable instruction is seen, this entire def-use graph is marked
40// as non-transformable. If we see an instruction that converts from the
41// integer domain to FP domain (uitofp,sitofp), we terminate our walk.
42
43/// The largest integer type worth dealing with.
45MaxIntegerBW("float2int-max-integer-bw", cl::init(64), cl::Hidden,
46 cl::desc("Max integer bitwidth to consider in float2int"
47 "(default=64)"));
48
49// Given a FCmp predicate, return a matching ICmp predicate if one
50// exists, otherwise return BAD_ICMP_PREDICATE.
52 switch (P) {
55 return CmpInst::ICMP_EQ;
58 return CmpInst::ICMP_SGT;
61 return CmpInst::ICMP_SGE;
64 return CmpInst::ICMP_SLT;
67 return CmpInst::ICMP_SLE;
70 return CmpInst::ICMP_NE;
71 default:
73 }
74}
75
76// Given a floating point binary operator, return the matching
77// integer version.
78static Instruction::BinaryOps mapBinOpcode(unsigned Opcode) {
79 switch (Opcode) {
80 default: llvm_unreachable("Unhandled opcode!");
81 case Instruction::FAdd: return Instruction::Add;
82 case Instruction::FSub: return Instruction::Sub;
83 case Instruction::FMul: return Instruction::Mul;
84 }
85}
86
87// Find the roots - instructions that convert from the FP domain to
88// integer domain.
89void Float2IntPass::findRoots(Function &F, const DominatorTree &DT) {
90 for (BasicBlock &BB : F) {
91 // Unreachable code can take on strange forms that we are not prepared to
92 // handle. For example, an instruction may have itself as an operand.
93 if (!DT.isReachableFromEntry(&BB))
94 continue;
95
96 for (Instruction &I : BB) {
97 if (isa<VectorType>(I.getType()))
98 continue;
99 switch (I.getOpcode()) {
100 default: break;
101 case Instruction::FPToUI:
102 case Instruction::FPToSI:
103 Roots.insert(&I);
104 break;
105 case Instruction::FCmp:
106 if (mapFCmpPred(cast<CmpInst>(&I)->getPredicate()) !=
108 Roots.insert(&I);
109 break;
110 }
111 }
112 }
113}
114
115// Helper - mark I as having been traversed, having range R.
116void Float2IntPass::seen(Instruction *I, ConstantRange R) {
117 LLVM_DEBUG(dbgs() << "F2I: " << *I << ":" << R << "\n");
118 auto IT = SeenInsts.find(I);
119 if (IT != SeenInsts.end())
120 IT->second = std::move(R);
121 else
122 SeenInsts.insert(std::make_pair(I, std::move(R)));
123}
124
125// Helper - get a range representing a poison value.
126ConstantRange Float2IntPass::badRange() {
127 return ConstantRange::getFull(MaxIntegerBW + 1);
128}
129ConstantRange Float2IntPass::unknownRange() {
130 return ConstantRange::getEmpty(MaxIntegerBW + 1);
131}
132ConstantRange Float2IntPass::validateRange(ConstantRange R) {
133 if (R.getBitWidth() > MaxIntegerBW + 1)
134 return badRange();
135 return R;
136}
137
138// The most obvious way to structure the search is a depth-first, eager
139// search from each root. However, that require direct recursion and so
140// can only handle small instruction sequences. Instead, we split the search
141// up into two phases:
142// - walkBackwards: A breadth-first walk of the use-def graph starting from
143// the roots. Populate "SeenInsts" with interesting
144// instructions and poison values if they're obvious and
145// cheap to compute. Calculate the equivalance set structure
146// while we're here too.
147// - walkForwards: Iterate over SeenInsts in reverse order, so we visit
148// defs before their uses. Calculate the real range info.
149
150// Breadth-first walk of the use-def graph; determine the set of nodes
151// we care about and eagerly determine if some of them are poisonous.
152void Float2IntPass::walkBackwards() {
153 std::deque<Instruction*> Worklist(Roots.begin(), Roots.end());
154 while (!Worklist.empty()) {
155 Instruction *I = Worklist.back();
156 Worklist.pop_back();
157
158 if (SeenInsts.contains(I))
159 // Seen already.
160 continue;
161
162 switch (I->getOpcode()) {
163 // FIXME: Handle select and phi nodes.
164 default:
165 // Path terminated uncleanly.
166 seen(I, badRange());
167 break;
168
169 case Instruction::UIToFP:
170 case Instruction::SIToFP: {
171 // Path terminated cleanly - use the type of the integer input to seed
172 // the analysis.
173 unsigned BW = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
174 auto Input = ConstantRange::getFull(BW);
175 auto CastOp = (Instruction::CastOps)I->getOpcode();
176 seen(I, validateRange(Input.castOp(CastOp, MaxIntegerBW+1)));
177 continue;
178 }
179
180 case Instruction::FNeg:
181 case Instruction::FAdd:
182 case Instruction::FSub:
183 case Instruction::FMul:
184 case Instruction::FPToUI:
185 case Instruction::FPToSI:
186 case Instruction::FCmp:
187 seen(I, unknownRange());
188 break;
189 }
190
191 for (Value *O : I->operands()) {
192 if (Instruction *OI = dyn_cast<Instruction>(O)) {
193 // Unify def-use chains if they interfere.
194 ECs.unionSets(I, OI);
195 if (SeenInsts.find(I)->second != badRange())
196 Worklist.push_back(OI);
197 } else if (!isa<ConstantFP>(O)) {
198 // Not an instruction or ConstantFP? we can't do anything.
199 seen(I, badRange());
200 }
201 }
202 }
203}
204
205// Calculate result range from operand ranges.
206// Return std::nullopt if the range cannot be calculated yet.
207std::optional<ConstantRange> Float2IntPass::calcRange(Instruction *I) {
209 for (Value *O : I->operands()) {
210 if (Instruction *OI = dyn_cast<Instruction>(O)) {
211 auto OpIt = SeenInsts.find(OI);
212 assert(OpIt != SeenInsts.end() && "def not seen before use!");
213 if (OpIt->second == unknownRange())
214 return std::nullopt; // Wait until operand range has been calculated.
215 OpRanges.push_back(OpIt->second);
216 } else if (ConstantFP *CF = dyn_cast<ConstantFP>(O)) {
217 // Work out if the floating point number can be losslessly represented
218 // as an integer.
219 // APFloat::convertToInteger(&Exact) purports to do what we want, but
220 // the exactness can be too precise. For example, negative zero can
221 // never be exactly converted to an integer.
222 //
223 // Instead, we ask APFloat to round itself to an integral value - this
224 // preserves sign-of-zero - then compare the result with the original.
225 //
226 const APFloat &F = CF->getValueAPF();
227
228 // First, weed out obviously incorrect values. Non-finite numbers
229 // can't be represented and neither can negative zero, unless
230 // we're in fast math mode.
231 if (!F.isFinite() ||
232 (F.isZero() && F.isNegative() && isa<FPMathOperator>(I) &&
233 !I->hasNoSignedZeros()))
234 return badRange();
235
236 APFloat NewF = F;
238 if (Res != APFloat::opOK || NewF != F)
239 return badRange();
240
241 // OK, it's representable. Now get it.
242 APSInt Int(MaxIntegerBW+1, false);
243 bool Exact;
244 CF->getValueAPF().convertToInteger(Int,
246 &Exact);
247 OpRanges.push_back(ConstantRange(Int));
248 } else {
249 llvm_unreachable("Should have already marked this as badRange!");
250 }
251 }
252
253 switch (I->getOpcode()) {
254 // FIXME: Handle select and phi nodes.
255 default:
256 case Instruction::UIToFP:
257 case Instruction::SIToFP:
258 llvm_unreachable("Should have been handled in walkForwards!");
259
260 case Instruction::FNeg: {
261 assert(OpRanges.size() == 1 && "FNeg is a unary operator!");
262 unsigned Size = OpRanges[0].getBitWidth();
264 return Zero.sub(OpRanges[0]);
265 }
266
267 case Instruction::FAdd:
268 case Instruction::FSub:
269 case Instruction::FMul: {
270 assert(OpRanges.size() == 2 && "its a binary operator!");
271 auto BinOp = (Instruction::BinaryOps) I->getOpcode();
272 return OpRanges[0].binaryOp(BinOp, OpRanges[1]);
273 }
274
275 //
276 // Root-only instructions - we'll only see these if they're the
277 // first node in a walk.
278 //
279 case Instruction::FPToUI:
280 case Instruction::FPToSI: {
281 assert(OpRanges.size() == 1 && "FPTo[US]I is a unary operator!");
282 // Note: We're ignoring the casts output size here as that's what the
283 // caller expects.
284 auto CastOp = (Instruction::CastOps)I->getOpcode();
285 return OpRanges[0].castOp(CastOp, MaxIntegerBW+1);
286 }
287
288 case Instruction::FCmp:
289 assert(OpRanges.size() == 2 && "FCmp is a binary operator!");
290 return OpRanges[0].unionWith(OpRanges[1]);
291 }
292}
293
294// Walk forwards down the list of seen instructions, so we visit defs before
295// uses.
296void Float2IntPass::walkForwards() {
297 std::deque<Instruction *> Worklist;
298 for (const auto &Pair : SeenInsts)
299 if (Pair.second == unknownRange())
300 Worklist.push_back(Pair.first);
301
302 while (!Worklist.empty()) {
303 Instruction *I = Worklist.back();
304 Worklist.pop_back();
305
306 if (std::optional<ConstantRange> Range = calcRange(I))
307 seen(I, *Range);
308 else
309 Worklist.push_front(I); // Reprocess later.
310 }
311}
312
313// If there is a valid transform to be done, do it.
314bool Float2IntPass::validateAndTransform() {
315 bool MadeChange = false;
316
317 // Iterate over every disjoint partition of the def-use graph.
318 for (auto It = ECs.begin(), E = ECs.end(); It != E; ++It) {
319 ConstantRange R(MaxIntegerBW + 1, false);
320 bool Fail = false;
321 Type *ConvertedToTy = nullptr;
322
323 // For every member of the partition, union all the ranges together.
324 for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
325 MI != ME; ++MI) {
326 Instruction *I = *MI;
327 auto SeenI = SeenInsts.find(I);
328 if (SeenI == SeenInsts.end())
329 continue;
330
331 R = R.unionWith(SeenI->second);
332 // We need to ensure I has no users that have not been seen.
333 // If it does, transformation would be illegal.
334 //
335 // Don't count the roots, as they terminate the graphs.
336 if (!Roots.contains(I)) {
337 // Set the type of the conversion while we're here.
338 if (!ConvertedToTy)
339 ConvertedToTy = I->getType();
340 for (User *U : I->users()) {
341 Instruction *UI = dyn_cast<Instruction>(U);
342 if (!UI || !SeenInsts.contains(UI)) {
343 LLVM_DEBUG(dbgs() << "F2I: Failing because of " << *U << "\n");
344 Fail = true;
345 break;
346 }
347 }
348 }
349 if (Fail)
350 break;
351 }
352
353 // If the set was empty, or we failed, or the range is poisonous,
354 // bail out.
355 if (ECs.member_begin(It) == ECs.member_end() || Fail ||
356 R.isFullSet() || R.isSignWrappedSet())
357 continue;
358 assert(ConvertedToTy && "Must have set the convertedtoty by this point!");
359
360 // The number of bits required is the maximum of the upper and
361 // lower limits, plus one so it can be signed.
362 unsigned MinBW = std::max(R.getLower().getSignificantBits(),
363 R.getUpper().getSignificantBits()) +
364 1;
365 LLVM_DEBUG(dbgs() << "F2I: MinBitwidth=" << MinBW << ", R: " << R << "\n");
366
367 // If we've run off the realms of the exactly representable integers,
368 // the floating point result will differ from an integer approximation.
369
370 // Do we need more bits than are in the mantissa of the type we converted
371 // to? semanticsPrecision returns the number of mantissa bits plus one
372 // for the sign bit.
373 unsigned MaxRepresentableBits
374 = APFloat::semanticsPrecision(ConvertedToTy->getFltSemantics()) - 1;
375 if (MinBW > MaxRepresentableBits) {
376 LLVM_DEBUG(dbgs() << "F2I: Value not guaranteed to be representable!\n");
377 continue;
378 }
379 if (MinBW > 64) {
381 dbgs() << "F2I: Value requires more than 64 bits to represent!\n");
382 continue;
383 }
384
385 // OK, R is known to be representable. Now pick a type for it.
386 // FIXME: Pick the smallest legal type that will fit.
387 Type *Ty = (MinBW > 32) ? Type::getInt64Ty(*Ctx) : Type::getInt32Ty(*Ctx);
388
389 for (auto MI = ECs.member_begin(It), ME = ECs.member_end();
390 MI != ME; ++MI)
391 convert(*MI, Ty);
392 MadeChange = true;
393 }
394
395 return MadeChange;
396}
397
398Value *Float2IntPass::convert(Instruction *I, Type *ToTy) {
399 if (ConvertedInsts.contains(I))
400 // Already converted this instruction.
401 return ConvertedInsts[I];
402
403 SmallVector<Value*,4> NewOperands;
404 for (Value *V : I->operands()) {
405 // Don't recurse if we're an instruction that terminates the path.
406 if (I->getOpcode() == Instruction::UIToFP ||
407 I->getOpcode() == Instruction::SIToFP) {
408 NewOperands.push_back(V);
409 } else if (Instruction *VI = dyn_cast<Instruction>(V)) {
410 NewOperands.push_back(convert(VI, ToTy));
411 } else if (ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
412 APSInt Val(ToTy->getPrimitiveSizeInBits(), /*isUnsigned=*/false);
413 bool Exact;
414 CF->getValueAPF().convertToInteger(Val,
416 &Exact);
417 NewOperands.push_back(ConstantInt::get(ToTy, Val));
418 } else {
419 llvm_unreachable("Unhandled operand type?");
420 }
421 }
422
423 // Now create a new instruction.
424 IRBuilder<> IRB(I);
425 Value *NewV = nullptr;
426 switch (I->getOpcode()) {
427 default: llvm_unreachable("Unhandled instruction!");
428
429 case Instruction::FPToUI:
430 NewV = IRB.CreateZExtOrTrunc(NewOperands[0], I->getType());
431 break;
432
433 case Instruction::FPToSI:
434 NewV = IRB.CreateSExtOrTrunc(NewOperands[0], I->getType());
435 break;
436
437 case Instruction::FCmp: {
438 CmpInst::Predicate P = mapFCmpPred(cast<CmpInst>(I)->getPredicate());
439 assert(P != CmpInst::BAD_ICMP_PREDICATE && "Unhandled predicate!");
440 NewV = IRB.CreateICmp(P, NewOperands[0], NewOperands[1], I->getName());
441 break;
442 }
443
444 case Instruction::UIToFP:
445 NewV = IRB.CreateZExtOrTrunc(NewOperands[0], ToTy);
446 break;
447
448 case Instruction::SIToFP:
449 NewV = IRB.CreateSExtOrTrunc(NewOperands[0], ToTy);
450 break;
451
452 case Instruction::FNeg:
453 NewV = IRB.CreateNeg(NewOperands[0], I->getName());
454 break;
455
456 case Instruction::FAdd:
457 case Instruction::FSub:
458 case Instruction::FMul:
459 NewV = IRB.CreateBinOp(mapBinOpcode(I->getOpcode()),
460 NewOperands[0], NewOperands[1],
461 I->getName());
462 break;
463 }
464
465 // If we're a root instruction, RAUW.
466 if (Roots.count(I))
467 I->replaceAllUsesWith(NewV);
468
469 ConvertedInsts[I] = NewV;
470 return NewV;
471}
472
473// Perform dead code elimination on the instructions we just modified.
474void Float2IntPass::cleanup() {
475 for (auto &I : reverse(ConvertedInsts))
476 I.first->eraseFromParent();
477}
478
480 LLVM_DEBUG(dbgs() << "F2I: Looking at function " << F.getName() << "\n");
481 // Clear out all state.
483 SeenInsts.clear();
484 ConvertedInsts.clear();
485 Roots.clear();
486
487 Ctx = &F.getParent()->getContext();
488
489 findRoots(F, DT);
490
491 walkBackwards();
492 walkForwards();
493
494 bool Modified = validateAndTransform();
495 if (Modified)
496 cleanup();
497 return Modified;
498}
499
502 if (!runImpl(F, DT))
503 return PreservedAnalyses::all();
504
507 return PA;
508}
#define Fail
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Size
expand large fp convert
static CmpInst::Predicate mapFCmpPred(CmpInst::Predicate P)
Definition: Float2Int.cpp:51
static Instruction::BinaryOps mapBinOpcode(unsigned Opcode)
Definition: Float2Int.cpp:78
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)"))
The largest integer type worth dealing with.
This is the interface for a simple mod/ref and alias analysis over globals.
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
opStatus roundToIntegral(roundingMode RM)
Definition: APFloat.h:1109
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:178
An arbitrary precision integer that knows its signedness.
Definition: APSInt.h:23
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:348
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:500
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:70
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:965
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:968
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:994
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:995
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:971
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:980
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:969
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:970
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:992
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:979
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:973
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:976
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:977
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:972
@ ICMP_EQ
equal
Definition: InstrTypes.h:986
@ ICMP_NE
not equal
Definition: InstrTypes.h:987
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:993
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:981
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:978
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:267
This class represents a range of values.
Definition: ConstantRange.h:47
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:275
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
bool runImpl(Function &F, const DominatorTree &DT)
Definition: Float2Int.cpp:479
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: Float2Int.cpp:500
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2649
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:144
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
const fltSemantics & getFltSemantics() const
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM Value Representation.
Definition: Value.h:74
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
Definition: PPCPredicates.h:87
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:428
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
static constexpr roundingMode rmNearestTiesToEven
Definition: APFloat.h:230
static unsigned int semanticsPrecision(const fltSemantics &)
Definition: APFloat.cpp:292