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