blob: 16c4bff6629639dcdf9813d21c366d4984af523a [file] [log] [blame]
Clement Courbet65130e22017-09-01 10:56:34 +00001//===- 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.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000022
Clement Courbet65130e22017-09-01 10:56:34 +000023//===----------------------------------------------------------------------===//
24
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000025#include <algorithm>
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000026#include <numeric>
27#include <utility>
28#include <vector>
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000029#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"
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000034#include "llvm/Pass.h"
35#include "llvm/Transforms/Scalar.h"
36#include "llvm/Transforms/Utils/BuildLibCalls.h"
Clement Courbet65130e22017-09-01 10:56:34 +000037
38using namespace llvm;
39
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000040namespace {
41
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000042#define DEBUG_TYPE "mergeicmps"
43
Clement Courbet65130e22017-09-01 10:56:34 +000044// A BCE atom.
45struct BCEAtom {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000046 BCEAtom() : GEP(nullptr), LoadI(nullptr), Offset() {}
Clement Courbetbc0c4452017-09-01 11:51:23 +000047
Clement Courbet65130e22017-09-01 10:56:34 +000048 const Value *Base() const { return GEP ? GEP->getPointerOperand() : nullptr; }
49
50 bool operator<(const BCEAtom &O) const {
Clement Courbete2e8a5c2017-10-10 08:00:45 +000051 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;
Clement Courbet65130e22017-09-01 10:56:34 +000066 }
67
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000068 GetElementPtrInst *GEP;
69 LoadInst *LoadI;
Clement Courbet65130e22017-09-01 10:56:34 +000070 APInt Offset;
71};
72
73// If this value is a load from a constant offset w.r.t. a base address, and
Xin Tong256869d2018-02-28 12:09:53 +000074// there are no other users of the load or address, returns the base address and
Clement Courbet65130e22017-09-01 10:56:34 +000075// the offset.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +000076BCEAtom visitICmpLoadOperand(Value *const Val) {
Clement Courbet65130e22017-09-01 10:56:34 +000077 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
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000114// 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.
Clement Courbet65130e22017-09-01 10:56:34 +0000117class BCECmpBlock {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000118 public:
119 BCECmpBlock() {}
Clement Courbet65130e22017-09-01 10:56:34 +0000120
121 BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits)
122 : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000123 if (Rhs_ < Lhs_) std::swap(Rhs_, Lhs_);
Clement Courbet65130e22017-09-01 10:56:34 +0000124 }
125
126 bool IsValid() const {
127 return Lhs_.Base() != nullptr && Rhs_.Base() != nullptr;
128 }
129
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000130 // Assert the block is consistent: If valid, it should also have
Clement Courbet65130e22017-09-01 10:56:34 +0000131 // 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
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000154 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000155 BCEAtom Lhs_;
156 BCEAtom Rhs_;
157 int SizeBits_ = 0;
158};
159
160bool BCECmpBlock::doesOtherWork() const {
161 AssertConsistent();
Xin Tong8fd561f2018-03-06 02:24:02 +0000162 // All the instructions we care about in the BCE cmp block.
163 DenseSet<Instruction *> BlockInsts(
164 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
Clement Courbet65130e22017-09-01 10:56:34 +0000165 // TODO(courbet): Can we allow some other things ? This is very conservative.
166 // We might be able to get away with anything does does not have any side
167 // effects outside of the basic block.
168 // Note: The GEPs and/or loads are not necessarily in the same block.
169 for (const Instruction &Inst : *BB) {
Xin Tong8fd561f2018-03-06 02:24:02 +0000170 if (!BlockInsts.count(&Inst))
Clement Courbet65130e22017-09-01 10:56:34 +0000171 return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000172 }
173 return false;
174}
175
176// Visit the given comparison. If this is a comparison between two valid
177// BCE atoms, returns the comparison.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000178BCECmpBlock visitICmp(const ICmpInst *const CmpI,
179 const ICmpInst::Predicate ExpectedPredicate) {
Clement Courbet9f0b3172018-03-13 07:05:55 +0000180 // The comparison can only be used once:
181 // - For intermediate blocks, as a branch condition.
182 // - For the final block, as an incoming value for the Phi.
183 // If there are any other uses of the comparison, we cannot merge it with
184 // other comparisons as we would create an orphan use of the value.
185 if (!CmpI->hasOneUse()) {
186 DEBUG(dbgs() << "cmp has several uses\n");
187 return {};
188 }
Clement Courbet65130e22017-09-01 10:56:34 +0000189 if (CmpI->getPredicate() == ExpectedPredicate) {
190 DEBUG(dbgs() << "cmp "
191 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
192 << "\n");
193 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0));
Clement Courbet98eaa882017-10-04 15:13:52 +0000194 if (!Lhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000195 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1));
Clement Courbet98eaa882017-10-04 15:13:52 +0000196 if (!Rhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000197 return BCECmpBlock(std::move(Lhs), std::move(Rhs),
198 CmpI->getOperand(0)->getType()->getScalarSizeInBits());
199 }
200 return {};
201}
202
203// Visit the given comparison block. If this is a comparison between two valid
204// BCE atoms, returns the comparison.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000205BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block,
206 const BasicBlock *const PhiBlock) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000207 if (Block->empty()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000208 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
Clement Courbet98eaa882017-10-04 15:13:52 +0000209 if (!BranchI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000210 DEBUG(dbgs() << "branch\n");
211 if (BranchI->isUnconditional()) {
212 // In this case, we expect an incoming value which is the result of the
213 // comparison. This is the last link in the chain of comparisons (note
214 // that this does not mean that this is the last incoming value, blocks
215 // can be reordered).
216 auto *const CmpI = dyn_cast<ICmpInst>(Val);
Clement Courbet98eaa882017-10-04 15:13:52 +0000217 if (!CmpI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000218 DEBUG(dbgs() << "icmp\n");
219 auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ);
220 Result.CmpI = CmpI;
221 Result.BranchI = BranchI;
222 return Result;
223 } else {
224 // In this case, we expect a constant incoming value (the comparison is
225 // chained).
226 const auto *const Const = dyn_cast<ConstantInt>(Val);
227 DEBUG(dbgs() << "const\n");
Clement Courbet98eaa882017-10-04 15:13:52 +0000228 if (!Const->isZero()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000229 DEBUG(dbgs() << "false\n");
230 auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition());
Clement Courbet98eaa882017-10-04 15:13:52 +0000231 if (!CmpI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000232 DEBUG(dbgs() << "icmp\n");
233 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
234 BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
235 auto Result = visitICmp(
236 CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE);
237 Result.CmpI = CmpI;
238 Result.BranchI = BranchI;
239 return Result;
240 }
241 return {};
242}
243
244// A chain of comparisons.
245class BCECmpChain {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000246 public:
Clement Courbet65130e22017-09-01 10:56:34 +0000247 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi);
248
249 int size() const { return Comparisons_.size(); }
250
251#ifdef MERGEICMPS_DOT_ON
252 void dump() const;
253#endif // MERGEICMPS_DOT_ON
254
255 bool simplify(const TargetLibraryInfo *const TLI);
256
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000257 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000258 static bool IsContiguous(const BCECmpBlock &First,
259 const BCECmpBlock &Second) {
260 return First.Lhs().Base() == Second.Lhs().Base() &&
261 First.Rhs().Base() == Second.Rhs().Base() &&
262 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
263 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
264 }
265
266 // Merges the given comparison blocks into one memcmp block and update
267 // branches. Comparisons are assumed to be continguous. If NextBBInChain is
268 // null, the merged block will link to the phi block.
269 static void mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
270 BasicBlock *const NextBBInChain, PHINode &Phi,
271 const TargetLibraryInfo *const TLI);
272
273 PHINode &Phi_;
274 std::vector<BCECmpBlock> Comparisons_;
275 // The original entry block (before sorting);
276 BasicBlock *EntryBlock_;
277};
278
279BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi)
280 : Phi_(Phi) {
Clement Courbetc2109c82018-02-06 09:14:00 +0000281 assert(!Blocks.empty() && "a chain should have at least one block");
Clement Courbet65130e22017-09-01 10:56:34 +0000282 // Now look inside blocks to check for BCE comparisons.
283 std::vector<BCECmpBlock> Comparisons;
Clement Courbeta7a17462018-02-06 12:25:33 +0000284 for (size_t BlockIdx = 0; BlockIdx < Blocks.size(); ++BlockIdx) {
285 BasicBlock *const Block = Blocks[BlockIdx];
Clement Courbetc2109c82018-02-06 09:14:00 +0000286 assert(Block && "invalid block");
Clement Courbet65130e22017-09-01 10:56:34 +0000287 BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block),
288 Block, Phi.getParent());
289 Comparison.BB = Block;
290 if (!Comparison.IsValid()) {
291 DEBUG(dbgs() << "skip: not a valid BCECmpBlock\n");
292 return;
293 }
294 if (Comparison.doesOtherWork()) {
Clement Courbet34be1b02018-03-05 08:21:47 +0000295 DEBUG(dbgs() << "block '" << Comparison.BB->getName()
296 << "' does extra work besides compare\n");
Xin Tong8345c0e2018-03-05 13:54:47 +0000297 if (Comparisons.empty()) {
298 // TODO(courbet): The initial block can do other things, and we should
Clement Courbet65130e22017-09-01 10:56:34 +0000299 // split them apart in a separate block before the comparison chain.
300 // Right now we just discard it and make the chain shorter.
301 DEBUG(dbgs()
Xin Tong98af9ef2018-03-06 02:04:57 +0000302 << "ignoring initial block '" << Comparison.BB->getName()
Clement Courbet34be1b02018-03-05 08:21:47 +0000303 << "' that does extra work besides compare\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000304 continue;
305 }
306 // TODO(courbet): Right now we abort the whole chain. We could be
307 // merging only the blocks that don't do other work and resume the
308 // chain from there. For example:
309 // if (a[0] == b[0]) { // bb1
310 // if (a[1] == b[1]) { // bb2
311 // some_value = 3; //bb3
312 // if (a[2] == b[2]) { //bb3
313 // do a ton of stuff //bb4
314 // }
315 // }
316 // }
317 //
318 // This is:
319 //
320 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
321 // \ \ \ \
322 // ne ne ne \
323 // \ \ \ v
324 // +------------+-----------+----------> bb_phi
325 //
326 // We can only merge the first two comparisons, because bb3* does
327 // "other work" (setting some_value to 3).
328 // We could still merge bb1 and bb2 though.
329 return;
330 }
Clement Courbet34be1b02018-03-05 08:21:47 +0000331 DEBUG(dbgs() << "Block '" << Comparison.BB->getName()<< "': Found cmp of "
332 << Comparison.SizeBits() << " bits between "
333 << Comparison.Lhs().Base() << " + " << Comparison.Lhs().Offset
334 << " and " << Comparison.Rhs().Base() << " + "
335 << Comparison.Rhs().Offset << "\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000336 DEBUG(dbgs() << "\n");
337 Comparisons.push_back(Comparison);
338 }
Xin Tong8345c0e2018-03-05 13:54:47 +0000339
340 // It is possible we have no suitable comparison to merge.
341 if (Comparisons.empty()) {
342 DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
343 return;
344 }
Clement Courbet65130e22017-09-01 10:56:34 +0000345 EntryBlock_ = Comparisons[0].BB;
346 Comparisons_ = std::move(Comparisons);
347#ifdef MERGEICMPS_DOT_ON
348 errs() << "BEFORE REORDERING:\n\n";
349 dump();
350#endif // MERGEICMPS_DOT_ON
351 // Reorder blocks by LHS. We can do that without changing the
352 // semantics because we are only accessing dereferencable memory.
353 std::sort(Comparisons_.begin(), Comparisons_.end(),
354 [](const BCECmpBlock &a, const BCECmpBlock &b) {
355 return a.Lhs() < b.Lhs();
356 });
357#ifdef MERGEICMPS_DOT_ON
358 errs() << "AFTER REORDERING:\n\n";
359 dump();
360#endif // MERGEICMPS_DOT_ON
361}
362
363#ifdef MERGEICMPS_DOT_ON
364void BCECmpChain::dump() const {
365 errs() << "digraph dag {\n";
366 errs() << " graph [bgcolor=transparent];\n";
367 errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n";
368 errs() << " edge [color=black];\n";
369 for (size_t I = 0; I < Comparisons_.size(); ++I) {
370 const auto &Comparison = Comparisons_[I];
371 errs() << " \"" << I << "\" [label=\"%"
372 << Comparison.Lhs().Base()->getName() << " + "
373 << Comparison.Lhs().Offset << " == %"
374 << Comparison.Rhs().Base()->getName() << " + "
375 << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8)
376 << " bytes)\"];\n";
377 const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
Clement Courbet98eaa882017-10-04 15:13:52 +0000378 if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n";
Clement Courbet65130e22017-09-01 10:56:34 +0000379 errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n";
380 }
381 errs() << " \"Phi\" [label=\"Phi\"];\n";
382 errs() << "}\n\n";
383}
384#endif // MERGEICMPS_DOT_ON
385
386bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI) {
387 // First pass to check if there is at least one merge. If not, we don't do
388 // anything and we keep analysis passes intact.
389 {
390 bool AtLeastOneMerged = false;
391 for (size_t I = 1; I < Comparisons_.size(); ++I) {
392 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
393 AtLeastOneMerged = true;
394 break;
395 }
396 }
Clement Courbet98eaa882017-10-04 15:13:52 +0000397 if (!AtLeastOneMerged) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000398 }
399
400 // Remove phi references to comparison blocks, they will be rebuilt as we
401 // merge the blocks.
402 for (const auto &Comparison : Comparisons_) {
403 Phi_.removeIncomingValue(Comparison.BB, false);
404 }
405
Xin Tongbdbd97e2018-03-20 11:57:54 +0000406 // If entry block is part of the chain, we need to make the first block
407 // of the chain the new entry block of the function.
408 BasicBlock *Entry = &Comparisons_[0].BB->getParent()->getEntryBlock();
409 for (size_t I = 1; I < Comparisons_.size(); ++I) {
410 if (Entry == Comparisons_[I].BB) {
411 BasicBlock *NEntryBB = BasicBlock::Create(Entry->getContext(), "",
412 Entry->getParent(), Entry);
413 BranchInst::Create(Entry, NEntryBB);
Xin Tonga713ebe2018-03-20 12:03:25 +0000414 break;
Xin Tongbdbd97e2018-03-20 11:57:54 +0000415 }
416 }
417
Clement Courbet65130e22017-09-01 10:56:34 +0000418 // Point the predecessors of the chain to the first comparison block (which is
419 // the new entry point).
420 if (EntryBlock_ != Comparisons_[0].BB)
421 EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB);
422
423 // Effectively merge blocks.
424 int NumMerged = 1;
425 for (size_t I = 1; I < Comparisons_.size(); ++I) {
426 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
427 ++NumMerged;
428 } else {
429 // Merge all previous comparisons and start a new merge block.
430 mergeComparisons(
431 makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged),
432 Comparisons_[I].BB, Phi_, TLI);
433 NumMerged = 1;
434 }
435 }
436 mergeComparisons(makeArrayRef(Comparisons_)
437 .slice(Comparisons_.size() - NumMerged, NumMerged),
438 nullptr, Phi_, TLI);
439
440 return true;
441}
442
443void BCECmpChain::mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
444 BasicBlock *const NextBBInChain,
445 PHINode &Phi,
446 const TargetLibraryInfo *const TLI) {
447 assert(!Comparisons.empty());
448 const auto &FirstComparison = *Comparisons.begin();
449 BasicBlock *const BB = FirstComparison.BB;
450 LLVMContext &Context = BB->getContext();
451
452 if (Comparisons.size() >= 2) {
453 DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons\n");
454 const auto TotalSize =
455 std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
456 [](int Size, const BCECmpBlock &C) {
457 return Size + C.SizeBits();
458 }) /
459 8;
460
461 // Incoming edges do not need to be updated, and both GEPs are already
462 // computing the right address, we just need to:
463 // - replace the two loads and the icmp with the memcmp
464 // - update the branch
465 // - update the incoming values in the phi.
466 FirstComparison.BranchI->eraseFromParent();
467 FirstComparison.CmpI->eraseFromParent();
468 FirstComparison.Lhs().LoadI->eraseFromParent();
469 FirstComparison.Rhs().LoadI->eraseFromParent();
470
471 IRBuilder<> Builder(BB);
472 const auto &DL = Phi.getModule()->getDataLayout();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000473 Value *const MemCmpCall = emitMemCmp(
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000474 FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP, ConstantInt::get(DL.getIntPtrType(Context), TotalSize),
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000475 Builder, DL, TLI);
Clement Courbet65130e22017-09-01 10:56:34 +0000476 Value *const MemCmpIsZero = Builder.CreateICmpEQ(
477 MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0));
478
479 // Add a branch to the next basic block in the chain.
480 if (NextBBInChain) {
481 Builder.CreateCondBr(MemCmpIsZero, NextBBInChain, Phi.getParent());
482 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
483 } else {
484 Builder.CreateBr(Phi.getParent());
485 Phi.addIncoming(MemCmpIsZero, BB);
486 }
487
488 // Delete merged blocks.
489 for (size_t I = 1; I < Comparisons.size(); ++I) {
490 BasicBlock *CBB = Comparisons[I].BB;
491 CBB->replaceAllUsesWith(BB);
492 CBB->eraseFromParent();
493 }
494 } else {
495 assert(Comparisons.size() == 1);
496 // There are no blocks to merge, but we still need to update the branches.
497 DEBUG(dbgs() << "Only one comparison, updating branches\n");
498 if (NextBBInChain) {
499 if (FirstComparison.BranchI->isConditional()) {
500 DEBUG(dbgs() << "conditional -> conditional\n");
501 // Just update the "true" target, the "false" target should already be
502 // the phi block.
503 assert(FirstComparison.BranchI->getSuccessor(1) == Phi.getParent());
504 FirstComparison.BranchI->setSuccessor(0, NextBBInChain);
505 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
506 } else {
507 DEBUG(dbgs() << "unconditional -> conditional\n");
508 // Replace the unconditional branch by a conditional one.
509 FirstComparison.BranchI->eraseFromParent();
510 IRBuilder<> Builder(BB);
511 Builder.CreateCondBr(FirstComparison.CmpI, NextBBInChain,
512 Phi.getParent());
513 Phi.addIncoming(FirstComparison.CmpI, BB);
514 }
515 } else {
516 if (FirstComparison.BranchI->isConditional()) {
517 DEBUG(dbgs() << "conditional -> unconditional\n");
518 // Replace the conditional branch by an unconditional one.
519 FirstComparison.BranchI->eraseFromParent();
520 IRBuilder<> Builder(BB);
521 Builder.CreateBr(Phi.getParent());
522 Phi.addIncoming(FirstComparison.CmpI, BB);
523 } else {
524 DEBUG(dbgs() << "unconditional -> unconditional\n");
525 Phi.addIncoming(FirstComparison.CmpI, BB);
526 }
527 }
528 }
529}
530
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000531std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
532 BasicBlock *const LastBlock,
533 int NumBlocks) {
Clement Courbet65130e22017-09-01 10:56:34 +0000534 // Walk up from the last block to find other blocks.
535 std::vector<BasicBlock *> Blocks(NumBlocks);
Clement Courbetc2109c82018-02-06 09:14:00 +0000536 assert(LastBlock && "invalid last block");
Clement Courbet65130e22017-09-01 10:56:34 +0000537 BasicBlock *CurBlock = LastBlock;
538 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
539 if (CurBlock->hasAddressTaken()) {
540 // Somebody is jumping to the block through an address, all bets are
541 // off.
542 DEBUG(dbgs() << "skip: block " << BlockIndex
543 << " has its address taken\n");
544 return {};
545 }
546 Blocks[BlockIndex] = CurBlock;
547 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
548 if (!SinglePredecessor) {
549 // The block has two or more predecessors.
550 DEBUG(dbgs() << "skip: block " << BlockIndex
551 << " has two or more predecessors\n");
552 return {};
553 }
554 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
555 // The block does not link back to the phi.
556 DEBUG(dbgs() << "skip: block " << BlockIndex
557 << " does not link back to the phi\n");
558 return {};
559 }
560 CurBlock = SinglePredecessor;
561 }
562 Blocks[0] = CurBlock;
563 return Blocks;
564}
565
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000566bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI) {
Clement Courbet65130e22017-09-01 10:56:34 +0000567 DEBUG(dbgs() << "processPhi()\n");
568 if (Phi.getNumIncomingValues() <= 1) {
569 DEBUG(dbgs() << "skip: only one incoming value in phi\n");
570 return false;
571 }
572 // We are looking for something that has the following structure:
573 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
574 // \ \ \ \
575 // ne ne ne \
576 // \ \ \ v
577 // +------------+-----------+----------> bb_phi
578 //
579 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
580 // It's the only block that contributes a non-constant value to the Phi.
581 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000582 // them being the phi block.
Clement Courbet65130e22017-09-01 10:56:34 +0000583 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
584 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
585
586 // The blocks are not necessarily ordered in the phi, so we start from the
587 // last block and reconstruct the order.
588 BasicBlock *LastBlock = nullptr;
589 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000590 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
Clement Courbet65130e22017-09-01 10:56:34 +0000591 if (LastBlock) {
592 // There are several non-constant values.
593 DEBUG(dbgs() << "skip: several non-constant values\n");
594 return false;
595 }
Xin Tong8ba674e2018-02-28 12:08:00 +0000596 if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
597 cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
598 Phi.getIncomingBlock(I)) {
599 // Non-constant incoming value is not from a cmp instruction or not
600 // produced by the last block. We could end up processing the value
601 // producing block more than once.
602 //
603 // This is an uncommon case, so we bail.
604 DEBUG(
605 dbgs()
606 << "skip: non-constant value not from cmp or not from last block.\n");
607 return false;
608 }
Clement Courbet65130e22017-09-01 10:56:34 +0000609 LastBlock = Phi.getIncomingBlock(I);
610 }
611 if (!LastBlock) {
612 // There is no non-constant block.
613 DEBUG(dbgs() << "skip: no non-constant block\n");
614 return false;
615 }
616 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
617 DEBUG(dbgs() << "skip: last block non-phi successor\n");
618 return false;
619 }
620
621 const auto Blocks =
622 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
Clement Courbet98eaa882017-10-04 15:13:52 +0000623 if (Blocks.empty()) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000624 BCECmpChain CmpChain(Blocks, Phi);
625
626 if (CmpChain.size() < 2) {
627 DEBUG(dbgs() << "skip: only one compare block\n");
628 return false;
629 }
630
631 return CmpChain.simplify(TLI);
632}
633
634class MergeICmps : public FunctionPass {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000635 public:
Clement Courbet65130e22017-09-01 10:56:34 +0000636 static char ID;
637
638 MergeICmps() : FunctionPass(ID) {
639 initializeMergeICmpsPass(*PassRegistry::getPassRegistry());
640 }
641
642 bool runOnFunction(Function &F) override {
643 if (skipFunction(F)) return false;
644 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000645 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
646 auto PA = runImpl(F, &TLI, &TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000647 return !PA.areAllPreserved();
648 }
649
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000650 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000651 void getAnalysisUsage(AnalysisUsage &AU) const override {
652 AU.addRequired<TargetLibraryInfoWrapperPass>();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000653 AU.addRequired<TargetTransformInfoWrapperPass>();
Clement Courbet65130e22017-09-01 10:56:34 +0000654 }
655
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000656 PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
657 const TargetTransformInfo *TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000658};
659
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000660PreservedAnalyses MergeICmps::runImpl(Function &F, const TargetLibraryInfo *TLI,
661 const TargetTransformInfo *TTI) {
Clement Courbet65130e22017-09-01 10:56:34 +0000662 DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n");
663
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000664 // We only try merging comparisons if the target wants to expand memcmp later.
665 // The rationale is to avoid turning small chains into memcmp calls.
Clement Courbetb2c3eb82017-10-30 14:19:33 +0000666 if (!TTI->enableMemCmpExpansion(true)) return PreservedAnalyses::all();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000667
Clement Courbet65130e22017-09-01 10:56:34 +0000668 bool MadeChange = false;
669
670 for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) {
671 // A Phi operation is always first in a basic block.
672 if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
673 MadeChange |= processPhi(*Phi, TLI);
674 }
675
Clement Courbet98eaa882017-10-04 15:13:52 +0000676 if (MadeChange) return PreservedAnalyses::none();
Clement Courbet65130e22017-09-01 10:56:34 +0000677 return PreservedAnalyses::all();
678}
679
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000680} // namespace
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000681
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000682char MergeICmps::ID = 0;
Clement Courbet65130e22017-09-01 10:56:34 +0000683INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps",
684 "Merge contiguous icmps into a memcmp", false, false)
685INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000686INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Clement Courbet65130e22017-09-01 10:56:34 +0000687INITIALIZE_PASS_END(MergeICmps, "mergeicmps",
688 "Merge contiguous icmps into a memcmp", false, false)
689
690Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); }