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