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