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