blob: a880e9e75783e762911b1209b4b9d433b56b9712 [file] [log] [blame]
Clement Courbet65130e22017-09-01 10:56:34 +00001//===- MergeICmps.cpp - Optimize chains of integer comparisons ------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Clement Courbet65130e22017-09-01 10:56:34 +00006//
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//
Clement Courbetcc004df2019-02-15 12:58:06 +000013// 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
Clement Courbet65130e22017-09-01 10:56:34 +000015// 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.
Clement Courbetcc004df2019-02-15 12:58:06 +000021//
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//
Clement Courbet65130e22017-09-01 10:56:34 +000042//===----------------------------------------------------------------------===//
43
Clement Courbeta95d95d2019-05-21 11:02:23 +000044#include "llvm/Analysis/DomTreeUpdater.h"
45#include "llvm/Analysis/GlobalsModRef.h"
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000046#include "llvm/Analysis/Loads.h"
47#include "llvm/Analysis/TargetLibraryInfo.h"
48#include "llvm/Analysis/TargetTransformInfo.h"
Clement Courbeta95d95d2019-05-21 11:02:23 +000049#include "llvm/IR/Dominators.h"
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000050#include "llvm/IR/Function.h"
51#include "llvm/IR/IRBuilder.h"
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000052#include "llvm/Pass.h"
53#include "llvm/Transforms/Scalar.h"
Clement Courbet632dfdd2019-05-17 09:43:45 +000054#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000055#include "llvm/Transforms/Utils/BuildLibCalls.h"
Clement Courbetf7e84a22019-02-15 14:17:17 +000056#include <algorithm>
57#include <numeric>
58#include <utility>
59#include <vector>
Clement Courbet65130e22017-09-01 10:56:34 +000060
61using namespace llvm;
62
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000063namespace {
64
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000065#define DEBUG_TYPE "mergeicmps"
66
Christy Leee9437482018-09-24 20:47:12 +000067// Returns true if the instruction is a simple load or a simple store
68static 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
Clement Courbetcc004df2019-02-15 12:58:06 +000076// 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.
Clement Courbet65130e22017-09-01 10:56:34 +000079struct BCEAtom {
Clement Courbetf7e84a22019-02-15 14:17:17 +000080 BCEAtom() = default;
81 BCEAtom(GetElementPtrInst *GEP, LoadInst *LoadI, int BaseId, APInt Offset)
82 : GEP(GEP), LoadI(LoadI), BaseId(BaseId), Offset(Offset) {}
Clement Courbetbc0c4452017-09-01 11:51:23 +000083
Clement Courbetf7e84a22019-02-15 14:17:17 +000084 // We want to order BCEAtoms by (Base, Offset). However we cannot use
85 // the pointer values for Base because these are non-deterministic.
86 // To make sure that the sort order is stable, we first assign to each atom
87 // base value an index based on its order of appearance in the chain of
88 // comparisons. We call this index `BaseOrdering`. For example, for:
89 // b[3] == c[2] && a[1] == d[1] && b[4] == c[3]
90 // | block 1 | | block 2 | | block 3 |
91 // b gets assigned index 0 and a index 1, because b appears as LHS in block 1,
92 // which is before block 2.
93 // We then sort by (BaseOrdering[LHS.Base()], LHS.Offset), which is stable.
Clement Courbet65130e22017-09-01 10:56:34 +000094 bool operator<(const BCEAtom &O) const {
Clement Courbetf7e84a22019-02-15 14:17:17 +000095 return BaseId != O.BaseId ? BaseId < O.BaseId : Offset.slt(O.Offset);
Clement Courbet65130e22017-09-01 10:56:34 +000096 }
97
Clement Courbetf7e84a22019-02-15 14:17:17 +000098 GetElementPtrInst *GEP = nullptr;
99 LoadInst *LoadI = nullptr;
100 unsigned BaseId = 0;
Clement Courbet65130e22017-09-01 10:56:34 +0000101 APInt Offset;
102};
103
Clement Courbetf7e84a22019-02-15 14:17:17 +0000104// A class that assigns increasing ids to values in the order in which they are
105// seen. See comment in `BCEAtom::operator<()``.
106class BaseIdentifier {
107public:
108 // Returns the id for value `Base`, after assigning one if `Base` has not been
109 // seen before.
110 int getBaseId(const Value *Base) {
111 assert(Base && "invalid base");
112 const auto Insertion = BaseToIndex.try_emplace(Base, Order);
113 if (Insertion.second)
114 ++Order;
115 return Insertion.first->second;
116 }
117
118private:
119 unsigned Order = 1;
120 DenseMap<const Value*, int> BaseToIndex;
121};
122
Clement Courbet65130e22017-09-01 10:56:34 +0000123// If this value is a load from a constant offset w.r.t. a base address, and
Xin Tong256869d2018-02-28 12:09:53 +0000124// there are no other users of the load or address, returns the base address and
Clement Courbet65130e22017-09-01 10:56:34 +0000125// the offset.
Clement Courbetf7e84a22019-02-15 14:17:17 +0000126BCEAtom visitICmpLoadOperand(Value *const Val, BaseIdentifier &BaseId) {
127 auto *const LoadI = dyn_cast<LoadInst>(Val);
128 if (!LoadI)
129 return {};
130 LLVM_DEBUG(dbgs() << "load\n");
131 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
132 LLVM_DEBUG(dbgs() << "used outside of block\n");
133 return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000134 }
Clement Courbetf7e84a22019-02-15 14:17:17 +0000135 // Do not optimize atomic loads to non-atomic memcmp
136 if (!LoadI->isSimple()) {
137 LLVM_DEBUG(dbgs() << "volatile or atomic\n");
138 return {};
139 }
140 Value *const Addr = LoadI->getOperand(0);
141 auto *const GEP = dyn_cast<GetElementPtrInst>(Addr);
142 if (!GEP)
143 return {};
144 LLVM_DEBUG(dbgs() << "GEP\n");
145 if (GEP->isUsedOutsideOfBlock(LoadI->getParent())) {
146 LLVM_DEBUG(dbgs() << "used outside of block\n");
147 return {};
148 }
149 const auto &DL = GEP->getModule()->getDataLayout();
150 if (!isDereferenceablePointer(GEP, DL)) {
151 LLVM_DEBUG(dbgs() << "not dereferenceable\n");
152 // We need to make sure that we can do comparison in any order, so we
153 // require memory to be unconditionnally dereferencable.
154 return {};
155 }
156 APInt Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
157 if (!GEP->accumulateConstantOffset(DL, Offset))
158 return {};
159 return BCEAtom(GEP, LoadI, BaseId.getBaseId(GEP->getPointerOperand()),
160 Offset);
Clement Courbet65130e22017-09-01 10:56:34 +0000161}
162
Clement Courbetcc004df2019-02-15 12:58:06 +0000163// A basic block with a comparison between two BCE atoms, e.g. `a == o.a` in the
164// example at the top.
Xin Tong0efadbb2018-04-09 13:14:06 +0000165// The block might do extra work besides the atom comparison, in which case
166// doesOtherWork() returns true. Under some conditions, the block can be
167// split into the atom comparison part and the "other work" part
168// (see canSplit()).
Clement Courbet65130e22017-09-01 10:56:34 +0000169// Note: the terminology is misleading: the comparison is symmetric, so there
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000170// is no real {l/r}hs. What we want though is to have the same base on the
171// left (resp. right), so that we can detect consecutive loads. To ensure this
172// we put the smallest atom on the left.
Clement Courbet65130e22017-09-01 10:56:34 +0000173class BCECmpBlock {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000174 public:
175 BCECmpBlock() {}
Clement Courbet65130e22017-09-01 10:56:34 +0000176
177 BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits)
Clement Courbet8361a102019-05-21 14:24:46 +0000178 : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000179 if (Rhs_ < Lhs_) std::swap(Rhs_, Lhs_);
Clement Courbet65130e22017-09-01 10:56:34 +0000180 }
181
Clement Courbetf7e84a22019-02-15 14:17:17 +0000182 bool IsValid() const { return Lhs_.BaseId != 0 && Rhs_.BaseId != 0; }
Clement Courbet65130e22017-09-01 10:56:34 +0000183
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000184 // Assert the block is consistent: If valid, it should also have
Clement Courbet65130e22017-09-01 10:56:34 +0000185 // non-null members besides Lhs_ and Rhs_.
186 void AssertConsistent() const {
187 if (IsValid()) {
188 assert(BB);
189 assert(CmpI);
190 assert(BranchI);
191 }
192 }
193
194 const BCEAtom &Lhs() const { return Lhs_; }
195 const BCEAtom &Rhs() const { return Rhs_; }
196 int SizeBits() const { return SizeBits_; }
197
198 // Returns true if the block does other works besides comparison.
199 bool doesOtherWork() const;
200
Xin Tong0efadbb2018-04-09 13:14:06 +0000201 // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp
202 // instructions in the block.
Christy Leee9437482018-09-24 20:47:12 +0000203 bool canSplit(AliasAnalysis *AA) const;
Xin Tong0efadbb2018-04-09 13:14:06 +0000204
205 // Return true if this all the relevant instructions in the BCE-cmp-block can
206 // be sunk below this instruction. By doing this, we know we can separate the
207 // BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the
208 // block.
Christy Leee9437482018-09-24 20:47:12 +0000209 bool canSinkBCECmpInst(const Instruction *, DenseSet<Instruction *> &,
210 AliasAnalysis *AA) const;
Xin Tong0efadbb2018-04-09 13:14:06 +0000211
212 // We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block
213 // instructions. Split the old block and move all non-BCE-cmp-insts into the
214 // new parent block.
Christy Leee9437482018-09-24 20:47:12 +0000215 void split(BasicBlock *NewParent, AliasAnalysis *AA) const;
Xin Tong0efadbb2018-04-09 13:14:06 +0000216
Clement Courbet65130e22017-09-01 10:56:34 +0000217 // The basic block where this comparison happens.
218 BasicBlock *BB = nullptr;
219 // The ICMP for this comparison.
220 ICmpInst *CmpI = nullptr;
221 // The terminating branch.
222 BranchInst *BranchI = nullptr;
Xin Tong0efadbb2018-04-09 13:14:06 +0000223 // The block requires splitting.
224 bool RequireSplit = false;
Clement Courbet65130e22017-09-01 10:56:34 +0000225
Xin Tong0efadbb2018-04-09 13:14:06 +0000226private:
Clement Courbet65130e22017-09-01 10:56:34 +0000227 BCEAtom Lhs_;
228 BCEAtom Rhs_;
229 int SizeBits_ = 0;
230};
231
Xin Tong0efadbb2018-04-09 13:14:06 +0000232bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst,
Christy Leee9437482018-09-24 20:47:12 +0000233 DenseSet<Instruction *> &BlockInsts,
234 AliasAnalysis *AA) const {
Xin Tong0efadbb2018-04-09 13:14:06 +0000235 // If this instruction has side effects and its in middle of the BCE cmp block
236 // instructions, then bail for now.
Christy Leee9437482018-09-24 20:47:12 +0000237 if (Inst->mayHaveSideEffects()) {
238 // Bail if this is not a simple load or store
239 if (!isSimpleLoadOrStore(Inst))
240 return false;
241 // Disallow stores that might alias the BCE operands
242 MemoryLocation LLoc = MemoryLocation::get(Lhs_.LoadI);
243 MemoryLocation RLoc = MemoryLocation::get(Rhs_.LoadI);
244 if (isModSet(AA->getModRefInfo(Inst, LLoc)) ||
245 isModSet(AA->getModRefInfo(Inst, RLoc)))
246 return false;
247 }
Xin Tong0efadbb2018-04-09 13:14:06 +0000248 // Make sure this instruction does not use any of the BCE cmp block
249 // instructions as operand.
250 for (auto BI : BlockInsts) {
251 if (is_contained(Inst->operands(), BI))
252 return false;
253 }
254 return true;
255}
256
Christy Leee9437482018-09-24 20:47:12 +0000257void BCECmpBlock::split(BasicBlock *NewParent, AliasAnalysis *AA) const {
Xin Tong0efadbb2018-04-09 13:14:06 +0000258 DenseSet<Instruction *> BlockInsts(
259 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
260 llvm::SmallVector<Instruction *, 4> OtherInsts;
261 for (Instruction &Inst : *BB) {
262 if (BlockInsts.count(&Inst))
263 continue;
Christy Leee9437482018-09-24 20:47:12 +0000264 assert(canSinkBCECmpInst(&Inst, BlockInsts, AA) &&
265 "Split unsplittable block");
Xin Tong0efadbb2018-04-09 13:14:06 +0000266 // This is a non-BCE-cmp-block instruction. And it can be separated
267 // from the BCE-cmp-block instruction.
268 OtherInsts.push_back(&Inst);
269 }
270
271 // Do the actual spliting.
272 for (Instruction *Inst : reverse(OtherInsts)) {
273 Inst->moveBefore(&*NewParent->begin());
274 }
275}
276
Christy Leee9437482018-09-24 20:47:12 +0000277bool BCECmpBlock::canSplit(AliasAnalysis *AA) const {
Xin Tong0efadbb2018-04-09 13:14:06 +0000278 DenseSet<Instruction *> BlockInsts(
279 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
280 for (Instruction &Inst : *BB) {
281 if (!BlockInsts.count(&Inst)) {
Christy Leee9437482018-09-24 20:47:12 +0000282 if (!canSinkBCECmpInst(&Inst, BlockInsts, AA))
Xin Tong0efadbb2018-04-09 13:14:06 +0000283 return false;
284 }
285 }
286 return true;
287}
288
Clement Courbet65130e22017-09-01 10:56:34 +0000289bool BCECmpBlock::doesOtherWork() const {
290 AssertConsistent();
Xin Tong8fd561f2018-03-06 02:24:02 +0000291 // All the instructions we care about in the BCE cmp block.
292 DenseSet<Instruction *> BlockInsts(
293 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
Clement Courbet65130e22017-09-01 10:56:34 +0000294 // TODO(courbet): Can we allow some other things ? This is very conservative.
Hiroshi Inoueae179002018-04-14 08:59:00 +0000295 // We might be able to get away with anything does not have any side
Clement Courbet65130e22017-09-01 10:56:34 +0000296 // effects outside of the basic block.
297 // Note: The GEPs and/or loads are not necessarily in the same block.
298 for (const Instruction &Inst : *BB) {
Xin Tong8fd561f2018-03-06 02:24:02 +0000299 if (!BlockInsts.count(&Inst))
Clement Courbet65130e22017-09-01 10:56:34 +0000300 return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000301 }
302 return false;
303}
304
305// Visit the given comparison. If this is a comparison between two valid
306// BCE atoms, returns the comparison.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000307BCECmpBlock visitICmp(const ICmpInst *const CmpI,
Clement Courbetf7e84a22019-02-15 14:17:17 +0000308 const ICmpInst::Predicate ExpectedPredicate,
309 BaseIdentifier &BaseId) {
Clement Courbet9f0b3172018-03-13 07:05:55 +0000310 // The comparison can only be used once:
311 // - For intermediate blocks, as a branch condition.
312 // - For the final block, as an incoming value for the Phi.
313 // If there are any other uses of the comparison, we cannot merge it with
314 // other comparisons as we would create an orphan use of the value.
315 if (!CmpI->hasOneUse()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000316 LLVM_DEBUG(dbgs() << "cmp has several uses\n");
Clement Courbet9f0b3172018-03-13 07:05:55 +0000317 return {};
318 }
Clement Courbetf7e84a22019-02-15 14:17:17 +0000319 if (CmpI->getPredicate() != ExpectedPredicate)
320 return {};
321 LLVM_DEBUG(dbgs() << "cmp "
322 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
323 << "\n");
324 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0), BaseId);
325 if (!Lhs.BaseId)
326 return {};
327 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1), BaseId);
328 if (!Rhs.BaseId)
329 return {};
330 const auto &DL = CmpI->getModule()->getDataLayout();
331 return BCECmpBlock(std::move(Lhs), std::move(Rhs),
332 DL.getTypeSizeInBits(CmpI->getOperand(0)->getType()));
Clement Courbet65130e22017-09-01 10:56:34 +0000333}
334
335// Visit the given comparison block. If this is a comparison between two valid
336// BCE atoms, returns the comparison.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000337BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block,
Clement Courbetf7e84a22019-02-15 14:17:17 +0000338 const BasicBlock *const PhiBlock,
339 BaseIdentifier &BaseId) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000340 if (Block->empty()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000341 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
Clement Courbet98eaa882017-10-04 15:13:52 +0000342 if (!BranchI) return {};
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000343 LLVM_DEBUG(dbgs() << "branch\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000344 if (BranchI->isUnconditional()) {
345 // In this case, we expect an incoming value which is the result of the
346 // comparison. This is the last link in the chain of comparisons (note
347 // that this does not mean that this is the last incoming value, blocks
348 // can be reordered).
349 auto *const CmpI = dyn_cast<ICmpInst>(Val);
Clement Courbet98eaa882017-10-04 15:13:52 +0000350 if (!CmpI) return {};
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000351 LLVM_DEBUG(dbgs() << "icmp\n");
Clement Courbetf7e84a22019-02-15 14:17:17 +0000352 auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ, BaseId);
Clement Courbet65130e22017-09-01 10:56:34 +0000353 Result.CmpI = CmpI;
354 Result.BranchI = BranchI;
355 return Result;
356 } else {
357 // In this case, we expect a constant incoming value (the comparison is
358 // chained).
359 const auto *const Const = dyn_cast<ConstantInt>(Val);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000360 LLVM_DEBUG(dbgs() << "const\n");
Clement Courbet98eaa882017-10-04 15:13:52 +0000361 if (!Const->isZero()) return {};
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000362 LLVM_DEBUG(dbgs() << "false\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000363 auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition());
Clement Courbet98eaa882017-10-04 15:13:52 +0000364 if (!CmpI) return {};
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000365 LLVM_DEBUG(dbgs() << "icmp\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000366 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
367 BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
368 auto Result = visitICmp(
Clement Courbetf7e84a22019-02-15 14:17:17 +0000369 CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
370 BaseId);
Clement Courbet65130e22017-09-01 10:56:34 +0000371 Result.CmpI = CmpI;
372 Result.BranchI = BranchI;
373 return Result;
374 }
375 return {};
376}
377
Xin Tong0efadbb2018-04-09 13:14:06 +0000378static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
Clement Courbet8361a102019-05-21 14:24:46 +0000379 BCECmpBlock &Comparison) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000380 LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName()
381 << "': Found cmp of " << Comparison.SizeBits()
Clement Courbetf7e84a22019-02-15 14:17:17 +0000382 << " bits between " << Comparison.Lhs().BaseId << " + "
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000383 << Comparison.Lhs().Offset << " and "
Clement Courbetf7e84a22019-02-15 14:17:17 +0000384 << Comparison.Rhs().BaseId << " + "
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000385 << Comparison.Rhs().Offset << "\n");
386 LLVM_DEBUG(dbgs() << "\n");
Clement Courbet8361a102019-05-21 14:24:46 +0000387 Comparisons.push_back(Comparison);
Xin Tong0efadbb2018-04-09 13:14:06 +0000388}
389
Clement Courbet65130e22017-09-01 10:56:34 +0000390// A chain of comparisons.
391class BCECmpChain {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000392 public:
Christy Leee9437482018-09-24 20:47:12 +0000393 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
394 AliasAnalysis *AA);
Clement Courbet65130e22017-09-01 10:56:34 +0000395
396 int size() const { return Comparisons_.size(); }
397
398#ifdef MERGEICMPS_DOT_ON
399 void dump() const;
400#endif // MERGEICMPS_DOT_ON
401
Clement Courbeta95d95d2019-05-21 11:02:23 +0000402 bool simplify(const TargetLibraryInfo *const TLI, AliasAnalysis *AA,
403 DomTreeUpdater &DTU);
Clement Courbet65130e22017-09-01 10:56:34 +0000404
Clement Courbeta95d95d2019-05-21 11:02:23 +0000405private:
Clement Courbet65130e22017-09-01 10:56:34 +0000406 static bool IsContiguous(const BCECmpBlock &First,
407 const BCECmpBlock &Second) {
Clement Courbetf7e84a22019-02-15 14:17:17 +0000408 return First.Lhs().BaseId == Second.Lhs().BaseId &&
409 First.Rhs().BaseId == Second.Rhs().BaseId &&
Clement Courbet65130e22017-09-01 10:56:34 +0000410 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
411 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
412 }
413
Clement Courbet65130e22017-09-01 10:56:34 +0000414 PHINode &Phi_;
415 std::vector<BCECmpBlock> Comparisons_;
416 // The original entry block (before sorting);
417 BasicBlock *EntryBlock_;
418};
419
Christy Leee9437482018-09-24 20:47:12 +0000420BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
421 AliasAnalysis *AA)
Clement Courbet65130e22017-09-01 10:56:34 +0000422 : Phi_(Phi) {
Clement Courbetc2109c82018-02-06 09:14:00 +0000423 assert(!Blocks.empty() && "a chain should have at least one block");
Clement Courbet65130e22017-09-01 10:56:34 +0000424 // Now look inside blocks to check for BCE comparisons.
425 std::vector<BCECmpBlock> Comparisons;
Clement Courbetf7e84a22019-02-15 14:17:17 +0000426 BaseIdentifier BaseId;
Clement Courbeta7a17462018-02-06 12:25:33 +0000427 for (size_t BlockIdx = 0; BlockIdx < Blocks.size(); ++BlockIdx) {
428 BasicBlock *const Block = Blocks[BlockIdx];
Clement Courbetc2109c82018-02-06 09:14:00 +0000429 assert(Block && "invalid block");
Clement Courbet65130e22017-09-01 10:56:34 +0000430 BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block),
Clement Courbetf7e84a22019-02-15 14:17:17 +0000431 Block, Phi.getParent(), BaseId);
Clement Courbet65130e22017-09-01 10:56:34 +0000432 Comparison.BB = Block;
433 if (!Comparison.IsValid()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000434 LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000435 return;
436 }
437 if (Comparison.doesOtherWork()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000438 LLVM_DEBUG(dbgs() << "block '" << Comparison.BB->getName()
439 << "' does extra work besides compare\n");
Xin Tong8345c0e2018-03-05 13:54:47 +0000440 if (Comparisons.empty()) {
Xin Tong0efadbb2018-04-09 13:14:06 +0000441 // This is the initial block in the chain, in case this block does other
442 // work, we can try to split the block and move the irrelevant
443 // instructions to the predecessor.
444 //
445 // If this is not the initial block in the chain, splitting it wont
446 // work.
447 //
448 // As once split, there will still be instructions before the BCE cmp
449 // instructions that do other work in program order, i.e. within the
450 // chain before sorting. Unless we can abort the chain at this point
451 // and start anew.
452 //
Clement Courbet632dfdd2019-05-17 09:43:45 +0000453 // NOTE: we only handle blocks a with single predecessor for now.
Christy Leee9437482018-09-24 20:47:12 +0000454 if (Comparison.canSplit(AA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000455 LLVM_DEBUG(dbgs()
456 << "Split initial block '" << Comparison.BB->getName()
457 << "' that does extra work besides compare\n");
Xin Tong0efadbb2018-04-09 13:14:06 +0000458 Comparison.RequireSplit = true;
Clement Courbet8361a102019-05-21 14:24:46 +0000459 enqueueBlock(Comparisons, Comparison);
Xin Tong0efadbb2018-04-09 13:14:06 +0000460 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000461 LLVM_DEBUG(dbgs()
462 << "ignoring initial block '" << Comparison.BB->getName()
463 << "' that does extra work besides compare\n");
Xin Tong0efadbb2018-04-09 13:14:06 +0000464 }
Clement Courbet65130e22017-09-01 10:56:34 +0000465 continue;
466 }
467 // TODO(courbet): Right now we abort the whole chain. We could be
468 // merging only the blocks that don't do other work and resume the
469 // chain from there. For example:
470 // if (a[0] == b[0]) { // bb1
471 // if (a[1] == b[1]) { // bb2
472 // some_value = 3; //bb3
473 // if (a[2] == b[2]) { //bb3
474 // do a ton of stuff //bb4
475 // }
476 // }
477 // }
478 //
479 // This is:
480 //
481 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
482 // \ \ \ \
483 // ne ne ne \
484 // \ \ \ v
485 // +------------+-----------+----------> bb_phi
486 //
487 // We can only merge the first two comparisons, because bb3* does
488 // "other work" (setting some_value to 3).
489 // We could still merge bb1 and bb2 though.
490 return;
491 }
Clement Courbet8361a102019-05-21 14:24:46 +0000492 enqueueBlock(Comparisons, Comparison);
Clement Courbet65130e22017-09-01 10:56:34 +0000493 }
Xin Tong8345c0e2018-03-05 13:54:47 +0000494
495 // It is possible we have no suitable comparison to merge.
496 if (Comparisons.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000497 LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
Xin Tong8345c0e2018-03-05 13:54:47 +0000498 return;
499 }
Clement Courbet65130e22017-09-01 10:56:34 +0000500 EntryBlock_ = Comparisons[0].BB;
501 Comparisons_ = std::move(Comparisons);
502#ifdef MERGEICMPS_DOT_ON
503 errs() << "BEFORE REORDERING:\n\n";
504 dump();
505#endif // MERGEICMPS_DOT_ON
506 // Reorder blocks by LHS. We can do that without changing the
507 // semantics because we are only accessing dereferencable memory.
Clement Courbetf7e84a22019-02-15 14:17:17 +0000508 llvm::sort(Comparisons_,
509 [](const BCECmpBlock &LhsBlock, const BCECmpBlock &RhsBlock) {
Clement Courbet122c6e62019-05-21 17:58:42 +0000510 return std::tie(LhsBlock.Lhs(), LhsBlock.Rhs()) <
511 std::tie(RhsBlock.Lhs(), RhsBlock.Rhs());
Clement Courbetf7e84a22019-02-15 14:17:17 +0000512 });
Clement Courbet65130e22017-09-01 10:56:34 +0000513#ifdef MERGEICMPS_DOT_ON
514 errs() << "AFTER REORDERING:\n\n";
515 dump();
516#endif // MERGEICMPS_DOT_ON
517}
518
519#ifdef MERGEICMPS_DOT_ON
520void BCECmpChain::dump() const {
521 errs() << "digraph dag {\n";
522 errs() << " graph [bgcolor=transparent];\n";
523 errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n";
524 errs() << " edge [color=black];\n";
525 for (size_t I = 0; I < Comparisons_.size(); ++I) {
526 const auto &Comparison = Comparisons_[I];
527 errs() << " \"" << I << "\" [label=\"%"
528 << Comparison.Lhs().Base()->getName() << " + "
529 << Comparison.Lhs().Offset << " == %"
530 << Comparison.Rhs().Base()->getName() << " + "
531 << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8)
532 << " bytes)\"];\n";
533 const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
Clement Courbet98eaa882017-10-04 15:13:52 +0000534 if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n";
Clement Courbet65130e22017-09-01 10:56:34 +0000535 errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n";
536 }
537 errs() << " \"Phi\" [label=\"Phi\"];\n";
538 errs() << "}\n\n";
539}
540#endif // MERGEICMPS_DOT_ON
541
Clement Courbet632dfdd2019-05-17 09:43:45 +0000542namespace {
543
544// A class to compute the name of a set of merged basic blocks.
545// This is optimized for the common case of no block names.
546class MergedBlockName {
547 // Storage for the uncommon case of several named blocks.
548 SmallString<16> Scratch;
549
550public:
551 explicit MergedBlockName(ArrayRef<BCECmpBlock> Comparisons)
552 : Name(makeName(Comparisons)) {}
553 const StringRef Name;
554
555private:
556 StringRef makeName(ArrayRef<BCECmpBlock> Comparisons) {
557 assert(!Comparisons.empty() && "no basic block");
558 // Fast path: only one block, or no names at all.
559 if (Comparisons.size() == 1)
560 return Comparisons[0].BB->getName();
561 const int size = std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
562 [](int i, const BCECmpBlock &Cmp) {
563 return i + Cmp.BB->getName().size();
564 });
565 if (size == 0)
566 return StringRef("", 0);
567
568 // Slow path: at least two blocks, at least one block with a name.
569 Scratch.clear();
570 // We'll have `size` bytes for name and `Comparisons.size() - 1` bytes for
571 // separators.
572 Scratch.reserve(size + Comparisons.size() - 1);
573 const auto append = [this](StringRef str) {
574 Scratch.append(str.begin(), str.end());
575 };
576 append(Comparisons[0].BB->getName());
577 for (int I = 1, E = Comparisons.size(); I < E; ++I) {
578 const BasicBlock *const BB = Comparisons[I].BB;
579 if (!BB->getName().empty()) {
580 append("+");
581 append(BB->getName());
Nico Weberd764e7c2019-05-17 00:43:53 +0000582 }
Clement Courbetc4fdd712019-05-16 06:18:02 +0000583 }
Clement Courbet632dfdd2019-05-17 09:43:45 +0000584 return StringRef(Scratch);
Nico Weberd764e7c2019-05-17 00:43:53 +0000585 }
Clement Courbet632dfdd2019-05-17 09:43:45 +0000586};
587} // namespace
Clement Courbetc4fdd712019-05-16 06:18:02 +0000588
Clement Courbet632dfdd2019-05-17 09:43:45 +0000589// Merges the given contiguous comparison blocks into one memcmp block.
590static BasicBlock *mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
Clement Courbeta95d95d2019-05-21 11:02:23 +0000591 BasicBlock *const InsertBefore,
Clement Courbet632dfdd2019-05-17 09:43:45 +0000592 BasicBlock *const NextCmpBlock,
593 PHINode &Phi,
594 const TargetLibraryInfo *const TLI,
Clement Courbeta95d95d2019-05-21 11:02:23 +0000595 AliasAnalysis *AA, DomTreeUpdater &DTU) {
Clement Courbet632dfdd2019-05-17 09:43:45 +0000596 assert(!Comparisons.empty() && "merging zero comparisons");
597 LLVMContext &Context = NextCmpBlock->getContext();
598 const BCECmpBlock &FirstCmp = Comparisons[0];
Nico Weberd764e7c2019-05-17 00:43:53 +0000599
Clement Courbet632dfdd2019-05-17 09:43:45 +0000600 // Create a new cmp block before next cmp block.
601 BasicBlock *const BB =
602 BasicBlock::Create(Context, MergedBlockName(Comparisons).Name,
Clement Courbeta95d95d2019-05-21 11:02:23 +0000603 NextCmpBlock->getParent(), InsertBefore);
Clement Courbet632dfdd2019-05-17 09:43:45 +0000604 IRBuilder<> Builder(BB);
605 // Add the GEPs from the first BCECmpBlock.
606 Value *const Lhs = Builder.Insert(FirstCmp.Lhs().GEP->clone());
607 Value *const Rhs = Builder.Insert(FirstCmp.Rhs().GEP->clone());
Nico Weberd764e7c2019-05-17 00:43:53 +0000608
Clement Courbet632dfdd2019-05-17 09:43:45 +0000609 Value *IsEqual = nullptr;
Clement Courbeta95d95d2019-05-21 11:02:23 +0000610 LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons -> "
611 << BB->getName() << "\n");
Clement Courbet632dfdd2019-05-17 09:43:45 +0000612 if (Comparisons.size() == 1) {
613 LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n");
614 Value *const LhsLoad =
615 Builder.CreateLoad(FirstCmp.Lhs().LoadI->getType(), Lhs);
616 Value *const RhsLoad =
617 Builder.CreateLoad(FirstCmp.Rhs().LoadI->getType(), Rhs);
618 // There are no blocks to merge, just do the comparison.
619 IsEqual = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
620 } else {
Nico Weberd764e7c2019-05-17 00:43:53 +0000621 // If there is one block that requires splitting, we do it now, i.e.
622 // just before we know we will collapse the chain. The instructions
623 // can be executed before any of the instructions in the chain.
Clement Courbet632dfdd2019-05-17 09:43:45 +0000624 const auto ToSplit =
625 std::find_if(Comparisons.begin(), Comparisons.end(),
626 [](const BCECmpBlock &B) { return B.RequireSplit; });
627 if (ToSplit != Comparisons.end()) {
628 LLVM_DEBUG(dbgs() << "Splitting non_BCE work to header\n");
629 ToSplit->split(BB, AA);
630 }
Nico Weberd764e7c2019-05-17 00:43:53 +0000631
Clement Courbet632dfdd2019-05-17 09:43:45 +0000632 const unsigned TotalSizeBits = std::accumulate(
633 Comparisons.begin(), Comparisons.end(), 0u,
634 [](int Size, const BCECmpBlock &C) { return Size + C.SizeBits(); });
Nico Weberd764e7c2019-05-17 00:43:53 +0000635
Clement Courbet632dfdd2019-05-17 09:43:45 +0000636 // Create memcmp() == 0.
Nico Weberd764e7c2019-05-17 00:43:53 +0000637 const auto &DL = Phi.getModule()->getDataLayout();
638 Value *const MemCmpCall = emitMemCmp(
Clement Courbet632dfdd2019-05-17 09:43:45 +0000639 Lhs, Rhs,
640 ConstantInt::get(DL.getIntPtrType(Context), TotalSizeBits / 8), Builder,
641 DL, TLI);
642 IsEqual = Builder.CreateICmpEQ(
Nico Weberd764e7c2019-05-17 00:43:53 +0000643 MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0));
Clement Courbet632dfdd2019-05-17 09:43:45 +0000644 }
Nico Weberd764e7c2019-05-17 00:43:53 +0000645
Clement Courbet632dfdd2019-05-17 09:43:45 +0000646 BasicBlock *const PhiBB = Phi.getParent();
647 // Add a branch to the next basic block in the chain.
648 if (NextCmpBlock == PhiBB) {
649 // Continue to phi, passing it the comparison result.
Clement Courbeta95d95d2019-05-21 11:02:23 +0000650 Builder.CreateBr(PhiBB);
Clement Courbet632dfdd2019-05-17 09:43:45 +0000651 Phi.addIncoming(IsEqual, BB);
Clement Courbeta95d95d2019-05-21 11:02:23 +0000652 DTU.applyUpdates({{DominatorTree::Insert, BB, PhiBB}});
Nico Weberd764e7c2019-05-17 00:43:53 +0000653 } else {
Clement Courbet632dfdd2019-05-17 09:43:45 +0000654 // Continue to next block if equal, exit to phi else.
655 Builder.CreateCondBr(IsEqual, NextCmpBlock, PhiBB);
656 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
Clement Courbeta95d95d2019-05-21 11:02:23 +0000657 DTU.applyUpdates({{DominatorTree::Insert, BB, NextCmpBlock},
658 {DominatorTree::Insert, BB, PhiBB}});
Clement Courbet632dfdd2019-05-17 09:43:45 +0000659 }
660 return BB;
661}
662
663bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI,
Clement Courbeta95d95d2019-05-21 11:02:23 +0000664 AliasAnalysis *AA, DomTreeUpdater &DTU) {
Clement Courbet632dfdd2019-05-17 09:43:45 +0000665 assert(Comparisons_.size() >= 2 && "simplifying trivial BCECmpChain");
666 // First pass to check if there is at least one merge. If not, we don't do
667 // anything and we keep analysis passes intact.
668 const auto AtLeastOneMerged = [this]() {
669 for (size_t I = 1; I < Comparisons_.size(); ++I) {
670 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I]))
671 return true;
672 }
673 return false;
674 };
675 if (!AtLeastOneMerged())
676 return false;
677
Clement Courbet90900fb2019-05-17 12:07:51 +0000678 LLVM_DEBUG(dbgs() << "Simplifying comparison chain starting at block "
679 << EntryBlock_->getName() << "\n");
680
Clement Courbet632dfdd2019-05-17 09:43:45 +0000681 // Effectively merge blocks. We go in the reverse direction from the phi block
682 // so that the next block is always available to branch to.
Clement Courbeta95d95d2019-05-21 11:02:23 +0000683 const auto mergeRange = [this, TLI, AA, &DTU](int I, int Num,
684 BasicBlock *InsertBefore,
685 BasicBlock *Next) {
686 return mergeComparisons(makeArrayRef(Comparisons_).slice(I, Num),
687 InsertBefore, Next, Phi_, TLI, AA, DTU);
Clement Courbet632dfdd2019-05-17 09:43:45 +0000688 };
689 int NumMerged = 1;
690 BasicBlock *NextCmpBlock = Phi_.getParent();
691 for (int I = static_cast<int>(Comparisons_.size()) - 2; I >= 0; --I) {
692 if (IsContiguous(Comparisons_[I], Comparisons_[I + 1])) {
Clement Courbet90900fb2019-05-17 12:07:51 +0000693 LLVM_DEBUG(dbgs() << "Merging block " << Comparisons_[I].BB->getName()
694 << " into " << Comparisons_[I + 1].BB->getName()
695 << "\n");
Clement Courbet632dfdd2019-05-17 09:43:45 +0000696 ++NumMerged;
Nico Weberd764e7c2019-05-17 00:43:53 +0000697 } else {
Clement Courbeta95d95d2019-05-21 11:02:23 +0000698 NextCmpBlock = mergeRange(I + 1, NumMerged, NextCmpBlock, NextCmpBlock);
Clement Courbet632dfdd2019-05-17 09:43:45 +0000699 NumMerged = 1;
Nico Weberd764e7c2019-05-17 00:43:53 +0000700 }
701 }
Clement Courbeta95d95d2019-05-21 11:02:23 +0000702 // Insert the entry block for the new chain before the old entry block.
703 // If the old entry block was the function entry, this ensures that the new
704 // entry can become the function entry.
705 NextCmpBlock = mergeRange(0, NumMerged, EntryBlock_, NextCmpBlock);
Clement Courbet632dfdd2019-05-17 09:43:45 +0000706
707 // Replace the original cmp chain with the new cmp chain by pointing all
708 // predecessors of EntryBlock_ to NextCmpBlock instead. This makes all cmp
709 // blocks in the old chain unreachable.
710 while (!pred_empty(EntryBlock_)) {
711 BasicBlock* const Pred = *pred_begin(EntryBlock_);
Clement Courbet90900fb2019-05-17 12:07:51 +0000712 LLVM_DEBUG(dbgs() << "Updating jump into old chain from " << Pred->getName()
713 << "\n");
Clement Courbet632dfdd2019-05-17 09:43:45 +0000714 Pred->getTerminator()->replaceUsesOfWith(EntryBlock_, NextCmpBlock);
Clement Courbeta95d95d2019-05-21 11:02:23 +0000715 DTU.applyUpdates({{DominatorTree::Delete, Pred, EntryBlock_},
716 {DominatorTree::Insert, Pred, NextCmpBlock}});
717 }
718
719 // If the old cmp chain was the function entry, we need to update the function
720 // entry.
721 const bool ChainEntryIsFnEntry =
722 (EntryBlock_ == &EntryBlock_->getParent()->getEntryBlock());
723 if (ChainEntryIsFnEntry && DTU.hasDomTree()) {
724 LLVM_DEBUG(dbgs() << "Changing function entry from "
725 << EntryBlock_->getName() << " to "
726 << NextCmpBlock->getName() << "\n");
727 DTU.getDomTree().setNewRoot(NextCmpBlock);
728 DTU.applyUpdates({{DominatorTree::Delete, NextCmpBlock, EntryBlock_}});
Clement Courbet632dfdd2019-05-17 09:43:45 +0000729 }
730 EntryBlock_ = nullptr;
731
732 // Delete merged blocks. This also removes incoming values in phi.
733 SmallVector<BasicBlock *, 16> DeadBlocks;
734 for (auto &Cmp : Comparisons_) {
Clement Courbet90900fb2019-05-17 12:07:51 +0000735 LLVM_DEBUG(dbgs() << "Deleting merged block " << Cmp.BB->getName() << "\n");
Clement Courbet632dfdd2019-05-17 09:43:45 +0000736 DeadBlocks.push_back(Cmp.BB);
737 }
Clement Courbeta95d95d2019-05-21 11:02:23 +0000738 DeleteDeadBlocks(DeadBlocks, &DTU);
Clement Courbet632dfdd2019-05-17 09:43:45 +0000739
740 Comparisons_.clear();
741 return true;
Nico Weberd764e7c2019-05-17 00:43:53 +0000742}
743
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000744std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
745 BasicBlock *const LastBlock,
746 int NumBlocks) {
Clement Courbet65130e22017-09-01 10:56:34 +0000747 // Walk up from the last block to find other blocks.
748 std::vector<BasicBlock *> Blocks(NumBlocks);
Clement Courbetc2109c82018-02-06 09:14:00 +0000749 assert(LastBlock && "invalid last block");
Clement Courbet65130e22017-09-01 10:56:34 +0000750 BasicBlock *CurBlock = LastBlock;
751 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
752 if (CurBlock->hasAddressTaken()) {
753 // Somebody is jumping to the block through an address, all bets are
754 // off.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000755 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
756 << " has its address taken\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000757 return {};
758 }
759 Blocks[BlockIndex] = CurBlock;
760 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
761 if (!SinglePredecessor) {
762 // The block has two or more predecessors.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000763 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
764 << " has two or more predecessors\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000765 return {};
766 }
767 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
768 // The block does not link back to the phi.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000769 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
770 << " does not link back to the phi\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000771 return {};
772 }
773 CurBlock = SinglePredecessor;
774 }
775 Blocks[0] = CurBlock;
776 return Blocks;
777}
778
Christy Leee9437482018-09-24 20:47:12 +0000779bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI,
Clement Courbeta95d95d2019-05-21 11:02:23 +0000780 AliasAnalysis *AA, DomTreeUpdater &DTU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000781 LLVM_DEBUG(dbgs() << "processPhi()\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000782 if (Phi.getNumIncomingValues() <= 1) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000783 LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000784 return false;
785 }
786 // We are looking for something that has the following structure:
787 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
788 // \ \ \ \
789 // ne ne ne \
790 // \ \ \ v
791 // +------------+-----------+----------> bb_phi
792 //
793 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
794 // It's the only block that contributes a non-constant value to the Phi.
795 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000796 // them being the phi block.
Clement Courbet65130e22017-09-01 10:56:34 +0000797 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
798 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
799
800 // The blocks are not necessarily ordered in the phi, so we start from the
801 // last block and reconstruct the order.
802 BasicBlock *LastBlock = nullptr;
803 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000804 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
Clement Courbet65130e22017-09-01 10:56:34 +0000805 if (LastBlock) {
806 // There are several non-constant values.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000807 LLVM_DEBUG(dbgs() << "skip: several non-constant values\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000808 return false;
809 }
Xin Tong8ba674e2018-02-28 12:08:00 +0000810 if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
811 cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
812 Phi.getIncomingBlock(I)) {
813 // Non-constant incoming value is not from a cmp instruction or not
814 // produced by the last block. We could end up processing the value
815 // producing block more than once.
816 //
817 // This is an uncommon case, so we bail.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000818 LLVM_DEBUG(
Xin Tong8ba674e2018-02-28 12:08:00 +0000819 dbgs()
820 << "skip: non-constant value not from cmp or not from last block.\n");
821 return false;
822 }
Clement Courbet65130e22017-09-01 10:56:34 +0000823 LastBlock = Phi.getIncomingBlock(I);
824 }
825 if (!LastBlock) {
826 // There is no non-constant block.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000827 LLVM_DEBUG(dbgs() << "skip: no non-constant block\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000828 return false;
829 }
830 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000831 LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000832 return false;
833 }
834
835 const auto Blocks =
836 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
Clement Courbet98eaa882017-10-04 15:13:52 +0000837 if (Blocks.empty()) return false;
Christy Leee9437482018-09-24 20:47:12 +0000838 BCECmpChain CmpChain(Blocks, Phi, AA);
Clement Courbet65130e22017-09-01 10:56:34 +0000839
840 if (CmpChain.size() < 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000841 LLVM_DEBUG(dbgs() << "skip: only one compare block\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000842 return false;
843 }
844
Clement Courbeta95d95d2019-05-21 11:02:23 +0000845 return CmpChain.simplify(TLI, AA, DTU);
Clement Courbet65130e22017-09-01 10:56:34 +0000846}
847
848class MergeICmps : public FunctionPass {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000849 public:
Clement Courbet65130e22017-09-01 10:56:34 +0000850 static char ID;
851
852 MergeICmps() : FunctionPass(ID) {
853 initializeMergeICmpsPass(*PassRegistry::getPassRegistry());
854 }
855
856 bool runOnFunction(Function &F) override {
857 if (skipFunction(F)) return false;
858 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000859 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Clement Courbeta95d95d2019-05-21 11:02:23 +0000860 // MergeICmps does not need the DominatorTree, but we update it if it's
861 // already available.
862 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
863 DomTreeUpdater DTU(DTWP ? &DTWP->getDomTree() : nullptr,
864 /*PostDominatorTree*/ nullptr,
865 DomTreeUpdater::UpdateStrategy::Eager);
Christy Leee9437482018-09-24 20:47:12 +0000866 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Clement Courbeta95d95d2019-05-21 11:02:23 +0000867 auto PA = runImpl(F, &TLI, &TTI, AA, DTU);
Clement Courbet65130e22017-09-01 10:56:34 +0000868 return !PA.areAllPreserved();
869 }
870
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000871 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000872 void getAnalysisUsage(AnalysisUsage &AU) const override {
873 AU.addRequired<TargetLibraryInfoWrapperPass>();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000874 AU.addRequired<TargetTransformInfoWrapperPass>();
Christy Leee9437482018-09-24 20:47:12 +0000875 AU.addRequired<AAResultsWrapperPass>();
Clement Courbeta95d95d2019-05-21 11:02:23 +0000876 AU.addPreserved<GlobalsAAWrapperPass>();
877 AU.addPreserved<DominatorTreeWrapperPass>();
Clement Courbet65130e22017-09-01 10:56:34 +0000878 }
879
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000880 PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
Clement Courbeta95d95d2019-05-21 11:02:23 +0000881 const TargetTransformInfo *TTI, AliasAnalysis *AA,
882 DomTreeUpdater &DTU);
Clement Courbet65130e22017-09-01 10:56:34 +0000883};
884
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000885PreservedAnalyses MergeICmps::runImpl(Function &F, const TargetLibraryInfo *TLI,
Christy Leee9437482018-09-24 20:47:12 +0000886 const TargetTransformInfo *TTI,
Clement Courbeta95d95d2019-05-21 11:02:23 +0000887 AliasAnalysis *AA, DomTreeUpdater &DTU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000888 LLVM_DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000889
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000890 // 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.
Clement Courbetb2c3eb82017-10-30 14:19:33 +0000892 if (!TTI->enableMemCmpExpansion(true)) return PreservedAnalyses::all();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000893
Benjamin Kramera76b64f2018-05-19 12:51:59 +0000894 // If we don't have memcmp avaiable we can't emit calls to it.
895 if (!TLI->has(LibFunc_memcmp))
896 return PreservedAnalyses::all();
897
Clement Courbet65130e22017-09-01 10:56:34 +0000898 bool MadeChange = false;
899
900 for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) {
901 // A Phi operation is always first in a basic block.
902 if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
Clement Courbeta95d95d2019-05-21 11:02:23 +0000903 MadeChange |= processPhi(*Phi, TLI, AA, DTU);
Clement Courbet65130e22017-09-01 10:56:34 +0000904 }
905
Clement Courbeta95d95d2019-05-21 11:02:23 +0000906 if (!MadeChange)
907 return PreservedAnalyses::all();
908 PreservedAnalyses PA;
909 PA.preserve<GlobalsAA>();
910 PA.preserve<DominatorTreeAnalysis>();
911 return PA;
Clement Courbet65130e22017-09-01 10:56:34 +0000912}
913
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000914} // namespace
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000915
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000916char MergeICmps::ID = 0;
Clement Courbet65130e22017-09-01 10:56:34 +0000917INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps",
918 "Merge contiguous icmps into a memcmp", false, false)
919INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000920INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Christy Leee9437482018-09-24 20:47:12 +0000921INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Clement Courbet65130e22017-09-01 10:56:34 +0000922INITIALIZE_PASS_END(MergeICmps, "mergeicmps",
923 "Merge contiguous icmps into a memcmp", false, false)
924
925Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); }