MergeICmps.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. //===- MergeICmps.cpp - Optimize chains of integer comparisons ------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass turns chains of integer comparisons into memcmp (the memcmp is
  10. // later typically inlined as a chain of efficient hardware comparisons). This
  11. // typically benefits c++ member or nonmember operator==().
  12. //
  13. // The basic idea is to replace a longer chain of integer comparisons loaded
  14. // from contiguous memory locations into a shorter chain of larger integer
  15. // comparisons. Benefits are double:
  16. // - There are less jumps, and therefore less opportunities for mispredictions
  17. // and I-cache misses.
  18. // - Code size is smaller, both because jumps are removed and because the
  19. // encoding of a 2*n byte compare is smaller than that of two n-byte
  20. // compares.
  21. //
  22. // Example:
  23. //
  24. // struct S {
  25. // int a;
  26. // char b;
  27. // char c;
  28. // uint16_t d;
  29. // bool operator==(const S& o) const {
  30. // return a == o.a && b == o.b && c == o.c && d == o.d;
  31. // }
  32. // };
  33. //
  34. // Is optimized as :
  35. //
  36. // bool S::operator==(const S& o) const {
  37. // return memcmp(this, &o, 8) == 0;
  38. // }
  39. //
  40. // Which will later be expanded (ExpandMemCmp) as a single 8-bytes icmp.
  41. //
  42. //===----------------------------------------------------------------------===//
  43. #include "llvm/Transforms/Scalar/MergeICmps.h"
  44. #include "llvm/Analysis/DomTreeUpdater.h"
  45. #include "llvm/Analysis/GlobalsModRef.h"
  46. #include "llvm/Analysis/Loads.h"
  47. #include "llvm/Analysis/TargetLibraryInfo.h"
  48. #include "llvm/Analysis/TargetTransformInfo.h"
  49. #include "llvm/IR/Dominators.h"
  50. #include "llvm/IR/Function.h"
  51. #include "llvm/IR/IRBuilder.h"
  52. #include "llvm/InitializePasses.h"
  53. #include "llvm/Pass.h"
  54. #include "llvm/Transforms/Scalar.h"
  55. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  56. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  57. #include <algorithm>
  58. #include <numeric>
  59. #include <utility>
  60. #include <vector>
  61. using namespace llvm;
  62. namespace {
  63. #define DEBUG_TYPE "mergeicmps"
  64. // A BCE atom "Binary Compare Expression Atom" represents an integer load
  65. // that is a constant offset from a base value, e.g. `a` or `o.c` in the example
  66. // at the top.
  67. struct BCEAtom {
  68. BCEAtom() = default;
  69. BCEAtom(GetElementPtrInst *GEP, LoadInst *LoadI, int BaseId, APInt Offset)
  70. : GEP(GEP), LoadI(LoadI), BaseId(BaseId), Offset(Offset) {}
  71. BCEAtom(const BCEAtom &) = delete;
  72. BCEAtom &operator=(const BCEAtom &) = delete;
  73. BCEAtom(BCEAtom &&that) = default;
  74. BCEAtom &operator=(BCEAtom &&that) {
  75. if (this == &that)
  76. return *this;
  77. GEP = that.GEP;
  78. LoadI = that.LoadI;
  79. BaseId = that.BaseId;
  80. Offset = std::move(that.Offset);
  81. return *this;
  82. }
  83. // We want to order BCEAtoms by (Base, Offset). However we cannot use
  84. // the pointer values for Base because these are non-deterministic.
  85. // To make sure that the sort order is stable, we first assign to each atom
  86. // base value an index based on its order of appearance in the chain of
  87. // comparisons. We call this index `BaseOrdering`. For example, for:
  88. // b[3] == c[2] && a[1] == d[1] && b[4] == c[3]
  89. // | block 1 | | block 2 | | block 3 |
  90. // b gets assigned index 0 and a index 1, because b appears as LHS in block 1,
  91. // which is before block 2.
  92. // We then sort by (BaseOrdering[LHS.Base()], LHS.Offset), which is stable.
  93. bool operator<(const BCEAtom &O) const {
  94. return BaseId != O.BaseId ? BaseId < O.BaseId : Offset.slt(O.Offset);
  95. }
  96. GetElementPtrInst *GEP = nullptr;
  97. LoadInst *LoadI = nullptr;
  98. unsigned BaseId = 0;
  99. APInt Offset;
  100. };
  101. // A class that assigns increasing ids to values in the order in which they are
  102. // seen. See comment in `BCEAtom::operator<()``.
  103. class BaseIdentifier {
  104. public:
  105. // Returns the id for value `Base`, after assigning one if `Base` has not been
  106. // seen before.
  107. int getBaseId(const Value *Base) {
  108. assert(Base && "invalid base");
  109. const auto Insertion = BaseToIndex.try_emplace(Base, Order);
  110. if (Insertion.second)
  111. ++Order;
  112. return Insertion.first->second;
  113. }
  114. private:
  115. unsigned Order = 1;
  116. DenseMap<const Value*, int> BaseToIndex;
  117. };
  118. // If this value is a load from a constant offset w.r.t. a base address, and
  119. // there are no other users of the load or address, returns the base address and
  120. // the offset.
  121. BCEAtom visitICmpLoadOperand(Value *const Val, BaseIdentifier &BaseId) {
  122. auto *const LoadI = dyn_cast<LoadInst>(Val);
  123. if (!LoadI)
  124. return {};
  125. LLVM_DEBUG(dbgs() << "load\n");
  126. if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
  127. LLVM_DEBUG(dbgs() << "used outside of block\n");
  128. return {};
  129. }
  130. // Do not optimize atomic loads to non-atomic memcmp
  131. if (!LoadI->isSimple()) {
  132. LLVM_DEBUG(dbgs() << "volatile or atomic\n");
  133. return {};
  134. }
  135. Value *const Addr = LoadI->getOperand(0);
  136. if (Addr->getType()->getPointerAddressSpace() != 0) {
  137. LLVM_DEBUG(dbgs() << "from non-zero AddressSpace\n");
  138. return {};
  139. }
  140. auto *const GEP = dyn_cast<GetElementPtrInst>(Addr);
  141. if (!GEP)
  142. return {};
  143. LLVM_DEBUG(dbgs() << "GEP\n");
  144. if (GEP->isUsedOutsideOfBlock(LoadI->getParent())) {
  145. LLVM_DEBUG(dbgs() << "used outside of block\n");
  146. return {};
  147. }
  148. const auto &DL = GEP->getModule()->getDataLayout();
  149. if (!isDereferenceablePointer(GEP, LoadI->getType(), DL)) {
  150. LLVM_DEBUG(dbgs() << "not dereferenceable\n");
  151. // We need to make sure that we can do comparison in any order, so we
  152. // require memory to be unconditionnally dereferencable.
  153. return {};
  154. }
  155. APInt Offset = APInt(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
  156. if (!GEP->accumulateConstantOffset(DL, Offset))
  157. return {};
  158. return BCEAtom(GEP, LoadI, BaseId.getBaseId(GEP->getPointerOperand()),
  159. Offset);
  160. }
  161. // A comparison between two BCE atoms, e.g. `a == o.a` in the example at the
  162. // top.
  163. // Note: the terminology is misleading: the comparison is symmetric, so there
  164. // is no real {l/r}hs. What we want though is to have the same base on the
  165. // left (resp. right), so that we can detect consecutive loads. To ensure this
  166. // we put the smallest atom on the left.
  167. struct BCECmp {
  168. BCEAtom Lhs;
  169. BCEAtom Rhs;
  170. int SizeBits;
  171. const ICmpInst *CmpI;
  172. BCECmp(BCEAtom L, BCEAtom R, int SizeBits, const ICmpInst *CmpI)
  173. : Lhs(std::move(L)), Rhs(std::move(R)), SizeBits(SizeBits), CmpI(CmpI) {
  174. if (Rhs < Lhs) std::swap(Rhs, Lhs);
  175. }
  176. };
  177. // A basic block with a comparison between two BCE atoms.
  178. // The block might do extra work besides the atom comparison, in which case
  179. // doesOtherWork() returns true. Under some conditions, the block can be
  180. // split into the atom comparison part and the "other work" part
  181. // (see canSplit()).
  182. class BCECmpBlock {
  183. public:
  184. typedef SmallDenseSet<const Instruction *, 8> InstructionSet;
  185. BCECmpBlock(BCECmp Cmp, BasicBlock *BB, InstructionSet BlockInsts)
  186. : BB(BB), BlockInsts(std::move(BlockInsts)), Cmp(std::move(Cmp)) {}
  187. const BCEAtom &Lhs() const { return Cmp.Lhs; }
  188. const BCEAtom &Rhs() const { return Cmp.Rhs; }
  189. int SizeBits() const { return Cmp.SizeBits; }
  190. // Returns true if the block does other works besides comparison.
  191. bool doesOtherWork() const;
  192. // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp
  193. // instructions in the block.
  194. bool canSplit(AliasAnalysis &AA) const;
  195. // Return true if this all the relevant instructions in the BCE-cmp-block can
  196. // be sunk below this instruction. By doing this, we know we can separate the
  197. // BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the
  198. // block.
  199. bool canSinkBCECmpInst(const Instruction *, AliasAnalysis &AA) const;
  200. // We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block
  201. // instructions. Split the old block and move all non-BCE-cmp-insts into the
  202. // new parent block.
  203. void split(BasicBlock *NewParent, AliasAnalysis &AA) const;
  204. // The basic block where this comparison happens.
  205. BasicBlock *BB;
  206. // Instructions relating to the BCECmp and branch.
  207. InstructionSet BlockInsts;
  208. // The block requires splitting.
  209. bool RequireSplit = false;
  210. // Original order of this block in the chain.
  211. unsigned OrigOrder = 0;
  212. private:
  213. BCECmp Cmp;
  214. };
  215. bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst,
  216. AliasAnalysis &AA) const {
  217. // If this instruction may clobber the loads and is in middle of the BCE cmp
  218. // block instructions, then bail for now.
  219. if (Inst->mayWriteToMemory()) {
  220. auto MayClobber = [&](LoadInst *LI) {
  221. // If a potentially clobbering instruction comes before the load,
  222. // we can still safely sink the load.
  223. return !Inst->comesBefore(LI) &&
  224. isModSet(AA.getModRefInfo(Inst, MemoryLocation::get(LI)));
  225. };
  226. if (MayClobber(Cmp.Lhs.LoadI) || MayClobber(Cmp.Rhs.LoadI))
  227. return false;
  228. }
  229. // Make sure this instruction does not use any of the BCE cmp block
  230. // instructions as operand.
  231. return llvm::none_of(Inst->operands(), [&](const Value *Op) {
  232. const Instruction *OpI = dyn_cast<Instruction>(Op);
  233. return OpI && BlockInsts.contains(OpI);
  234. });
  235. }
  236. void BCECmpBlock::split(BasicBlock *NewParent, AliasAnalysis &AA) const {
  237. llvm::SmallVector<Instruction *, 4> OtherInsts;
  238. for (Instruction &Inst : *BB) {
  239. if (BlockInsts.count(&Inst))
  240. continue;
  241. assert(canSinkBCECmpInst(&Inst, AA) && "Split unsplittable block");
  242. // This is a non-BCE-cmp-block instruction. And it can be separated
  243. // from the BCE-cmp-block instruction.
  244. OtherInsts.push_back(&Inst);
  245. }
  246. // Do the actual spliting.
  247. for (Instruction *Inst : reverse(OtherInsts)) {
  248. Inst->moveBefore(&*NewParent->begin());
  249. }
  250. }
  251. bool BCECmpBlock::canSplit(AliasAnalysis &AA) const {
  252. for (Instruction &Inst : *BB) {
  253. if (!BlockInsts.count(&Inst)) {
  254. if (!canSinkBCECmpInst(&Inst, AA))
  255. return false;
  256. }
  257. }
  258. return true;
  259. }
  260. bool BCECmpBlock::doesOtherWork() const {
  261. // TODO(courbet): Can we allow some other things ? This is very conservative.
  262. // We might be able to get away with anything does not have any side
  263. // effects outside of the basic block.
  264. // Note: The GEPs and/or loads are not necessarily in the same block.
  265. for (const Instruction &Inst : *BB) {
  266. if (!BlockInsts.count(&Inst))
  267. return true;
  268. }
  269. return false;
  270. }
  271. // Visit the given comparison. If this is a comparison between two valid
  272. // BCE atoms, returns the comparison.
  273. Optional<BCECmp> visitICmp(const ICmpInst *const CmpI,
  274. const ICmpInst::Predicate ExpectedPredicate,
  275. BaseIdentifier &BaseId) {
  276. // The comparison can only be used once:
  277. // - For intermediate blocks, as a branch condition.
  278. // - For the final block, as an incoming value for the Phi.
  279. // If there are any other uses of the comparison, we cannot merge it with
  280. // other comparisons as we would create an orphan use of the value.
  281. if (!CmpI->hasOneUse()) {
  282. LLVM_DEBUG(dbgs() << "cmp has several uses\n");
  283. return None;
  284. }
  285. if (CmpI->getPredicate() != ExpectedPredicate)
  286. return None;
  287. LLVM_DEBUG(dbgs() << "cmp "
  288. << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
  289. << "\n");
  290. auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0), BaseId);
  291. if (!Lhs.BaseId)
  292. return None;
  293. auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1), BaseId);
  294. if (!Rhs.BaseId)
  295. return None;
  296. const auto &DL = CmpI->getModule()->getDataLayout();
  297. return BCECmp(std::move(Lhs), std::move(Rhs),
  298. DL.getTypeSizeInBits(CmpI->getOperand(0)->getType()), CmpI);
  299. }
  300. // Visit the given comparison block. If this is a comparison between two valid
  301. // BCE atoms, returns the comparison.
  302. Optional<BCECmpBlock> visitCmpBlock(Value *const Val, BasicBlock *const Block,
  303. const BasicBlock *const PhiBlock,
  304. BaseIdentifier &BaseId) {
  305. if (Block->empty()) return None;
  306. auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
  307. if (!BranchI) return None;
  308. LLVM_DEBUG(dbgs() << "branch\n");
  309. Value *Cond;
  310. ICmpInst::Predicate ExpectedPredicate;
  311. if (BranchI->isUnconditional()) {
  312. // In this case, we expect an incoming value which is the result of the
  313. // comparison. This is the last link in the chain of comparisons (note
  314. // that this does not mean that this is the last incoming value, blocks
  315. // can be reordered).
  316. Cond = Val;
  317. ExpectedPredicate = ICmpInst::ICMP_EQ;
  318. } else {
  319. // In this case, we expect a constant incoming value (the comparison is
  320. // chained).
  321. const auto *const Const = cast<ConstantInt>(Val);
  322. LLVM_DEBUG(dbgs() << "const\n");
  323. if (!Const->isZero()) return None;
  324. LLVM_DEBUG(dbgs() << "false\n");
  325. assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
  326. BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
  327. Cond = BranchI->getCondition();
  328. ExpectedPredicate =
  329. FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
  330. }
  331. auto *CmpI = dyn_cast<ICmpInst>(Cond);
  332. if (!CmpI) return None;
  333. LLVM_DEBUG(dbgs() << "icmp\n");
  334. Optional<BCECmp> Result = visitICmp(CmpI, ExpectedPredicate, BaseId);
  335. if (!Result)
  336. return None;
  337. BCECmpBlock::InstructionSet BlockInsts(
  338. {Result->Lhs.GEP, Result->Rhs.GEP, Result->Lhs.LoadI, Result->Rhs.LoadI,
  339. Result->CmpI, BranchI});
  340. return BCECmpBlock(std::move(*Result), Block, BlockInsts);
  341. }
  342. static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
  343. BCECmpBlock &&Comparison) {
  344. LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName()
  345. << "': Found cmp of " << Comparison.SizeBits()
  346. << " bits between " << Comparison.Lhs().BaseId << " + "
  347. << Comparison.Lhs().Offset << " and "
  348. << Comparison.Rhs().BaseId << " + "
  349. << Comparison.Rhs().Offset << "\n");
  350. LLVM_DEBUG(dbgs() << "\n");
  351. Comparison.OrigOrder = Comparisons.size();
  352. Comparisons.push_back(std::move(Comparison));
  353. }
  354. // A chain of comparisons.
  355. class BCECmpChain {
  356. public:
  357. using ContiguousBlocks = std::vector<BCECmpBlock>;
  358. BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
  359. AliasAnalysis &AA);
  360. bool simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
  361. DomTreeUpdater &DTU);
  362. bool atLeastOneMerged() const {
  363. return any_of(MergedBlocks_,
  364. [](const auto &Blocks) { return Blocks.size() > 1; });
  365. }
  366. private:
  367. PHINode &Phi_;
  368. // The list of all blocks in the chain, grouped by contiguity.
  369. std::vector<ContiguousBlocks> MergedBlocks_;
  370. // The original entry block (before sorting);
  371. BasicBlock *EntryBlock_;
  372. };
  373. static bool areContiguous(const BCECmpBlock &First, const BCECmpBlock &Second) {
  374. return First.Lhs().BaseId == Second.Lhs().BaseId &&
  375. First.Rhs().BaseId == Second.Rhs().BaseId &&
  376. First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
  377. First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
  378. }
  379. static unsigned getMinOrigOrder(const BCECmpChain::ContiguousBlocks &Blocks) {
  380. unsigned MinOrigOrder = std::numeric_limits<unsigned>::max();
  381. for (const BCECmpBlock &Block : Blocks)
  382. MinOrigOrder = std::min(MinOrigOrder, Block.OrigOrder);
  383. return MinOrigOrder;
  384. }
  385. /// Given a chain of comparison blocks, groups the blocks into contiguous
  386. /// ranges that can be merged together into a single comparison.
  387. static std::vector<BCECmpChain::ContiguousBlocks>
  388. mergeBlocks(std::vector<BCECmpBlock> &&Blocks) {
  389. std::vector<BCECmpChain::ContiguousBlocks> MergedBlocks;
  390. // Sort to detect continuous offsets.
  391. llvm::sort(Blocks,
  392. [](const BCECmpBlock &LhsBlock, const BCECmpBlock &RhsBlock) {
  393. return std::tie(LhsBlock.Lhs(), LhsBlock.Rhs()) <
  394. std::tie(RhsBlock.Lhs(), RhsBlock.Rhs());
  395. });
  396. BCECmpChain::ContiguousBlocks *LastMergedBlock = nullptr;
  397. for (BCECmpBlock &Block : Blocks) {
  398. if (!LastMergedBlock || !areContiguous(LastMergedBlock->back(), Block)) {
  399. MergedBlocks.emplace_back();
  400. LastMergedBlock = &MergedBlocks.back();
  401. } else {
  402. LLVM_DEBUG(dbgs() << "Merging block " << Block.BB->getName() << " into "
  403. << LastMergedBlock->back().BB->getName() << "\n");
  404. }
  405. LastMergedBlock->push_back(std::move(Block));
  406. }
  407. // While we allow reordering for merging, do not reorder unmerged comparisons.
  408. // Doing so may introduce branch on poison.
  409. llvm::sort(MergedBlocks, [](const BCECmpChain::ContiguousBlocks &LhsBlocks,
  410. const BCECmpChain::ContiguousBlocks &RhsBlocks) {
  411. return getMinOrigOrder(LhsBlocks) < getMinOrigOrder(RhsBlocks);
  412. });
  413. return MergedBlocks;
  414. }
  415. BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
  416. AliasAnalysis &AA)
  417. : Phi_(Phi) {
  418. assert(!Blocks.empty() && "a chain should have at least one block");
  419. // Now look inside blocks to check for BCE comparisons.
  420. std::vector<BCECmpBlock> Comparisons;
  421. BaseIdentifier BaseId;
  422. for (BasicBlock *const Block : Blocks) {
  423. assert(Block && "invalid block");
  424. Optional<BCECmpBlock> Comparison = visitCmpBlock(
  425. Phi.getIncomingValueForBlock(Block), Block, Phi.getParent(), BaseId);
  426. if (!Comparison) {
  427. LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n");
  428. return;
  429. }
  430. if (Comparison->doesOtherWork()) {
  431. LLVM_DEBUG(dbgs() << "block '" << Comparison->BB->getName()
  432. << "' does extra work besides compare\n");
  433. if (Comparisons.empty()) {
  434. // This is the initial block in the chain, in case this block does other
  435. // work, we can try to split the block and move the irrelevant
  436. // instructions to the predecessor.
  437. //
  438. // If this is not the initial block in the chain, splitting it wont
  439. // work.
  440. //
  441. // As once split, there will still be instructions before the BCE cmp
  442. // instructions that do other work in program order, i.e. within the
  443. // chain before sorting. Unless we can abort the chain at this point
  444. // and start anew.
  445. //
  446. // NOTE: we only handle blocks a with single predecessor for now.
  447. if (Comparison->canSplit(AA)) {
  448. LLVM_DEBUG(dbgs()
  449. << "Split initial block '" << Comparison->BB->getName()
  450. << "' that does extra work besides compare\n");
  451. Comparison->RequireSplit = true;
  452. enqueueBlock(Comparisons, std::move(*Comparison));
  453. } else {
  454. LLVM_DEBUG(dbgs()
  455. << "ignoring initial block '" << Comparison->BB->getName()
  456. << "' that does extra work besides compare\n");
  457. }
  458. continue;
  459. }
  460. // TODO(courbet): Right now we abort the whole chain. We could be
  461. // merging only the blocks that don't do other work and resume the
  462. // chain from there. For example:
  463. // if (a[0] == b[0]) { // bb1
  464. // if (a[1] == b[1]) { // bb2
  465. // some_value = 3; //bb3
  466. // if (a[2] == b[2]) { //bb3
  467. // do a ton of stuff //bb4
  468. // }
  469. // }
  470. // }
  471. //
  472. // This is:
  473. //
  474. // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
  475. // \ \ \ \
  476. // ne ne ne \
  477. // \ \ \ v
  478. // +------------+-----------+----------> bb_phi
  479. //
  480. // We can only merge the first two comparisons, because bb3* does
  481. // "other work" (setting some_value to 3).
  482. // We could still merge bb1 and bb2 though.
  483. return;
  484. }
  485. enqueueBlock(Comparisons, std::move(*Comparison));
  486. }
  487. // It is possible we have no suitable comparison to merge.
  488. if (Comparisons.empty()) {
  489. LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
  490. return;
  491. }
  492. EntryBlock_ = Comparisons[0].BB;
  493. MergedBlocks_ = mergeBlocks(std::move(Comparisons));
  494. }
  495. namespace {
  496. // A class to compute the name of a set of merged basic blocks.
  497. // This is optimized for the common case of no block names.
  498. class MergedBlockName {
  499. // Storage for the uncommon case of several named blocks.
  500. SmallString<16> Scratch;
  501. public:
  502. explicit MergedBlockName(ArrayRef<BCECmpBlock> Comparisons)
  503. : Name(makeName(Comparisons)) {}
  504. const StringRef Name;
  505. private:
  506. StringRef makeName(ArrayRef<BCECmpBlock> Comparisons) {
  507. assert(!Comparisons.empty() && "no basic block");
  508. // Fast path: only one block, or no names at all.
  509. if (Comparisons.size() == 1)
  510. return Comparisons[0].BB->getName();
  511. const int size = std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
  512. [](int i, const BCECmpBlock &Cmp) {
  513. return i + Cmp.BB->getName().size();
  514. });
  515. if (size == 0)
  516. return StringRef("", 0);
  517. // Slow path: at least two blocks, at least one block with a name.
  518. Scratch.clear();
  519. // We'll have `size` bytes for name and `Comparisons.size() - 1` bytes for
  520. // separators.
  521. Scratch.reserve(size + Comparisons.size() - 1);
  522. const auto append = [this](StringRef str) {
  523. Scratch.append(str.begin(), str.end());
  524. };
  525. append(Comparisons[0].BB->getName());
  526. for (int I = 1, E = Comparisons.size(); I < E; ++I) {
  527. const BasicBlock *const BB = Comparisons[I].BB;
  528. if (!BB->getName().empty()) {
  529. append("+");
  530. append(BB->getName());
  531. }
  532. }
  533. return Scratch.str();
  534. }
  535. };
  536. } // namespace
  537. // Merges the given contiguous comparison blocks into one memcmp block.
  538. static BasicBlock *mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
  539. BasicBlock *const InsertBefore,
  540. BasicBlock *const NextCmpBlock,
  541. PHINode &Phi, const TargetLibraryInfo &TLI,
  542. AliasAnalysis &AA, DomTreeUpdater &DTU) {
  543. assert(!Comparisons.empty() && "merging zero comparisons");
  544. LLVMContext &Context = NextCmpBlock->getContext();
  545. const BCECmpBlock &FirstCmp = Comparisons[0];
  546. // Create a new cmp block before next cmp block.
  547. BasicBlock *const BB =
  548. BasicBlock::Create(Context, MergedBlockName(Comparisons).Name,
  549. NextCmpBlock->getParent(), InsertBefore);
  550. IRBuilder<> Builder(BB);
  551. // Add the GEPs from the first BCECmpBlock.
  552. Value *const Lhs = Builder.Insert(FirstCmp.Lhs().GEP->clone());
  553. Value *const Rhs = Builder.Insert(FirstCmp.Rhs().GEP->clone());
  554. Value *IsEqual = nullptr;
  555. LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons -> "
  556. << BB->getName() << "\n");
  557. // If there is one block that requires splitting, we do it now, i.e.
  558. // just before we know we will collapse the chain. The instructions
  559. // can be executed before any of the instructions in the chain.
  560. const auto ToSplit = llvm::find_if(
  561. Comparisons, [](const BCECmpBlock &B) { return B.RequireSplit; });
  562. if (ToSplit != Comparisons.end()) {
  563. LLVM_DEBUG(dbgs() << "Splitting non_BCE work to header\n");
  564. ToSplit->split(BB, AA);
  565. }
  566. if (Comparisons.size() == 1) {
  567. LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n");
  568. Value *const LhsLoad =
  569. Builder.CreateLoad(FirstCmp.Lhs().LoadI->getType(), Lhs);
  570. Value *const RhsLoad =
  571. Builder.CreateLoad(FirstCmp.Rhs().LoadI->getType(), Rhs);
  572. // There are no blocks to merge, just do the comparison.
  573. IsEqual = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
  574. } else {
  575. const unsigned TotalSizeBits = std::accumulate(
  576. Comparisons.begin(), Comparisons.end(), 0u,
  577. [](int Size, const BCECmpBlock &C) { return Size + C.SizeBits(); });
  578. // Create memcmp() == 0.
  579. const auto &DL = Phi.getModule()->getDataLayout();
  580. Value *const MemCmpCall = emitMemCmp(
  581. Lhs, Rhs,
  582. ConstantInt::get(DL.getIntPtrType(Context), TotalSizeBits / 8), Builder,
  583. DL, &TLI);
  584. IsEqual = Builder.CreateICmpEQ(
  585. MemCmpCall, ConstantInt::get(Type::getInt32Ty(Context), 0));
  586. }
  587. BasicBlock *const PhiBB = Phi.getParent();
  588. // Add a branch to the next basic block in the chain.
  589. if (NextCmpBlock == PhiBB) {
  590. // Continue to phi, passing it the comparison result.
  591. Builder.CreateBr(PhiBB);
  592. Phi.addIncoming(IsEqual, BB);
  593. DTU.applyUpdates({{DominatorTree::Insert, BB, PhiBB}});
  594. } else {
  595. // Continue to next block if equal, exit to phi else.
  596. Builder.CreateCondBr(IsEqual, NextCmpBlock, PhiBB);
  597. Phi.addIncoming(ConstantInt::getFalse(Context), BB);
  598. DTU.applyUpdates({{DominatorTree::Insert, BB, NextCmpBlock},
  599. {DominatorTree::Insert, BB, PhiBB}});
  600. }
  601. return BB;
  602. }
  603. bool BCECmpChain::simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
  604. DomTreeUpdater &DTU) {
  605. assert(atLeastOneMerged() && "simplifying trivial BCECmpChain");
  606. LLVM_DEBUG(dbgs() << "Simplifying comparison chain starting at block "
  607. << EntryBlock_->getName() << "\n");
  608. // Effectively merge blocks. We go in the reverse direction from the phi block
  609. // so that the next block is always available to branch to.
  610. BasicBlock *InsertBefore = EntryBlock_;
  611. BasicBlock *NextCmpBlock = Phi_.getParent();
  612. for (const auto &Blocks : reverse(MergedBlocks_)) {
  613. InsertBefore = NextCmpBlock = mergeComparisons(
  614. Blocks, InsertBefore, NextCmpBlock, Phi_, TLI, AA, DTU);
  615. }
  616. // Replace the original cmp chain with the new cmp chain by pointing all
  617. // predecessors of EntryBlock_ to NextCmpBlock instead. This makes all cmp
  618. // blocks in the old chain unreachable.
  619. while (!pred_empty(EntryBlock_)) {
  620. BasicBlock* const Pred = *pred_begin(EntryBlock_);
  621. LLVM_DEBUG(dbgs() << "Updating jump into old chain from " << Pred->getName()
  622. << "\n");
  623. Pred->getTerminator()->replaceUsesOfWith(EntryBlock_, NextCmpBlock);
  624. DTU.applyUpdates({{DominatorTree::Delete, Pred, EntryBlock_},
  625. {DominatorTree::Insert, Pred, NextCmpBlock}});
  626. }
  627. // If the old cmp chain was the function entry, we need to update the function
  628. // entry.
  629. const bool ChainEntryIsFnEntry = EntryBlock_->isEntryBlock();
  630. if (ChainEntryIsFnEntry && DTU.hasDomTree()) {
  631. LLVM_DEBUG(dbgs() << "Changing function entry from "
  632. << EntryBlock_->getName() << " to "
  633. << NextCmpBlock->getName() << "\n");
  634. DTU.getDomTree().setNewRoot(NextCmpBlock);
  635. DTU.applyUpdates({{DominatorTree::Delete, NextCmpBlock, EntryBlock_}});
  636. }
  637. EntryBlock_ = nullptr;
  638. // Delete merged blocks. This also removes incoming values in phi.
  639. SmallVector<BasicBlock *, 16> DeadBlocks;
  640. for (const auto &Blocks : MergedBlocks_) {
  641. for (const BCECmpBlock &Block : Blocks) {
  642. LLVM_DEBUG(dbgs() << "Deleting merged block " << Block.BB->getName()
  643. << "\n");
  644. DeadBlocks.push_back(Block.BB);
  645. }
  646. }
  647. DeleteDeadBlocks(DeadBlocks, &DTU);
  648. MergedBlocks_.clear();
  649. return true;
  650. }
  651. std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
  652. BasicBlock *const LastBlock,
  653. int NumBlocks) {
  654. // Walk up from the last block to find other blocks.
  655. std::vector<BasicBlock *> Blocks(NumBlocks);
  656. assert(LastBlock && "invalid last block");
  657. BasicBlock *CurBlock = LastBlock;
  658. for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
  659. if (CurBlock->hasAddressTaken()) {
  660. // Somebody is jumping to the block through an address, all bets are
  661. // off.
  662. LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
  663. << " has its address taken\n");
  664. return {};
  665. }
  666. Blocks[BlockIndex] = CurBlock;
  667. auto *SinglePredecessor = CurBlock->getSinglePredecessor();
  668. if (!SinglePredecessor) {
  669. // The block has two or more predecessors.
  670. LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
  671. << " has two or more predecessors\n");
  672. return {};
  673. }
  674. if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
  675. // The block does not link back to the phi.
  676. LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
  677. << " does not link back to the phi\n");
  678. return {};
  679. }
  680. CurBlock = SinglePredecessor;
  681. }
  682. Blocks[0] = CurBlock;
  683. return Blocks;
  684. }
  685. bool processPhi(PHINode &Phi, const TargetLibraryInfo &TLI, AliasAnalysis &AA,
  686. DomTreeUpdater &DTU) {
  687. LLVM_DEBUG(dbgs() << "processPhi()\n");
  688. if (Phi.getNumIncomingValues() <= 1) {
  689. LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n");
  690. return false;
  691. }
  692. // We are looking for something that has the following structure:
  693. // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
  694. // \ \ \ \
  695. // ne ne ne \
  696. // \ \ \ v
  697. // +------------+-----------+----------> bb_phi
  698. //
  699. // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
  700. // It's the only block that contributes a non-constant value to the Phi.
  701. // - All other blocks (b1, b2, b3) must have exactly two successors, one of
  702. // them being the phi block.
  703. // - All intermediate blocks (bb2, bb3) must have only one predecessor.
  704. // - Blocks cannot do other work besides the comparison, see doesOtherWork()
  705. // The blocks are not necessarily ordered in the phi, so we start from the
  706. // last block and reconstruct the order.
  707. BasicBlock *LastBlock = nullptr;
  708. for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
  709. if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
  710. if (LastBlock) {
  711. // There are several non-constant values.
  712. LLVM_DEBUG(dbgs() << "skip: several non-constant values\n");
  713. return false;
  714. }
  715. if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
  716. cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
  717. Phi.getIncomingBlock(I)) {
  718. // Non-constant incoming value is not from a cmp instruction or not
  719. // produced by the last block. We could end up processing the value
  720. // producing block more than once.
  721. //
  722. // This is an uncommon case, so we bail.
  723. LLVM_DEBUG(
  724. dbgs()
  725. << "skip: non-constant value not from cmp or not from last block.\n");
  726. return false;
  727. }
  728. LastBlock = Phi.getIncomingBlock(I);
  729. }
  730. if (!LastBlock) {
  731. // There is no non-constant block.
  732. LLVM_DEBUG(dbgs() << "skip: no non-constant block\n");
  733. return false;
  734. }
  735. if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
  736. LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n");
  737. return false;
  738. }
  739. const auto Blocks =
  740. getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
  741. if (Blocks.empty()) return false;
  742. BCECmpChain CmpChain(Blocks, Phi, AA);
  743. if (!CmpChain.atLeastOneMerged()) {
  744. LLVM_DEBUG(dbgs() << "skip: nothing merged\n");
  745. return false;
  746. }
  747. return CmpChain.simplify(TLI, AA, DTU);
  748. }
  749. static bool runImpl(Function &F, const TargetLibraryInfo &TLI,
  750. const TargetTransformInfo &TTI, AliasAnalysis &AA,
  751. DominatorTree *DT) {
  752. LLVM_DEBUG(dbgs() << "MergeICmpsLegacyPass: " << F.getName() << "\n");
  753. // We only try merging comparisons if the target wants to expand memcmp later.
  754. // The rationale is to avoid turning small chains into memcmp calls.
  755. if (!TTI.enableMemCmpExpansion(F.hasOptSize(), true))
  756. return false;
  757. // If we don't have memcmp avaiable we can't emit calls to it.
  758. if (!TLI.has(LibFunc_memcmp))
  759. return false;
  760. DomTreeUpdater DTU(DT, /*PostDominatorTree*/ nullptr,
  761. DomTreeUpdater::UpdateStrategy::Eager);
  762. bool MadeChange = false;
  763. for (BasicBlock &BB : llvm::drop_begin(F)) {
  764. // A Phi operation is always first in a basic block.
  765. if (auto *const Phi = dyn_cast<PHINode>(&*BB.begin()))
  766. MadeChange |= processPhi(*Phi, TLI, AA, DTU);
  767. }
  768. return MadeChange;
  769. }
  770. class MergeICmpsLegacyPass : public FunctionPass {
  771. public:
  772. static char ID;
  773. MergeICmpsLegacyPass() : FunctionPass(ID) {
  774. initializeMergeICmpsLegacyPassPass(*PassRegistry::getPassRegistry());
  775. }
  776. bool runOnFunction(Function &F) override {
  777. if (skipFunction(F)) return false;
  778. const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  779. const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  780. // MergeICmps does not need the DominatorTree, but we update it if it's
  781. // already available.
  782. auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  783. auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
  784. return runImpl(F, TLI, TTI, AA, DTWP ? &DTWP->getDomTree() : nullptr);
  785. }
  786. private:
  787. void getAnalysisUsage(AnalysisUsage &AU) const override {
  788. AU.addRequired<TargetLibraryInfoWrapperPass>();
  789. AU.addRequired<TargetTransformInfoWrapperPass>();
  790. AU.addRequired<AAResultsWrapperPass>();
  791. AU.addPreserved<GlobalsAAWrapperPass>();
  792. AU.addPreserved<DominatorTreeWrapperPass>();
  793. }
  794. };
  795. } // namespace
  796. char MergeICmpsLegacyPass::ID = 0;
  797. INITIALIZE_PASS_BEGIN(MergeICmpsLegacyPass, "mergeicmps",
  798. "Merge contiguous icmps into a memcmp", false, false)
  799. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  800. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  801. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  802. INITIALIZE_PASS_END(MergeICmpsLegacyPass, "mergeicmps",
  803. "Merge contiguous icmps into a memcmp", false, false)
  804. Pass *llvm::createMergeICmpsLegacyPass() { return new MergeICmpsLegacyPass(); }
  805. PreservedAnalyses MergeICmpsPass::run(Function &F,
  806. FunctionAnalysisManager &AM) {
  807. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  808. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  809. auto &AA = AM.getResult<AAManager>(F);
  810. auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
  811. const bool MadeChanges = runImpl(F, TLI, TTI, AA, DT);
  812. if (!MadeChanges)
  813. return PreservedAnalyses::all();
  814. PreservedAnalyses PA;
  815. PA.preserve<DominatorTreeAnalysis>();
  816. return PA;
  817. }