blob: 3a5431b5171bd367e3d5b17a4e6d96f16ce31afc [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();
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)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000168 if (!(Lhs_.GEP == GEP || Rhs_.GEP == GEP)) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000169 } else if (const auto *const L = dyn_cast<LoadInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000170 if (!(Lhs_.LoadI == L || Rhs_.LoadI == L)) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000171 } else if (const auto *const C = dyn_cast<ICmpInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000172 if (C != CmpI) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000173 } else if (const auto *const Br = dyn_cast<BranchInst>(&Inst)) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000174 if (Br != BranchI) return true;
Clement Courbet65130e22017-09-01 10:56:34 +0000175 } 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.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000184BCECmpBlock visitICmp(const ICmpInst *const CmpI,
185 const ICmpInst::Predicate ExpectedPredicate) {
Clement Courbet65130e22017-09-01 10:56:34 +0000186 if (CmpI->getPredicate() == ExpectedPredicate) {
187 DEBUG(dbgs() << "cmp "
188 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
189 << "\n");
190 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0));
Clement Courbet98eaa882017-10-04 15:13:52 +0000191 if (!Lhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000192 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1));
Clement Courbet98eaa882017-10-04 15:13:52 +0000193 if (!Rhs.Base()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000194 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.
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000202BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block,
203 const BasicBlock *const PhiBlock) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000204 if (Block->empty()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000205 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
Clement Courbet98eaa882017-10-04 15:13:52 +0000206 if (!BranchI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000207 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);
Clement Courbet98eaa882017-10-04 15:13:52 +0000214 if (!CmpI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000215 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");
Clement Courbet98eaa882017-10-04 15:13:52 +0000225 if (!Const->isZero()) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000226 DEBUG(dbgs() << "false\n");
227 auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition());
Clement Courbet98eaa882017-10-04 15:13:52 +0000228 if (!CmpI) return {};
Clement Courbet65130e22017-09-01 10:56:34 +0000229 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.
242class BCECmpChain {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000243 public:
Clement Courbet65130e22017-09-01 10:56:34 +0000244 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
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000254 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000255 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
276BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi)
277 : Phi_(Phi) {
Clement Courbetc2109c82018-02-06 09:14:00 +0000278 assert(!Blocks.empty() && "a chain should have at least one block");
Clement Courbet65130e22017-09-01 10:56:34 +0000279 // Now look inside blocks to check for BCE comparisons.
280 std::vector<BCECmpBlock> Comparisons;
Clement Courbeta7a17462018-02-06 12:25:33 +0000281 for (size_t BlockIdx = 0; BlockIdx < Blocks.size(); ++BlockIdx) {
282 BasicBlock *const Block = Blocks[BlockIdx];
Clement Courbetc2109c82018-02-06 09:14:00 +0000283 assert(Block && "invalid block");
Clement Courbet65130e22017-09-01 10:56:34 +0000284 BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block),
285 Block, Phi.getParent());
286 Comparison.BB = Block;
287 if (!Comparison.IsValid()) {
288 DEBUG(dbgs() << "skip: not a valid BCECmpBlock\n");
289 return;
290 }
291 if (Comparison.doesOtherWork()) {
Clement Courbet34be1b02018-03-05 08:21:47 +0000292 DEBUG(dbgs() << "block '" << Comparison.BB->getName()
293 << "' does extra work besides compare\n");
Xin Tong8345c0e2018-03-05 13:54:47 +0000294 if (Comparisons.empty()) {
295 // TODO(courbet): The initial block can do other things, and we should
Clement Courbet65130e22017-09-01 10:56:34 +0000296 // split them apart in a separate block before the comparison chain.
297 // Right now we just discard it and make the chain shorter.
298 DEBUG(dbgs()
Xin Tong98af9ef2018-03-06 02:04:57 +0000299 << "ignoring initial block '" << Comparison.BB->getName()
Clement Courbet34be1b02018-03-05 08:21:47 +0000300 << "' that does extra work besides compare\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000301 continue;
302 }
303 // TODO(courbet): Right now we abort the whole chain. We could be
304 // merging only the blocks that don't do other work and resume the
305 // chain from there. For example:
306 // if (a[0] == b[0]) { // bb1
307 // if (a[1] == b[1]) { // bb2
308 // some_value = 3; //bb3
309 // if (a[2] == b[2]) { //bb3
310 // do a ton of stuff //bb4
311 // }
312 // }
313 // }
314 //
315 // This is:
316 //
317 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
318 // \ \ \ \
319 // ne ne ne \
320 // \ \ \ v
321 // +------------+-----------+----------> bb_phi
322 //
323 // We can only merge the first two comparisons, because bb3* does
324 // "other work" (setting some_value to 3).
325 // We could still merge bb1 and bb2 though.
326 return;
327 }
Clement Courbet34be1b02018-03-05 08:21:47 +0000328 DEBUG(dbgs() << "Block '" << Comparison.BB->getName()<< "': Found cmp of "
329 << Comparison.SizeBits() << " bits between "
330 << Comparison.Lhs().Base() << " + " << Comparison.Lhs().Offset
331 << " and " << Comparison.Rhs().Base() << " + "
332 << Comparison.Rhs().Offset << "\n");
Clement Courbet65130e22017-09-01 10:56:34 +0000333 DEBUG(dbgs() << "\n");
334 Comparisons.push_back(Comparison);
335 }
Xin Tong8345c0e2018-03-05 13:54:47 +0000336
337 // It is possible we have no suitable comparison to merge.
338 if (Comparisons.empty()) {
339 DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
340 return;
341 }
Clement Courbet65130e22017-09-01 10:56:34 +0000342 EntryBlock_ = Comparisons[0].BB;
343 Comparisons_ = std::move(Comparisons);
344#ifdef MERGEICMPS_DOT_ON
345 errs() << "BEFORE REORDERING:\n\n";
346 dump();
347#endif // MERGEICMPS_DOT_ON
348 // Reorder blocks by LHS. We can do that without changing the
349 // semantics because we are only accessing dereferencable memory.
350 std::sort(Comparisons_.begin(), Comparisons_.end(),
351 [](const BCECmpBlock &a, const BCECmpBlock &b) {
352 return a.Lhs() < b.Lhs();
353 });
354#ifdef MERGEICMPS_DOT_ON
355 errs() << "AFTER REORDERING:\n\n";
356 dump();
357#endif // MERGEICMPS_DOT_ON
358}
359
360#ifdef MERGEICMPS_DOT_ON
361void BCECmpChain::dump() const {
362 errs() << "digraph dag {\n";
363 errs() << " graph [bgcolor=transparent];\n";
364 errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n";
365 errs() << " edge [color=black];\n";
366 for (size_t I = 0; I < Comparisons_.size(); ++I) {
367 const auto &Comparison = Comparisons_[I];
368 errs() << " \"" << I << "\" [label=\"%"
369 << Comparison.Lhs().Base()->getName() << " + "
370 << Comparison.Lhs().Offset << " == %"
371 << Comparison.Rhs().Base()->getName() << " + "
372 << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8)
373 << " bytes)\"];\n";
374 const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
Clement Courbet98eaa882017-10-04 15:13:52 +0000375 if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n";
Clement Courbet65130e22017-09-01 10:56:34 +0000376 errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n";
377 }
378 errs() << " \"Phi\" [label=\"Phi\"];\n";
379 errs() << "}\n\n";
380}
381#endif // MERGEICMPS_DOT_ON
382
383bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI) {
384 // First pass to check if there is at least one merge. If not, we don't do
385 // anything and we keep analysis passes intact.
386 {
387 bool AtLeastOneMerged = false;
388 for (size_t I = 1; I < Comparisons_.size(); ++I) {
389 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
390 AtLeastOneMerged = true;
391 break;
392 }
393 }
Clement Courbet98eaa882017-10-04 15:13:52 +0000394 if (!AtLeastOneMerged) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000395 }
396
397 // Remove phi references to comparison blocks, they will be rebuilt as we
398 // merge the blocks.
399 for (const auto &Comparison : Comparisons_) {
400 Phi_.removeIncomingValue(Comparison.BB, false);
401 }
402
403 // Point the predecessors of the chain to the first comparison block (which is
404 // the new entry point).
405 if (EntryBlock_ != Comparisons_[0].BB)
406 EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB);
407
408 // Effectively merge blocks.
409 int NumMerged = 1;
410 for (size_t I = 1; I < Comparisons_.size(); ++I) {
411 if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) {
412 ++NumMerged;
413 } else {
414 // Merge all previous comparisons and start a new merge block.
415 mergeComparisons(
416 makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged),
417 Comparisons_[I].BB, Phi_, TLI);
418 NumMerged = 1;
419 }
420 }
421 mergeComparisons(makeArrayRef(Comparisons_)
422 .slice(Comparisons_.size() - NumMerged, NumMerged),
423 nullptr, Phi_, TLI);
424
425 return true;
426}
427
428void BCECmpChain::mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
429 BasicBlock *const NextBBInChain,
430 PHINode &Phi,
431 const TargetLibraryInfo *const TLI) {
432 assert(!Comparisons.empty());
433 const auto &FirstComparison = *Comparisons.begin();
434 BasicBlock *const BB = FirstComparison.BB;
435 LLVMContext &Context = BB->getContext();
436
437 if (Comparisons.size() >= 2) {
438 DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons\n");
439 const auto TotalSize =
440 std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
441 [](int Size, const BCECmpBlock &C) {
442 return Size + C.SizeBits();
443 }) /
444 8;
445
446 // Incoming edges do not need to be updated, and both GEPs are already
447 // computing the right address, we just need to:
448 // - replace the two loads and the icmp with the memcmp
449 // - update the branch
450 // - update the incoming values in the phi.
451 FirstComparison.BranchI->eraseFromParent();
452 FirstComparison.CmpI->eraseFromParent();
453 FirstComparison.Lhs().LoadI->eraseFromParent();
454 FirstComparison.Rhs().LoadI->eraseFromParent();
455
456 IRBuilder<> Builder(BB);
457 const auto &DL = Phi.getModule()->getDataLayout();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000458 Value *const MemCmpCall = emitMemCmp(
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000459 FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP, ConstantInt::get(DL.getIntPtrType(Context), TotalSize),
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000460 Builder, DL, TLI);
Clement Courbet65130e22017-09-01 10:56:34 +0000461 Value *const MemCmpIsZero = Builder.CreateICmpEQ(
462 MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0));
463
464 // Add a branch to the next basic block in the chain.
465 if (NextBBInChain) {
466 Builder.CreateCondBr(MemCmpIsZero, NextBBInChain, Phi.getParent());
467 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
468 } else {
469 Builder.CreateBr(Phi.getParent());
470 Phi.addIncoming(MemCmpIsZero, BB);
471 }
472
473 // Delete merged blocks.
474 for (size_t I = 1; I < Comparisons.size(); ++I) {
475 BasicBlock *CBB = Comparisons[I].BB;
476 CBB->replaceAllUsesWith(BB);
477 CBB->eraseFromParent();
478 }
479 } else {
480 assert(Comparisons.size() == 1);
481 // There are no blocks to merge, but we still need to update the branches.
482 DEBUG(dbgs() << "Only one comparison, updating branches\n");
483 if (NextBBInChain) {
484 if (FirstComparison.BranchI->isConditional()) {
485 DEBUG(dbgs() << "conditional -> conditional\n");
486 // Just update the "true" target, the "false" target should already be
487 // the phi block.
488 assert(FirstComparison.BranchI->getSuccessor(1) == Phi.getParent());
489 FirstComparison.BranchI->setSuccessor(0, NextBBInChain);
490 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
491 } else {
492 DEBUG(dbgs() << "unconditional -> conditional\n");
493 // Replace the unconditional branch by a conditional one.
494 FirstComparison.BranchI->eraseFromParent();
495 IRBuilder<> Builder(BB);
496 Builder.CreateCondBr(FirstComparison.CmpI, NextBBInChain,
497 Phi.getParent());
498 Phi.addIncoming(FirstComparison.CmpI, BB);
499 }
500 } else {
501 if (FirstComparison.BranchI->isConditional()) {
502 DEBUG(dbgs() << "conditional -> unconditional\n");
503 // Replace the conditional branch by an unconditional one.
504 FirstComparison.BranchI->eraseFromParent();
505 IRBuilder<> Builder(BB);
506 Builder.CreateBr(Phi.getParent());
507 Phi.addIncoming(FirstComparison.CmpI, BB);
508 } else {
509 DEBUG(dbgs() << "unconditional -> unconditional\n");
510 Phi.addIncoming(FirstComparison.CmpI, BB);
511 }
512 }
513 }
514}
515
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000516std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
517 BasicBlock *const LastBlock,
518 int NumBlocks) {
Clement Courbet65130e22017-09-01 10:56:34 +0000519 // Walk up from the last block to find other blocks.
520 std::vector<BasicBlock *> Blocks(NumBlocks);
Clement Courbetc2109c82018-02-06 09:14:00 +0000521 assert(LastBlock && "invalid last block");
Clement Courbet65130e22017-09-01 10:56:34 +0000522 BasicBlock *CurBlock = LastBlock;
523 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
524 if (CurBlock->hasAddressTaken()) {
525 // Somebody is jumping to the block through an address, all bets are
526 // off.
527 DEBUG(dbgs() << "skip: block " << BlockIndex
528 << " has its address taken\n");
529 return {};
530 }
531 Blocks[BlockIndex] = CurBlock;
532 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
533 if (!SinglePredecessor) {
534 // The block has two or more predecessors.
535 DEBUG(dbgs() << "skip: block " << BlockIndex
536 << " has two or more predecessors\n");
537 return {};
538 }
539 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
540 // The block does not link back to the phi.
541 DEBUG(dbgs() << "skip: block " << BlockIndex
542 << " does not link back to the phi\n");
543 return {};
544 }
545 CurBlock = SinglePredecessor;
546 }
547 Blocks[0] = CurBlock;
548 return Blocks;
549}
550
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000551bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI) {
Clement Courbet65130e22017-09-01 10:56:34 +0000552 DEBUG(dbgs() << "processPhi()\n");
553 if (Phi.getNumIncomingValues() <= 1) {
554 DEBUG(dbgs() << "skip: only one incoming value in phi\n");
555 return false;
556 }
557 // We are looking for something that has the following structure:
558 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
559 // \ \ \ \
560 // ne ne ne \
561 // \ \ \ v
562 // +------------+-----------+----------> bb_phi
563 //
564 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
565 // It's the only block that contributes a non-constant value to the Phi.
566 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000567 // them being the phi block.
Clement Courbet65130e22017-09-01 10:56:34 +0000568 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
569 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
570
571 // The blocks are not necessarily ordered in the phi, so we start from the
572 // last block and reconstruct the order.
573 BasicBlock *LastBlock = nullptr;
574 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
Clement Courbet98eaa882017-10-04 15:13:52 +0000575 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
Clement Courbet65130e22017-09-01 10:56:34 +0000576 if (LastBlock) {
577 // There are several non-constant values.
578 DEBUG(dbgs() << "skip: several non-constant values\n");
579 return false;
580 }
Xin Tong8ba674e2018-02-28 12:08:00 +0000581 if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
582 cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
583 Phi.getIncomingBlock(I)) {
584 // Non-constant incoming value is not from a cmp instruction or not
585 // produced by the last block. We could end up processing the value
586 // producing block more than once.
587 //
588 // This is an uncommon case, so we bail.
589 DEBUG(
590 dbgs()
591 << "skip: non-constant value not from cmp or not from last block.\n");
592 return false;
593 }
Clement Courbet65130e22017-09-01 10:56:34 +0000594 LastBlock = Phi.getIncomingBlock(I);
595 }
596 if (!LastBlock) {
597 // There is no non-constant block.
598 DEBUG(dbgs() << "skip: no non-constant block\n");
599 return false;
600 }
601 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
602 DEBUG(dbgs() << "skip: last block non-phi successor\n");
603 return false;
604 }
605
606 const auto Blocks =
607 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
Clement Courbet98eaa882017-10-04 15:13:52 +0000608 if (Blocks.empty()) return false;
Clement Courbet65130e22017-09-01 10:56:34 +0000609 BCECmpChain CmpChain(Blocks, Phi);
610
611 if (CmpChain.size() < 2) {
612 DEBUG(dbgs() << "skip: only one compare block\n");
613 return false;
614 }
615
616 return CmpChain.simplify(TLI);
617}
618
619class MergeICmps : public FunctionPass {
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000620 public:
Clement Courbet65130e22017-09-01 10:56:34 +0000621 static char ID;
622
623 MergeICmps() : FunctionPass(ID) {
624 initializeMergeICmpsPass(*PassRegistry::getPassRegistry());
625 }
626
627 bool runOnFunction(Function &F) override {
628 if (skipFunction(F)) return false;
629 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000630 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
631 auto PA = runImpl(F, &TLI, &TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000632 return !PA.areAllPreserved();
633 }
634
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000635 private:
Clement Courbet65130e22017-09-01 10:56:34 +0000636 void getAnalysisUsage(AnalysisUsage &AU) const override {
637 AU.addRequired<TargetLibraryInfoWrapperPass>();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000638 AU.addRequired<TargetTransformInfoWrapperPass>();
Clement Courbet65130e22017-09-01 10:56:34 +0000639 }
640
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000641 PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
642 const TargetTransformInfo *TTI);
Clement Courbet65130e22017-09-01 10:56:34 +0000643};
644
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000645PreservedAnalyses MergeICmps::runImpl(Function &F, const TargetLibraryInfo *TLI,
646 const TargetTransformInfo *TTI) {
Clement Courbet65130e22017-09-01 10:56:34 +0000647 DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n");
648
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000649 // We only try merging comparisons if the target wants to expand memcmp later.
650 // The rationale is to avoid turning small chains into memcmp calls.
Clement Courbetb2c3eb82017-10-30 14:19:33 +0000651 if (!TTI->enableMemCmpExpansion(true)) return PreservedAnalyses::all();
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000652
Clement Courbet65130e22017-09-01 10:56:34 +0000653 bool MadeChange = false;
654
655 for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) {
656 // A Phi operation is always first in a basic block.
657 if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
658 MadeChange |= processPhi(*Phi, TLI);
659 }
660
Clement Courbet98eaa882017-10-04 15:13:52 +0000661 if (MadeChange) return PreservedAnalyses::none();
Clement Courbet65130e22017-09-01 10:56:34 +0000662 return PreservedAnalyses::all();
663}
664
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000665} // namespace
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000666
Eugene Zelenko5c2aece2017-10-26 01:25:14 +0000667char MergeICmps::ID = 0;
Clement Courbet65130e22017-09-01 10:56:34 +0000668INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps",
669 "Merge contiguous icmps into a memcmp", false, false)
670INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Clement Courbete2e8a5c2017-10-10 08:00:45 +0000671INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Clement Courbet65130e22017-09-01 10:56:34 +0000672INITIALIZE_PASS_END(MergeICmps, "mergeicmps",
673 "Merge contiguous icmps into a memcmp", false, false)
674
675Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); }