1 //===- MergeICmps.cpp - Optimize chains of integer comparisons ------------===// 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 pass turns chains of integer comparisons into memcmp (the memcmp is 11 // later typically inlined as a chain of efficient hardware comparisons). This 12 // typically benefits c++ member or nonmember operator==(). 13 // 14 // The basic idea is to replace a larger chain of integer comparisons loaded 15 // from contiguous memory locations into a smaller chain of such integer 16 // comparisons. Benefits are double: 17 // - There are less jumps, and therefore less opportunities for mispredictions 18 // and I-cache misses. 19 // - Code size is smaller, both because jumps are removed and because the 20 // encoding of a 2*n byte compare is smaller than that of two n-byte 21 // compares. 22 23 //===----------------------------------------------------------------------===// 24 25 #include "llvm/ADT/APSInt.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/IRBuilder.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/Pass.h" 31 #include "llvm/Transforms/Scalar.h" 32 #include "llvm/Transforms/Utils/BuildLibCalls.h" 33 34 using namespace llvm; 35 36 namespace { 37 38 #define DEBUG_TYPE "mergeicmps" 39 40 #define MERGEICMPS_DOT_ON 41 42 // A BCE atom. 43 struct BCEAtom { 44 const Value *Base() const { return GEP ? GEP->getPointerOperand() : nullptr; } 45 46 bool operator<(const BCEAtom &O) const { 47 return Base() == O.Base() ? Offset.slt(O.Offset) : Base() < O.Base(); 48 } 49 50 GetElementPtrInst *GEP = nullptr; 51 LoadInst *LoadI = nullptr; 52 APInt Offset; 53 }; 54 55 // If this value is a load from a constant offset w.r.t. a base address, and 56 // there are no othe rusers of the load or address, returns the base address and 57 // the offset. 58 BCEAtom visitICmpLoadOperand(Value *const Val) { 59 BCEAtom Result; 60 if (auto *const LoadI = dyn_cast<LoadInst>(Val)) { 61 DEBUG(dbgs() << "load\n"); 62 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) { 63 DEBUG(dbgs() << "used outside of block\n"); 64 return {}; 65 } 66 if (LoadI->isVolatile()) { 67 DEBUG(dbgs() << "volatile\n"); 68 return {}; 69 } 70 Value *const Addr = LoadI->getOperand(0); 71 if (auto *const GEP = dyn_cast<GetElementPtrInst>(Addr)) { 72 DEBUG(dbgs() << "GEP\n"); 73 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) { 74 DEBUG(dbgs() << "used outside of block\n"); 75 return {}; 76 } 77 const auto &DL = GEP->getModule()->getDataLayout(); 78 if (!isDereferenceablePointer(GEP, DL)) { 79 DEBUG(dbgs() << "not dereferenceable\n"); 80 // We need to make sure that we can do comparison in any order, so we 81 // require memory to be unconditionnally dereferencable. 82 return {}; 83 } 84 Result.Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0); 85 if (GEP->accumulateConstantOffset(DL, Result.Offset)) { 86 Result.GEP = GEP; 87 Result.LoadI = LoadI; 88 } 89 } 90 } 91 return Result; 92 } 93 94 // A basic block with a comparison between two BCE atoms. 95 // Note: the terminology is misleading: the comparison is symmetric, so there 96 // is no real {l/r}hs. To break the symmetry, we use the smallest atom as Lhs. 97 class BCECmpBlock { 98 public: 99 BCECmpBlock() {} 100 101 BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits) 102 : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) { 103 if (Rhs_ < Lhs_) 104 std::swap(Rhs_, Lhs_); 105 } 106 107 bool IsValid() const { 108 return Lhs_.Base() != nullptr && Rhs_.Base() != nullptr; 109 } 110 111 // Assert the the block is consistent: If valid, it should also have 112 // non-null members besides Lhs_ and Rhs_. 113 void AssertConsistent() const { 114 if (IsValid()) { 115 assert(BB); 116 assert(CmpI); 117 assert(BranchI); 118 } 119 } 120 121 const BCEAtom &Lhs() const { return Lhs_; } 122 const BCEAtom &Rhs() const { return Rhs_; } 123 int SizeBits() const { return SizeBits_; } 124 125 // Returns true if the block does other works besides comparison. 126 bool doesOtherWork() const; 127 128 // The basic block where this comparison happens. 129 BasicBlock *BB = nullptr; 130 // The ICMP for this comparison. 131 ICmpInst *CmpI = nullptr; 132 // The terminating branch. 133 BranchInst *BranchI = nullptr; 134 135 private: 136 BCEAtom Lhs_; 137 BCEAtom Rhs_; 138 int SizeBits_ = 0; 139 }; 140 141 bool BCECmpBlock::doesOtherWork() const { 142 AssertConsistent(); 143 // TODO(courbet): Can we allow some other things ? This is very conservative. 144 // We might be able to get away with anything does does not have any side 145 // effects outside of the basic block. 146 // Note: The GEPs and/or loads are not necessarily in the same block. 147 for (const Instruction &Inst : *BB) { 148 if (const auto *const GEP = dyn_cast<GetElementPtrInst>(&Inst)) { 149 if (!(Lhs_.GEP == GEP || Rhs_.GEP == GEP)) 150 return true; 151 } else if (const auto *const L = dyn_cast<LoadInst>(&Inst)) { 152 if (!(Lhs_.LoadI == L || Rhs_.LoadI == L)) 153 return true; 154 } else if (const auto *const C = dyn_cast<ICmpInst>(&Inst)) { 155 if (C != CmpI) 156 return true; 157 } else if (const auto *const Br = dyn_cast<BranchInst>(&Inst)) { 158 if (Br != BranchI) 159 return true; 160 } else { 161 return true; 162 } 163 } 164 return false; 165 } 166 167 // Visit the given comparison. If this is a comparison between two valid 168 // BCE atoms, returns the comparison. 169 BCECmpBlock visitICmp(const ICmpInst *const CmpI, 170 const ICmpInst::Predicate ExpectedPredicate) { 171 if (CmpI->getPredicate() == ExpectedPredicate) { 172 DEBUG(dbgs() << "cmp " 173 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne") 174 << "\n"); 175 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0)); 176 if (!Lhs.Base()) 177 return {}; 178 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1)); 179 if (!Rhs.Base()) 180 return {}; 181 return BCECmpBlock(std::move(Lhs), std::move(Rhs), 182 CmpI->getOperand(0)->getType()->getScalarSizeInBits()); 183 } 184 return {}; 185 } 186 187 // Visit the given comparison block. If this is a comparison between two valid 188 // BCE atoms, returns the comparison. 189 BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block, 190 const BasicBlock *const PhiBlock) { 191 if (Block->empty()) 192 return {}; 193 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator()); 194 if (!BranchI) 195 return {}; 196 DEBUG(dbgs() << "branch\n"); 197 if (BranchI->isUnconditional()) { 198 // In this case, we expect an incoming value which is the result of the 199 // comparison. This is the last link in the chain of comparisons (note 200 // that this does not mean that this is the last incoming value, blocks 201 // can be reordered). 202 auto *const CmpI = dyn_cast<ICmpInst>(Val); 203 if (!CmpI) 204 return {}; 205 DEBUG(dbgs() << "icmp\n"); 206 auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ); 207 Result.CmpI = CmpI; 208 Result.BranchI = BranchI; 209 return Result; 210 } else { 211 // In this case, we expect a constant incoming value (the comparison is 212 // chained). 213 const auto *const Const = dyn_cast<ConstantInt>(Val); 214 DEBUG(dbgs() << "const\n"); 215 if (!Const->isZero()) 216 return {}; 217 DEBUG(dbgs() << "false\n"); 218 auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition()); 219 if (!CmpI) 220 return {}; 221 DEBUG(dbgs() << "icmp\n"); 222 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch"); 223 BasicBlock *const FalseBlock = BranchI->getSuccessor(1); 224 auto Result = visitICmp( 225 CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE); 226 Result.CmpI = CmpI; 227 Result.BranchI = BranchI; 228 return Result; 229 } 230 return {}; 231 } 232 233 // A chain of comparisons. 234 class BCECmpChain { 235 public: 236 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi); 237 238 int size() const { return Comparisons_.size(); } 239 240 #ifdef MERGEICMPS_DOT_ON 241 void dump() const; 242 #endif // MERGEICMPS_DOT_ON 243 244 bool simplify(const TargetLibraryInfo *const TLI); 245 246 private: 247 static bool IsContiguous(const BCECmpBlock &First, 248 const BCECmpBlock &Second) { 249 return First.Lhs().Base() == Second.Lhs().Base() && 250 First.Rhs().Base() == Second.Rhs().Base() && 251 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset && 252 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset; 253 } 254 255 // Merges the given comparison blocks into one memcmp block and update 256 // branches. Comparisons are assumed to be continguous. If NextBBInChain is 257 // null, the merged block will link to the phi block. 258 static void mergeComparisons(ArrayRef<BCECmpBlock> Comparisons, 259 BasicBlock *const NextBBInChain, PHINode &Phi, 260 const TargetLibraryInfo *const TLI); 261 262 PHINode &Phi_; 263 std::vector<BCECmpBlock> Comparisons_; 264 // The original entry block (before sorting); 265 BasicBlock *EntryBlock_; 266 }; 267 268 BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi) 269 : Phi_(Phi) { 270 // Now look inside blocks to check for BCE comparisons. 271 std::vector<BCECmpBlock> Comparisons; 272 for (BasicBlock *Block : Blocks) { 273 BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block), 274 Block, Phi.getParent()); 275 Comparison.BB = Block; 276 if (!Comparison.IsValid()) { 277 DEBUG(dbgs() << "skip: not a valid BCECmpBlock\n"); 278 return; 279 } 280 if (Comparison.doesOtherWork()) { 281 DEBUG(dbgs() << "block does extra work besides compare\n"); 282 if (Comparisons.empty()) { // First block. 283 // TODO(courbet): The first block can do other things, and we should 284 // split them apart in a separate block before the comparison chain. 285 // Right now we just discard it and make the chain shorter. 286 DEBUG(dbgs() 287 << "ignoring first block that does extra work besides compare\n"); 288 continue; 289 } 290 // TODO(courbet): Right now we abort the whole chain. We could be 291 // merging only the blocks that don't do other work and resume the 292 // chain from there. For example: 293 // if (a[0] == b[0]) { // bb1 294 // if (a[1] == b[1]) { // bb2 295 // some_value = 3; //bb3 296 // if (a[2] == b[2]) { //bb3 297 // do a ton of stuff //bb4 298 // } 299 // } 300 // } 301 // 302 // This is: 303 // 304 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+ 305 // \ \ \ \ 306 // ne ne ne \ 307 // \ \ \ v 308 // +------------+-----------+----------> bb_phi 309 // 310 // We can only merge the first two comparisons, because bb3* does 311 // "other work" (setting some_value to 3). 312 // We could still merge bb1 and bb2 though. 313 return; 314 } 315 DEBUG(dbgs() << "*Found cmp of " << Comparison.SizeBits() 316 << " bits between " << Comparison.Lhs().Base() << " + " 317 << Comparison.Lhs().Offset << " and " 318 << Comparison.Rhs().Base() << " + " << Comparison.Rhs().Offset 319 << "\n"); 320 DEBUG(dbgs() << "\n"); 321 Comparisons.push_back(Comparison); 322 } 323 EntryBlock_ = Comparisons[0].BB; 324 Comparisons_ = std::move(Comparisons); 325 #ifdef MERGEICMPS_DOT_ON 326 errs() << "BEFORE REORDERING:\n\n"; 327 dump(); 328 #endif // MERGEICMPS_DOT_ON 329 // Reorder blocks by LHS. We can do that without changing the 330 // semantics because we are only accessing dereferencable memory. 331 std::sort(Comparisons_.begin(), Comparisons_.end(), 332 [](const BCECmpBlock &a, const BCECmpBlock &b) { 333 return a.Lhs() < b.Lhs(); 334 }); 335 #ifdef MERGEICMPS_DOT_ON 336 errs() << "AFTER REORDERING:\n\n"; 337 dump(); 338 #endif // MERGEICMPS_DOT_ON 339 } 340 341 #ifdef MERGEICMPS_DOT_ON 342 void BCECmpChain::dump() const { 343 errs() << "digraph dag {\n"; 344 errs() << " graph [bgcolor=transparent];\n"; 345 errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n"; 346 errs() << " edge [color=black];\n"; 347 for (size_t I = 0; I < Comparisons_.size(); ++I) { 348 const auto &Comparison = Comparisons_[I]; 349 errs() << " \"" << I << "\" [label=\"%" 350 << Comparison.Lhs().Base()->getName() << " + " 351 << Comparison.Lhs().Offset << " == %" 352 << Comparison.Rhs().Base()->getName() << " + " 353 << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8) 354 << " bytes)\"];\n"; 355 const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB); 356 if (I > 0) 357 errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n"; 358 errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n"; 359 } 360 errs() << " \"Phi\" [label=\"Phi\"];\n"; 361 errs() << "}\n\n"; 362 } 363 #endif // MERGEICMPS_DOT_ON 364 365 bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI) { 366 // First pass to check if there is at least one merge. If not, we don't do 367 // anything and we keep analysis passes intact. 368 { 369 bool AtLeastOneMerged = false; 370 for (size_t I = 1; I < Comparisons_.size(); ++I) { 371 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) { 372 AtLeastOneMerged = true; 373 break; 374 } 375 } 376 if (!AtLeastOneMerged) 377 return false; 378 } 379 380 // Remove phi references to comparison blocks, they will be rebuilt as we 381 // merge the blocks. 382 for (const auto &Comparison : Comparisons_) { 383 Phi_.removeIncomingValue(Comparison.BB, false); 384 } 385 386 // Point the predecessors of the chain to the first comparison block (which is 387 // the new entry point). 388 if (EntryBlock_ != Comparisons_[0].BB) 389 EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB); 390 391 // Effectively merge blocks. 392 int NumMerged = 1; 393 for (size_t I = 1; I < Comparisons_.size(); ++I) { 394 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) { 395 ++NumMerged; 396 } else { 397 // Merge all previous comparisons and start a new merge block. 398 mergeComparisons( 399 makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged), 400 Comparisons_[I].BB, Phi_, TLI); 401 NumMerged = 1; 402 } 403 } 404 mergeComparisons(makeArrayRef(Comparisons_) 405 .slice(Comparisons_.size() - NumMerged, NumMerged), 406 nullptr, Phi_, TLI); 407 408 return true; 409 } 410 411 void BCECmpChain::mergeComparisons(ArrayRef<BCECmpBlock> Comparisons, 412 BasicBlock *const NextBBInChain, 413 PHINode &Phi, 414 const TargetLibraryInfo *const TLI) { 415 assert(!Comparisons.empty()); 416 const auto &FirstComparison = *Comparisons.begin(); 417 BasicBlock *const BB = FirstComparison.BB; 418 LLVMContext &Context = BB->getContext(); 419 420 if (Comparisons.size() >= 2) { 421 DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons\n"); 422 const auto TotalSize = 423 std::accumulate(Comparisons.begin(), Comparisons.end(), 0, 424 [](int Size, const BCECmpBlock &C) { 425 return Size + C.SizeBits(); 426 }) / 427 8; 428 429 // Incoming edges do not need to be updated, and both GEPs are already 430 // computing the right address, we just need to: 431 // - replace the two loads and the icmp with the memcmp 432 // - update the branch 433 // - update the incoming values in the phi. 434 FirstComparison.BranchI->eraseFromParent(); 435 FirstComparison.CmpI->eraseFromParent(); 436 FirstComparison.Lhs().LoadI->eraseFromParent(); 437 FirstComparison.Rhs().LoadI->eraseFromParent(); 438 439 IRBuilder<> Builder(BB); 440 const auto &DL = Phi.getModule()->getDataLayout(); 441 Value *const MemCmpCall = 442 emitMemCmp(FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP, 443 ConstantInt::get(DL.getIntPtrType(Context), TotalSize), 444 Builder, DL, TLI); 445 Value *const MemCmpIsZero = Builder.CreateICmpEQ( 446 MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0)); 447 448 // Add a branch to the next basic block in the chain. 449 if (NextBBInChain) { 450 Builder.CreateCondBr(MemCmpIsZero, NextBBInChain, Phi.getParent()); 451 Phi.addIncoming(ConstantInt::getFalse(Context), BB); 452 } else { 453 Builder.CreateBr(Phi.getParent()); 454 Phi.addIncoming(MemCmpIsZero, BB); 455 } 456 457 // Delete merged blocks. 458 for (size_t I = 1; I < Comparisons.size(); ++I) { 459 BasicBlock *CBB = Comparisons[I].BB; 460 CBB->replaceAllUsesWith(BB); 461 CBB->eraseFromParent(); 462 } 463 } else { 464 assert(Comparisons.size() == 1); 465 // There are no blocks to merge, but we still need to update the branches. 466 DEBUG(dbgs() << "Only one comparison, updating branches\n"); 467 if (NextBBInChain) { 468 if (FirstComparison.BranchI->isConditional()) { 469 DEBUG(dbgs() << "conditional -> conditional\n"); 470 // Just update the "true" target, the "false" target should already be 471 // the phi block. 472 assert(FirstComparison.BranchI->getSuccessor(1) == Phi.getParent()); 473 FirstComparison.BranchI->setSuccessor(0, NextBBInChain); 474 Phi.addIncoming(ConstantInt::getFalse(Context), BB); 475 } else { 476 DEBUG(dbgs() << "unconditional -> conditional\n"); 477 // Replace the unconditional branch by a conditional one. 478 FirstComparison.BranchI->eraseFromParent(); 479 IRBuilder<> Builder(BB); 480 Builder.CreateCondBr(FirstComparison.CmpI, NextBBInChain, 481 Phi.getParent()); 482 Phi.addIncoming(FirstComparison.CmpI, BB); 483 } 484 } else { 485 if (FirstComparison.BranchI->isConditional()) { 486 DEBUG(dbgs() << "conditional -> unconditional\n"); 487 // Replace the conditional branch by an unconditional one. 488 FirstComparison.BranchI->eraseFromParent(); 489 IRBuilder<> Builder(BB); 490 Builder.CreateBr(Phi.getParent()); 491 Phi.addIncoming(FirstComparison.CmpI, BB); 492 } else { 493 DEBUG(dbgs() << "unconditional -> unconditional\n"); 494 Phi.addIncoming(FirstComparison.CmpI, BB); 495 } 496 } 497 } 498 } 499 500 std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi, 501 BasicBlock *const LastBlock, 502 int NumBlocks) { 503 // Walk up from the last block to find other blocks. 504 std::vector<BasicBlock *> Blocks(NumBlocks); 505 BasicBlock *CurBlock = LastBlock; 506 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) { 507 if (CurBlock->hasAddressTaken()) { 508 // Somebody is jumping to the block through an address, all bets are 509 // off. 510 DEBUG(dbgs() << "skip: block " << BlockIndex 511 << " has its address taken\n"); 512 return {}; 513 } 514 Blocks[BlockIndex] = CurBlock; 515 auto *SinglePredecessor = CurBlock->getSinglePredecessor(); 516 if (!SinglePredecessor) { 517 // The block has two or more predecessors. 518 DEBUG(dbgs() << "skip: block " << BlockIndex 519 << " has two or more predecessors\n"); 520 return {}; 521 } 522 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) { 523 // The block does not link back to the phi. 524 DEBUG(dbgs() << "skip: block " << BlockIndex 525 << " does not link back to the phi\n"); 526 return {}; 527 } 528 CurBlock = SinglePredecessor; 529 } 530 Blocks[0] = CurBlock; 531 return Blocks; 532 } 533 534 bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI) { 535 DEBUG(dbgs() << "processPhi()\n"); 536 if (Phi.getNumIncomingValues() <= 1) { 537 DEBUG(dbgs() << "skip: only one incoming value in phi\n"); 538 return false; 539 } 540 // We are looking for something that has the following structure: 541 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+ 542 // \ \ \ \ 543 // ne ne ne \ 544 // \ \ \ v 545 // +------------+-----------+----------> bb_phi 546 // 547 // - The last basic block (bb4 here) must branch unconditionally to bb_phi. 548 // It's the only block that contributes a non-constant value to the Phi. 549 // - All other blocks (b1, b2, b3) must have exactly two successors, one of 550 // them being the the phi block. 551 // - All intermediate blocks (bb2, bb3) must have only one predecessor. 552 // - Blocks cannot do other work besides the comparison, see doesOtherWork() 553 554 // The blocks are not necessarily ordered in the phi, so we start from the 555 // last block and reconstruct the order. 556 BasicBlock *LastBlock = nullptr; 557 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) { 558 if (isa<ConstantInt>(Phi.getIncomingValue(I))) 559 continue; 560 if (LastBlock) { 561 // There are several non-constant values. 562 DEBUG(dbgs() << "skip: several non-constant values\n"); 563 return false; 564 } 565 LastBlock = Phi.getIncomingBlock(I); 566 } 567 if (!LastBlock) { 568 // There is no non-constant block. 569 DEBUG(dbgs() << "skip: no non-constant block\n"); 570 return false; 571 } 572 if (LastBlock->getSingleSuccessor() != Phi.getParent()) { 573 DEBUG(dbgs() << "skip: last block non-phi successor\n"); 574 return false; 575 } 576 577 const auto Blocks = 578 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues()); 579 if (Blocks.empty()) 580 return false; 581 BCECmpChain CmpChain(Blocks, Phi); 582 583 if (CmpChain.size() < 2) { 584 DEBUG(dbgs() << "skip: only one compare block\n"); 585 return false; 586 } 587 588 return CmpChain.simplify(TLI); 589 } 590 591 class MergeICmps : public FunctionPass { 592 public: 593 static char ID; 594 595 MergeICmps() : FunctionPass(ID) { 596 initializeMergeICmpsPass(*PassRegistry::getPassRegistry()); 597 } 598 599 bool runOnFunction(Function &F) override { 600 if (skipFunction(F)) return false; 601 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 602 auto PA = runImpl(F, &TLI); 603 return !PA.areAllPreserved(); 604 } 605 606 private: 607 void getAnalysisUsage(AnalysisUsage &AU) const override { 608 AU.addRequired<TargetLibraryInfoWrapperPass>(); 609 } 610 611 PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI); 612 }; 613 614 PreservedAnalyses MergeICmps::runImpl(Function &F, 615 const TargetLibraryInfo *TLI) { 616 DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n"); 617 618 bool MadeChange = false; 619 620 for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) { 621 // A Phi operation is always first in a basic block. 622 if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin())) 623 MadeChange |= processPhi(*Phi, TLI); 624 } 625 626 if (MadeChange) 627 return PreservedAnalyses::none(); 628 return PreservedAnalyses::all(); 629 } 630 631 } // namespace 632 633 char MergeICmps::ID = 0; 634 INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps", 635 "Merge contiguous icmps into a memcmp", false, false) 636 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 637 INITIALIZE_PASS_END(MergeICmps, "mergeicmps", 638 "Merge contiguous icmps into a memcmp", false, false) 639 640 Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); } 641 642