1 //===- MergeICmps.cpp - Optimize chains of integer comparisons ------------===// 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 pass turns chains of integer comparisons into memcmp (the memcmp is 10 // later typically inlined as a chain of efficient hardware comparisons). This 11 // typically benefits c++ member or nonmember operator==(). 12 // 13 // The basic idea is to replace a longer chain of integer comparisons loaded 14 // from contiguous memory locations into a shorter chain of larger integer 15 // comparisons. Benefits are double: 16 // - There are less jumps, and therefore less opportunities for mispredictions 17 // and I-cache misses. 18 // - Code size is smaller, both because jumps are removed and because the 19 // encoding of a 2*n byte compare is smaller than that of two n-byte 20 // compares. 21 // 22 // Example: 23 // 24 // struct S { 25 // int a; 26 // char b; 27 // char c; 28 // uint16_t d; 29 // bool operator==(const S& o) const { 30 // return a == o.a && b == o.b && c == o.c && d == o.d; 31 // } 32 // }; 33 // 34 // Is optimized as : 35 // 36 // bool S::operator==(const S& o) const { 37 // return memcmp(this, &o, 8) == 0; 38 // } 39 // 40 // Which will later be expanded (ExpandMemCmp) as a single 8-bytes icmp. 41 // 42 //===----------------------------------------------------------------------===// 43 44 #include "llvm/Transforms/Scalar/MergeICmps.h" 45 #include "llvm/Analysis/DomTreeUpdater.h" 46 #include "llvm/Analysis/GlobalsModRef.h" 47 #include "llvm/Analysis/Loads.h" 48 #include "llvm/Analysis/TargetLibraryInfo.h" 49 #include "llvm/Analysis/TargetTransformInfo.h" 50 #include "llvm/IR/Dominators.h" 51 #include "llvm/IR/Function.h" 52 #include "llvm/IR/IRBuilder.h" 53 #include "llvm/InitializePasses.h" 54 #include "llvm/Pass.h" 55 #include "llvm/Transforms/Scalar.h" 56 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 57 #include "llvm/Transforms/Utils/BuildLibCalls.h" 58 #include <algorithm> 59 #include <numeric> 60 #include <utility> 61 #include <vector> 62 63 using namespace llvm; 64 65 namespace { 66 67 #define DEBUG_TYPE "mergeicmps" 68 69 // Returns true if the instruction is a simple load or a simple store 70 static bool isSimpleLoadOrStore(const Instruction *I) { 71 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) 72 return LI->isSimple(); 73 if (const StoreInst *SI = dyn_cast<StoreInst>(I)) 74 return SI->isSimple(); 75 return false; 76 } 77 78 // A BCE atom "Binary Compare Expression Atom" represents an integer load 79 // that is a constant offset from a base value, e.g. `a` or `o.c` in the example 80 // at the top. 81 struct BCEAtom { 82 BCEAtom() = default; 83 BCEAtom(GetElementPtrInst *GEP, LoadInst *LoadI, int BaseId, APInt Offset) 84 : GEP(GEP), LoadI(LoadI), BaseId(BaseId), Offset(Offset) {} 85 86 BCEAtom(const BCEAtom &) = delete; 87 BCEAtom &operator=(const BCEAtom &) = delete; 88 89 BCEAtom(BCEAtom &&that) = default; 90 BCEAtom &operator=(BCEAtom &&that) { 91 if (this == &that) 92 return *this; 93 GEP = that.GEP; 94 LoadI = that.LoadI; 95 BaseId = that.BaseId; 96 Offset = std::move(that.Offset); 97 return *this; 98 } 99 100 // We want to order BCEAtoms by (Base, Offset). However we cannot use 101 // the pointer values for Base because these are non-deterministic. 102 // To make sure that the sort order is stable, we first assign to each atom 103 // base value an index based on its order of appearance in the chain of 104 // comparisons. We call this index `BaseOrdering`. For example, for: 105 // b[3] == c[2] && a[1] == d[1] && b[4] == c[3] 106 // | block 1 | | block 2 | | block 3 | 107 // b gets assigned index 0 and a index 1, because b appears as LHS in block 1, 108 // which is before block 2. 109 // We then sort by (BaseOrdering[LHS.Base()], LHS.Offset), which is stable. 110 bool operator<(const BCEAtom &O) const { 111 return BaseId != O.BaseId ? BaseId < O.BaseId : Offset.slt(O.Offset); 112 } 113 114 GetElementPtrInst *GEP = nullptr; 115 LoadInst *LoadI = nullptr; 116 unsigned BaseId = 0; 117 APInt Offset; 118 }; 119 120 // A class that assigns increasing ids to values in the order in which they are 121 // seen. See comment in `BCEAtom::operator<()``. 122 class BaseIdentifier { 123 public: 124 // Returns the id for value `Base`, after assigning one if `Base` has not been 125 // seen before. 126 int getBaseId(const Value *Base) { 127 assert(Base && "invalid base"); 128 const auto Insertion = BaseToIndex.try_emplace(Base, Order); 129 if (Insertion.second) 130 ++Order; 131 return Insertion.first->second; 132 } 133 134 private: 135 unsigned Order = 1; 136 DenseMap<const Value*, int> BaseToIndex; 137 }; 138 139 // If this value is a load from a constant offset w.r.t. a base address, and 140 // there are no other users of the load or address, returns the base address and 141 // the offset. 142 BCEAtom visitICmpLoadOperand(Value *const Val, BaseIdentifier &BaseId) { 143 auto *const LoadI = dyn_cast<LoadInst>(Val); 144 if (!LoadI) 145 return {}; 146 LLVM_DEBUG(dbgs() << "load\n"); 147 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) { 148 LLVM_DEBUG(dbgs() << "used outside of block\n"); 149 return {}; 150 } 151 // Do not optimize atomic loads to non-atomic memcmp 152 if (!LoadI->isSimple()) { 153 LLVM_DEBUG(dbgs() << "volatile or atomic\n"); 154 return {}; 155 } 156 Value *const Addr = LoadI->getOperand(0); 157 auto *const GEP = dyn_cast<GetElementPtrInst>(Addr); 158 if (!GEP) 159 return {}; 160 LLVM_DEBUG(dbgs() << "GEP\n"); 161 if (GEP->isUsedOutsideOfBlock(LoadI->getParent())) { 162 LLVM_DEBUG(dbgs() << "used outside of block\n"); 163 return {}; 164 } 165 const auto &DL = GEP->getModule()->getDataLayout(); 166 if (!isDereferenceablePointer(GEP, LoadI->getType(), DL)) { 167 LLVM_DEBUG(dbgs() << "not dereferenceable\n"); 168 // We need to make sure that we can do comparison in any order, so we 169 // require memory to be unconditionnally dereferencable. 170 return {}; 171 } 172 APInt Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0); 173 if (!GEP->accumulateConstantOffset(DL, Offset)) 174 return {}; 175 return BCEAtom(GEP, LoadI, BaseId.getBaseId(GEP->getPointerOperand()), 176 Offset); 177 } 178 179 // A comparison between two BCE atoms, e.g. `a == o.a` in the example at the 180 // top. 181 // Note: the terminology is misleading: the comparison is symmetric, so there 182 // is no real {l/r}hs. What we want though is to have the same base on the 183 // left (resp. right), so that we can detect consecutive loads. To ensure this 184 // we put the smallest atom on the left. 185 struct BCECmp { 186 BCEAtom Lhs; 187 BCEAtom Rhs; 188 int SizeBits; 189 const ICmpInst *CmpI; 190 191 BCECmp(BCEAtom L, BCEAtom R, int SizeBits, const ICmpInst *CmpI) 192 : Lhs(std::move(L)), Rhs(std::move(R)), SizeBits(SizeBits), CmpI(CmpI) { 193 if (Rhs < Lhs) std::swap(Rhs, Lhs); 194 } 195 }; 196 197 // A basic block with a comparison between two BCE atoms. 198 // The block might do extra work besides the atom comparison, in which case 199 // doesOtherWork() returns true. Under some conditions, the block can be 200 // split into the atom comparison part and the "other work" part 201 // (see canSplit()). 202 class BCECmpBlock { 203 public: 204 typedef SmallDenseSet<const Instruction *, 8> InstructionSet; 205 206 BCECmpBlock(BCECmp Cmp, BasicBlock *BB, InstructionSet BlockInsts) 207 : BB(BB), BlockInsts(std::move(BlockInsts)), Cmp(std::move(Cmp)) {} 208 209 const BCEAtom &Lhs() const { return Cmp.Lhs; } 210 const BCEAtom &Rhs() const { return Cmp.Rhs; } 211 int SizeBits() const { return Cmp.SizeBits; } 212 213 // Returns true if the block does other works besides comparison. 214 bool doesOtherWork() const; 215 216 // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp 217 // instructions in the block. 218 bool canSplit(AliasAnalysis &AA) const; 219 220 // Return true if this all the relevant instructions in the BCE-cmp-block can 221 // be sunk below this instruction. By doing this, we know we can separate the 222 // BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the 223 // block. 224 bool canSinkBCECmpInst(const Instruction *, AliasAnalysis &AA) const; 225 226 // We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block 227 // instructions. Split the old block and move all non-BCE-cmp-insts into the 228 // new parent block. 229 void split(BasicBlock *NewParent, AliasAnalysis &AA) const; 230 231 // The basic block where this comparison happens. 232 BasicBlock *BB; 233 // Instructions relating to the BCECmp and branch. 234 InstructionSet BlockInsts; 235 // The block requires splitting. 236 bool RequireSplit = false; 237 238 private: 239 BCECmp Cmp; 240 }; 241 242 bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst, 243 AliasAnalysis &AA) const { 244 // If this instruction may clobber the loads and is in middle of the BCE cmp 245 // block instructions, then bail for now. 246 if (Inst->mayWriteToMemory()) { 247 // Bail if this is not a simple load or store 248 if (!isSimpleLoadOrStore(Inst)) 249 return false; 250 // Disallow stores that might alias the BCE operands 251 MemoryLocation LLoc = MemoryLocation::get(Cmp.Lhs.LoadI); 252 MemoryLocation RLoc = MemoryLocation::get(Cmp.Rhs.LoadI); 253 if (isModSet(AA.getModRefInfo(Inst, LLoc)) || 254 isModSet(AA.getModRefInfo(Inst, RLoc))) 255 return false; 256 } 257 // Make sure this instruction does not use any of the BCE cmp block 258 // instructions as operand. 259 return llvm::none_of(Inst->operands(), [&](const Value *Op) { 260 const Instruction *OpI = dyn_cast<Instruction>(Op); 261 return OpI && BlockInsts.contains(OpI); 262 }); 263 } 264 265 void BCECmpBlock::split(BasicBlock *NewParent, AliasAnalysis &AA) const { 266 llvm::SmallVector<Instruction *, 4> OtherInsts; 267 for (Instruction &Inst : *BB) { 268 if (BlockInsts.count(&Inst)) 269 continue; 270 assert(canSinkBCECmpInst(&Inst, AA) && "Split unsplittable block"); 271 // This is a non-BCE-cmp-block instruction. And it can be separated 272 // from the BCE-cmp-block instruction. 273 OtherInsts.push_back(&Inst); 274 } 275 276 // Do the actual spliting. 277 for (Instruction *Inst : reverse(OtherInsts)) { 278 Inst->moveBefore(&*NewParent->begin()); 279 } 280 } 281 282 bool BCECmpBlock::canSplit(AliasAnalysis &AA) const { 283 for (Instruction &Inst : *BB) { 284 if (!BlockInsts.count(&Inst)) { 285 if (!canSinkBCECmpInst(&Inst, AA)) 286 return false; 287 } 288 } 289 return true; 290 } 291 292 bool BCECmpBlock::doesOtherWork() const { 293 // TODO(courbet): Can we allow some other things ? This is very conservative. 294 // We might be able to get away with anything does not have any side 295 // effects outside of the basic block. 296 // Note: The GEPs and/or loads are not necessarily in the same block. 297 for (const Instruction &Inst : *BB) { 298 if (!BlockInsts.count(&Inst)) 299 return true; 300 } 301 return false; 302 } 303 304 // Visit the given comparison. If this is a comparison between two valid 305 // BCE atoms, returns the comparison. 306 Optional<BCECmp> visitICmp(const ICmpInst *const CmpI, 307 const ICmpInst::Predicate ExpectedPredicate, 308 BaseIdentifier &BaseId) { 309 // The comparison can only be used once: 310 // - For intermediate blocks, as a branch condition. 311 // - For the final block, as an incoming value for the Phi. 312 // If there are any other uses of the comparison, we cannot merge it with 313 // other comparisons as we would create an orphan use of the value. 314 if (!CmpI->hasOneUse()) { 315 LLVM_DEBUG(dbgs() << "cmp has several uses\n"); 316 return None; 317 } 318 if (CmpI->getPredicate() != ExpectedPredicate) 319 return None; 320 LLVM_DEBUG(dbgs() << "cmp " 321 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne") 322 << "\n"); 323 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0), BaseId); 324 if (!Lhs.BaseId) 325 return None; 326 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1), BaseId); 327 if (!Rhs.BaseId) 328 return None; 329 const auto &DL = CmpI->getModule()->getDataLayout(); 330 return BCECmp(std::move(Lhs), std::move(Rhs), 331 DL.getTypeSizeInBits(CmpI->getOperand(0)->getType()), CmpI); 332 } 333 334 // Visit the given comparison block. If this is a comparison between two valid 335 // BCE atoms, returns the comparison. 336 Optional<BCECmpBlock> visitCmpBlock(Value *const Val, BasicBlock *const Block, 337 const BasicBlock *const PhiBlock, 338 BaseIdentifier &BaseId) { 339 if (Block->empty()) return None; 340 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator()); 341 if (!BranchI) return None; 342 LLVM_DEBUG(dbgs() << "branch\n"); 343 Value *Cond; 344 ICmpInst::Predicate ExpectedPredicate; 345 if (BranchI->isUnconditional()) { 346 // In this case, we expect an incoming value which is the result of the 347 // comparison. This is the last link in the chain of comparisons (note 348 // that this does not mean that this is the last incoming value, blocks 349 // can be reordered). 350 Cond = Val; 351 ExpectedPredicate = ICmpInst::ICMP_EQ; 352 } else { 353 // In this case, we expect a constant incoming value (the comparison is 354 // chained). 355 const auto *const Const = cast<ConstantInt>(Val); 356 LLVM_DEBUG(dbgs() << "const\n"); 357 if (!Const->isZero()) return None; 358 LLVM_DEBUG(dbgs() << "false\n"); 359 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch"); 360 BasicBlock *const FalseBlock = BranchI->getSuccessor(1); 361 Cond = BranchI->getCondition(); 362 ExpectedPredicate = 363 FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 364 } 365 366 auto *CmpI = dyn_cast<ICmpInst>(Cond); 367 if (!CmpI) return None; 368 LLVM_DEBUG(dbgs() << "icmp\n"); 369 370 Optional<BCECmp> Result = visitICmp(CmpI, ExpectedPredicate, BaseId); 371 if (!Result) 372 return None; 373 374 BCECmpBlock::InstructionSet BlockInsts( 375 {Result->Lhs.GEP, Result->Rhs.GEP, Result->Lhs.LoadI, Result->Rhs.LoadI, 376 Result->CmpI, BranchI}); 377 return BCECmpBlock(std::move(*Result), Block, BlockInsts); 378 } 379 380 static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons, 381 BCECmpBlock &&Comparison) { 382 LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName() 383 << "': Found cmp of " << Comparison.SizeBits() 384 << " bits between " << Comparison.Lhs().BaseId << " + " 385 << Comparison.Lhs().Offset << " and " 386 << Comparison.Rhs().BaseId << " + " 387 << Comparison.Rhs().Offset << "\n"); 388 LLVM_DEBUG(dbgs() << "\n"); 389 Comparisons.push_back(std::move(Comparison)); 390 } 391 392 // A chain of comparisons. 393 class BCECmpChain { 394 public: 395 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi, 396 AliasAnalysis &AA); 397 398 int size() const { return Comparisons_.size(); } 399 400 #ifdef MERGEICMPS_DOT_ON 401 void dump() const; 402 #endif // MERGEICMPS_DOT_ON 403 404 bool simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA, 405 DomTreeUpdater &DTU); 406 407 private: 408 static bool IsContiguous(const BCECmpBlock &First, 409 const BCECmpBlock &Second) { 410 return First.Lhs().BaseId == Second.Lhs().BaseId && 411 First.Rhs().BaseId == Second.Rhs().BaseId && 412 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset && 413 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset; 414 } 415 416 PHINode &Phi_; 417 std::vector<BCECmpBlock> Comparisons_; 418 // The original entry block (before sorting); 419 BasicBlock *EntryBlock_; 420 }; 421 422 BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi, 423 AliasAnalysis &AA) 424 : Phi_(Phi) { 425 assert(!Blocks.empty() && "a chain should have at least one block"); 426 // Now look inside blocks to check for BCE comparisons. 427 std::vector<BCECmpBlock> Comparisons; 428 BaseIdentifier BaseId; 429 for (BasicBlock *const Block : Blocks) { 430 assert(Block && "invalid block"); 431 Optional<BCECmpBlock> Comparison = visitCmpBlock( 432 Phi.getIncomingValueForBlock(Block), Block, Phi.getParent(), BaseId); 433 if (!Comparison) { 434 LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n"); 435 return; 436 } 437 if (Comparison->doesOtherWork()) { 438 LLVM_DEBUG(dbgs() << "block '" << Comparison->BB->getName() 439 << "' does extra work besides compare\n"); 440 if (Comparisons.empty()) { 441 // This is the initial block in the chain, in case this block does other 442 // work, we can try to split the block and move the irrelevant 443 // instructions to the predecessor. 444 // 445 // If this is not the initial block in the chain, splitting it wont 446 // work. 447 // 448 // As once split, there will still be instructions before the BCE cmp 449 // instructions that do other work in program order, i.e. within the 450 // chain before sorting. Unless we can abort the chain at this point 451 // and start anew. 452 // 453 // NOTE: we only handle blocks a with single predecessor for now. 454 if (Comparison->canSplit(AA)) { 455 LLVM_DEBUG(dbgs() 456 << "Split initial block '" << Comparison->BB->getName() 457 << "' that does extra work besides compare\n"); 458 Comparison->RequireSplit = true; 459 enqueueBlock(Comparisons, std::move(*Comparison)); 460 } else { 461 LLVM_DEBUG(dbgs() 462 << "ignoring initial block '" << Comparison->BB->getName() 463 << "' that does extra work besides compare\n"); 464 } 465 continue; 466 } 467 // TODO(courbet): Right now we abort the whole chain. We could be 468 // merging only the blocks that don't do other work and resume the 469 // chain from there. For example: 470 // if (a[0] == b[0]) { // bb1 471 // if (a[1] == b[1]) { // bb2 472 // some_value = 3; //bb3 473 // if (a[2] == b[2]) { //bb3 474 // do a ton of stuff //bb4 475 // } 476 // } 477 // } 478 // 479 // This is: 480 // 481 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+ 482 // \ \ \ \ 483 // ne ne ne \ 484 // \ \ \ v 485 // +------------+-----------+----------> bb_phi 486 // 487 // We can only merge the first two comparisons, because bb3* does 488 // "other work" (setting some_value to 3). 489 // We could still merge bb1 and bb2 though. 490 return; 491 } 492 enqueueBlock(Comparisons, std::move(*Comparison)); 493 } 494 495 // It is possible we have no suitable comparison to merge. 496 if (Comparisons.empty()) { 497 LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n"); 498 return; 499 } 500 EntryBlock_ = Comparisons[0].BB; 501 Comparisons_ = std::move(Comparisons); 502 #ifdef MERGEICMPS_DOT_ON 503 errs() << "BEFORE REORDERING:\n\n"; 504 dump(); 505 #endif // MERGEICMPS_DOT_ON 506 // Reorder blocks by LHS. We can do that without changing the 507 // semantics because we are only accessing dereferencable memory. 508 llvm::sort(Comparisons_, 509 [](const BCECmpBlock &LhsBlock, const BCECmpBlock &RhsBlock) { 510 return std::tie(LhsBlock.Lhs(), LhsBlock.Rhs()) < 511 std::tie(RhsBlock.Lhs(), RhsBlock.Rhs()); 512 }); 513 #ifdef MERGEICMPS_DOT_ON 514 errs() << "AFTER REORDERING:\n\n"; 515 dump(); 516 #endif // MERGEICMPS_DOT_ON 517 } 518 519 #ifdef MERGEICMPS_DOT_ON 520 void BCECmpChain::dump() const { 521 errs() << "digraph dag {\n"; 522 errs() << " graph [bgcolor=transparent];\n"; 523 errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n"; 524 errs() << " edge [color=black];\n"; 525 for (size_t I = 0; I < Comparisons_.size(); ++I) { 526 const auto &Comparison = Comparisons_[I]; 527 errs() << " \"" << I << "\" [label=\"%" 528 << Comparison.Lhs().Base()->getName() << " + " 529 << Comparison.Lhs().Offset << " == %" 530 << Comparison.Rhs().Base()->getName() << " + " 531 << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8) 532 << " bytes)\"];\n"; 533 const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB); 534 if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n"; 535 errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n"; 536 } 537 errs() << " \"Phi\" [label=\"Phi\"];\n"; 538 errs() << "}\n\n"; 539 } 540 #endif // MERGEICMPS_DOT_ON 541 542 namespace { 543 544 // A class to compute the name of a set of merged basic blocks. 545 // This is optimized for the common case of no block names. 546 class MergedBlockName { 547 // Storage for the uncommon case of several named blocks. 548 SmallString<16> Scratch; 549 550 public: 551 explicit MergedBlockName(ArrayRef<BCECmpBlock> Comparisons) 552 : Name(makeName(Comparisons)) {} 553 const StringRef Name; 554 555 private: 556 StringRef makeName(ArrayRef<BCECmpBlock> Comparisons) { 557 assert(!Comparisons.empty() && "no basic block"); 558 // Fast path: only one block, or no names at all. 559 if (Comparisons.size() == 1) 560 return Comparisons[0].BB->getName(); 561 const int size = std::accumulate(Comparisons.begin(), Comparisons.end(), 0, 562 [](int i, const BCECmpBlock &Cmp) { 563 return i + Cmp.BB->getName().size(); 564 }); 565 if (size == 0) 566 return StringRef("", 0); 567 568 // Slow path: at least two blocks, at least one block with a name. 569 Scratch.clear(); 570 // We'll have `size` bytes for name and `Comparisons.size() - 1` bytes for 571 // separators. 572 Scratch.reserve(size + Comparisons.size() - 1); 573 const auto append = [this](StringRef str) { 574 Scratch.append(str.begin(), str.end()); 575 }; 576 append(Comparisons[0].BB->getName()); 577 for (int I = 1, E = Comparisons.size(); I < E; ++I) { 578 const BasicBlock *const BB = Comparisons[I].BB; 579 if (!BB->getName().empty()) { 580 append("+"); 581 append(BB->getName()); 582 } 583 } 584 return Scratch.str(); 585 } 586 }; 587 } // namespace 588 589 // Merges the given contiguous comparison blocks into one memcmp block. 590 static BasicBlock *mergeComparisons(ArrayRef<BCECmpBlock> Comparisons, 591 BasicBlock *const InsertBefore, 592 BasicBlock *const NextCmpBlock, 593 PHINode &Phi, const TargetLibraryInfo &TLI, 594 AliasAnalysis &AA, DomTreeUpdater &DTU) { 595 assert(!Comparisons.empty() && "merging zero comparisons"); 596 LLVMContext &Context = NextCmpBlock->getContext(); 597 const BCECmpBlock &FirstCmp = Comparisons[0]; 598 599 // Create a new cmp block before next cmp block. 600 BasicBlock *const BB = 601 BasicBlock::Create(Context, MergedBlockName(Comparisons).Name, 602 NextCmpBlock->getParent(), InsertBefore); 603 IRBuilder<> Builder(BB); 604 // Add the GEPs from the first BCECmpBlock. 605 Value *const Lhs = Builder.Insert(FirstCmp.Lhs().GEP->clone()); 606 Value *const Rhs = Builder.Insert(FirstCmp.Rhs().GEP->clone()); 607 608 Value *IsEqual = nullptr; 609 LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons -> " 610 << BB->getName() << "\n"); 611 612 // If there is one block that requires splitting, we do it now, i.e. 613 // just before we know we will collapse the chain. The instructions 614 // can be executed before any of the instructions in the chain. 615 const auto ToSplit = llvm::find_if( 616 Comparisons, [](const BCECmpBlock &B) { return B.RequireSplit; }); 617 if (ToSplit != Comparisons.end()) { 618 LLVM_DEBUG(dbgs() << "Splitting non_BCE work to header\n"); 619 ToSplit->split(BB, AA); 620 } 621 622 if (Comparisons.size() == 1) { 623 LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n"); 624 Value *const LhsLoad = 625 Builder.CreateLoad(FirstCmp.Lhs().LoadI->getType(), Lhs); 626 Value *const RhsLoad = 627 Builder.CreateLoad(FirstCmp.Rhs().LoadI->getType(), Rhs); 628 // There are no blocks to merge, just do the comparison. 629 IsEqual = Builder.CreateICmpEQ(LhsLoad, RhsLoad); 630 } else { 631 const unsigned TotalSizeBits = std::accumulate( 632 Comparisons.begin(), Comparisons.end(), 0u, 633 [](int Size, const BCECmpBlock &C) { return Size + C.SizeBits(); }); 634 635 // Create memcmp() == 0. 636 const auto &DL = Phi.getModule()->getDataLayout(); 637 Value *const MemCmpCall = emitMemCmp( 638 Lhs, Rhs, 639 ConstantInt::get(DL.getIntPtrType(Context), TotalSizeBits / 8), Builder, 640 DL, &TLI); 641 IsEqual = Builder.CreateICmpEQ( 642 MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0)); 643 } 644 645 BasicBlock *const PhiBB = Phi.getParent(); 646 // Add a branch to the next basic block in the chain. 647 if (NextCmpBlock == PhiBB) { 648 // Continue to phi, passing it the comparison result. 649 Builder.CreateBr(PhiBB); 650 Phi.addIncoming(IsEqual, BB); 651 DTU.applyUpdates({{DominatorTree::Insert, BB, PhiBB}}); 652 } else { 653 // Continue to next block if equal, exit to phi else. 654 Builder.CreateCondBr(IsEqual, NextCmpBlock, PhiBB); 655 Phi.addIncoming(ConstantInt::getFalse(Context), BB); 656 DTU.applyUpdates({{DominatorTree::Insert, BB, NextCmpBlock}, 657 {DominatorTree::Insert, BB, PhiBB}}); 658 } 659 return BB; 660 } 661 662 bool BCECmpChain::simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA, 663 DomTreeUpdater &DTU) { 664 assert(Comparisons_.size() >= 2 && "simplifying trivial BCECmpChain"); 665 // First pass to check if there is at least one merge. If not, we don't do 666 // anything and we keep analysis passes intact. 667 const auto AtLeastOneMerged = [this]() { 668 for (size_t I = 1; I < Comparisons_.size(); ++I) { 669 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) 670 return true; 671 } 672 return false; 673 }; 674 if (!AtLeastOneMerged()) 675 return false; 676 677 LLVM_DEBUG(dbgs() << "Simplifying comparison chain starting at block " 678 << EntryBlock_->getName() << "\n"); 679 680 // Effectively merge blocks. We go in the reverse direction from the phi block 681 // so that the next block is always available to branch to. 682 const auto mergeRange = [this, &TLI, &AA, &DTU](int I, int Num, 683 BasicBlock *InsertBefore, 684 BasicBlock *Next) { 685 return mergeComparisons(makeArrayRef(Comparisons_).slice(I, Num), 686 InsertBefore, Next, Phi_, TLI, AA, DTU); 687 }; 688 int NumMerged = 1; 689 BasicBlock *NextCmpBlock = Phi_.getParent(); 690 for (int I = static_cast<int>(Comparisons_.size()) - 2; I >= 0; --I) { 691 if (IsContiguous(Comparisons_[I], Comparisons_[I + 1])) { 692 LLVM_DEBUG(dbgs() << "Merging block " << Comparisons_[I].BB->getName() 693 << " into " << Comparisons_[I + 1].BB->getName() 694 << "\n"); 695 ++NumMerged; 696 } else { 697 NextCmpBlock = mergeRange(I + 1, NumMerged, NextCmpBlock, NextCmpBlock); 698 NumMerged = 1; 699 } 700 } 701 // Insert the entry block for the new chain before the old entry block. 702 // If the old entry block was the function entry, this ensures that the new 703 // entry can become the function entry. 704 NextCmpBlock = mergeRange(0, NumMerged, EntryBlock_, NextCmpBlock); 705 706 // Replace the original cmp chain with the new cmp chain by pointing all 707 // predecessors of EntryBlock_ to NextCmpBlock instead. This makes all cmp 708 // blocks in the old chain unreachable. 709 while (!pred_empty(EntryBlock_)) { 710 BasicBlock* const Pred = *pred_begin(EntryBlock_); 711 LLVM_DEBUG(dbgs() << "Updating jump into old chain from " << Pred->getName() 712 << "\n"); 713 Pred->getTerminator()->replaceUsesOfWith(EntryBlock_, NextCmpBlock); 714 DTU.applyUpdates({{DominatorTree::Delete, Pred, EntryBlock_}, 715 {DominatorTree::Insert, Pred, NextCmpBlock}}); 716 } 717 718 // If the old cmp chain was the function entry, we need to update the function 719 // entry. 720 const bool ChainEntryIsFnEntry = EntryBlock_->isEntryBlock(); 721 if (ChainEntryIsFnEntry && DTU.hasDomTree()) { 722 LLVM_DEBUG(dbgs() << "Changing function entry from " 723 << EntryBlock_->getName() << " to " 724 << NextCmpBlock->getName() << "\n"); 725 DTU.getDomTree().setNewRoot(NextCmpBlock); 726 DTU.applyUpdates({{DominatorTree::Delete, NextCmpBlock, EntryBlock_}}); 727 } 728 EntryBlock_ = nullptr; 729 730 // Delete merged blocks. This also removes incoming values in phi. 731 SmallVector<BasicBlock *, 16> DeadBlocks; 732 for (auto &Cmp : Comparisons_) { 733 LLVM_DEBUG(dbgs() << "Deleting merged block " << Cmp.BB->getName() << "\n"); 734 DeadBlocks.push_back(Cmp.BB); 735 } 736 DeleteDeadBlocks(DeadBlocks, &DTU); 737 738 Comparisons_.clear(); 739 return true; 740 } 741 742 std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi, 743 BasicBlock *const LastBlock, 744 int NumBlocks) { 745 // Walk up from the last block to find other blocks. 746 std::vector<BasicBlock *> Blocks(NumBlocks); 747 assert(LastBlock && "invalid last block"); 748 BasicBlock *CurBlock = LastBlock; 749 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) { 750 if (CurBlock->hasAddressTaken()) { 751 // Somebody is jumping to the block through an address, all bets are 752 // off. 753 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex 754 << " has its address taken\n"); 755 return {}; 756 } 757 Blocks[BlockIndex] = CurBlock; 758 auto *SinglePredecessor = CurBlock->getSinglePredecessor(); 759 if (!SinglePredecessor) { 760 // The block has two or more predecessors. 761 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex 762 << " has two or more predecessors\n"); 763 return {}; 764 } 765 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) { 766 // The block does not link back to the phi. 767 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex 768 << " does not link back to the phi\n"); 769 return {}; 770 } 771 CurBlock = SinglePredecessor; 772 } 773 Blocks[0] = CurBlock; 774 return Blocks; 775 } 776 777 bool processPhi(PHINode &Phi, const TargetLibraryInfo &TLI, AliasAnalysis &AA, 778 DomTreeUpdater &DTU) { 779 LLVM_DEBUG(dbgs() << "processPhi()\n"); 780 if (Phi.getNumIncomingValues() <= 1) { 781 LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n"); 782 return false; 783 } 784 // We are looking for something that has the following structure: 785 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+ 786 // \ \ \ \ 787 // ne ne ne \ 788 // \ \ \ v 789 // +------------+-----------+----------> bb_phi 790 // 791 // - The last basic block (bb4 here) must branch unconditionally to bb_phi. 792 // It's the only block that contributes a non-constant value to the Phi. 793 // - All other blocks (b1, b2, b3) must have exactly two successors, one of 794 // them being the phi block. 795 // - All intermediate blocks (bb2, bb3) must have only one predecessor. 796 // - Blocks cannot do other work besides the comparison, see doesOtherWork() 797 798 // The blocks are not necessarily ordered in the phi, so we start from the 799 // last block and reconstruct the order. 800 BasicBlock *LastBlock = nullptr; 801 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) { 802 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue; 803 if (LastBlock) { 804 // There are several non-constant values. 805 LLVM_DEBUG(dbgs() << "skip: several non-constant values\n"); 806 return false; 807 } 808 if (!isa<ICmpInst>(Phi.getIncomingValue(I)) || 809 cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() != 810 Phi.getIncomingBlock(I)) { 811 // Non-constant incoming value is not from a cmp instruction or not 812 // produced by the last block. We could end up processing the value 813 // producing block more than once. 814 // 815 // This is an uncommon case, so we bail. 816 LLVM_DEBUG( 817 dbgs() 818 << "skip: non-constant value not from cmp or not from last block.\n"); 819 return false; 820 } 821 LastBlock = Phi.getIncomingBlock(I); 822 } 823 if (!LastBlock) { 824 // There is no non-constant block. 825 LLVM_DEBUG(dbgs() << "skip: no non-constant block\n"); 826 return false; 827 } 828 if (LastBlock->getSingleSuccessor() != Phi.getParent()) { 829 LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n"); 830 return false; 831 } 832 833 const auto Blocks = 834 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues()); 835 if (Blocks.empty()) return false; 836 BCECmpChain CmpChain(Blocks, Phi, AA); 837 838 if (CmpChain.size() < 2) { 839 LLVM_DEBUG(dbgs() << "skip: only one compare block\n"); 840 return false; 841 } 842 843 return CmpChain.simplify(TLI, AA, DTU); 844 } 845 846 static bool runImpl(Function &F, const TargetLibraryInfo &TLI, 847 const TargetTransformInfo &TTI, AliasAnalysis &AA, 848 DominatorTree *DT) { 849 LLVM_DEBUG(dbgs() << "MergeICmpsLegacyPass: " << F.getName() << "\n"); 850 851 // We only try merging comparisons if the target wants to expand memcmp later. 852 // The rationale is to avoid turning small chains into memcmp calls. 853 if (!TTI.enableMemCmpExpansion(F.hasOptSize(), true)) 854 return false; 855 856 // If we don't have memcmp avaiable we can't emit calls to it. 857 if (!TLI.has(LibFunc_memcmp)) 858 return false; 859 860 DomTreeUpdater DTU(DT, /*PostDominatorTree*/ nullptr, 861 DomTreeUpdater::UpdateStrategy::Eager); 862 863 bool MadeChange = false; 864 865 for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) { 866 // A Phi operation is always first in a basic block. 867 if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin())) 868 MadeChange |= processPhi(*Phi, TLI, AA, DTU); 869 } 870 871 return MadeChange; 872 } 873 874 class MergeICmpsLegacyPass : public FunctionPass { 875 public: 876 static char ID; 877 878 MergeICmpsLegacyPass() : FunctionPass(ID) { 879 initializeMergeICmpsLegacyPassPass(*PassRegistry::getPassRegistry()); 880 } 881 882 bool runOnFunction(Function &F) override { 883 if (skipFunction(F)) return false; 884 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 885 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 886 // MergeICmps does not need the DominatorTree, but we update it if it's 887 // already available. 888 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 889 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 890 return runImpl(F, TLI, TTI, AA, DTWP ? &DTWP->getDomTree() : nullptr); 891 } 892 893 private: 894 void getAnalysisUsage(AnalysisUsage &AU) const override { 895 AU.addRequired<TargetLibraryInfoWrapperPass>(); 896 AU.addRequired<TargetTransformInfoWrapperPass>(); 897 AU.addRequired<AAResultsWrapperPass>(); 898 AU.addPreserved<GlobalsAAWrapperPass>(); 899 AU.addPreserved<DominatorTreeWrapperPass>(); 900 } 901 }; 902 903 } // namespace 904 905 char MergeICmpsLegacyPass::ID = 0; 906 INITIALIZE_PASS_BEGIN(MergeICmpsLegacyPass, "mergeicmps", 907 "Merge contiguous icmps into a memcmp", false, false) 908 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 909 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 910 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 911 INITIALIZE_PASS_END(MergeICmpsLegacyPass, "mergeicmps", 912 "Merge contiguous icmps into a memcmp", false, false) 913 914 Pass *llvm::createMergeICmpsLegacyPass() { return new MergeICmpsLegacyPass(); } 915 916 PreservedAnalyses MergeICmpsPass::run(Function &F, 917 FunctionAnalysisManager &AM) { 918 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 919 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 920 auto &AA = AM.getResult<AAManager>(F); 921 auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F); 922 const bool MadeChanges = runImpl(F, TLI, TTI, AA, DT); 923 if (!MadeChanges) 924 return PreservedAnalyses::all(); 925 PreservedAnalyses PA; 926 PA.preserve<DominatorTreeAnalysis>(); 927 return PA; 928 } 929