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