LLVM 24.0.0git
EarlyCSE.cpp
Go to the documentation of this file.
1//===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
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 performs a simple dominator tree walk that eliminates trivially
10// redundant instructions.
11//
12//===----------------------------------------------------------------------===//
13
15#include "ScalarOptions.h"
17#include "llvm/ADT/Hashing.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/Statistic.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Instruction.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/PassManager.h"
42#include "llvm/IR/Type.h"
43#include "llvm/IR/Value.h"
45#include "llvm/Pass.h"
49#include "llvm/Support/Debug.h"
56#include <cassert>
57#include <deque>
58#include <memory>
59#include <utility>
60
61using namespace llvm;
62using namespace llvm::PatternMatch;
63
64#define DEBUG_TYPE "early-cse"
65
66STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
67STATISTIC(NumCSE, "Number of instructions CSE'd");
68STATISTIC(NumCSECVP, "Number of compare instructions CVP'd");
69STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
70STATISTIC(NumCSECall, "Number of call instructions CSE'd");
71STATISTIC(NumCSEGEP, "Number of GEP instructions CSE'd");
72STATISTIC(NumDSE, "Number of trivial dead stores removed");
73
74DEBUG_COUNTER(CSECounter, "early-cse",
75 "Controls which instructions are removed");
76
77//===----------------------------------------------------------------------===//
78// SimpleValue
79//===----------------------------------------------------------------------===//
80
81namespace {
82
83/// Struct representing the available values in the scoped hash table.
84struct SimpleValue {
85 Instruction *Inst;
86
87 SimpleValue(Instruction *I) : Inst(I) {
88 assert(canHandle(I) && "Inst can't be handled!");
89 }
90
91 static bool canHandle(Instruction *Inst) {
92 // This can only handle non-void readnone functions.
93 // Also handled are constrained intrinsic that look like the types
94 // of instruction handled below (UnaryOperator, etc.).
95 if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
96 if (Function *F = CI->getCalledFunction()) {
97 switch (F->getIntrinsicID()) {
98 case Intrinsic::experimental_constrained_fadd:
99 case Intrinsic::experimental_constrained_fsub:
100 case Intrinsic::experimental_constrained_fmul:
101 case Intrinsic::experimental_constrained_fdiv:
102 case Intrinsic::experimental_constrained_frem:
103 case Intrinsic::experimental_constrained_fptosi:
104 case Intrinsic::experimental_constrained_sitofp:
105 case Intrinsic::experimental_constrained_fptoui:
106 case Intrinsic::experimental_constrained_uitofp:
107 case Intrinsic::experimental_constrained_fcmp:
108 case Intrinsic::experimental_constrained_fcmps: {
109 auto *CFP = cast<ConstrainedFPIntrinsic>(CI);
110 if (CFP->getExceptionBehavior() &&
111 CFP->getExceptionBehavior() == fp::ebStrict)
112 return false;
113 // Since we CSE across function calls we must not allow
114 // the rounding mode to change.
115 if (CFP->getRoundingMode() &&
116 CFP->getRoundingMode() == RoundingMode::Dynamic)
117 return false;
118 return true;
119 }
120 }
121 }
122 return CI->doesNotAccessMemory() &&
123 // FIXME: Currently the calls which may access the thread id may
124 // be considered as not accessing the memory. But this is
125 // problematic for coroutines, since coroutines may resume in a
126 // different thread. So we disable the optimization here for the
127 // correctness. However, it may block many other correct
128 // optimizations. Revert this one when we detect the memory
129 // accessing kind more precisely.
130 !CI->getFunction()->isPresplitCoroutine();
131 }
132 return isa<CastInst>(Inst) || isa<UnaryOperator>(Inst) ||
133 isa<BinaryOperator>(Inst) || isa<CmpInst>(Inst) ||
137 isa<FreezeInst>(Inst);
138 }
139};
140
141} // end anonymous namespace
142
143template <> struct llvm::DenseMapInfo<SimpleValue> {
144 static unsigned getHashValue(SimpleValue Val);
145 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
146};
147
148/// Match a 'select' including an optional 'not's of the condition.
150 Value *&B,
151 SelectPatternFlavor &Flavor) {
152 // Return false if V is not even a select.
153 if (!match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))))
154 return false;
155
156 // Look through a 'not' of the condition operand by swapping A/B.
157 Value *CondNot;
158 if (match(Cond, m_Not(m_Value(CondNot)))) {
159 Cond = CondNot;
160 std::swap(A, B);
161 }
162
163 // Match canonical forms of min/max. We are not using ValueTracking's
164 // more powerful matchSelectPattern() because it may rely on instruction flags
165 // such as "nsw". That would be incompatible with the current hashing
166 // mechanism that may remove flags to increase the likelihood of CSE.
167
168 Flavor = SPF_UNKNOWN;
169 CmpPredicate Pred;
170
171 if (!match(Cond, m_ICmp(Pred, m_Specific(A), m_Specific(B)))) {
172 // Check for commuted variants of min/max by swapping predicate.
173 // If we do not match the standard or commuted patterns, this is not a
174 // recognized form of min/max, but it is still a select, so return true.
175 if (!match(Cond, m_ICmp(Pred, m_Specific(B), m_Specific(A))))
176 return true;
178 }
179
180 switch (Pred) {
181 case CmpInst::ICMP_UGT: Flavor = SPF_UMAX; break;
182 case CmpInst::ICMP_ULT: Flavor = SPF_UMIN; break;
183 case CmpInst::ICMP_SGT: Flavor = SPF_SMAX; break;
184 case CmpInst::ICMP_SLT: Flavor = SPF_SMIN; break;
185 // Non-strict inequalities.
186 case CmpInst::ICMP_ULE: Flavor = SPF_UMIN; break;
187 case CmpInst::ICMP_UGE: Flavor = SPF_UMAX; break;
188 case CmpInst::ICMP_SLE: Flavor = SPF_SMIN; break;
189 case CmpInst::ICMP_SGE: Flavor = SPF_SMAX; break;
190 default: break;
191 }
192
193 return true;
194}
195
196static unsigned hashCallInst(CallInst *CI) {
197 // Don't CSE convergent calls in different basic blocks, because they
198 // implicitly depend on the set of threads that is currently executing.
199 if (CI->isConvergent()) {
200 return hash_combine(CI->getOpcode(), CI->getParent(),
202 }
203 return hash_combine(CI->getOpcode(),
205}
206
207static unsigned getHashValueImpl(SimpleValue Val) {
208 Instruction *Inst = Val.Inst;
209 // Hash in all of the operands as pointers.
210 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
211 Value *LHS = BinOp->getOperand(0);
212 Value *RHS = BinOp->getOperand(1);
213 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
214 std::swap(LHS, RHS);
215
216 return hash_combine(BinOp->getOpcode(), LHS, RHS);
217 }
218
219 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
220 // Compares can be commuted by swapping the comparands and
221 // updating the predicate. Choose the form that has the
222 // comparands in sorted order, or in the case of a tie, the
223 // one with the lower predicate.
224 Value *LHS = CI->getOperand(0);
225 Value *RHS = CI->getOperand(1);
226 CmpInst::Predicate Pred = CI->getPredicate();
227 CmpInst::Predicate SwappedPred = CI->getSwappedPredicate();
228 if (std::tie(LHS, Pred) > std::tie(RHS, SwappedPred)) {
229 std::swap(LHS, RHS);
230 Pred = SwappedPred;
231 }
232 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
233 }
234
235 // Hash general selects to allow matching commuted true/false operands.
237 Value *Cond, *A, *B;
238 if (matchSelectWithOptionalNotCond(Inst, Cond, A, B, SPF)) {
239 // Hash min/max (cmp + select) to allow for commuted operands.
240 // Min/max may also have non-canonical compare predicate (eg, the compare for
241 // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
242 // compare.
243 // TODO: We should also detect FP min/max.
244 if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
245 SPF == SPF_UMIN || SPF == SPF_UMAX) {
246 if (A > B)
247 std::swap(A, B);
248 return hash_combine(Inst->getOpcode(), SPF, A, B);
249 }
250
251 // Hash general selects to allow matching commuted true/false operands.
252
253 // If we do not have a compare as the condition, just hash in the condition.
254 CmpPredicate Pred;
255 Value *X, *Y;
256 if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y))))
257 return hash_combine(Inst->getOpcode(), Cond, A, B);
258
259 // Similar to cmp normalization (above) - canonicalize the predicate value:
260 // select (icmp Pred, X, Y), A, B --> select (icmp InvPred, X, Y), B, A
261 if (CmpInst::getInversePredicate(Pred) < Pred) {
262 Pred = CmpInst::getInversePredicate(Pred);
263 std::swap(A, B);
264 }
265 return hash_combine(Inst->getOpcode(),
266 static_cast<CmpInst::Predicate>(Pred), X, Y, A, B);
267 }
268
269 if (CastInst *CI = dyn_cast<CastInst>(Inst))
270 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
271
272 if (FreezeInst *FI = dyn_cast<FreezeInst>(Inst))
273 return hash_combine(FI->getOpcode(), FI->getOperand(0));
274
275 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
276 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
277 hash_combine_range(EVI->indices()));
278
279 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
280 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
281 IVI->getOperand(1), hash_combine_range(IVI->indices()));
282
285 isa<UnaryOperator>(Inst) || isa<FreezeInst>(Inst)) &&
286 "Invalid/unknown instruction");
287
288 // Handle intrinsics with commutative operands.
289 auto *II = dyn_cast<IntrinsicInst>(Inst);
290 if (II && II->isCommutative() && II->arg_size() >= 2) {
291 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
292 if (LHS > RHS)
293 std::swap(LHS, RHS);
294 return hash_combine(
295 II->getOpcode(), LHS, RHS,
296 hash_combine_range(drop_begin(II->operand_values(), 2)));
297 }
298
299 // gc.relocate is 'special' call: its second and third operands are
300 // not real values, but indices into statepoint's argument list.
301 // Get values they point to.
302 if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(Inst))
303 return hash_combine(GCR->getOpcode(), GCR->getOperand(0),
304 GCR->getBasePtr(), GCR->getDerivedPtr());
305
306 // Don't CSE convergent calls in different basic blocks, because they
307 // implicitly depend on the set of threads that is currently executing.
308 if (CallInst *CI = dyn_cast<CallInst>(Inst))
309 return hashCallInst(CI);
310
311 // Mix in the opcode.
312 return hash_combine(Inst->getOpcode(),
314}
315
316unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
317#ifndef NDEBUG
318 // If -earlycse-debug-hash was specified, return a constant -- this
319 // will force all hashing to collide, so we'll exhaustively search
320 // the table for a match, and the assertion in isEqual will fire if
321 // there's a bug causing equal keys to hash differently.
322 if (ScalarOptions::Global.earlycse_debug_hash)
323 return 0;
324#endif
325 return getHashValueImpl(Val);
326}
327
328static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS) {
329 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
330
331 if (LHSI->getOpcode() != RHSI->getOpcode())
332 return false;
333 if (LHSI->isIdenticalToWhenDefined(RHSI, /*IntersectAttrs=*/true)) {
334 // Convergent calls implicitly depend on the set of threads that is
335 // currently executing, so conservatively return false if they are in
336 // different basic blocks.
337 if (CallInst *CI = dyn_cast<CallInst>(LHSI);
338 CI && CI->isConvergent() && LHSI->getParent() != RHSI->getParent())
339 return false;
340
341 return true;
342 }
343
344 // If we're not strictly identical, we still might be a commutable instruction
345 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
346 if (!LHSBinOp->isCommutative())
347 return false;
348
350 "same opcode, but different instruction type?");
351 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
352
353 // Commuted equality
354 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
355 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
356 }
357 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
358 assert(isa<CmpInst>(RHSI) &&
359 "same opcode, but different instruction type?");
360 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
361 // Commuted equality
362 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
363 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
364 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
365 }
366
367 auto *LII = dyn_cast<IntrinsicInst>(LHSI);
368 auto *RII = dyn_cast<IntrinsicInst>(RHSI);
369 if (LII && RII && LII->getIntrinsicID() == RII->getIntrinsicID() &&
370 LII->isCommutative() && LII->arg_size() >= 2) {
371 return LII->getArgOperand(0) == RII->getArgOperand(1) &&
372 LII->getArgOperand(1) == RII->getArgOperand(0) &&
373 std::equal(LII->arg_begin() + 2, LII->arg_end(),
374 RII->arg_begin() + 2, RII->arg_end()) &&
375 LII->hasSameSpecialState(RII, /*IgnoreAlignment=*/false,
376 /*IntersectAttrs=*/true);
377 }
378
379 // See comment above in `getHashValue()`.
380 if (const GCRelocateInst *GCR1 = dyn_cast<GCRelocateInst>(LHSI))
381 if (const GCRelocateInst *GCR2 = dyn_cast<GCRelocateInst>(RHSI))
382 return GCR1->getOperand(0) == GCR2->getOperand(0) &&
383 GCR1->getBasePtr() == GCR2->getBasePtr() &&
384 GCR1->getDerivedPtr() == GCR2->getDerivedPtr();
385
386 // Min/max can occur with commuted operands, non-canonical predicates,
387 // and/or non-canonical operands.
388 // Selects can be non-trivially equivalent via inverted conditions and swaps.
389 SelectPatternFlavor LSPF, RSPF;
390 Value *CondL, *CondR, *LHSA, *RHSA, *LHSB, *RHSB;
391 if (matchSelectWithOptionalNotCond(LHSI, CondL, LHSA, LHSB, LSPF) &&
392 matchSelectWithOptionalNotCond(RHSI, CondR, RHSA, RHSB, RSPF)) {
393 if (LSPF == RSPF) {
394 // TODO: We should also detect FP min/max.
395 if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
396 LSPF == SPF_UMIN || LSPF == SPF_UMAX)
397 return ((LHSA == RHSA && LHSB == RHSB) ||
398 (LHSA == RHSB && LHSB == RHSA));
399
400 // select Cond, A, B <--> select not(Cond), B, A
401 if (CondL == CondR && LHSA == RHSA && LHSB == RHSB)
402 return true;
403 }
404
405 // If the true/false operands are swapped and the conditions are compares
406 // with inverted predicates, the selects are equal:
407 // select (icmp Pred, X, Y), A, B <--> select (icmp InvPred, X, Y), B, A
408 //
409 // This also handles patterns with a double-negation in the sense of not +
410 // inverse, because we looked through a 'not' in the matching function and
411 // swapped A/B:
412 // select (cmp Pred, X, Y), A, B <--> select (not (cmp InvPred, X, Y)), B, A
413 //
414 // This intentionally does NOT handle patterns with a double-negation in
415 // the sense of not + not, because doing so could result in values
416 // comparing
417 // as equal that hash differently in the min/max cases like:
418 // select (cmp slt, X, Y), X, Y <--> select (not (not (cmp slt, X, Y))), X, Y
419 // ^ hashes as min ^ would not hash as min
420 // In the context of the EarlyCSE pass, however, such cases never reach
421 // this code, as we simplify the double-negation before hashing the second
422 // select (and so still succeed at CSEing them).
423 if (LHSA == RHSB && LHSB == RHSA) {
424 CmpPredicate PredL, PredR;
425 Value *X, *Y;
426 if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) &&
427 match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) &&
428 CmpInst::getInversePredicate(PredL) == PredR)
429 return true;
430 }
431 }
432
433 return false;
434}
435
436bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
437 // These comparisons are nontrivial, so assert that equality implies
438 // hash equality (DenseMap demands this as an invariant).
439 bool Result = isEqualImpl(LHS, RHS);
441 return Result;
442}
443
444//===----------------------------------------------------------------------===//
445// CallValue
446//===----------------------------------------------------------------------===//
447
448namespace {
449
450/// Struct representing the available call values in the scoped hash
451/// table.
452struct CallValue {
453 Instruction *Inst;
454
455 CallValue(Instruction *I) : Inst(I) {
456 assert(canHandle(I) && "Inst can't be handled!");
457 }
458
459 static bool canHandle(Instruction *Inst) {
460 CallInst *CI = dyn_cast<CallInst>(Inst);
461 if (!CI || (!CI->onlyReadsMemory() && !CI->onlyWritesMemory()) ||
462 // FIXME: Currently the calls which may access the thread id may
463 // be considered as not accessing the memory. But this is
464 // problematic for coroutines, since coroutines may resume in a
465 // different thread. So we disable the optimization here for the
466 // correctness. However, it may block many other correct
467 // optimizations. Revert this one when we detect the memory
468 // accessing kind more precisely.
470 return false;
471 return true;
472 }
473};
474
475} // end anonymous namespace
476
477template <> struct llvm::DenseMapInfo<CallValue> {
478 static unsigned getHashValue(CallValue Val);
479 static bool isEqual(CallValue LHS, CallValue RHS);
480};
481
482unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
483 Instruction *Inst = Val.Inst;
484
485 // Hash all of the operands as pointers and mix in the opcode.
486 return hashCallInst(cast<CallInst>(Inst));
487}
488
489bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
490 CallInst *LHSI = cast<CallInst>(LHS.Inst);
491 CallInst *RHSI = cast<CallInst>(RHS.Inst);
492
493 // Convergent calls implicitly depend on the set of threads that is
494 // currently executing, so conservatively return false if they are in
495 // different basic blocks.
496 if (LHSI->isConvergent() && LHSI->getParent() != RHSI->getParent())
497 return false;
498
499 return LHSI->isIdenticalToWhenDefined(RHSI, /*IntersectAttrs=*/true);
500}
501
502//===----------------------------------------------------------------------===//
503// GEPValue
504//===----------------------------------------------------------------------===//
505
506namespace {
507
508struct GEPValue {
509 Instruction *Inst;
510 std::optional<int64_t> ConstantOffset;
511
512 GEPValue(Instruction *I) : Inst(I) {
513 assert(canHandle(I) && "Inst can't be handled!");
514 }
515
516 GEPValue(Instruction *I, std::optional<int64_t> ConstantOffset)
517 : Inst(I), ConstantOffset(ConstantOffset) {
518 assert(canHandle(I) && "Inst can't be handled!");
519 }
520
521 static bool canHandle(Instruction *Inst) {
522 return isa<GetElementPtrInst>(Inst);
523 }
524};
525
526} // namespace
527
528template <> struct llvm::DenseMapInfo<GEPValue> {
529 static unsigned getHashValue(const GEPValue &Val);
530 static bool isEqual(const GEPValue &LHS, const GEPValue &RHS);
531};
532
533unsigned DenseMapInfo<GEPValue>::getHashValue(const GEPValue &Val) {
534 auto *GEP = cast<GetElementPtrInst>(Val.Inst);
535 if (Val.ConstantOffset.has_value())
536 return hash_combine(GEP->getOpcode(), GEP->getPointerOperand(),
537 Val.ConstantOffset.value());
538 return hash_combine(GEP->getOpcode(),
539 hash_combine_range(GEP->operand_values()));
540}
541
542bool DenseMapInfo<GEPValue>::isEqual(const GEPValue &LHS, const GEPValue &RHS) {
543 auto *LGEP = cast<GetElementPtrInst>(LHS.Inst);
544 auto *RGEP = cast<GetElementPtrInst>(RHS.Inst);
545 if (LGEP->getPointerOperand() != RGEP->getPointerOperand())
546 return false;
547 if (LHS.ConstantOffset.has_value() && RHS.ConstantOffset.has_value())
548 return LHS.ConstantOffset.value() == RHS.ConstantOffset.value();
549 return LGEP->isIdenticalToWhenDefined(RGEP);
550}
551
552//===----------------------------------------------------------------------===//
553// EarlyCSE implementation
554//===----------------------------------------------------------------------===//
555
556namespace {
557
558/// A simple and fast domtree-based CSE pass.
559///
560/// This pass does a simple depth-first walk over the dominator tree,
561/// eliminating trivially redundant instructions and using instsimplify to
562/// canonicalize things as it goes. It is intended to be fast and catch obvious
563/// cases so that instcombine and other passes are more effective. It is
564/// expected that a later pass of GVN will catch the interesting/hard cases.
565class EarlyCSE {
566public:
567 const TargetLibraryInfo &TLI;
568 const TargetTransformInfo &TTI;
569 DominatorTree &DT;
570 AssumptionCache &AC;
571 const SimplifyQuery SQ;
572 MemorySSA *MSSA;
573 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
574
575 using AllocatorTy =
576 RecyclingAllocator<BumpPtrAllocator,
577 ScopedHashTableVal<SimpleValue, Value *>>;
578 using ScopedHTType =
579 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
580 AllocatorTy>;
581
582 /// A scoped hash table of the current values of all of our simple
583 /// scalar expressions.
584 ///
585 /// As we walk down the domtree, we look to see if instructions are in this:
586 /// if so, we replace them with what we find, otherwise we insert them so
587 /// that dominated values can succeed in their lookup.
588 ScopedHTType AvailableValues;
589
590 /// A scoped hash table of the current values of previously encountered
591 /// memory locations.
592 ///
593 /// This allows us to get efficient access to dominating loads or stores when
594 /// we have a fully redundant load. In addition to the most recent load, we
595 /// keep track of a generation count of the read, which is compared against
596 /// the current generation count. The current generation count is incremented
597 /// after every possibly writing memory operation, which ensures that we only
598 /// CSE loads with other loads that have no intervening store. Ordering
599 /// events (such as fences or atomic instructions) increment the generation
600 /// count as well; essentially, we model these as writes to all possible
601 /// locations. Note that atomic and/or volatile loads and stores can be
602 /// present the table; it is the responsibility of the consumer to inspect
603 /// the atomicity/volatility if needed.
604 struct LoadValue {
605 Instruction *DefInst = nullptr;
606 unsigned Generation = 0;
607 int MatchingId = -1;
608 bool IsAtomic = false;
609 bool IsLoad = false;
610
611 LoadValue() = default;
612 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
613 bool IsAtomic, bool IsLoad)
614 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
615 IsAtomic(IsAtomic), IsLoad(IsLoad) {}
616 };
617
618 using LoadMapAllocator =
619 RecyclingAllocator<BumpPtrAllocator,
620 ScopedHashTableVal<Value *, LoadValue>>;
621 using LoadHTType =
622 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
623 LoadMapAllocator>;
624
625 LoadHTType AvailableLoads;
626
627 // A scoped hash table mapping memory locations (represented as typed
628 // addresses) to generation numbers at which that memory location became
629 // (henceforth indefinitely) invariant.
630 using InvariantMapAllocator =
631 RecyclingAllocator<BumpPtrAllocator,
632 ScopedHashTableVal<MemoryLocation, unsigned>>;
633 using InvariantHTType =
634 ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
635 InvariantMapAllocator>;
636 InvariantHTType AvailableInvariants;
637
638 /// A scoped hash table of the current values of read-only call
639 /// values.
640 ///
641 /// It uses the same generation count as loads.
642 using CallHTType =
643 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
644 CallHTType AvailableCalls;
645
646 using GEPMapAllocatorTy =
647 RecyclingAllocator<BumpPtrAllocator,
648 ScopedHashTableVal<GEPValue, Value *>>;
649 using GEPHTType = ScopedHashTable<GEPValue, Value *, DenseMapInfo<GEPValue>,
650 GEPMapAllocatorTy>;
651 GEPHTType AvailableGEPs;
652
653 /// This is the current generation of the memory value.
654 unsigned CurrentGeneration = 0;
655
656 /// Set up the EarlyCSE runner for a particular function.
657 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
658 const TargetTransformInfo &TTI, DominatorTree &DT,
659 AssumptionCache &AC, MemorySSA *MSSA)
660 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
661 MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {}
662
663 bool run();
664
665private:
666 unsigned ClobberCounter = 0;
667 // Almost a POD, but needs to call the constructors for the scoped hash
668 // tables so that a new scope gets pushed on. These are RAII so that the
669 // scope gets popped when the NodeScope is destroyed.
670 class NodeScope {
671 public:
672 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
673 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
674 GEPHTType &AvailableGEPs)
675 : Scope(AvailableValues), LoadScope(AvailableLoads),
676 InvariantScope(AvailableInvariants), CallScope(AvailableCalls),
677 GEPScope(AvailableGEPs) {}
678 NodeScope(const NodeScope &) = delete;
679 NodeScope &operator=(const NodeScope &) = delete;
680
681 private:
683 LoadHTType::ScopeTy LoadScope;
684 InvariantHTType::ScopeTy InvariantScope;
685 CallHTType::ScopeTy CallScope;
686 GEPHTType::ScopeTy GEPScope;
687 };
688
689 // Contains all the needed information to create a stack for doing a depth
690 // first traversal of the tree. This includes scopes for values, loads, and
691 // calls as well as the generation. There is a child iterator so that the
692 // children do not need to be store separately.
693 class StackNode {
694 public:
695 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
696 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
697 GEPHTType &AvailableGEPs, unsigned cg, DomTreeNode *n,
698 DomTreeNode::const_iterator child,
699 DomTreeNode::const_iterator end)
700 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
701 EndIter(end),
702 Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
703 AvailableCalls, AvailableGEPs) {}
704 StackNode(const StackNode &) = delete;
705 StackNode &operator=(const StackNode &) = delete;
706
707 // Accessors.
708 unsigned currentGeneration() const { return CurrentGeneration; }
709 unsigned childGeneration() const { return ChildGeneration; }
710 void childGeneration(unsigned generation) { ChildGeneration = generation; }
711 DomTreeNode *node() { return Node; }
712 DomTreeNode::const_iterator childIter() const { return ChildIter; }
713
714 DomTreeNode *nextChild() {
715 DomTreeNode *child = *ChildIter;
716 ++ChildIter;
717 return child;
718 }
719
720 DomTreeNode::const_iterator end() const { return EndIter; }
721 bool isProcessed() const { return Processed; }
722 void process() { Processed = true; }
723
724 private:
725 unsigned CurrentGeneration;
726 unsigned ChildGeneration;
727 DomTreeNode *Node;
728 DomTreeNode::const_iterator ChildIter;
729 DomTreeNode::const_iterator EndIter;
730 NodeScope Scopes;
731 bool Processed = false;
732 };
733
734 /// Wrapper class to handle memory instructions, including loads,
735 /// stores and intrinsic loads and stores defined by the target.
736 class ParseMemoryInst {
737 public:
738 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
739 : Inst(Inst) {
740 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
741 IntrID = II->getIntrinsicID();
742 if (TTI.getTgtMemIntrinsic(II, Info))
743 return;
744 if (isHandledNonTargetIntrinsic(IntrID)) {
745 switch (IntrID) {
746 case Intrinsic::masked_load:
747 Info.PtrVal = Inst->getOperand(0);
748 Info.MatchingId = Intrinsic::masked_load;
749 Info.ReadMem = true;
750 Info.WriteMem = false;
751 Info.IsVolatile = false;
752 break;
753 case Intrinsic::masked_store:
754 Info.PtrVal = Inst->getOperand(1);
755 // Use the ID of masked load as the "matching id". This will
756 // prevent matching non-masked loads/stores with masked ones
757 // (which could be done), but at the moment, the code here
758 // does not support matching intrinsics with non-intrinsics,
759 // so keep the MatchingIds specific to masked instructions
760 // for now (TODO).
761 Info.MatchingId = Intrinsic::masked_load;
762 Info.ReadMem = false;
763 Info.WriteMem = true;
764 Info.IsVolatile = false;
765 break;
766 }
767 } else if (auto *MI = dyn_cast<MemSetInst>(Inst)) {
768 Info.PtrVal = MI->getDest();
769 Info.MatchingId = 0;
770 Info.ReadMem = false;
771 Info.WriteMem = true;
772 Info.IsVolatile = MI->isVolatile();
773 }
774 }
775 }
776
777 Instruction *get() { return Inst; }
778 const Instruction *get() const { return Inst; }
779
780 bool isLoad() const {
781 if (IntrID != 0)
782 return Info.ReadMem;
783 return isa<LoadInst>(Inst);
784 }
785
786 bool isStore() const {
787 if (IntrID != 0)
788 return Info.WriteMem;
789 return isa<StoreInst>(Inst);
790 }
791
792 bool isAtomic() const {
793 if (IntrID != 0)
794 return Info.Ordering != AtomicOrdering::NotAtomic;
795 return Inst->isAtomic();
796 }
797
798 bool isUnordered() const {
799 if (IntrID != 0)
800 return Info.isUnordered();
801
802 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
803 return LI->isUnordered();
804 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
805 return SI->isUnordered();
806 }
807 // Conservative answer
808 return !Inst->isAtomic();
809 }
810
811 bool isVolatile() const {
812 if (IntrID != 0)
813 return Info.IsVolatile;
814
815 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
816 return LI->isVolatile();
817 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
818 return SI->isVolatile();
819 }
820 // Conservative answer
821 return true;
822 }
823
824 bool isInvariantLoad() const {
825 if (auto *LI = dyn_cast<LoadInst>(Inst))
826 return LI->hasMetadata(LLVMContext::MD_invariant_load);
827 return false;
828 }
829
830 bool isValid() const { return getPointerOperand() != nullptr; }
831
832 // For regular (non-intrinsic) loads/stores, this is set to -1. For
833 // intrinsic loads/stores, the id is retrieved from the corresponding
834 // field in the MemIntrinsicInfo structure. That field contains
835 // non-negative values only.
836 int getMatchingId() const {
837 if (IntrID != 0)
838 return Info.MatchingId;
839 return -1;
840 }
841
842 Value *getPointerOperand() const {
843 if (IntrID != 0)
844 return Info.PtrVal;
845 return getLoadStorePointerOperand(Inst);
846 }
847
848 Type *getValueType() const {
849 // TODO: handle target-specific intrinsics.
850 return Inst->getAccessType();
851 }
852
853 bool mayReadFromMemory() const {
854 if (IntrID != 0)
855 return Info.ReadMem;
856 return Inst->mayReadFromMemory();
857 }
858
859 bool mayWriteToMemory() const {
860 if (IntrID != 0)
861 return Info.WriteMem;
862 return Inst->mayWriteToMemory();
863 }
864
865 private:
866 Intrinsic::ID IntrID = 0;
867 MemIntrinsicInfo Info;
868 Instruction *Inst;
869 };
870
871 // This function is to prevent accidentally passing a non-target
872 // intrinsic ID to TargetTransformInfo.
873 static bool isHandledNonTargetIntrinsic(Intrinsic::ID ID) {
874 switch (ID) {
875 case Intrinsic::masked_load:
876 case Intrinsic::masked_store:
877 return true;
878 }
879 return false;
880 }
881 static bool isHandledNonTargetIntrinsic(const Value *V) {
882 if (auto *II = dyn_cast<IntrinsicInst>(V))
883 return isHandledNonTargetIntrinsic(II->getIntrinsicID());
884 return false;
885 }
886
887 bool processNode(DomTreeNode *Node);
888
889 bool handleBranchCondition(Instruction *CondInst, const CondBrInst *BI,
890 const BasicBlock *BB, const BasicBlock *Pred);
891
892 Value *getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
893 unsigned CurrentGeneration);
894
895 bool overridingStores(const ParseMemoryInst &Earlier,
896 const ParseMemoryInst &Later);
897
898 Value *getOrCreateResult(Instruction *Inst, Type *ExpectedType,
899 bool CanCreate) const {
900 // TODO: We could insert relevant casts on type mismatch.
901 // The load or the store's first operand.
902 Value *V;
903 if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
904 switch (II->getIntrinsicID()) {
905 case Intrinsic::masked_load:
906 V = II;
907 break;
908 case Intrinsic::masked_store:
909 V = II->getOperand(0);
910 break;
911 default:
912 return TTI.getOrCreateResultFromMemIntrinsic(II, ExpectedType,
913 CanCreate);
914 }
915 } else {
916 V = isa<LoadInst>(Inst) ? Inst : cast<StoreInst>(Inst)->getValueOperand();
917 }
918
919 return V->getType() == ExpectedType ? V : nullptr;
920 }
921
922 /// Return true if the instruction is known to only operate on memory
923 /// provably invariant in the given "generation".
924 bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
925
926 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
927 Instruction *EarlierInst, Instruction *LaterInst);
928
929 bool isNonTargetIntrinsicMatch(const IntrinsicInst *Earlier,
930 const IntrinsicInst *Later) {
931 auto IsSubmask = [](const Value *Mask0, const Value *Mask1) {
932 // Is Mask0 a submask of Mask1?
933 if (Mask0 == Mask1)
934 return true;
935 if (isa<UndefValue>(Mask0) || isa<UndefValue>(Mask1))
936 return false;
937 auto *Vec0 = dyn_cast<ConstantVector>(Mask0);
938 auto *Vec1 = dyn_cast<ConstantVector>(Mask1);
939 if (!Vec0 || !Vec1)
940 return false;
941 if (Vec0->getType() != Vec1->getType())
942 return false;
943 for (int i = 0, e = Vec0->getNumOperands(); i != e; ++i) {
944 Constant *Elem0 = Vec0->getOperand(i);
945 Constant *Elem1 = Vec1->getOperand(i);
946 auto *Int0 = dyn_cast<ConstantInt>(Elem0);
947 if (Int0 && Int0->isZero())
948 continue;
949 auto *Int1 = dyn_cast<ConstantInt>(Elem1);
950 if (Int1 && !Int1->isZero())
951 continue;
952 if (isa<UndefValue>(Elem0) || isa<UndefValue>(Elem1))
953 return false;
954 if (Elem0 == Elem1)
955 continue;
956 return false;
957 }
958 return true;
959 };
960 auto PtrOp = [](const IntrinsicInst *II) {
961 if (II->getIntrinsicID() == Intrinsic::masked_load)
962 return II->getOperand(0);
963 if (II->getIntrinsicID() == Intrinsic::masked_store)
964 return II->getOperand(1);
965 llvm_unreachable("Unexpected IntrinsicInst");
966 };
967 auto MaskOp = [](const IntrinsicInst *II) {
968 if (II->getIntrinsicID() == Intrinsic::masked_load)
969 return II->getOperand(1);
970 if (II->getIntrinsicID() == Intrinsic::masked_store)
971 return II->getOperand(2);
972 llvm_unreachable("Unexpected IntrinsicInst");
973 };
974 auto ThruOp = [](const IntrinsicInst *II) {
975 if (II->getIntrinsicID() == Intrinsic::masked_load)
976 return II->getOperand(2);
977 llvm_unreachable("Unexpected IntrinsicInst");
978 };
979
980 if (PtrOp(Earlier) != PtrOp(Later))
981 return false;
982
983 Intrinsic::ID IDE = Earlier->getIntrinsicID();
984 Intrinsic::ID IDL = Later->getIntrinsicID();
985 // We could really use specific intrinsic classes for masked loads
986 // and stores in IntrinsicInst.h.
987 if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_load) {
988 // Trying to replace later masked load with the earlier one.
989 // Check that the pointers are the same, and
990 // - masks and pass-throughs are the same, or
991 // - replacee's pass-through is "undef" and replacer's mask is a
992 // super-set of the replacee's mask.
993 if (MaskOp(Earlier) == MaskOp(Later) && ThruOp(Earlier) == ThruOp(Later))
994 return true;
995 if (!isa<UndefValue>(ThruOp(Later)))
996 return false;
997 return IsSubmask(MaskOp(Later), MaskOp(Earlier));
998 }
999 if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_load) {
1000 // Trying to replace a load of a stored value with the store's value.
1001 // Check that the pointers are the same, and
1002 // - load's mask is a subset of store's mask, and
1003 // - load's pass-through is "undef".
1004 if (!IsSubmask(MaskOp(Later), MaskOp(Earlier)))
1005 return false;
1006 return isa<UndefValue>(ThruOp(Later));
1007 }
1008 if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_store) {
1009 // Trying to remove a store of the loaded value.
1010 // Check that the pointers are the same, and
1011 // - store's mask is a subset of the load's mask.
1012 return IsSubmask(MaskOp(Later), MaskOp(Earlier));
1013 }
1014 if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_store) {
1015 // Trying to remove a dead store (earlier).
1016 // Check that the pointers are the same,
1017 // - the to-be-removed store's mask is a subset of the other store's
1018 // mask.
1019 return IsSubmask(MaskOp(Earlier), MaskOp(Later));
1020 }
1021 return false;
1022 }
1023
1024 void removeMSSA(Instruction &Inst) {
1025 if (!MSSA)
1026 return;
1027 if (VerifyMemorySSA)
1028 MSSA->verifyMemorySSA();
1029 // Removing a store here can leave MemorySSA in an unoptimized state by
1030 // creating MemoryPhis that have identical arguments and by creating
1031 // MemoryUses whose defining access is not an actual clobber. The phi case
1032 // is handled by MemorySSA when passing OptimizePhis = true to
1033 // removeMemoryAccess. The non-optimized MemoryUse case is lazily updated
1034 // by MemorySSA's getClobberingMemoryAccess.
1035 MSSAUpdater->removeMemoryAccess(&Inst, true);
1036 }
1037};
1038
1039} // end anonymous namespace
1040
1041/// Determine if the memory referenced by LaterInst is from the same heap
1042/// version as EarlierInst.
1043/// This is currently called in two scenarios:
1044///
1045/// load p
1046/// ...
1047/// load p
1048///
1049/// and
1050///
1051/// x = load p
1052/// ...
1053/// store x, p
1054///
1055/// in both cases we want to verify that there are no possible writes to the
1056/// memory referenced by p between the earlier and later instruction.
1057bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
1058 unsigned LaterGeneration,
1059 Instruction *EarlierInst,
1060 Instruction *LaterInst) {
1061 // Check the simple memory generation tracking first.
1062 if (EarlierGeneration == LaterGeneration)
1063 return true;
1064
1065 if (!MSSA)
1066 return false;
1067
1068 // If MemorySSA has determined that one of EarlierInst or LaterInst does not
1069 // read/write memory, then we can safely return true here.
1070 // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
1071 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
1072 // by also checking the MemorySSA MemoryAccess on the instruction. Initial
1073 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
1074 // with the default optimization pipeline.
1075 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
1076 if (!EarlierMA)
1077 return true;
1078 auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
1079 if (!LaterMA)
1080 return true;
1081
1082 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
1083 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
1084 // EarlierInst and LaterInst and neither can any other write that potentially
1085 // clobbers LaterInst.
1086 MemoryAccess *LaterDef;
1087 if (ClobberCounter < ScalarOptions::Global.earlycse_mssa_optimization_cap) {
1088 LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
1089 ClobberCounter++;
1090 } else
1091 LaterDef = LaterMA->getDefiningAccess();
1092
1093 return MSSA->dominates(LaterDef, EarlierMA);
1094}
1095
1096bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
1097 // A location loaded from with an invariant_load is assumed to *never* change
1098 // within the visible scope of the compilation.
1099 if (auto *LI = dyn_cast<LoadInst>(I))
1100 if (LI->hasMetadata(LLVMContext::MD_invariant_load))
1101 return true;
1102
1103 auto MemLocOpt = MemoryLocation::getOrNone(I);
1104 if (!MemLocOpt)
1105 // "target" intrinsic forms of loads aren't currently known to
1106 // MemoryLocation::get. TODO
1107 return false;
1108 MemoryLocation MemLoc = *MemLocOpt;
1109 if (!AvailableInvariants.count(MemLoc))
1110 return false;
1111
1112 // Is the generation at which this became invariant older than the
1113 // current one?
1114 return AvailableInvariants.lookup(MemLoc) <= GenAt;
1115}
1116
1117bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
1118 const CondBrInst *BI, const BasicBlock *BB,
1119 const BasicBlock *Pred) {
1120 assert(BI->getCondition() == CondInst && "Wrong condition?");
1121 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
1122 auto *TorF = (BI->getSuccessor(0) == BB)
1124 : ConstantInt::getFalse(BB->getContext());
1125 auto MatchBinOp = [](Instruction *I, unsigned Opcode, Value *&LHS,
1126 Value *&RHS) {
1127 if (Opcode == Instruction::And &&
1129 return true;
1130 else if (Opcode == Instruction::Or &&
1132 return true;
1133 return false;
1134 };
1135 // If the condition is AND operation, we can propagate its operands into the
1136 // true branch. If it is OR operation, we can propagate them into the false
1137 // branch.
1138 unsigned PropagateOpcode =
1139 (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
1140
1141 bool MadeChanges = false;
1142 SmallVector<Instruction *, 4> WorkList;
1143 SmallPtrSet<Instruction *, 4> Visited;
1144 WorkList.push_back(CondInst);
1145 while (!WorkList.empty()) {
1146 Instruction *Curr = WorkList.pop_back_val();
1147
1148 AvailableValues.insert(Curr, TorF);
1149 LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
1150 << Curr->getName() << "' as " << *TorF << " in "
1151 << BB->getName() << "\n");
1152 if (!DebugCounter::shouldExecute(CSECounter)) {
1153 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1154 } else {
1155 // Replace all dominated uses with the known value.
1156 if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
1157 BasicBlockEdge(Pred, BB))) {
1158 NumCSECVP += Count;
1159 MadeChanges = true;
1160 }
1161 }
1162
1163 Value *LHS, *RHS;
1164 if (MatchBinOp(Curr, PropagateOpcode, LHS, RHS))
1165 for (auto *Op : { LHS, RHS })
1166 if (Instruction *OPI = dyn_cast<Instruction>(Op))
1167 if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
1168 WorkList.push_back(OPI);
1169 }
1170
1171 return MadeChanges;
1172}
1173
1174Value *EarlyCSE::getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
1175 unsigned CurrentGeneration) {
1176 if (InVal.DefInst == nullptr)
1177 return nullptr;
1178 if (auto *MSI = dyn_cast<MemSetInst>(InVal.DefInst)) {
1179 if (!MemInst.isLoad() || MemInst.isVolatile() || !MemInst.isUnordered() ||
1180 MemInst.getMatchingId() != -1)
1181 return nullptr;
1182 if (MSI->isVolatile())
1183 return nullptr;
1184 auto *Val = dyn_cast<ConstantInt>(MSI->getValue());
1185 if (!Val || !Val->isZero())
1186 return nullptr;
1187 auto Len = MSI->getLengthInBytes();
1188 if (!Len)
1189 return nullptr;
1190 Type *InstType = MemInst.getValueType();
1191 if (!InstType)
1192 return nullptr;
1193 TypeSize LoadSize = SQ.DL.getTypeStoreSize(InstType);
1194 if (LoadSize.isScalable() || Len->ult(LoadSize.getFixedValue()))
1195 return nullptr;
1196 if (!isOperatingOnInvariantMemAt(MemInst.get(), InVal.Generation) &&
1197 !isSameMemGeneration(InVal.Generation, CurrentGeneration, InVal.DefInst,
1198 MemInst.get()))
1199 return nullptr;
1200 return Constant::getNullValue(MemInst.getValueType());
1201 }
1202 if (InVal.MatchingId != MemInst.getMatchingId())
1203 return nullptr;
1204 // We don't yet handle removing loads with ordering of any kind.
1205 if (MemInst.isVolatile() || !MemInst.isUnordered())
1206 return nullptr;
1207 // We can't replace an atomic load with one which isn't also atomic.
1208 if (MemInst.isLoad() && !InVal.IsAtomic && MemInst.isAtomic())
1209 return nullptr;
1210 // The value V returned from this function is used differently depending
1211 // on whether MemInst is a load or a store. If it's a load, we will replace
1212 // MemInst with V, if it's a store, we will check if V is the same as the
1213 // available value.
1214 bool MemInstMatching = !MemInst.isLoad();
1215 Instruction *Matching = MemInstMatching ? MemInst.get() : InVal.DefInst;
1216 Instruction *Other = MemInstMatching ? InVal.DefInst : MemInst.get();
1217
1218 // For stores check the result values before checking memory generation
1219 // (otherwise isSameMemGeneration may crash).
1220 Value *Result =
1221 MemInst.isStore()
1222 ? getOrCreateResult(Matching, Other->getType(), /*CanCreate=*/false)
1223 : nullptr;
1224 if (MemInst.isStore() && InVal.DefInst != Result)
1225 return nullptr;
1226
1227 // Deal with non-target memory intrinsics.
1228 bool MatchingNTI = isHandledNonTargetIntrinsic(Matching);
1229 bool OtherNTI = isHandledNonTargetIntrinsic(Other);
1230 if (OtherNTI != MatchingNTI)
1231 return nullptr;
1232 if (OtherNTI && MatchingNTI) {
1233 if (!isNonTargetIntrinsicMatch(cast<IntrinsicInst>(InVal.DefInst),
1234 cast<IntrinsicInst>(MemInst.get())))
1235 return nullptr;
1236 }
1237
1238 if (!isOperatingOnInvariantMemAt(MemInst.get(), InVal.Generation) &&
1239 !isSameMemGeneration(InVal.Generation, CurrentGeneration, InVal.DefInst,
1240 MemInst.get()))
1241 return nullptr;
1242
1243 if (!Result)
1244 Result = getOrCreateResult(Matching, Other->getType(), /*CanCreate=*/true);
1245 return Result;
1246}
1247
1248static void combineIRFlags(Instruction &From, Value *To) {
1249 if (auto *I = dyn_cast<Instruction>(To)) {
1250 // If I being poison triggers UB, there is no need to drop those
1251 // flags. Otherwise, only retain flags present on both I and Inst.
1252 // TODO: Currently some fast-math flags are not treated as
1253 // poison-generating even though they should. Until this is fixed,
1254 // always retain flags present on both I and Inst for floating point
1255 // instructions.
1256 if (isa<FPMathOperator>(I) ||
1257 (I->hasPoisonGeneratingFlags() && !programUndefinedIfPoison(I)))
1258 I->andIRFlags(&From);
1259 }
1260 if (isa<CallBase>(&From) && isa<CallBase>(To)) {
1261 // NB: Intersection of attrs between InVal.first and Inst is overly
1262 // conservative. Since we only CSE readonly functions that have the same
1263 // memory state, we can preserve (or possibly in some cases combine)
1264 // more attributes. Likewise this implies when checking equality of
1265 // callsite for CSEing, we can probably ignore more attributes.
1266 // Generally poison generating attributes need to be handled with more
1267 // care as they can create *new* UB if preserved/combined and violated.
1268 // Attributes that imply immediate UB on the other hand would have been
1269 // violated either way.
1270 bool Success =
1271 cast<CallBase>(To)->tryIntersectAttributes(cast<CallBase>(&From));
1272 assert(Success && "Failed to intersect attributes in callsites that "
1273 "passed identical check");
1274 // For NDEBUG Compile.
1275 (void)Success;
1276 }
1277}
1278
1279bool EarlyCSE::overridingStores(const ParseMemoryInst &Earlier,
1280 const ParseMemoryInst &Later) {
1281 // Can we remove Earlier store because of Later store?
1282
1283 assert(Earlier.isUnordered() && !Earlier.isVolatile() &&
1284 "Violated invariant");
1285 if (Earlier.getPointerOperand() != Later.getPointerOperand())
1286 return false;
1287 if (!Earlier.getValueType() || !Later.getValueType() ||
1288 Earlier.getValueType() != Later.getValueType())
1289 return false;
1290 if (Earlier.getMatchingId() != Later.getMatchingId())
1291 return false;
1292 // At the moment, we don't remove ordered stores, but do remove
1293 // unordered atomic stores. There's no special requirement (for
1294 // unordered atomics) about removing atomic stores only in favor of
1295 // other atomic stores since we were going to execute the non-atomic
1296 // one anyway and the atomic one might never have become visible.
1297 if (!Earlier.isUnordered() || !Later.isUnordered())
1298 return false;
1299
1300 // Deal with non-target memory intrinsics.
1301 bool ENTI = isHandledNonTargetIntrinsic(Earlier.get());
1302 bool LNTI = isHandledNonTargetIntrinsic(Later.get());
1303 if (ENTI && LNTI)
1304 return isNonTargetIntrinsicMatch(cast<IntrinsicInst>(Earlier.get()),
1305 cast<IntrinsicInst>(Later.get()));
1306
1307 // Because of the check above, at least one of them is false.
1308 // For now disallow matching intrinsics with non-intrinsics,
1309 // so assume that the stores match if neither is an intrinsic.
1310 return ENTI == LNTI;
1311}
1312
1313bool EarlyCSE::processNode(DomTreeNode *Node) {
1314 bool Changed = false;
1315 BasicBlock *BB = Node->getBlock();
1316
1317 // If this block has a single predecessor, then the predecessor is the parent
1318 // of the domtree node and all of the live out memory values are still current
1319 // in this block. If this block has multiple predecessors, then they could
1320 // have invalidated the live-out memory values of our parent value. For now,
1321 // just be conservative and invalidate memory if this block has multiple
1322 // predecessors.
1323 if (!BB->getSinglePredecessor())
1324 ++CurrentGeneration;
1325
1326 // If this node has a single predecessor which ends in a conditional branch,
1327 // we can infer the value of the branch condition given that we took this
1328 // path. We need the single predecessor to ensure there's not another path
1329 // which reaches this block where the condition might hold a different
1330 // value. Since we're adding this to the scoped hash table (like any other
1331 // def), it will have been popped if we encounter a future merge block.
1332 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1333 if (auto *BI = dyn_cast<CondBrInst>(Pred->getTerminator())) {
1334 auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
1335 if (CondInst && SimpleValue::canHandle(CondInst))
1336 Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
1337 }
1338 }
1339
1340 /// LastStore - Keep track of the last non-volatile store that we saw... for
1341 /// as long as there in no instruction that reads memory. If we see a store
1342 /// to the same location, we delete the dead store. This zaps trivial dead
1343 /// stores which can occur in bitfield code among other things.
1344 Instruction *LastStore = nullptr;
1345
1346 // See if any instructions in the block can be eliminated. If so, do it. If
1347 // not, add them to AvailableValues.
1348 for (Instruction &Inst : make_early_inc_range(*BB)) {
1349 // Dead instructions should just be removed.
1350 if (isInstructionTriviallyDead(&Inst, &TLI)) {
1351 LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << Inst << '\n');
1352 if (!DebugCounter::shouldExecute(CSECounter)) {
1353 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1354 continue;
1355 }
1356
1357 salvageKnowledge(&Inst, &AC);
1358 salvageDebugInfo(Inst);
1359 removeMSSA(Inst);
1360 Inst.eraseFromParent();
1361 Changed = true;
1362 ++NumSimplify;
1363 continue;
1364 }
1365
1366 // Skip assume intrinsics, they don't really have side effects (although
1367 // they're marked as such to ensure preservation of control dependencies),
1368 // and this pass will not bother with its removal. However, we should mark
1369 // its condition as true for all dominated blocks.
1370 if (auto *Assume = dyn_cast<AssumeInst>(&Inst)) {
1371 auto *CondI = dyn_cast<Instruction>(Assume->getArgOperand(0));
1372 if (CondI && SimpleValue::canHandle(CondI)) {
1373 LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << Inst
1374 << '\n');
1375 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1376 } else
1377 LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << Inst << '\n');
1378 continue;
1379 }
1380
1381 // Likewise, noalias intrinsics don't actually write.
1382 if (match(&Inst,
1384 LLVM_DEBUG(dbgs() << "EarlyCSE skipping noalias intrinsic: " << Inst
1385 << '\n');
1386 continue;
1387 }
1388
1389 // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
1391 LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << Inst << '\n');
1392 continue;
1393 }
1394
1395 // Skip pseudoprobe intrinsics, for the same reason as assume intrinsics.
1397 LLVM_DEBUG(dbgs() << "EarlyCSE skipping pseudoprobe: " << Inst << '\n');
1398 continue;
1399 }
1400
1401 // We can skip all invariant.start intrinsics since they only read memory,
1402 // and we can forward values across it. For invariant starts without
1403 // invariant ends, we can use the fact that the invariantness never ends to
1404 // start a scope in the current generaton which is true for all future
1405 // generations. Also, we dont need to consume the last store since the
1406 // semantics of invariant.start allow us to perform DSE of the last
1407 // store, if there was a store following invariant.start. Consider:
1408 //
1409 // store 30, i8* p
1410 // invariant.start(p)
1411 // store 40, i8* p
1412 // We can DSE the store to 30, since the store 40 to invariant location p
1413 // causes undefined behaviour.
1415 // If there are any uses, the scope might end.
1416 if (!Inst.use_empty())
1417 continue;
1418 MemoryLocation MemLoc =
1420 // Don't start a scope if we already have a better one pushed
1421 if (!AvailableInvariants.count(MemLoc))
1422 AvailableInvariants.insert(MemLoc, CurrentGeneration);
1423 continue;
1424 }
1425
1426 if (isGuard(&Inst)) {
1427 if (auto *CondI =
1428 dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0))) {
1429 if (SimpleValue::canHandle(CondI)) {
1430 // Do we already know the actual value of this condition?
1431 if (auto *KnownCond = AvailableValues.lookup(CondI)) {
1432 // Is the condition known to be true?
1433 if (isa<ConstantInt>(KnownCond) &&
1434 cast<ConstantInt>(KnownCond)->isOne()) {
1436 << "EarlyCSE removing guard: " << Inst << '\n');
1437 salvageKnowledge(&Inst, &AC);
1438 removeMSSA(Inst);
1439 Inst.eraseFromParent();
1440 Changed = true;
1441 continue;
1442 } else
1443 // Use the known value if it wasn't true.
1444 cast<CallInst>(Inst).setArgOperand(0, KnownCond);
1445 }
1446 // The condition we're on guarding here is true for all dominated
1447 // locations.
1448 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1449 }
1450 }
1451
1452 // Guard intrinsics read all memory, but don't write any memory.
1453 // Accordingly, don't update the generation but consume the last store (to
1454 // avoid an incorrect DSE).
1455 LastStore = nullptr;
1456 continue;
1457 }
1458
1459 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
1460 // its simpler value.
1461 if (Value *V = simplifyInstruction(&Inst, SQ)) {
1462 LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << Inst << " to: " << *V
1463 << '\n');
1464 if (!DebugCounter::shouldExecute(CSECounter)) {
1465 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1466 } else {
1467 bool Killed = false;
1468 if (!Inst.use_empty()) {
1469 Inst.replaceAllUsesWith(V);
1470 Changed = true;
1471 }
1472 if (isInstructionTriviallyDead(&Inst, &TLI)) {
1473 salvageKnowledge(&Inst, &AC);
1474 removeMSSA(Inst);
1475 Inst.eraseFromParent();
1476 Changed = true;
1477 Killed = true;
1478 }
1479 if (Changed)
1480 ++NumSimplify;
1481 if (Killed)
1482 continue;
1483 }
1484 }
1485
1486 // Make sure stores prior to a potential unwind are not removed, as the
1487 // caller may read the memory.
1488 if (Inst.mayThrow())
1489 LastStore = nullptr;
1490
1491 // If this is a simple instruction that we can value number, process it.
1492 if (SimpleValue::canHandle(&Inst)) {
1493 if ([[maybe_unused]] auto *CI = dyn_cast<ConstrainedFPIntrinsic>(&Inst)) {
1494 assert(CI->getExceptionBehavior() != fp::ebStrict &&
1495 "Unexpected ebStrict from SimpleValue::canHandle()");
1496 assert((!CI->getRoundingMode() ||
1497 CI->getRoundingMode() != RoundingMode::Dynamic) &&
1498 "Unexpected dynamic rounding from SimpleValue::canHandle()");
1499 }
1500 // See if the instruction has an available value. If so, use it.
1501 if (Value *V = AvailableValues.lookup(&Inst)) {
1502 LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << Inst << " to: " << *V
1503 << '\n');
1504 if (!DebugCounter::shouldExecute(CSECounter)) {
1505 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1506 continue;
1507 }
1508 combineIRFlags(Inst, V);
1509 Inst.replaceAllUsesWith(V);
1510 salvageKnowledge(&Inst, &AC);
1511 removeMSSA(Inst);
1512 Inst.eraseFromParent();
1513 Changed = true;
1514 ++NumCSE;
1515 continue;
1516 }
1517
1518 // Otherwise, just remember that this value is available.
1519 AvailableValues.insert(&Inst, &Inst);
1520 continue;
1521 }
1522
1523 ParseMemoryInst MemInst(&Inst, TTI);
1524 // If this is a non-volatile load, process it.
1525 if (MemInst.isValid() && MemInst.isLoad()) {
1526 // (conservatively) we can't peak past the ordering implied by this
1527 // operation, but we can add this load to our set of available values
1528 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
1529 LastStore = nullptr;
1530 ++CurrentGeneration;
1531 }
1532
1533 if (MemInst.isInvariantLoad()) {
1534 // If we pass an invariant load, we know that memory location is
1535 // indefinitely constant from the moment of first dereferenceability.
1536 // We conservatively treat the invariant_load as that moment. If we
1537 // pass a invariant load after already establishing a scope, don't
1538 // restart it since we want to preserve the earliest point seen.
1539 auto MemLoc = MemoryLocation::get(&Inst);
1540 if (!AvailableInvariants.count(MemLoc))
1541 AvailableInvariants.insert(MemLoc, CurrentGeneration);
1542 }
1543
1544 // If we have an available version of this load, and if it is the right
1545 // generation or the load is known to be from an invariant location,
1546 // replace this instruction.
1547 //
1548 // If either the dominating load or the current load are invariant, then
1549 // we can assume the current load loads the same value as the dominating
1550 // load.
1551 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1552 if (Value *Op = getMatchingValue(InVal, MemInst, CurrentGeneration)) {
1553 LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << Inst
1554 << " to: " << *InVal.DefInst << '\n');
1555 if (!DebugCounter::shouldExecute(CSECounter)) {
1556 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1557 continue;
1558 }
1559 if (InVal.IsLoad)
1560 if (auto *I = dyn_cast<Instruction>(Op))
1561 combineMetadataForCSE(I, &Inst, false);
1562 if (!Inst.use_empty())
1563 Inst.replaceAllUsesWith(Op);
1564 salvageKnowledge(&Inst, &AC);
1565 removeMSSA(Inst);
1566 Inst.eraseFromParent();
1567 Changed = true;
1568 ++NumCSELoad;
1569 continue;
1570 }
1571
1572 // Otherwise, remember that we have this instruction.
1573 AvailableLoads.insert(MemInst.getPointerOperand(),
1574 LoadValue(&Inst, CurrentGeneration,
1575 MemInst.getMatchingId(),
1576 MemInst.isAtomic(),
1577 MemInst.isLoad()));
1578 LastStore = nullptr;
1579 continue;
1580 }
1581
1582 // If this instruction may read from memory, forget LastStore. Load/store
1583 // intrinsics will indicate both a read and a write to memory. The target
1584 // may override this (e.g. so that a store intrinsic does not read from
1585 // memory, and thus will be treated the same as a regular store for
1586 // commoning purposes).
1587 if (Inst.mayReadFromMemory() &&
1588 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
1589 LastStore = nullptr;
1590
1591 // If this is a read-only or write-only call, process it. Skip store
1592 // MemInsts, as they will be more precisely handled later on. Also skip
1593 // memsets, as DSE may be able to optimize them better by removing the
1594 // earlier rather than later store.
1595 if (CallValue::canHandle(&Inst) &&
1596 (!MemInst.isValid() || !MemInst.isStore()) && !isa<MemSetInst>(&Inst)) {
1597 // If we have an available version of this call, and if it is the right
1598 // generation, replace this instruction.
1599 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(&Inst);
1600 if (InVal.first != nullptr &&
1601 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
1602 &Inst) &&
1603 InVal.first->mayReadFromMemory() == Inst.mayReadFromMemory()) {
1604 LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << Inst
1605 << " to: " << *InVal.first << '\n');
1606 if (!DebugCounter::shouldExecute(CSECounter)) {
1607 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1608 continue;
1609 }
1610 combineIRFlags(Inst, InVal.first);
1611 if (!Inst.use_empty())
1612 Inst.replaceAllUsesWith(InVal.first);
1613 salvageKnowledge(&Inst, &AC);
1614 removeMSSA(Inst);
1615 Inst.eraseFromParent();
1616 Changed = true;
1617 ++NumCSECall;
1618 continue;
1619 }
1620
1621 // Increase memory generation for writes. Do this before inserting
1622 // the call, so it has the generation after the write occurred.
1623 if (Inst.mayWriteToMemory())
1624 ++CurrentGeneration;
1625
1626 // Otherwise, remember that we have this instruction.
1627 AvailableCalls.insert(&Inst, std::make_pair(&Inst, CurrentGeneration));
1628 continue;
1629 }
1630
1631 // Compare GEP instructions based on offset.
1632 if (GEPValue::canHandle(&Inst)) {
1633 auto *GEP = cast<GetElementPtrInst>(&Inst);
1634 APInt Offset = APInt(SQ.DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1635 GEPValue GEPVal(GEP, GEP->accumulateConstantOffset(SQ.DL, Offset)
1636 ? Offset.trySExtValue()
1637 : std::nullopt);
1638 if (Value *V = AvailableGEPs.lookup(GEPVal)) {
1639 LLVM_DEBUG(dbgs() << "EarlyCSE CSE GEP: " << Inst << " to: " << *V
1640 << '\n');
1641 combineIRFlags(Inst, V);
1642 Inst.replaceAllUsesWith(V);
1643 salvageKnowledge(&Inst, &AC);
1644 removeMSSA(Inst);
1645 Inst.eraseFromParent();
1646 Changed = true;
1647 ++NumCSEGEP;
1648 continue;
1649 }
1650
1651 // Otherwise, just remember that we have this GEP.
1652 AvailableGEPs.insert(GEPVal, &Inst);
1653 continue;
1654 }
1655
1656 // A release fence requires that all stores complete before it, but does
1657 // not prevent the reordering of following loads 'before' the fence. As a
1658 // result, we don't need to consider it as writing to memory and don't need
1659 // to advance the generation. We do need to prevent DSE across the fence,
1660 // but that's handled above.
1661 if (auto *FI = dyn_cast<FenceInst>(&Inst))
1662 if (FI->getOrdering() == AtomicOrdering::Release) {
1663 assert(Inst.mayReadFromMemory() && "relied on to prevent DSE above");
1664 continue;
1665 }
1666
1667 // write back DSE - If we write back the same value we just loaded from
1668 // the same location and haven't passed any intervening writes or ordering
1669 // operations, we can remove the write. The primary benefit is in allowing
1670 // the available load table to remain valid and value forward past where
1671 // the store originally was.
1672 if (MemInst.isValid() && MemInst.isStore()) {
1673 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1674 if (InVal.DefInst &&
1675 InVal.DefInst ==
1676 getMatchingValue(InVal, MemInst, CurrentGeneration)) {
1677 LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << Inst << '\n');
1678 if (!DebugCounter::shouldExecute(CSECounter)) {
1679 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1680 continue;
1681 }
1682 salvageKnowledge(&Inst, &AC);
1683 removeMSSA(Inst);
1684 Inst.eraseFromParent();
1685 Changed = true;
1686 ++NumDSE;
1687 // We can avoid incrementing the generation count since we were able
1688 // to eliminate this store.
1689 continue;
1690 }
1691 }
1692
1693 // Okay, this isn't something we can CSE at all. Check to see if it is
1694 // something that could modify memory. If so, our available memory values
1695 // cannot be used so bump the generation count.
1696 if (Inst.mayWriteToMemory()) {
1697 ++CurrentGeneration;
1698
1699 if (MemInst.isValid() && MemInst.isStore()) {
1700 // We do a trivial form of DSE if there are two stores to the same
1701 // location with no intervening loads. Delete the earlier store.
1702 if (LastStore) {
1703 if (overridingStores(ParseMemoryInst(LastStore, TTI), MemInst)) {
1704 LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1705 << " due to: " << Inst << '\n');
1706 if (!DebugCounter::shouldExecute(CSECounter)) {
1707 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1708 } else {
1709 salvageKnowledge(&Inst, &AC);
1710 removeMSSA(*LastStore);
1711 LastStore->eraseFromParent();
1712 Changed = true;
1713 ++NumDSE;
1714 LastStore = nullptr;
1715 }
1716 }
1717 // fallthrough - we can exploit information about this store
1718 }
1719
1720 // Okay, we just invalidated anything we knew about loaded values. Try
1721 // to salvage *something* by remembering that the stored value is a live
1722 // version of the pointer. It is safe to forward from volatile stores
1723 // to non-volatile loads, so we don't have to check for volatility of
1724 // the store.
1725 AvailableLoads.insert(MemInst.getPointerOperand(),
1726 LoadValue(&Inst, CurrentGeneration,
1727 MemInst.getMatchingId(),
1728 MemInst.isAtomic(),
1729 MemInst.isLoad()));
1730
1731 // Remember that this was the last unordered store we saw for DSE. We
1732 // don't yet handle DSE on ordered or volatile stores since we don't
1733 // have a good way to model the ordering requirement for following
1734 // passes once the store is removed. We could insert a fence, but
1735 // since fences are slightly stronger than stores in their ordering,
1736 // it's not clear this is a profitable transform. Another option would
1737 // be to merge the ordering with that of the post dominating store.
1738 if (MemInst.isUnordered() && !MemInst.isVolatile())
1739 LastStore = &Inst;
1740 else
1741 LastStore = nullptr;
1742 }
1743 }
1744 }
1745
1746 return Changed;
1747}
1748
1749bool EarlyCSE::run() {
1750 // Note, deque is being used here because there is significant performance
1751 // gains over vector when the container becomes very large due to the
1752 // specific access patterns. For more information see the mailing list
1753 // discussion on this:
1754 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
1755 std::deque<StackNode *> nodesToProcess;
1756
1757 bool Changed = false;
1758
1759 // Process the root node.
1760 nodesToProcess.push_back(new StackNode(
1761 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1762 AvailableGEPs, CurrentGeneration, DT.getRootNode(),
1763 DT.getRootNode()->begin(), DT.getRootNode()->end()));
1764
1765 assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it.");
1766
1767 // Process the stack.
1768 while (!nodesToProcess.empty()) {
1769 // Grab the first item off the stack. Set the current generation, remove
1770 // the node from the stack, and process it.
1771 StackNode *NodeToProcess = nodesToProcess.back();
1772
1773 // Initialize class members.
1774 CurrentGeneration = NodeToProcess->currentGeneration();
1775
1776 // Check if the node needs to be processed.
1777 if (!NodeToProcess->isProcessed()) {
1778 // Process the node.
1779 Changed |= processNode(NodeToProcess->node());
1780 NodeToProcess->childGeneration(CurrentGeneration);
1781 NodeToProcess->process();
1782 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1783 // Push the next child onto the stack.
1784 DomTreeNode *child = NodeToProcess->nextChild();
1785 nodesToProcess.push_back(new StackNode(
1786 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1787 AvailableGEPs, NodeToProcess->childGeneration(), child,
1788 child->begin(), child->end()));
1789 } else {
1790 // It has been processed, and there are no more children to process,
1791 // so delete it and pop it off the stack.
1792 delete NodeToProcess;
1793 nodesToProcess.pop_back();
1794 }
1795 } // while (!nodes...)
1796
1797 return Changed;
1798}
1799
1802 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1803 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1804 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1805 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1806 auto *MSSA =
1807 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
1808
1809 EarlyCSE CSE(F.getDataLayout(), TLI, TTI, DT, AC, MSSA);
1810
1811 if (!CSE.run())
1812 return PreservedAnalyses::all();
1813
1816 if (UseMemorySSA)
1818 return PA;
1819}
1820
1822 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1823 static_cast<PassInfoMixin<EarlyCSEPass> *>(this)->printPipeline(
1824 OS, MapClassName2PassName);
1825 OS << '<';
1826 if (UseMemorySSA)
1827 OS << "memssa";
1828 OS << '>';
1829}
1830
1831namespace {
1832
1833/// A simple and fast domtree-based CSE pass.
1834///
1835/// This pass does a simple depth-first walk over the dominator tree,
1836/// eliminating trivially redundant instructions and using instsimplify to
1837/// canonicalize things as it goes. It is intended to be fast and catch obvious
1838/// cases so that instcombine and other passes are more effective. It is
1839/// expected that a later pass of GVN will catch the interesting/hard cases.
1840template<bool UseMemorySSA>
1841class EarlyCSELegacyCommonPass : public FunctionPass {
1842public:
1843 static char ID;
1844
1845 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1846 if (UseMemorySSA)
1848 else
1850 }
1851
1852 bool runOnFunction(Function &F) override {
1853 if (skipFunction(F))
1854 return false;
1855
1856 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1857 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1858 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1859 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1860 auto *MSSA =
1861 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
1862
1863 EarlyCSE CSE(F.getDataLayout(), TLI, TTI, DT, AC, MSSA);
1864
1865 return CSE.run();
1866 }
1867
1868 void getAnalysisUsage(AnalysisUsage &AU) const override {
1869 AU.addRequired<AssumptionCacheTracker>();
1870 AU.addRequired<DominatorTreeWrapperPass>();
1871 AU.addRequired<TargetLibraryInfoWrapperPass>();
1872 AU.addRequired<TargetTransformInfoWrapperPass>();
1873 if (UseMemorySSA) {
1874 AU.addRequired<AAResultsWrapperPass>();
1875 AU.addRequired<MemorySSAWrapperPass>();
1876 AU.addPreserved<MemorySSAWrapperPass>();
1877 }
1878 AU.addPreserved<GlobalsAAWrapperPass>();
1879 AU.addPreserved<AAResultsWrapperPass>();
1880 AU.setPreservesCFG();
1881 }
1882};
1883
1884} // end anonymous namespace
1885
1886using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
1887
1888template<>
1889char EarlyCSELegacyPass::ID = 0;
1890
1891INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1892 false)
1897INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
1898
1899using EarlyCSEMemSSALegacyPass =
1900 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1901
1902template<>
1903char EarlyCSEMemSSALegacyPass::ID = 0;
1904
1906 if (UseMemorySSA)
1907 return new EarlyCSEMemSSALegacyPass();
1908 else
1909 return new EarlyCSELegacyPass();
1910}
1911
1912INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1913 "Early CSE w/ MemorySSA", false, false)
1920INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1921 "Early CSE w/ MemorySSA", false, false)
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isLoad(int Opcode)
static bool isStore(int Opcode)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the BumpPtrAllocator interface.
Atomic ordering constants.
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Optimize for code generation
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines DenseMapInfo traits for DenseMap.
static void combineIRFlags(Instruction &From, Value *To)
EarlyCSELegacyCommonPass< false > EarlyCSELegacyPass
early cse Early CSE w MemorySSA
static unsigned getHashValueImpl(SimpleValue Val)
Definition EarlyCSE.cpp:207
static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS)
Definition EarlyCSE.cpp:328
static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond, Value *&A, Value *&B, SelectPatternFlavor &Flavor)
Match a 'select' including an optional 'not's of the condition.
Definition EarlyCSE.cpp:149
static unsigned hashCallInst(CallInst *CI)
Definition EarlyCSE.cpp:196
This file provides the interface for a simple, fast CSE pass.
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
IRTranslator LLVM IR MI
This header defines various interfaces for pass management in LLVM.
static Constant * getFalse(Type *Ty)
For a boolean type or a vector of boolean type, return false or a vector with every element false.
Value * getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
static bool isInvariantLoad(const Instruction *I, const Value *Ptr, const bool IsKernelFn)
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
const SmallVectorImpl< MachineOperand > & Cond
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
separate const offset from Split GEPs to a variadic base and a constant offset for better CSE
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
bool isProcessed() const
unsigned currentGeneration() const
unsigned childGeneration() const
DomTreeNode::const_iterator end() const
void process()
DomTreeNode * nextChild()
DomTreeNode::const_iterator childIter() const
DomTreeNode * node()
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:278
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
bool onlyWritesMemory(unsigned OpNo) const
bool onlyReadsMemory(unsigned OpNo) const
bool isConvergent() const
Determine if the invoke is convergent.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:579
static bool shouldExecute(CounterInfo &Counter)
iterator begin() const
iterator end() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
This instruction extracts a struct member or array element value from an aggregate value.
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
bool isPresplitCoroutine() const
Determine if the function is presplit coroutine.
Definition Function.h:522
Represents calls to the gc.relocate intrinsic.
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI bool mayThrow(bool IncludePhaseOneUnwind=false) const LLVM_READONLY
Return true if this instruction may throw an exception.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition MemorySSA.h:1035
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:975
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
LLVM_ABI MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:720
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
ScopedHashTableScope< SimpleValue, Value *, DenseMapInfo< SimpleValue >, AllocatorTy > ScopeTy
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Wrapper pass for TargetTransformInfo.
LLVM_ABI bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const
Value * getOperand(unsigned i) const
Definition User.h:207
iterator_range< value_op_iterator > operand_values()
Definition User.h:291
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
bool use_empty() const
Definition Value.h:348
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
auto m_Cmp()
Matches any compare instruction and ignore it.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
constexpr bool isAtomic(const T &...O)
Definition SIDefines.h:390
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ ebStrict
This corresponds to "fpexcept.strict".
Definition FPEnv.h:42
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
Type * getValueType(Value *V, bool ReVec, bool LookThroughCmp)
Returns the "element type" of the given value/instruction V.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1676
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI void initializeEarlyCSEMemSSALegacyPassPass(PassRegistry &)
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:406
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3126
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
LLVM_ABI bool salvageKnowledge(Instruction *I, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Calls BuildAssumeFromInst and if the resulting llvm.assume is valid insert if before I.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
LLVM_ABI FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
LLVM_ABI void initializeEarlyCSELegacyPassPass(PassRegistry &)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
unsigned Generation
static unsigned getHashValue(CallValue Val)
static bool isEqual(CallValue LHS, CallValue RHS)
static bool isEqual(const GEPValue &LHS, const GEPValue &RHS)
static unsigned getHashValue(const GEPValue &Val)
static unsigned getHashValue(SimpleValue Val)
static bool isEqual(SimpleValue LHS, SimpleValue RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
const DataLayout & DL