Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 1 | //===- MergeICmps.cpp - Optimize chains of integer comparisons ------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass turns chains of integer comparisons into memcmp (the memcmp is |
| 11 | // later typically inlined as a chain of efficient hardware comparisons). This |
| 12 | // typically benefits c++ member or nonmember operator==(). |
| 13 | // |
| 14 | // The basic idea is to replace a larger chain of integer comparisons loaded |
| 15 | // from contiguous memory locations into a smaller chain of such integer |
| 16 | // comparisons. Benefits are double: |
| 17 | // - There are less jumps, and therefore less opportunities for mispredictions |
| 18 | // and I-cache misses. |
| 19 | // - Code size is smaller, both because jumps are removed and because the |
| 20 | // encoding of a 2*n byte compare is smaller than that of two n-byte |
| 21 | // compares. |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 22 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 23 | //===----------------------------------------------------------------------===// |
| 24 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame] | 25 | #include <algorithm> |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame] | 26 | #include <numeric> |
| 27 | #include <utility> |
| 28 | #include <vector> |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 29 | #include "llvm/Analysis/Loads.h" |
| 30 | #include "llvm/Analysis/TargetLibraryInfo.h" |
| 31 | #include "llvm/Analysis/TargetTransformInfo.h" |
| 32 | #include "llvm/IR/Function.h" |
| 33 | #include "llvm/IR/IRBuilder.h" |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 34 | #include "llvm/Pass.h" |
| 35 | #include "llvm/Transforms/Scalar.h" |
| 36 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 37 | |
| 38 | using namespace llvm; |
| 39 | |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame] | 40 | namespace { |
| 41 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 42 | #define DEBUG_TYPE "mergeicmps" |
| 43 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 44 | // Returns true if the instruction is a simple load or a simple store |
| 45 | static bool isSimpleLoadOrStore(const Instruction *I) { |
| 46 | if (const LoadInst *LI = dyn_cast<LoadInst>(I)) |
| 47 | return LI->isSimple(); |
| 48 | if (const StoreInst *SI = dyn_cast<StoreInst>(I)) |
| 49 | return SI->isSimple(); |
| 50 | return false; |
| 51 | } |
| 52 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 53 | // A BCE atom. |
| 54 | struct BCEAtom { |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 55 | BCEAtom() : GEP(nullptr), LoadI(nullptr), Offset() {} |
Clement Courbet | bc0c445 | 2017-09-01 11:51:23 +0000 | [diff] [blame] | 56 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 57 | const Value *Base() const { return GEP ? GEP->getPointerOperand() : nullptr; } |
| 58 | |
| 59 | bool operator<(const BCEAtom &O) const { |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 60 | assert(Base() && "invalid atom"); |
| 61 | assert(O.Base() && "invalid atom"); |
| 62 | // Just ordering by (Base(), Offset) is sufficient. However because this |
| 63 | // means that the ordering will depend on the addresses of the base |
| 64 | // values, which are not reproducible from run to run. To guarantee |
| 65 | // stability, we use the names of the values if they exist; we sort by: |
| 66 | // (Base.getName(), Base(), Offset). |
| 67 | const int NameCmp = Base()->getName().compare(O.Base()->getName()); |
| 68 | if (NameCmp == 0) { |
| 69 | if (Base() == O.Base()) { |
| 70 | return Offset.slt(O.Offset); |
| 71 | } |
| 72 | return Base() < O.Base(); |
| 73 | } |
| 74 | return NameCmp < 0; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 75 | } |
| 76 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 77 | GetElementPtrInst *GEP; |
| 78 | LoadInst *LoadI; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 79 | APInt Offset; |
| 80 | }; |
| 81 | |
| 82 | // If this value is a load from a constant offset w.r.t. a base address, and |
Xin Tong | 256869d | 2018-02-28 12:09:53 +0000 | [diff] [blame] | 83 | // there are no other users of the load or address, returns the base address and |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 84 | // the offset. |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 85 | BCEAtom visitICmpLoadOperand(Value *const Val) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 86 | BCEAtom Result; |
| 87 | if (auto *const LoadI = dyn_cast<LoadInst>(Val)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 88 | LLVM_DEBUG(dbgs() << "load\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 89 | if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 90 | LLVM_DEBUG(dbgs() << "used outside of block\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 91 | return {}; |
| 92 | } |
Christy Lee | c85da8b | 2018-09-18 17:02:42 +0000 | [diff] [blame] | 93 | // Do not optimize atomic loads to non-atomic memcmp |
| 94 | if (!LoadI->isSimple()) { |
| 95 | LLVM_DEBUG(dbgs() << "volatile or atomic\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 96 | return {}; |
| 97 | } |
| 98 | Value *const Addr = LoadI->getOperand(0); |
| 99 | if (auto *const GEP = dyn_cast<GetElementPtrInst>(Addr)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 100 | LLVM_DEBUG(dbgs() << "GEP\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 101 | if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 102 | LLVM_DEBUG(dbgs() << "used outside of block\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 103 | return {}; |
| 104 | } |
| 105 | const auto &DL = GEP->getModule()->getDataLayout(); |
| 106 | if (!isDereferenceablePointer(GEP, DL)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 107 | LLVM_DEBUG(dbgs() << "not dereferenceable\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 108 | // We need to make sure that we can do comparison in any order, so we |
| 109 | // require memory to be unconditionnally dereferencable. |
| 110 | return {}; |
| 111 | } |
| 112 | Result.Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0); |
| 113 | if (GEP->accumulateConstantOffset(DL, Result.Offset)) { |
| 114 | Result.GEP = GEP; |
| 115 | Result.LoadI = LoadI; |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | return Result; |
| 120 | } |
| 121 | |
| 122 | // A basic block with a comparison between two BCE atoms. |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 123 | // The block might do extra work besides the atom comparison, in which case |
| 124 | // doesOtherWork() returns true. Under some conditions, the block can be |
| 125 | // split into the atom comparison part and the "other work" part |
| 126 | // (see canSplit()). |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 127 | // Note: the terminology is misleading: the comparison is symmetric, so there |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 128 | // is no real {l/r}hs. What we want though is to have the same base on the |
| 129 | // left (resp. right), so that we can detect consecutive loads. To ensure this |
| 130 | // we put the smallest atom on the left. |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 131 | class BCECmpBlock { |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 132 | public: |
| 133 | BCECmpBlock() {} |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 134 | |
| 135 | BCECmpBlock(BCEAtom L, BCEAtom R, int SizeBits) |
| 136 | : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 137 | if (Rhs_ < Lhs_) std::swap(Rhs_, Lhs_); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 138 | } |
| 139 | |
| 140 | bool IsValid() const { |
| 141 | return Lhs_.Base() != nullptr && Rhs_.Base() != nullptr; |
| 142 | } |
| 143 | |
Hiroshi Inoue | d24ddcd | 2018-01-19 10:55:29 +0000 | [diff] [blame] | 144 | // Assert the block is consistent: If valid, it should also have |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 145 | // non-null members besides Lhs_ and Rhs_. |
| 146 | void AssertConsistent() const { |
| 147 | if (IsValid()) { |
| 148 | assert(BB); |
| 149 | assert(CmpI); |
| 150 | assert(BranchI); |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | const BCEAtom &Lhs() const { return Lhs_; } |
| 155 | const BCEAtom &Rhs() const { return Rhs_; } |
| 156 | int SizeBits() const { return SizeBits_; } |
| 157 | |
| 158 | // Returns true if the block does other works besides comparison. |
| 159 | bool doesOtherWork() const; |
| 160 | |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 161 | // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp |
| 162 | // instructions in the block. |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 163 | bool canSplit(AliasAnalysis *AA) const; |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 164 | |
| 165 | // Return true if this all the relevant instructions in the BCE-cmp-block can |
| 166 | // be sunk below this instruction. By doing this, we know we can separate the |
| 167 | // BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the |
| 168 | // block. |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 169 | bool canSinkBCECmpInst(const Instruction *, DenseSet<Instruction *> &, |
| 170 | AliasAnalysis *AA) const; |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 171 | |
| 172 | // We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block |
| 173 | // instructions. Split the old block and move all non-BCE-cmp-insts into the |
| 174 | // new parent block. |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 175 | void split(BasicBlock *NewParent, AliasAnalysis *AA) const; |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 176 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 177 | // The basic block where this comparison happens. |
| 178 | BasicBlock *BB = nullptr; |
| 179 | // The ICMP for this comparison. |
| 180 | ICmpInst *CmpI = nullptr; |
| 181 | // The terminating branch. |
| 182 | BranchInst *BranchI = nullptr; |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 183 | // The block requires splitting. |
| 184 | bool RequireSplit = false; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 185 | |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 186 | private: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 187 | BCEAtom Lhs_; |
| 188 | BCEAtom Rhs_; |
| 189 | int SizeBits_ = 0; |
| 190 | }; |
| 191 | |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 192 | bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst, |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 193 | DenseSet<Instruction *> &BlockInsts, |
| 194 | AliasAnalysis *AA) const { |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 195 | // If this instruction has side effects and its in middle of the BCE cmp block |
| 196 | // instructions, then bail for now. |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 197 | if (Inst->mayHaveSideEffects()) { |
| 198 | // Bail if this is not a simple load or store |
| 199 | if (!isSimpleLoadOrStore(Inst)) |
| 200 | return false; |
| 201 | // Disallow stores that might alias the BCE operands |
| 202 | MemoryLocation LLoc = MemoryLocation::get(Lhs_.LoadI); |
| 203 | MemoryLocation RLoc = MemoryLocation::get(Rhs_.LoadI); |
| 204 | if (isModSet(AA->getModRefInfo(Inst, LLoc)) || |
| 205 | isModSet(AA->getModRefInfo(Inst, RLoc))) |
| 206 | return false; |
| 207 | } |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 208 | // Make sure this instruction does not use any of the BCE cmp block |
| 209 | // instructions as operand. |
| 210 | for (auto BI : BlockInsts) { |
| 211 | if (is_contained(Inst->operands(), BI)) |
| 212 | return false; |
| 213 | } |
| 214 | return true; |
| 215 | } |
| 216 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 217 | void BCECmpBlock::split(BasicBlock *NewParent, AliasAnalysis *AA) const { |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 218 | DenseSet<Instruction *> BlockInsts( |
| 219 | {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI}); |
| 220 | llvm::SmallVector<Instruction *, 4> OtherInsts; |
| 221 | for (Instruction &Inst : *BB) { |
| 222 | if (BlockInsts.count(&Inst)) |
| 223 | continue; |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 224 | assert(canSinkBCECmpInst(&Inst, BlockInsts, AA) && |
| 225 | "Split unsplittable block"); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 226 | // This is a non-BCE-cmp-block instruction. And it can be separated |
| 227 | // from the BCE-cmp-block instruction. |
| 228 | OtherInsts.push_back(&Inst); |
| 229 | } |
| 230 | |
| 231 | // Do the actual spliting. |
| 232 | for (Instruction *Inst : reverse(OtherInsts)) { |
| 233 | Inst->moveBefore(&*NewParent->begin()); |
| 234 | } |
| 235 | } |
| 236 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 237 | bool BCECmpBlock::canSplit(AliasAnalysis *AA) const { |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 238 | DenseSet<Instruction *> BlockInsts( |
| 239 | {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI}); |
| 240 | for (Instruction &Inst : *BB) { |
| 241 | if (!BlockInsts.count(&Inst)) { |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 242 | if (!canSinkBCECmpInst(&Inst, BlockInsts, AA)) |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 243 | return false; |
| 244 | } |
| 245 | } |
| 246 | return true; |
| 247 | } |
| 248 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 249 | bool BCECmpBlock::doesOtherWork() const { |
| 250 | AssertConsistent(); |
Xin Tong | 8fd561f | 2018-03-06 02:24:02 +0000 | [diff] [blame] | 251 | // All the instructions we care about in the BCE cmp block. |
| 252 | DenseSet<Instruction *> BlockInsts( |
| 253 | {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI}); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 254 | // TODO(courbet): Can we allow some other things ? This is very conservative. |
Hiroshi Inoue | ae17900 | 2018-04-14 08:59:00 +0000 | [diff] [blame] | 255 | // We might be able to get away with anything does not have any side |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 256 | // effects outside of the basic block. |
| 257 | // Note: The GEPs and/or loads are not necessarily in the same block. |
| 258 | for (const Instruction &Inst : *BB) { |
Xin Tong | 8fd561f | 2018-03-06 02:24:02 +0000 | [diff] [blame] | 259 | if (!BlockInsts.count(&Inst)) |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 260 | return true; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 261 | } |
| 262 | return false; |
| 263 | } |
| 264 | |
| 265 | // Visit the given comparison. If this is a comparison between two valid |
| 266 | // BCE atoms, returns the comparison. |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 267 | BCECmpBlock visitICmp(const ICmpInst *const CmpI, |
| 268 | const ICmpInst::Predicate ExpectedPredicate) { |
Clement Courbet | 9f0b317 | 2018-03-13 07:05:55 +0000 | [diff] [blame] | 269 | // The comparison can only be used once: |
| 270 | // - For intermediate blocks, as a branch condition. |
| 271 | // - For the final block, as an incoming value for the Phi. |
| 272 | // If there are any other uses of the comparison, we cannot merge it with |
| 273 | // other comparisons as we would create an orphan use of the value. |
| 274 | if (!CmpI->hasOneUse()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 275 | LLVM_DEBUG(dbgs() << "cmp has several uses\n"); |
Clement Courbet | 9f0b317 | 2018-03-13 07:05:55 +0000 | [diff] [blame] | 276 | return {}; |
| 277 | } |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 278 | if (CmpI->getPredicate() == ExpectedPredicate) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 279 | LLVM_DEBUG(dbgs() << "cmp " |
| 280 | << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne") |
| 281 | << "\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 282 | auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0)); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 283 | if (!Lhs.Base()) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 284 | auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1)); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 285 | if (!Rhs.Base()) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 286 | return BCECmpBlock(std::move(Lhs), std::move(Rhs), |
| 287 | CmpI->getOperand(0)->getType()->getScalarSizeInBits()); |
| 288 | } |
| 289 | return {}; |
| 290 | } |
| 291 | |
| 292 | // Visit the given comparison block. If this is a comparison between two valid |
| 293 | // BCE atoms, returns the comparison. |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 294 | BCECmpBlock visitCmpBlock(Value *const Val, BasicBlock *const Block, |
| 295 | const BasicBlock *const PhiBlock) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 296 | if (Block->empty()) return {}; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 297 | auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator()); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 298 | if (!BranchI) return {}; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 299 | LLVM_DEBUG(dbgs() << "branch\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 300 | if (BranchI->isUnconditional()) { |
| 301 | // In this case, we expect an incoming value which is the result of the |
| 302 | // comparison. This is the last link in the chain of comparisons (note |
| 303 | // that this does not mean that this is the last incoming value, blocks |
| 304 | // can be reordered). |
| 305 | auto *const CmpI = dyn_cast<ICmpInst>(Val); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 306 | if (!CmpI) return {}; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 307 | LLVM_DEBUG(dbgs() << "icmp\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 308 | auto Result = visitICmp(CmpI, ICmpInst::ICMP_EQ); |
| 309 | Result.CmpI = CmpI; |
| 310 | Result.BranchI = BranchI; |
| 311 | return Result; |
| 312 | } else { |
| 313 | // In this case, we expect a constant incoming value (the comparison is |
| 314 | // chained). |
| 315 | const auto *const Const = dyn_cast<ConstantInt>(Val); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 316 | LLVM_DEBUG(dbgs() << "const\n"); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 317 | if (!Const->isZero()) return {}; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 318 | LLVM_DEBUG(dbgs() << "false\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 319 | auto *const CmpI = dyn_cast<ICmpInst>(BranchI->getCondition()); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 320 | if (!CmpI) return {}; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 321 | LLVM_DEBUG(dbgs() << "icmp\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 322 | assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch"); |
| 323 | BasicBlock *const FalseBlock = BranchI->getSuccessor(1); |
| 324 | auto Result = visitICmp( |
| 325 | CmpI, FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE); |
| 326 | Result.CmpI = CmpI; |
| 327 | Result.BranchI = BranchI; |
| 328 | return Result; |
| 329 | } |
| 330 | return {}; |
| 331 | } |
| 332 | |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 333 | static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons, |
| 334 | BCECmpBlock &Comparison) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 335 | LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName() |
| 336 | << "': Found cmp of " << Comparison.SizeBits() |
| 337 | << " bits between " << Comparison.Lhs().Base() << " + " |
| 338 | << Comparison.Lhs().Offset << " and " |
| 339 | << Comparison.Rhs().Base() << " + " |
| 340 | << Comparison.Rhs().Offset << "\n"); |
| 341 | LLVM_DEBUG(dbgs() << "\n"); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 342 | Comparisons.push_back(Comparison); |
| 343 | } |
| 344 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 345 | // A chain of comparisons. |
| 346 | class BCECmpChain { |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 347 | public: |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 348 | BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi, |
| 349 | AliasAnalysis *AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 350 | |
| 351 | int size() const { return Comparisons_.size(); } |
| 352 | |
| 353 | #ifdef MERGEICMPS_DOT_ON |
| 354 | void dump() const; |
| 355 | #endif // MERGEICMPS_DOT_ON |
| 356 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 357 | bool simplify(const TargetLibraryInfo *const TLI, AliasAnalysis *AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 358 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 359 | private: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 360 | static bool IsContiguous(const BCECmpBlock &First, |
| 361 | const BCECmpBlock &Second) { |
| 362 | return First.Lhs().Base() == Second.Lhs().Base() && |
| 363 | First.Rhs().Base() == Second.Rhs().Base() && |
| 364 | First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset && |
| 365 | First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset; |
| 366 | } |
| 367 | |
| 368 | // Merges the given comparison blocks into one memcmp block and update |
| 369 | // branches. Comparisons are assumed to be continguous. If NextBBInChain is |
| 370 | // null, the merged block will link to the phi block. |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 371 | void mergeComparisons(ArrayRef<BCECmpBlock> Comparisons, |
| 372 | BasicBlock *const NextBBInChain, PHINode &Phi, |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 373 | const TargetLibraryInfo *const TLI, AliasAnalysis *AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 374 | |
| 375 | PHINode &Phi_; |
| 376 | std::vector<BCECmpBlock> Comparisons_; |
| 377 | // The original entry block (before sorting); |
| 378 | BasicBlock *EntryBlock_; |
| 379 | }; |
| 380 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 381 | BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi, |
| 382 | AliasAnalysis *AA) |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 383 | : Phi_(Phi) { |
Clement Courbet | c2109c8 | 2018-02-06 09:14:00 +0000 | [diff] [blame] | 384 | assert(!Blocks.empty() && "a chain should have at least one block"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 385 | // Now look inside blocks to check for BCE comparisons. |
| 386 | std::vector<BCECmpBlock> Comparisons; |
Clement Courbet | a7a1746 | 2018-02-06 12:25:33 +0000 | [diff] [blame] | 387 | for (size_t BlockIdx = 0; BlockIdx < Blocks.size(); ++BlockIdx) { |
| 388 | BasicBlock *const Block = Blocks[BlockIdx]; |
Clement Courbet | c2109c8 | 2018-02-06 09:14:00 +0000 | [diff] [blame] | 389 | assert(Block && "invalid block"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 390 | BCECmpBlock Comparison = visitCmpBlock(Phi.getIncomingValueForBlock(Block), |
| 391 | Block, Phi.getParent()); |
| 392 | Comparison.BB = Block; |
| 393 | if (!Comparison.IsValid()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 394 | LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 395 | return; |
| 396 | } |
| 397 | if (Comparison.doesOtherWork()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 398 | LLVM_DEBUG(dbgs() << "block '" << Comparison.BB->getName() |
| 399 | << "' does extra work besides compare\n"); |
Xin Tong | 8345c0e | 2018-03-05 13:54:47 +0000 | [diff] [blame] | 400 | if (Comparisons.empty()) { |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 401 | // This is the initial block in the chain, in case this block does other |
| 402 | // work, we can try to split the block and move the irrelevant |
| 403 | // instructions to the predecessor. |
| 404 | // |
| 405 | // If this is not the initial block in the chain, splitting it wont |
| 406 | // work. |
| 407 | // |
| 408 | // As once split, there will still be instructions before the BCE cmp |
| 409 | // instructions that do other work in program order, i.e. within the |
| 410 | // chain before sorting. Unless we can abort the chain at this point |
| 411 | // and start anew. |
| 412 | // |
| 413 | // NOTE: we only handle block with single predecessor for now. |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 414 | if (Comparison.canSplit(AA)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 415 | LLVM_DEBUG(dbgs() |
| 416 | << "Split initial block '" << Comparison.BB->getName() |
| 417 | << "' that does extra work besides compare\n"); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 418 | Comparison.RequireSplit = true; |
| 419 | enqueueBlock(Comparisons, Comparison); |
| 420 | } else { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 421 | LLVM_DEBUG(dbgs() |
| 422 | << "ignoring initial block '" << Comparison.BB->getName() |
| 423 | << "' that does extra work besides compare\n"); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 424 | } |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 425 | continue; |
| 426 | } |
| 427 | // TODO(courbet): Right now we abort the whole chain. We could be |
| 428 | // merging only the blocks that don't do other work and resume the |
| 429 | // chain from there. For example: |
| 430 | // if (a[0] == b[0]) { // bb1 |
| 431 | // if (a[1] == b[1]) { // bb2 |
| 432 | // some_value = 3; //bb3 |
| 433 | // if (a[2] == b[2]) { //bb3 |
| 434 | // do a ton of stuff //bb4 |
| 435 | // } |
| 436 | // } |
| 437 | // } |
| 438 | // |
| 439 | // This is: |
| 440 | // |
| 441 | // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+ |
| 442 | // \ \ \ \ |
| 443 | // ne ne ne \ |
| 444 | // \ \ \ v |
| 445 | // +------------+-----------+----------> bb_phi |
| 446 | // |
| 447 | // We can only merge the first two comparisons, because bb3* does |
| 448 | // "other work" (setting some_value to 3). |
| 449 | // We could still merge bb1 and bb2 though. |
| 450 | return; |
| 451 | } |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 452 | enqueueBlock(Comparisons, Comparison); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 453 | } |
Xin Tong | 8345c0e | 2018-03-05 13:54:47 +0000 | [diff] [blame] | 454 | |
| 455 | // It is possible we have no suitable comparison to merge. |
| 456 | if (Comparisons.empty()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 457 | LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n"); |
Xin Tong | 8345c0e | 2018-03-05 13:54:47 +0000 | [diff] [blame] | 458 | return; |
| 459 | } |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 460 | EntryBlock_ = Comparisons[0].BB; |
| 461 | Comparisons_ = std::move(Comparisons); |
| 462 | #ifdef MERGEICMPS_DOT_ON |
| 463 | errs() << "BEFORE REORDERING:\n\n"; |
| 464 | dump(); |
| 465 | #endif // MERGEICMPS_DOT_ON |
| 466 | // Reorder blocks by LHS. We can do that without changing the |
| 467 | // semantics because we are only accessing dereferencable memory. |
Mandeep Singh Grang | 636d94d | 2018-04-13 19:47:57 +0000 | [diff] [blame] | 468 | llvm::sort(Comparisons_.begin(), Comparisons_.end(), |
| 469 | [](const BCECmpBlock &a, const BCECmpBlock &b) { |
| 470 | return a.Lhs() < b.Lhs(); |
| 471 | }); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 472 | #ifdef MERGEICMPS_DOT_ON |
| 473 | errs() << "AFTER REORDERING:\n\n"; |
| 474 | dump(); |
| 475 | #endif // MERGEICMPS_DOT_ON |
| 476 | } |
| 477 | |
| 478 | #ifdef MERGEICMPS_DOT_ON |
| 479 | void BCECmpChain::dump() const { |
| 480 | errs() << "digraph dag {\n"; |
| 481 | errs() << " graph [bgcolor=transparent];\n"; |
| 482 | errs() << " node [color=black,style=filled,fillcolor=lightyellow];\n"; |
| 483 | errs() << " edge [color=black];\n"; |
| 484 | for (size_t I = 0; I < Comparisons_.size(); ++I) { |
| 485 | const auto &Comparison = Comparisons_[I]; |
| 486 | errs() << " \"" << I << "\" [label=\"%" |
| 487 | << Comparison.Lhs().Base()->getName() << " + " |
| 488 | << Comparison.Lhs().Offset << " == %" |
| 489 | << Comparison.Rhs().Base()->getName() << " + " |
| 490 | << Comparison.Rhs().Offset << " (" << (Comparison.SizeBits() / 8) |
| 491 | << " bytes)\"];\n"; |
| 492 | const Value *const Val = Phi_.getIncomingValueForBlock(Comparison.BB); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 493 | if (I > 0) errs() << " \"" << (I - 1) << "\" -> \"" << I << "\";\n"; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 494 | errs() << " \"" << I << "\" -> \"Phi\" [label=\"" << *Val << "\"];\n"; |
| 495 | } |
| 496 | errs() << " \"Phi\" [label=\"Phi\"];\n"; |
| 497 | errs() << "}\n\n"; |
| 498 | } |
| 499 | #endif // MERGEICMPS_DOT_ON |
| 500 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 501 | bool BCECmpChain::simplify(const TargetLibraryInfo *const TLI, |
| 502 | AliasAnalysis *AA) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 503 | // First pass to check if there is at least one merge. If not, we don't do |
| 504 | // anything and we keep analysis passes intact. |
| 505 | { |
| 506 | bool AtLeastOneMerged = false; |
| 507 | for (size_t I = 1; I < Comparisons_.size(); ++I) { |
| 508 | if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) { |
| 509 | AtLeastOneMerged = true; |
| 510 | break; |
| 511 | } |
| 512 | } |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 513 | if (!AtLeastOneMerged) return false; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 514 | } |
| 515 | |
| 516 | // Remove phi references to comparison blocks, they will be rebuilt as we |
| 517 | // merge the blocks. |
| 518 | for (const auto &Comparison : Comparisons_) { |
| 519 | Phi_.removeIncomingValue(Comparison.BB, false); |
| 520 | } |
| 521 | |
Xin Tong | bdbd97e | 2018-03-20 11:57:54 +0000 | [diff] [blame] | 522 | // If entry block is part of the chain, we need to make the first block |
| 523 | // of the chain the new entry block of the function. |
| 524 | BasicBlock *Entry = &Comparisons_[0].BB->getParent()->getEntryBlock(); |
| 525 | for (size_t I = 1; I < Comparisons_.size(); ++I) { |
| 526 | if (Entry == Comparisons_[I].BB) { |
| 527 | BasicBlock *NEntryBB = BasicBlock::Create(Entry->getContext(), "", |
| 528 | Entry->getParent(), Entry); |
| 529 | BranchInst::Create(Entry, NEntryBB); |
Xin Tong | a713ebe | 2018-03-20 12:03:25 +0000 | [diff] [blame] | 530 | break; |
Xin Tong | bdbd97e | 2018-03-20 11:57:54 +0000 | [diff] [blame] | 531 | } |
| 532 | } |
| 533 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 534 | // Point the predecessors of the chain to the first comparison block (which is |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 535 | // the new entry point) and update the entry block of the chain. |
| 536 | if (EntryBlock_ != Comparisons_[0].BB) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 537 | EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 538 | EntryBlock_ = Comparisons_[0].BB; |
| 539 | } |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 540 | |
| 541 | // Effectively merge blocks. |
| 542 | int NumMerged = 1; |
| 543 | for (size_t I = 1; I < Comparisons_.size(); ++I) { |
| 544 | if (IsContiguous(Comparisons_[I - 1], Comparisons_[I])) { |
| 545 | ++NumMerged; |
| 546 | } else { |
| 547 | // Merge all previous comparisons and start a new merge block. |
| 548 | mergeComparisons( |
| 549 | makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged), |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 550 | Comparisons_[I].BB, Phi_, TLI, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 551 | NumMerged = 1; |
| 552 | } |
| 553 | } |
| 554 | mergeComparisons(makeArrayRef(Comparisons_) |
| 555 | .slice(Comparisons_.size() - NumMerged, NumMerged), |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 556 | nullptr, Phi_, TLI, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 557 | |
| 558 | return true; |
| 559 | } |
| 560 | |
| 561 | void BCECmpChain::mergeComparisons(ArrayRef<BCECmpBlock> Comparisons, |
| 562 | BasicBlock *const NextBBInChain, |
| 563 | PHINode &Phi, |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 564 | const TargetLibraryInfo *const TLI, |
| 565 | AliasAnalysis *AA) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 566 | assert(!Comparisons.empty()); |
| 567 | const auto &FirstComparison = *Comparisons.begin(); |
| 568 | BasicBlock *const BB = FirstComparison.BB; |
| 569 | LLVMContext &Context = BB->getContext(); |
| 570 | |
| 571 | if (Comparisons.size() >= 2) { |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 572 | // If there is one block that requires splitting, we do it now, i.e. |
| 573 | // just before we know we will collapse the chain. The instructions |
| 574 | // can be executed before any of the instructions in the chain. |
| 575 | auto C = std::find_if(Comparisons.begin(), Comparisons.end(), |
| 576 | [](const BCECmpBlock &B) { return B.RequireSplit; }); |
| 577 | if (C != Comparisons.end()) |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 578 | C->split(EntryBlock_, AA); |
Xin Tong | 0efadbb | 2018-04-09 13:14:06 +0000 | [diff] [blame] | 579 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 580 | LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 581 | const auto TotalSize = |
| 582 | std::accumulate(Comparisons.begin(), Comparisons.end(), 0, |
| 583 | [](int Size, const BCECmpBlock &C) { |
| 584 | return Size + C.SizeBits(); |
| 585 | }) / |
| 586 | 8; |
| 587 | |
| 588 | // Incoming edges do not need to be updated, and both GEPs are already |
| 589 | // computing the right address, we just need to: |
| 590 | // - replace the two loads and the icmp with the memcmp |
| 591 | // - update the branch |
| 592 | // - update the incoming values in the phi. |
| 593 | FirstComparison.BranchI->eraseFromParent(); |
| 594 | FirstComparison.CmpI->eraseFromParent(); |
| 595 | FirstComparison.Lhs().LoadI->eraseFromParent(); |
| 596 | FirstComparison.Rhs().LoadI->eraseFromParent(); |
| 597 | |
| 598 | IRBuilder<> Builder(BB); |
| 599 | const auto &DL = Phi.getModule()->getDataLayout(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 600 | Value *const MemCmpCall = emitMemCmp( |
Xin Tong | 0272cb0 | 2018-03-27 19:43:02 +0000 | [diff] [blame] | 601 | FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP, |
| 602 | ConstantInt::get(DL.getIntPtrType(Context), TotalSize), |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 603 | Builder, DL, TLI); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 604 | Value *const MemCmpIsZero = Builder.CreateICmpEQ( |
| 605 | MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0)); |
| 606 | |
| 607 | // Add a branch to the next basic block in the chain. |
| 608 | if (NextBBInChain) { |
| 609 | Builder.CreateCondBr(MemCmpIsZero, NextBBInChain, Phi.getParent()); |
| 610 | Phi.addIncoming(ConstantInt::getFalse(Context), BB); |
| 611 | } else { |
| 612 | Builder.CreateBr(Phi.getParent()); |
| 613 | Phi.addIncoming(MemCmpIsZero, BB); |
| 614 | } |
| 615 | |
| 616 | // Delete merged blocks. |
| 617 | for (size_t I = 1; I < Comparisons.size(); ++I) { |
| 618 | BasicBlock *CBB = Comparisons[I].BB; |
| 619 | CBB->replaceAllUsesWith(BB); |
| 620 | CBB->eraseFromParent(); |
| 621 | } |
| 622 | } else { |
| 623 | assert(Comparisons.size() == 1); |
| 624 | // There are no blocks to merge, but we still need to update the branches. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 625 | LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 626 | if (NextBBInChain) { |
| 627 | if (FirstComparison.BranchI->isConditional()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 628 | LLVM_DEBUG(dbgs() << "conditional -> conditional\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 629 | // Just update the "true" target, the "false" target should already be |
| 630 | // the phi block. |
| 631 | assert(FirstComparison.BranchI->getSuccessor(1) == Phi.getParent()); |
| 632 | FirstComparison.BranchI->setSuccessor(0, NextBBInChain); |
| 633 | Phi.addIncoming(ConstantInt::getFalse(Context), BB); |
| 634 | } else { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 635 | LLVM_DEBUG(dbgs() << "unconditional -> conditional\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 636 | // Replace the unconditional branch by a conditional one. |
| 637 | FirstComparison.BranchI->eraseFromParent(); |
| 638 | IRBuilder<> Builder(BB); |
| 639 | Builder.CreateCondBr(FirstComparison.CmpI, NextBBInChain, |
| 640 | Phi.getParent()); |
| 641 | Phi.addIncoming(FirstComparison.CmpI, BB); |
| 642 | } |
| 643 | } else { |
| 644 | if (FirstComparison.BranchI->isConditional()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 645 | LLVM_DEBUG(dbgs() << "conditional -> unconditional\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 646 | // Replace the conditional branch by an unconditional one. |
| 647 | FirstComparison.BranchI->eraseFromParent(); |
| 648 | IRBuilder<> Builder(BB); |
| 649 | Builder.CreateBr(Phi.getParent()); |
| 650 | Phi.addIncoming(FirstComparison.CmpI, BB); |
| 651 | } else { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 652 | LLVM_DEBUG(dbgs() << "unconditional -> unconditional\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 653 | Phi.addIncoming(FirstComparison.CmpI, BB); |
| 654 | } |
| 655 | } |
| 656 | } |
| 657 | } |
| 658 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 659 | std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi, |
| 660 | BasicBlock *const LastBlock, |
| 661 | int NumBlocks) { |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 662 | // Walk up from the last block to find other blocks. |
| 663 | std::vector<BasicBlock *> Blocks(NumBlocks); |
Clement Courbet | c2109c8 | 2018-02-06 09:14:00 +0000 | [diff] [blame] | 664 | assert(LastBlock && "invalid last block"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 665 | BasicBlock *CurBlock = LastBlock; |
| 666 | for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) { |
| 667 | if (CurBlock->hasAddressTaken()) { |
| 668 | // Somebody is jumping to the block through an address, all bets are |
| 669 | // off. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 670 | LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex |
| 671 | << " has its address taken\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 672 | return {}; |
| 673 | } |
| 674 | Blocks[BlockIndex] = CurBlock; |
| 675 | auto *SinglePredecessor = CurBlock->getSinglePredecessor(); |
| 676 | if (!SinglePredecessor) { |
| 677 | // The block has two or more predecessors. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 678 | LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex |
| 679 | << " has two or more predecessors\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 680 | return {}; |
| 681 | } |
| 682 | if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) { |
| 683 | // The block does not link back to the phi. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 684 | LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex |
| 685 | << " does not link back to the phi\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 686 | return {}; |
| 687 | } |
| 688 | CurBlock = SinglePredecessor; |
| 689 | } |
| 690 | Blocks[0] = CurBlock; |
| 691 | return Blocks; |
| 692 | } |
| 693 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 694 | bool processPhi(PHINode &Phi, const TargetLibraryInfo *const TLI, |
| 695 | AliasAnalysis *AA) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 696 | LLVM_DEBUG(dbgs() << "processPhi()\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 697 | if (Phi.getNumIncomingValues() <= 1) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 698 | LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 699 | return false; |
| 700 | } |
| 701 | // We are looking for something that has the following structure: |
| 702 | // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+ |
| 703 | // \ \ \ \ |
| 704 | // ne ne ne \ |
| 705 | // \ \ \ v |
| 706 | // +------------+-----------+----------> bb_phi |
| 707 | // |
| 708 | // - The last basic block (bb4 here) must branch unconditionally to bb_phi. |
| 709 | // It's the only block that contributes a non-constant value to the Phi. |
| 710 | // - All other blocks (b1, b2, b3) must have exactly two successors, one of |
Hiroshi Inoue | d24ddcd | 2018-01-19 10:55:29 +0000 | [diff] [blame] | 711 | // them being the phi block. |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 712 | // - All intermediate blocks (bb2, bb3) must have only one predecessor. |
| 713 | // - Blocks cannot do other work besides the comparison, see doesOtherWork() |
| 714 | |
| 715 | // The blocks are not necessarily ordered in the phi, so we start from the |
| 716 | // last block and reconstruct the order. |
| 717 | BasicBlock *LastBlock = nullptr; |
| 718 | for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) { |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 719 | if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 720 | if (LastBlock) { |
| 721 | // There are several non-constant values. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 722 | LLVM_DEBUG(dbgs() << "skip: several non-constant values\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 723 | return false; |
| 724 | } |
Xin Tong | 8ba674e | 2018-02-28 12:08:00 +0000 | [diff] [blame] | 725 | if (!isa<ICmpInst>(Phi.getIncomingValue(I)) || |
| 726 | cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() != |
| 727 | Phi.getIncomingBlock(I)) { |
| 728 | // Non-constant incoming value is not from a cmp instruction or not |
| 729 | // produced by the last block. We could end up processing the value |
| 730 | // producing block more than once. |
| 731 | // |
| 732 | // This is an uncommon case, so we bail. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 733 | LLVM_DEBUG( |
Xin Tong | 8ba674e | 2018-02-28 12:08:00 +0000 | [diff] [blame] | 734 | dbgs() |
| 735 | << "skip: non-constant value not from cmp or not from last block.\n"); |
| 736 | return false; |
| 737 | } |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 738 | LastBlock = Phi.getIncomingBlock(I); |
| 739 | } |
| 740 | if (!LastBlock) { |
| 741 | // There is no non-constant block. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 742 | LLVM_DEBUG(dbgs() << "skip: no non-constant block\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 743 | return false; |
| 744 | } |
| 745 | if (LastBlock->getSingleSuccessor() != Phi.getParent()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 746 | LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 747 | return false; |
| 748 | } |
| 749 | |
| 750 | const auto Blocks = |
| 751 | getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues()); |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 752 | if (Blocks.empty()) return false; |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 753 | BCECmpChain CmpChain(Blocks, Phi, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 754 | |
| 755 | if (CmpChain.size() < 2) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 756 | LLVM_DEBUG(dbgs() << "skip: only one compare block\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 757 | return false; |
| 758 | } |
| 759 | |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 760 | return CmpChain.simplify(TLI, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 761 | } |
| 762 | |
| 763 | class MergeICmps : public FunctionPass { |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 764 | public: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 765 | static char ID; |
| 766 | |
| 767 | MergeICmps() : FunctionPass(ID) { |
| 768 | initializeMergeICmpsPass(*PassRegistry::getPassRegistry()); |
| 769 | } |
| 770 | |
| 771 | bool runOnFunction(Function &F) override { |
| 772 | if (skipFunction(F)) return false; |
| 773 | const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 774 | const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 775 | AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); |
| 776 | auto PA = runImpl(F, &TLI, &TTI, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 777 | return !PA.areAllPreserved(); |
| 778 | } |
| 779 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 780 | private: |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 781 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 782 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 783 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 784 | AU.addRequired<AAResultsWrapperPass>(); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 785 | } |
| 786 | |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 787 | PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI, |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 788 | const TargetTransformInfo *TTI, AliasAnalysis *AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 789 | }; |
| 790 | |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 791 | PreservedAnalyses MergeICmps::runImpl(Function &F, const TargetLibraryInfo *TLI, |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 792 | const TargetTransformInfo *TTI, |
| 793 | AliasAnalysis *AA) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 794 | LLVM_DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n"); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 795 | |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 796 | // We only try merging comparisons if the target wants to expand memcmp later. |
| 797 | // The rationale is to avoid turning small chains into memcmp calls. |
Clement Courbet | b2c3eb8 | 2017-10-30 14:19:33 +0000 | [diff] [blame] | 798 | if (!TTI->enableMemCmpExpansion(true)) return PreservedAnalyses::all(); |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 799 | |
Benjamin Kramer | a76b64f | 2018-05-19 12:51:59 +0000 | [diff] [blame] | 800 | // If we don't have memcmp avaiable we can't emit calls to it. |
| 801 | if (!TLI->has(LibFunc_memcmp)) |
| 802 | return PreservedAnalyses::all(); |
| 803 | |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 804 | bool MadeChange = false; |
| 805 | |
| 806 | for (auto BBIt = ++F.begin(); BBIt != F.end(); ++BBIt) { |
| 807 | // A Phi operation is always first in a basic block. |
| 808 | if (auto *const Phi = dyn_cast<PHINode>(&*BBIt->begin())) |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 809 | MadeChange |= processPhi(*Phi, TLI, AA); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 810 | } |
| 811 | |
Clement Courbet | 98eaa88 | 2017-10-04 15:13:52 +0000 | [diff] [blame] | 812 | if (MadeChange) return PreservedAnalyses::none(); |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 813 | return PreservedAnalyses::all(); |
| 814 | } |
| 815 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 816 | } // namespace |
Eugene Zelenko | 5adb96c | 2017-10-26 00:55:39 +0000 | [diff] [blame] | 817 | |
Eugene Zelenko | 5c2aece | 2017-10-26 01:25:14 +0000 | [diff] [blame] | 818 | char MergeICmps::ID = 0; |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 819 | INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps", |
| 820 | "Merge contiguous icmps into a memcmp", false, false) |
| 821 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Clement Courbet | e2e8a5c | 2017-10-10 08:00:45 +0000 | [diff] [blame] | 822 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Christy Lee | e943748 | 2018-09-24 20:47:12 +0000 | [diff] [blame^] | 823 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
Clement Courbet | 65130e2 | 2017-09-01 10:56:34 +0000 | [diff] [blame] | 824 | INITIALIZE_PASS_END(MergeICmps, "mergeicmps", |
| 825 | "Merge contiguous icmps into a memcmp", false, false) |
| 826 | |
| 827 | Pass *llvm::createMergeICmpsPass() { return new MergeICmps(); } |