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