LLVM 17.0.0git
MergeICmps.cpp
Go to the documentation of this file.
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
47#include "llvm/Analysis/Loads.h"
50#include "llvm/IR/Dominators.h"
51#include "llvm/IR/Function.h"
52#include "llvm/IR/IRBuilder.h"
54#include "llvm/Pass.h"
58#include <algorithm>
59#include <numeric>
60#include <utility>
61#include <vector>
62
63using namespace llvm;
64
65namespace {
66
67#define DEBUG_TYPE "mergeicmps"
68
69// A BCE atom "Binary Compare Expression Atom" represents an integer load
70// that is a constant offset from a base value, e.g. `a` or `o.c` in the example
71// at the top.
72struct BCEAtom {
73 BCEAtom() = default;
74 BCEAtom(GetElementPtrInst *GEP, LoadInst *LoadI, int BaseId, APInt Offset)
75 : GEP(GEP), LoadI(LoadI), BaseId(BaseId), Offset(Offset) {}
76
77 BCEAtom(const BCEAtom &) = delete;
78 BCEAtom &operator=(const BCEAtom &) = delete;
79
80 BCEAtom(BCEAtom &&that) = default;
81 BCEAtom &operator=(BCEAtom &&that) {
82 if (this == &that)
83 return *this;
84 GEP = that.GEP;
85 LoadI = that.LoadI;
86 BaseId = that.BaseId;
87 Offset = std::move(that.Offset);
88 return *this;
89 }
90
91 // We want to order BCEAtoms by (Base, Offset). However we cannot use
92 // the pointer values for Base because these are non-deterministic.
93 // To make sure that the sort order is stable, we first assign to each atom
94 // base value an index based on its order of appearance in the chain of
95 // comparisons. We call this index `BaseOrdering`. For example, for:
96 // b[3] == c[2] && a[1] == d[1] && b[4] == c[3]
97 // | block 1 | | block 2 | | block 3 |
98 // b gets assigned index 0 and a index 1, because b appears as LHS in block 1,
99 // which is before block 2.
100 // We then sort by (BaseOrdering[LHS.Base()], LHS.Offset), which is stable.
101 bool operator<(const BCEAtom &O) const {
102 return BaseId != O.BaseId ? BaseId < O.BaseId : Offset.slt(O.Offset);
103 }
104
105 GetElementPtrInst *GEP = nullptr;
106 LoadInst *LoadI = nullptr;
107 unsigned BaseId = 0;
108 APInt Offset;
109};
110
111// A class that assigns increasing ids to values in the order in which they are
112// seen. See comment in `BCEAtom::operator<()``.
113class BaseIdentifier {
114public:
115 // Returns the id for value `Base`, after assigning one if `Base` has not been
116 // seen before.
117 int getBaseId(const Value *Base) {
118 assert(Base && "invalid base");
119 const auto Insertion = BaseToIndex.try_emplace(Base, Order);
120 if (Insertion.second)
121 ++Order;
122 return Insertion.first->second;
123 }
124
125private:
126 unsigned Order = 1;
127 DenseMap<const Value*, int> BaseToIndex;
128};
129
130// If this value is a load from a constant offset w.r.t. a base address, and
131// there are no other users of the load or address, returns the base address and
132// the offset.
133BCEAtom visitICmpLoadOperand(Value *const Val, BaseIdentifier &BaseId) {
134 auto *const LoadI = dyn_cast<LoadInst>(Val);
135 if (!LoadI)
136 return {};
137 LLVM_DEBUG(dbgs() << "load\n");
138 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
139 LLVM_DEBUG(dbgs() << "used outside of block\n");
140 return {};
141 }
142 // Do not optimize atomic loads to non-atomic memcmp
143 if (!LoadI->isSimple()) {
144 LLVM_DEBUG(dbgs() << "volatile or atomic\n");
145 return {};
146 }
147 Value *Addr = LoadI->getOperand(0);
148 if (Addr->getType()->getPointerAddressSpace() != 0) {
149 LLVM_DEBUG(dbgs() << "from non-zero AddressSpace\n");
150 return {};
151 }
152 const auto &DL = LoadI->getModule()->getDataLayout();
153 if (!isDereferenceablePointer(Addr, LoadI->getType(), DL)) {
154 LLVM_DEBUG(dbgs() << "not dereferenceable\n");
155 // We need to make sure that we can do comparison in any order, so we
156 // require memory to be unconditionally dereferenceable.
157 return {};
158 }
159
160 APInt Offset = APInt(DL.getPointerTypeSizeInBits(Addr->getType()), 0);
161 Value *Base = Addr;
162 auto *GEP = dyn_cast<GetElementPtrInst>(Addr);
163 if (GEP) {
164 LLVM_DEBUG(dbgs() << "GEP\n");
165 if (GEP->isUsedOutsideOfBlock(LoadI->getParent())) {
166 LLVM_DEBUG(dbgs() << "used outside of block\n");
167 return {};
168 }
169 if (!GEP->accumulateConstantOffset(DL, Offset))
170 return {};
171 Base = GEP->getPointerOperand();
172 }
173 return BCEAtom(GEP, LoadI, BaseId.getBaseId(Base), Offset);
174}
175
176// A comparison between two BCE atoms, e.g. `a == o.a` in the example at the
177// top.
178// Note: the terminology is misleading: the comparison is symmetric, so there
179// is no real {l/r}hs. What we want though is to have the same base on the
180// left (resp. right), so that we can detect consecutive loads. To ensure this
181// we put the smallest atom on the left.
182struct BCECmp {
183 BCEAtom Lhs;
184 BCEAtom Rhs;
185 int SizeBits;
186 const ICmpInst *CmpI;
187
188 BCECmp(BCEAtom L, BCEAtom R, int SizeBits, const ICmpInst *CmpI)
189 : Lhs(std::move(L)), Rhs(std::move(R)), SizeBits(SizeBits), CmpI(CmpI) {
190 if (Rhs < Lhs) std::swap(Rhs, Lhs);
191 }
192};
193
194// A basic block with a comparison between two BCE atoms.
195// The block might do extra work besides the atom comparison, in which case
196// doesOtherWork() returns true. Under some conditions, the block can be
197// split into the atom comparison part and the "other work" part
198// (see canSplit()).
199class BCECmpBlock {
200 public:
201 typedef SmallDenseSet<const Instruction *, 8> InstructionSet;
202
203 BCECmpBlock(BCECmp Cmp, BasicBlock *BB, InstructionSet BlockInsts)
204 : BB(BB), BlockInsts(std::move(BlockInsts)), Cmp(std::move(Cmp)) {}
205
206 const BCEAtom &Lhs() const { return Cmp.Lhs; }
207 const BCEAtom &Rhs() const { return Cmp.Rhs; }
208 int SizeBits() const { return Cmp.SizeBits; }
209
210 // Returns true if the block does other works besides comparison.
211 bool doesOtherWork() const;
212
213 // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp
214 // instructions in the block.
215 bool canSplit(AliasAnalysis &AA) const;
216
217 // Return true if this all the relevant instructions in the BCE-cmp-block can
218 // be sunk below this instruction. By doing this, we know we can separate the
219 // BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the
220 // block.
221 bool canSinkBCECmpInst(const Instruction *, AliasAnalysis &AA) const;
222
223 // We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block
224 // instructions. Split the old block and move all non-BCE-cmp-insts into the
225 // new parent block.
226 void split(BasicBlock *NewParent, AliasAnalysis &AA) const;
227
228 // The basic block where this comparison happens.
229 BasicBlock *BB;
230 // Instructions relating to the BCECmp and branch.
231 InstructionSet BlockInsts;
232 // The block requires splitting.
233 bool RequireSplit = false;
234 // Original order of this block in the chain.
235 unsigned OrigOrder = 0;
236
237private:
238 BCECmp Cmp;
239};
240
241bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst,
242 AliasAnalysis &AA) const {
243 // If this instruction may clobber the loads and is in middle of the BCE cmp
244 // block instructions, then bail for now.
245 if (Inst->mayWriteToMemory()) {
246 auto MayClobber = [&](LoadInst *LI) {
247 // If a potentially clobbering instruction comes before the load,
248 // we can still safely sink the load.
249 return (Inst->getParent() != LI->getParent() || !Inst->comesBefore(LI)) &&
251 };
252 if (MayClobber(Cmp.Lhs.LoadI) || MayClobber(Cmp.Rhs.LoadI))
253 return false;
254 }
255 // Make sure this instruction does not use any of the BCE cmp block
256 // instructions as operand.
257 return llvm::none_of(Inst->operands(), [&](const Value *Op) {
258 const Instruction *OpI = dyn_cast<Instruction>(Op);
259 return OpI && BlockInsts.contains(OpI);
260 });
261}
262
263void BCECmpBlock::split(BasicBlock *NewParent, AliasAnalysis &AA) const {
265 for (Instruction &Inst : *BB) {
266 if (BlockInsts.count(&Inst))
267 continue;
268 assert(canSinkBCECmpInst(&Inst, AA) && "Split unsplittable block");
269 // This is a non-BCE-cmp-block instruction. And it can be separated
270 // from the BCE-cmp-block instruction.
271 OtherInsts.push_back(&Inst);
272 }
273
274 // Do the actual spliting.
275 for (Instruction *Inst : reverse(OtherInsts))
276 Inst->moveBefore(*NewParent, NewParent->begin());
277}
278
279bool BCECmpBlock::canSplit(AliasAnalysis &AA) const {
280 for (Instruction &Inst : *BB) {
281 if (!BlockInsts.count(&Inst)) {
282 if (!canSinkBCECmpInst(&Inst, AA))
283 return false;
284 }
285 }
286 return true;
287}
288
289bool BCECmpBlock::doesOtherWork() const {
290 // TODO(courbet): Can we allow some other things ? This is very conservative.
291 // We might be able to get away with anything does not have any side
292 // effects outside of the basic block.
293 // Note: The GEPs and/or loads are not necessarily in the same block.
294 for (const Instruction &Inst : *BB) {
295 if (!BlockInsts.count(&Inst))
296 return true;
297 }
298 return false;
299}
300
301// Visit the given comparison. If this is a comparison between two valid
302// BCE atoms, returns the comparison.
303std::optional<BCECmp> visitICmp(const ICmpInst *const CmpI,
304 const ICmpInst::Predicate ExpectedPredicate,
305 BaseIdentifier &BaseId) {
306 // The comparison can only be used once:
307 // - For intermediate blocks, as a branch condition.
308 // - For the final block, as an incoming value for the Phi.
309 // If there are any other uses of the comparison, we cannot merge it with
310 // other comparisons as we would create an orphan use of the value.
311 if (!CmpI->hasOneUse()) {
312 LLVM_DEBUG(dbgs() << "cmp has several uses\n");
313 return std::nullopt;
314 }
315 if (CmpI->getPredicate() != ExpectedPredicate)
316 return std::nullopt;
317 LLVM_DEBUG(dbgs() << "cmp "
318 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
319 << "\n");
320 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0), BaseId);
321 if (!Lhs.BaseId)
322 return std::nullopt;
323 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1), BaseId);
324 if (!Rhs.BaseId)
325 return std::nullopt;
326 const auto &DL = CmpI->getModule()->getDataLayout();
327 return BCECmp(std::move(Lhs), std::move(Rhs),
328 DL.getTypeSizeInBits(CmpI->getOperand(0)->getType()), CmpI);
329}
330
331// Visit the given comparison block. If this is a comparison between two valid
332// BCE atoms, returns the comparison.
333std::optional<BCECmpBlock> visitCmpBlock(Value *const Val,
334 BasicBlock *const Block,
335 const BasicBlock *const PhiBlock,
336 BaseIdentifier &BaseId) {
337 if (Block->empty())
338 return std::nullopt;
339 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
340 if (!BranchI)
341 return std::nullopt;
342 LLVM_DEBUG(dbgs() << "branch\n");
343 Value *Cond;
344 ICmpInst::Predicate ExpectedPredicate;
345 if (BranchI->isUnconditional()) {
346 // In this case, we expect an incoming value which is the result of the
347 // comparison. This is the last link in the chain of comparisons (note
348 // that this does not mean that this is the last incoming value, blocks
349 // can be reordered).
350 Cond = Val;
351 ExpectedPredicate = ICmpInst::ICMP_EQ;
352 } else {
353 // In this case, we expect a constant incoming value (the comparison is
354 // chained).
355 const auto *const Const = cast<ConstantInt>(Val);
356 LLVM_DEBUG(dbgs() << "const\n");
357 if (!Const->isZero())
358 return std::nullopt;
359 LLVM_DEBUG(dbgs() << "false\n");
360 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
361 BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
362 Cond = BranchI->getCondition();
363 ExpectedPredicate =
364 FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
365 }
366
367 auto *CmpI = dyn_cast<ICmpInst>(Cond);
368 if (!CmpI)
369 return std::nullopt;
370 LLVM_DEBUG(dbgs() << "icmp\n");
371
372 std::optional<BCECmp> Result = visitICmp(CmpI, ExpectedPredicate, BaseId);
373 if (!Result)
374 return std::nullopt;
375
377 {Result->Lhs.LoadI, Result->Rhs.LoadI, Result->CmpI, BranchI});
378 if (Result->Lhs.GEP)
379 BlockInsts.insert(Result->Lhs.GEP);
380 if (Result->Rhs.GEP)
381 BlockInsts.insert(Result->Rhs.GEP);
382 return BCECmpBlock(std::move(*Result), Block, BlockInsts);
383}
384
385static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
386 BCECmpBlock &&Comparison) {
387 LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName()
388 << "': Found cmp of " << Comparison.SizeBits()
389 << " bits between " << Comparison.Lhs().BaseId << " + "
390 << Comparison.Lhs().Offset << " and "
391 << Comparison.Rhs().BaseId << " + "
392 << Comparison.Rhs().Offset << "\n");
393 LLVM_DEBUG(dbgs() << "\n");
394 Comparison.OrigOrder = Comparisons.size();
395 Comparisons.push_back(std::move(Comparison));
396}
397
398// A chain of comparisons.
399class BCECmpChain {
400public:
401 using ContiguousBlocks = std::vector<BCECmpBlock>;
402
403 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
404 AliasAnalysis &AA);
405
406 bool simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
407 DomTreeUpdater &DTU);
408
409 bool atLeastOneMerged() const {
410 return any_of(MergedBlocks_,
411 [](const auto &Blocks) { return Blocks.size() > 1; });
412 }
413
414private:
415 PHINode &Phi_;
416 // The list of all blocks in the chain, grouped by contiguity.
417 std::vector<ContiguousBlocks> MergedBlocks_;
418 // The original entry block (before sorting);
419 BasicBlock *EntryBlock_;
420};
421
422static bool areContiguous(const BCECmpBlock &First, const BCECmpBlock &Second) {
423 return First.Lhs().BaseId == Second.Lhs().BaseId &&
424 First.Rhs().BaseId == Second.Rhs().BaseId &&
425 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
426 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
427}
428
429static unsigned getMinOrigOrder(const BCECmpChain::ContiguousBlocks &Blocks) {
430 unsigned MinOrigOrder = std::numeric_limits<unsigned>::max();
431 for (const BCECmpBlock &Block : Blocks)
432 MinOrigOrder = std::min(MinOrigOrder, Block.OrigOrder);
433 return MinOrigOrder;
434}
435
436/// Given a chain of comparison blocks, groups the blocks into contiguous
437/// ranges that can be merged together into a single comparison.
438static std::vector<BCECmpChain::ContiguousBlocks>
439mergeBlocks(std::vector<BCECmpBlock> &&Blocks) {
440 std::vector<BCECmpChain::ContiguousBlocks> MergedBlocks;
441
442 // Sort to detect continuous offsets.
443 llvm::sort(Blocks,
444 [](const BCECmpBlock &LhsBlock, const BCECmpBlock &RhsBlock) {
445 return std::tie(LhsBlock.Lhs(), LhsBlock.Rhs()) <
446 std::tie(RhsBlock.Lhs(), RhsBlock.Rhs());
447 });
448
449 BCECmpChain::ContiguousBlocks *LastMergedBlock = nullptr;
450 for (BCECmpBlock &Block : Blocks) {
451 if (!LastMergedBlock || !areContiguous(LastMergedBlock->back(), Block)) {
452 MergedBlocks.emplace_back();
453 LastMergedBlock = &MergedBlocks.back();
454 } else {
455 LLVM_DEBUG(dbgs() << "Merging block " << Block.BB->getName() << " into "
456 << LastMergedBlock->back().BB->getName() << "\n");
457 }
458 LastMergedBlock->push_back(std::move(Block));
459 }
460
461 // While we allow reordering for merging, do not reorder unmerged comparisons.
462 // Doing so may introduce branch on poison.
463 llvm::sort(MergedBlocks, [](const BCECmpChain::ContiguousBlocks &LhsBlocks,
464 const BCECmpChain::ContiguousBlocks &RhsBlocks) {
465 return getMinOrigOrder(LhsBlocks) < getMinOrigOrder(RhsBlocks);
466 });
467
468 return MergedBlocks;
469}
470
471BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
472 AliasAnalysis &AA)
473 : Phi_(Phi) {
474 assert(!Blocks.empty() && "a chain should have at least one block");
475 // Now look inside blocks to check for BCE comparisons.
476 std::vector<BCECmpBlock> Comparisons;
477 BaseIdentifier BaseId;
478 for (BasicBlock *const Block : Blocks) {
479 assert(Block && "invalid block");
480 std::optional<BCECmpBlock> Comparison = visitCmpBlock(
481 Phi.getIncomingValueForBlock(Block), Block, Phi.getParent(), BaseId);
482 if (!Comparison) {
483 LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n");
484 return;
485 }
486 if (Comparison->doesOtherWork()) {
487 LLVM_DEBUG(dbgs() << "block '" << Comparison->BB->getName()
488 << "' does extra work besides compare\n");
489 if (Comparisons.empty()) {
490 // This is the initial block in the chain, in case this block does other
491 // work, we can try to split the block and move the irrelevant
492 // instructions to the predecessor.
493 //
494 // If this is not the initial block in the chain, splitting it wont
495 // work.
496 //
497 // As once split, there will still be instructions before the BCE cmp
498 // instructions that do other work in program order, i.e. within the
499 // chain before sorting. Unless we can abort the chain at this point
500 // and start anew.
501 //
502 // NOTE: we only handle blocks a with single predecessor for now.
503 if (Comparison->canSplit(AA)) {
505 << "Split initial block '" << Comparison->BB->getName()
506 << "' that does extra work besides compare\n");
507 Comparison->RequireSplit = true;
508 enqueueBlock(Comparisons, std::move(*Comparison));
509 } else {
511 << "ignoring initial block '" << Comparison->BB->getName()
512 << "' that does extra work besides compare\n");
513 }
514 continue;
515 }
516 // TODO(courbet): Right now we abort the whole chain. We could be
517 // merging only the blocks that don't do other work and resume the
518 // chain from there. For example:
519 // if (a[0] == b[0]) { // bb1
520 // if (a[1] == b[1]) { // bb2
521 // some_value = 3; //bb3
522 // if (a[2] == b[2]) { //bb3
523 // do a ton of stuff //bb4
524 // }
525 // }
526 // }
527 //
528 // This is:
529 //
530 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
531 // \ \ \ \
532 // ne ne ne \
533 // \ \ \ v
534 // +------------+-----------+----------> bb_phi
535 //
536 // We can only merge the first two comparisons, because bb3* does
537 // "other work" (setting some_value to 3).
538 // We could still merge bb1 and bb2 though.
539 return;
540 }
541 enqueueBlock(Comparisons, std::move(*Comparison));
542 }
543
544 // It is possible we have no suitable comparison to merge.
545 if (Comparisons.empty()) {
546 LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
547 return;
548 }
549 EntryBlock_ = Comparisons[0].BB;
550 MergedBlocks_ = mergeBlocks(std::move(Comparisons));
551}
552
553namespace {
554
555// A class to compute the name of a set of merged basic blocks.
556// This is optimized for the common case of no block names.
557class MergedBlockName {
558 // Storage for the uncommon case of several named blocks.
559 SmallString<16> Scratch;
560
561public:
562 explicit MergedBlockName(ArrayRef<BCECmpBlock> Comparisons)
563 : Name(makeName(Comparisons)) {}
564 const StringRef Name;
565
566private:
567 StringRef makeName(ArrayRef<BCECmpBlock> Comparisons) {
568 assert(!Comparisons.empty() && "no basic block");
569 // Fast path: only one block, or no names at all.
570 if (Comparisons.size() == 1)
571 return Comparisons[0].BB->getName();
572 const int size = std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
573 [](int i, const BCECmpBlock &Cmp) {
574 return i + Cmp.BB->getName().size();
575 });
576 if (size == 0)
577 return StringRef("", 0);
578
579 // Slow path: at least two blocks, at least one block with a name.
580 Scratch.clear();
581 // We'll have `size` bytes for name and `Comparisons.size() - 1` bytes for
582 // separators.
583 Scratch.reserve(size + Comparisons.size() - 1);
584 const auto append = [this](StringRef str) {
585 Scratch.append(str.begin(), str.end());
586 };
587 append(Comparisons[0].BB->getName());
588 for (int I = 1, E = Comparisons.size(); I < E; ++I) {
589 const BasicBlock *const BB = Comparisons[I].BB;
590 if (!BB->getName().empty()) {
591 append("+");
592 append(BB->getName());
593 }
594 }
595 return Scratch.str();
596 }
597};
598} // namespace
599
600// Merges the given contiguous comparison blocks into one memcmp block.
601static BasicBlock *mergeComparisons(ArrayRef<BCECmpBlock> Comparisons,
602 BasicBlock *const InsertBefore,
603 BasicBlock *const NextCmpBlock,
604 PHINode &Phi, const TargetLibraryInfo &TLI,
605 AliasAnalysis &AA, DomTreeUpdater &DTU) {
606 assert(!Comparisons.empty() && "merging zero comparisons");
607 LLVMContext &Context = NextCmpBlock->getContext();
608 const BCECmpBlock &FirstCmp = Comparisons[0];
609
610 // Create a new cmp block before next cmp block.
611 BasicBlock *const BB =
612 BasicBlock::Create(Context, MergedBlockName(Comparisons).Name,
613 NextCmpBlock->getParent(), InsertBefore);
615 // Add the GEPs from the first BCECmpBlock.
616 Value *Lhs, *Rhs;
617 if (FirstCmp.Lhs().GEP)
618 Lhs = Builder.Insert(FirstCmp.Lhs().GEP->clone());
619 else
620 Lhs = FirstCmp.Lhs().LoadI->getPointerOperand();
621 if (FirstCmp.Rhs().GEP)
622 Rhs = Builder.Insert(FirstCmp.Rhs().GEP->clone());
623 else
624 Rhs = FirstCmp.Rhs().LoadI->getPointerOperand();
625
626 Value *IsEqual = nullptr;
627 LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons -> "
628 << BB->getName() << "\n");
629
630 // If there is one block that requires splitting, we do it now, i.e.
631 // just before we know we will collapse the chain. The instructions
632 // can be executed before any of the instructions in the chain.
633 const auto ToSplit = llvm::find_if(
634 Comparisons, [](const BCECmpBlock &B) { return B.RequireSplit; });
635 if (ToSplit != Comparisons.end()) {
636 LLVM_DEBUG(dbgs() << "Splitting non_BCE work to header\n");
637 ToSplit->split(BB, AA);
638 }
639
640 if (Comparisons.size() == 1) {
641 LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n");
642 Value *const LhsLoad =
643 Builder.CreateLoad(FirstCmp.Lhs().LoadI->getType(), Lhs);
644 Value *const RhsLoad =
645 Builder.CreateLoad(FirstCmp.Rhs().LoadI->getType(), Rhs);
646 // There are no blocks to merge, just do the comparison.
647 IsEqual = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
648 } else {
649 const unsigned TotalSizeBits = std::accumulate(
650 Comparisons.begin(), Comparisons.end(), 0u,
651 [](int Size, const BCECmpBlock &C) { return Size + C.SizeBits(); });
652
653 // memcmp expects a 'size_t' argument and returns 'int'.
654 unsigned SizeTBits = TLI.getSizeTSize(*Phi.getModule());
655 unsigned IntBits = TLI.getIntSize();
656
657 // Create memcmp() == 0.
658 const auto &DL = Phi.getModule()->getDataLayout();
659 Value *const MemCmpCall = emitMemCmp(
660 Lhs, Rhs,
661 ConstantInt::get(Builder.getIntNTy(SizeTBits), TotalSizeBits / 8),
662 Builder, DL, &TLI);
663 IsEqual = Builder.CreateICmpEQ(
664 MemCmpCall, ConstantInt::get(Builder.getIntNTy(IntBits), 0));
665 }
666
667 BasicBlock *const PhiBB = Phi.getParent();
668 // Add a branch to the next basic block in the chain.
669 if (NextCmpBlock == PhiBB) {
670 // Continue to phi, passing it the comparison result.
671 Builder.CreateBr(PhiBB);
672 Phi.addIncoming(IsEqual, BB);
673 DTU.applyUpdates({{DominatorTree::Insert, BB, PhiBB}});
674 } else {
675 // Continue to next block if equal, exit to phi else.
676 Builder.CreateCondBr(IsEqual, NextCmpBlock, PhiBB);
677 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
678 DTU.applyUpdates({{DominatorTree::Insert, BB, NextCmpBlock},
679 {DominatorTree::Insert, BB, PhiBB}});
680 }
681 return BB;
682}
683
684bool BCECmpChain::simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
685 DomTreeUpdater &DTU) {
686 assert(atLeastOneMerged() && "simplifying trivial BCECmpChain");
687 LLVM_DEBUG(dbgs() << "Simplifying comparison chain starting at block "
688 << EntryBlock_->getName() << "\n");
689
690 // Effectively merge blocks. We go in the reverse direction from the phi block
691 // so that the next block is always available to branch to.
692 BasicBlock *InsertBefore = EntryBlock_;
693 BasicBlock *NextCmpBlock = Phi_.getParent();
694 for (const auto &Blocks : reverse(MergedBlocks_)) {
695 InsertBefore = NextCmpBlock = mergeComparisons(
696 Blocks, InsertBefore, NextCmpBlock, Phi_, TLI, AA, DTU);
697 }
698
699 // Replace the original cmp chain with the new cmp chain by pointing all
700 // predecessors of EntryBlock_ to NextCmpBlock instead. This makes all cmp
701 // blocks in the old chain unreachable.
702 while (!pred_empty(EntryBlock_)) {
703 BasicBlock* const Pred = *pred_begin(EntryBlock_);
704 LLVM_DEBUG(dbgs() << "Updating jump into old chain from " << Pred->getName()
705 << "\n");
706 Pred->getTerminator()->replaceUsesOfWith(EntryBlock_, NextCmpBlock);
707 DTU.applyUpdates({{DominatorTree::Delete, Pred, EntryBlock_},
708 {DominatorTree::Insert, Pred, NextCmpBlock}});
709 }
710
711 // If the old cmp chain was the function entry, we need to update the function
712 // entry.
713 const bool ChainEntryIsFnEntry = EntryBlock_->isEntryBlock();
714 if (ChainEntryIsFnEntry && DTU.hasDomTree()) {
715 LLVM_DEBUG(dbgs() << "Changing function entry from "
716 << EntryBlock_->getName() << " to "
717 << NextCmpBlock->getName() << "\n");
718 DTU.getDomTree().setNewRoot(NextCmpBlock);
719 DTU.applyUpdates({{DominatorTree::Delete, NextCmpBlock, EntryBlock_}});
720 }
721 EntryBlock_ = nullptr;
722
723 // Delete merged blocks. This also removes incoming values in phi.
725 for (const auto &Blocks : MergedBlocks_) {
726 for (const BCECmpBlock &Block : Blocks) {
727 LLVM_DEBUG(dbgs() << "Deleting merged block " << Block.BB->getName()
728 << "\n");
729 DeadBlocks.push_back(Block.BB);
730 }
731 }
732 DeleteDeadBlocks(DeadBlocks, &DTU);
733
734 MergedBlocks_.clear();
735 return true;
736}
737
738std::vector<BasicBlock *> getOrderedBlocks(PHINode &Phi,
739 BasicBlock *const LastBlock,
740 int NumBlocks) {
741 // Walk up from the last block to find other blocks.
742 std::vector<BasicBlock *> Blocks(NumBlocks);
743 assert(LastBlock && "invalid last block");
744 BasicBlock *CurBlock = LastBlock;
745 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
746 if (CurBlock->hasAddressTaken()) {
747 // Somebody is jumping to the block through an address, all bets are
748 // off.
749 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
750 << " has its address taken\n");
751 return {};
752 }
753 Blocks[BlockIndex] = CurBlock;
754 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
755 if (!SinglePredecessor) {
756 // The block has two or more predecessors.
757 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
758 << " has two or more predecessors\n");
759 return {};
760 }
761 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
762 // The block does not link back to the phi.
763 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
764 << " does not link back to the phi\n");
765 return {};
766 }
767 CurBlock = SinglePredecessor;
768 }
769 Blocks[0] = CurBlock;
770 return Blocks;
771}
772
773bool processPhi(PHINode &Phi, const TargetLibraryInfo &TLI, AliasAnalysis &AA,
774 DomTreeUpdater &DTU) {
775 LLVM_DEBUG(dbgs() << "processPhi()\n");
776 if (Phi.getNumIncomingValues() <= 1) {
777 LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n");
778 return false;
779 }
780 // We are looking for something that has the following structure:
781 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
782 // \ \ \ \
783 // ne ne ne \
784 // \ \ \ v
785 // +------------+-----------+----------> bb_phi
786 //
787 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
788 // It's the only block that contributes a non-constant value to the Phi.
789 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
790 // them being the phi block.
791 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
792 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
793
794 // The blocks are not necessarily ordered in the phi, so we start from the
795 // last block and reconstruct the order.
796 BasicBlock *LastBlock = nullptr;
797 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
798 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
799 if (LastBlock) {
800 // There are several non-constant values.
801 LLVM_DEBUG(dbgs() << "skip: several non-constant values\n");
802 return false;
803 }
804 if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
805 cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
806 Phi.getIncomingBlock(I)) {
807 // Non-constant incoming value is not from a cmp instruction or not
808 // produced by the last block. We could end up processing the value
809 // producing block more than once.
810 //
811 // This is an uncommon case, so we bail.
813 dbgs()
814 << "skip: non-constant value not from cmp or not from last block.\n");
815 return false;
816 }
817 LastBlock = Phi.getIncomingBlock(I);
818 }
819 if (!LastBlock) {
820 // There is no non-constant block.
821 LLVM_DEBUG(dbgs() << "skip: no non-constant block\n");
822 return false;
823 }
824 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
825 LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n");
826 return false;
827 }
828
829 const auto Blocks =
830 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
831 if (Blocks.empty()) return false;
832 BCECmpChain CmpChain(Blocks, Phi, AA);
833
834 if (!CmpChain.atLeastOneMerged()) {
835 LLVM_DEBUG(dbgs() << "skip: nothing merged\n");
836 return false;
837 }
838
839 return CmpChain.simplify(TLI, AA, DTU);
840}
841
842static bool runImpl(Function &F, const TargetLibraryInfo &TLI,
844 DominatorTree *DT) {
845 LLVM_DEBUG(dbgs() << "MergeICmpsLegacyPass: " << F.getName() << "\n");
846
847 // We only try merging comparisons if the target wants to expand memcmp later.
848 // The rationale is to avoid turning small chains into memcmp calls.
849 if (!TTI.enableMemCmpExpansion(F.hasOptSize(), true))
850 return false;
851
852 // If we don't have memcmp avaiable we can't emit calls to it.
853 if (!TLI.has(LibFunc_memcmp))
854 return false;
855
856 DomTreeUpdater DTU(DT, /*PostDominatorTree*/ nullptr,
857 DomTreeUpdater::UpdateStrategy::Eager);
858
859 bool MadeChange = false;
860
861 for (BasicBlock &BB : llvm::drop_begin(F)) {
862 // A Phi operation is always first in a basic block.
863 if (auto *const Phi = dyn_cast<PHINode>(&*BB.begin()))
864 MadeChange |= processPhi(*Phi, TLI, AA, DTU);
865 }
866
867 return MadeChange;
868}
869
870class MergeICmpsLegacyPass : public FunctionPass {
871public:
872 static char ID;
873
874 MergeICmpsLegacyPass() : FunctionPass(ID) {
876 }
877
878 bool runOnFunction(Function &F) override {
879 if (skipFunction(F)) return false;
880 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
881 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
882 // MergeICmps does not need the DominatorTree, but we update it if it's
883 // already available.
884 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
885 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
886 return runImpl(F, TLI, TTI, AA, DTWP ? &DTWP->getDomTree() : nullptr);
887 }
888
889 private:
890 void getAnalysisUsage(AnalysisUsage &AU) const override {
896 }
897};
898
899} // namespace
900
901char MergeICmpsLegacyPass::ID = 0;
902INITIALIZE_PASS_BEGIN(MergeICmpsLegacyPass, "mergeicmps",
903 "Merge contiguous icmps into a memcmp", false, false)
907INITIALIZE_PASS_END(MergeICmpsLegacyPass, "mergeicmps",
908 "Merge contiguous icmps into a memcmp", false, false)
909
910Pass *llvm::createMergeICmpsLegacyPass() { return new MergeICmpsLegacyPass(); }
911
914 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
915 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
916 auto &AA = AM.getResult<AAManager>(F);
918 const bool MadeChanges = runImpl(F, TLI, TTI, AA, DT);
919 if (!MadeChanges)
920 return PreservedAnalyses::all();
923 return PA;
924}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
assume Assume Builder
SmallVector< MachineOperand, 4 > Cond
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static Error split(StringRef Str, char Separator, std::pair< StringRef, StringRef > &Split)
Checked version of split, to ensure mandatory subparts.
Definition: DataLayout.cpp:219
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Addr
std::string Name
uint64_t Size
static bool runImpl(Function &F, const TargetLowering &TLI)
This is the interface for a simple mod/ref and alias analysis over globals.
hexagon bit simplify
Hexagon Common GEP
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
mergeicmps
Definition: MergeICmps.cpp:907
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:908
LLVMContext & Context
return ToRemove size() > 0
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
R600 Clause Merge
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This pass exposes codegen information to IR-level passes.
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
Class for arbitrary precision integers.
Definition: APInt.h:75
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:793
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:152
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
iterator begin() const
Definition: ArrayRef.h:151
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:158
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:314
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition: BasicBlock.h:495
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:105
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:284
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:314
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:112
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:35
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:127
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:718
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:808
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:887
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:842
bool hasDomTree() const
Returns true if it holds a DominatorTree.
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
DominatorTree & getDomTree()
Flush DomTree updates and return DomTree.
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
DomTreeNodeBase< NodeT > * setNewRoot(NodeT *BB)
Add a new node to the forward dominator tree and make it a new root.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:314
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition: Pass.cpp:174
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:940
Legacy wrapper pass to provide the GlobalsAAResult object.
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2550
bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:70
const BasicBlock * getParent() const
Definition: Instruction.h:90
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:177
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:398
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:91
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:173
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:290
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition: SmallString.h:68
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:261
void reserve(size_type N)
Definition: SmallVector.h:667
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool has(LibFunc F) const
Tests whether a library function is available.
unsigned getSizeTSize(const Module &M) const
Returns the size of the size_t type in bits.
unsigned getIntSize() const
Get size of a C-level int or unsigned int, in bits.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const
op_range operands()
Definition: User.h:242
bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:21
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:308
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:456
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:386
@ Offset
Definition: DWP.cpp:406
bool operator<(int64_t V1, const APSInt &V2)
Definition: APSInt.h:361
void initializeMergeICmpsLegacyPassPass(PassRegistry &)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1742
Value * emitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memcmp function.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:484
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1683
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1749
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:109
Pass * createMergeICmpsLegacyPass()
Definition: MergeICmps.cpp:910
bool isDereferenceablePointer(const Value *V, Type *Ty, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if this is always a dereferenceable pointer.
Definition: Loads.cpp:221
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1862
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1762
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:118
void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
Definition: BitVector.h:851
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:853
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: MergeICmps.cpp:912