LLVM 24.0.0git
GVN.cpp
Go to the documentation of this file.
1//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
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 global value numbering to eliminate fully redundant
10// instructions. It also performs simple dead load elimination.
11//
12// Note that this pass does the value numbering itself; it does not use the
13// ValueNumbering analysis passes.
14//
15//===----------------------------------------------------------------------===//
16
18#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/Hashing.h"
21#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/SetVector.h"
27#include "llvm/ADT/Statistic.h"
31#include "llvm/Analysis/CFG.h"
36#include "llvm/Analysis/Loads.h"
46#include "llvm/IR/Attributes.h"
47#include "llvm/IR/BasicBlock.h"
48#include "llvm/IR/Constant.h"
49#include "llvm/IR/Constants.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/InstrTypes.h"
54#include "llvm/IR/Instruction.h"
57#include "llvm/IR/LLVMContext.h"
58#include "llvm/IR/Metadata.h"
59#include "llvm/IR/Module.h"
60#include "llvm/IR/PassManager.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Use.h"
64#include "llvm/IR/Value.h"
66#include "llvm/Pass.h"
70#include "llvm/Support/Debug.h"
79#include <algorithm>
80#include <cassert>
81#include <cstdint>
82#include <optional>
83#include <utility>
84#include <variant>
85
86using namespace llvm;
87using namespace llvm::VNCoercion;
88using namespace PatternMatch;
89
90#define DEBUG_TYPE "gvn"
91
92STATISTIC(NumGVNInstr, "Number of instructions deleted");
93STATISTIC(NumGVNLoad, "Number of loads deleted");
94STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
95STATISTIC(NumGVNBlocks, "Number of blocks merged");
96STATISTIC(NumGVNSimpl, "Number of instructions simplified");
97STATISTIC(NumGVNEqProp, "Number of equalities propagated");
98STATISTIC(NumPRELoad, "Number of loads PRE'd");
99STATISTIC(NumPRELoopLoad, "Number of loop loads PRE'd");
100STATISTIC(NumPRELoadMoved2CEPred,
101 "Number of loads moved to predecessor of a critical edge in PRE");
102
103STATISTIC(IsValueFullyAvailableInBlockNumSpeculationsMax,
104 "Number of blocks speculated as available in "
105 "IsValueFullyAvailableInBlock(), max");
106STATISTIC(MaxBBSpeculationCutoffReachedTimes,
107 "Number of times we we reached gvn-max-block-speculations cut-off "
108 "preventing further exploration");
109
110static cl::opt<bool> GVNEnableScalarPRE("enable-scalar-pre", cl::init(true),
111 cl::Hidden);
112static cl::opt<bool> GVNEnableLoadPRE("enable-load-pre", cl::init(true));
113static cl::opt<bool> GVNEnableLoadInLoopPRE("enable-load-in-loop-pre",
114 cl::init(true));
115static cl::opt<bool>
116GVNEnableSplitBackedgeInLoadPRE("enable-split-backedge-in-load-pre",
117 cl::init(false));
118static cl::opt<bool> GVNEnableMemDep("enable-gvn-memdep", cl::init(true));
119static cl::opt<bool> GVNEnableMemorySSA("enable-gvn-memoryssa",
120 cl::init(false));
121
123 "gvn-scan-users-limit", cl::Hidden, cl::init(100),
124 cl::desc("The number of memory accesses to scan in a block in reaching "
125 "memory values analysis (default = 100)"));
126
128 "gvn-max-num-deps", cl::Hidden, cl::init(100),
129 cl::desc("Max number of dependences to attempt Load PRE (default = 100)"));
130
132 "gvn-max-num-reaching-blocks", cl::Hidden, cl::init(200),
133 cl::desc("Max number of blocks scanned per load in the MemorySSA "
134 "reaching-value analysis (default = 200)"));
135
136// This is based on IsValueFullyAvailableInBlockNumSpeculationsMax stat.
138 "gvn-max-block-speculations", cl::Hidden, cl::init(600),
139 cl::desc("Max number of blocks we're willing to speculate on (and recurse "
140 "into) when deducing if a value is fully available or not in GVN "
141 "(default = 600)"));
142
144 "gvn-max-num-visited-insts", cl::Hidden, cl::init(100),
145 cl::desc("Max number of visited instructions when trying to find "
146 "dominating value of select dependency (default = 100)"));
147
149 "gvn-max-num-insns", cl::Hidden, cl::init(100),
150 cl::desc("Max number of instructions to scan in each basic block in GVN "
151 "(default = 100)"));
152
155 bool Commutative = false;
156 // The type is not necessarily the result type of the expression, it may be
157 // any additional type needed to disambiguate the expression.
158 Type *Ty = nullptr;
160
162
164
165 bool operator==(const Expression &Other) const {
166 if (Opcode != Other.Opcode)
167 return false;
168 if (Opcode == ~0U || Opcode == ~1U)
169 return true;
170 if (Ty != Other.Ty)
171 return false;
172 if (VarArgs != Other.VarArgs)
173 return false;
174 if ((!Attrs.isEmpty() || !Other.Attrs.isEmpty()) &&
175 !Attrs.intersectWith(Ty->getContext(), Other.Attrs).has_value())
176 return false;
177 return true;
178 }
179
181 return hash_combine(Value.Opcode, Value.Ty,
182 hash_combine_range(Value.VarArgs));
183 }
184};
185
187 static unsigned getHashValue(const GVNValueTable::Expression &E) {
188 using llvm::hash_value;
189
190 return static_cast<unsigned>(hash_value(E));
191 }
192
193 static bool isEqual(const GVNValueTable::Expression &LHS,
194 const GVNValueTable::Expression &RHS) {
195 return LHS == RHS;
196 }
197};
198
199/// A mapping from value numbers to lists of Value*'s that
200/// have that value number. Use getLeaders to query it.
202public:
204 // Use AssertingVH here to catch dangling Value*'s in the leader table.
205 // Will crash if the value gets deleted before the AssertingVH is
206 // destroyed.
210 };
211
212private:
213 struct LeaderListNode {
214 LeaderTableEntry Entry;
215 LeaderListNode *Next;
216 LeaderListNode(Value *V, const BasicBlock *BB, LeaderListNode *Next)
217 : Entry(V, BB), Next(Next) {}
218 };
219 DenseMap<uint32_t, LeaderListNode> NumToLeaders;
220 BumpPtrAllocator TableAllocator;
221
222public:
224 const LeaderListNode *Current;
225
226 public:
227 using iterator_category = std::forward_iterator_tag;
229 using difference_type = std::ptrdiff_t;
232
233 leader_iterator(const LeaderListNode *C) : Current(C) {}
235 assert(Current && "Dereferenced end of leader list!");
236 Current = Current->Next;
237 return *this;
238 }
239 bool operator==(const leader_iterator &Other) const {
240 return Current == Other.Current;
241 }
242 bool operator!=(const leader_iterator &Other) const {
243 return Current != Other.Current;
244 }
245 reference operator*() const { return Current->Entry; }
246 };
247
249 auto I = NumToLeaders.find(N);
250 if (I == NumToLeaders.end()) {
251 return iterator_range(leader_iterator(nullptr), leader_iterator(nullptr));
252 }
253
254 return iterator_range(leader_iterator(&I->second),
255 leader_iterator(nullptr));
256 }
257
258 LLVM_ABI void insert(uint32_t N, Value *V, const BasicBlock *BB);
259 LLVM_ABI void erase(uint32_t N, Instruction *I, const BasicBlock *BB);
260 void clear() {
261 // Manually destroy non-head nodes (in BumpPtrAllocator) to properly
262 // clean up AssertingVH handles before Reset(). Head nodes are destroyed
263 // by NumToLeaders.clear() below.
264 for (auto &[_, HeadNode] : NumToLeaders) {
265 LeaderListNode *N = HeadNode.Next;
266 while (N) {
267 auto *Next = N->Next;
268 N->~LeaderListNode();
269 N = Next;
270 }
271 }
272 NumToLeaders.clear();
273 TableAllocator.Reset();
274 }
275};
276
277/// The core GVN pass object.
278///
279/// FIXME: We should have a good summary of the GVN algorithm implemented by
280/// this particular pass here.
282 llvm::GVNOptions Options;
283
284public:
285 struct AvailableValue;
287
289
290 /// This removes the specified instruction from
291 /// our various maps and marks it for deletion.
292 void salvageAndRemoveInstruction(Instruction *I);
293
294 DominatorTree &getDominatorTree() const { return *DT; }
295 AAResults *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
296 MemoryDependenceResults &getMemDep() const { return *MD; }
297
298 bool isScalarPREEnabled() const;
299 bool isLoadPREEnabled() const;
300 bool isLoadInLoopPREEnabled() const;
302 bool isMemDepEnabled() const;
303 bool isMemorySSAEnabled() const;
304
305private:
306 friend class llvm::GVNPass;
307 friend class GVNLegacyPass;
308
309 MemoryDependenceResults *MD = nullptr;
310 DominatorTree *DT = nullptr;
311 const TargetLibraryInfo *TLI = nullptr;
312 AssumptionCache *AC = nullptr;
313 SetVector<BasicBlock *> DeadBlocks;
314 OptimizationRemarkEmitter *ORE = nullptr;
315 ImplicitControlFlowTracking *ICF = nullptr;
316 LoopInfo *LI = nullptr;
317 AAResults *AA = nullptr;
318 MemorySSAUpdater *MSSAU = nullptr;
319
320 GVNValueTable VN;
321
322 GVNLeaderMap LeaderTable;
323
324 // Map the block to reversed postorder traversal number. It is used to
325 // find back edge easily.
327
328 // This is set 'true' initially and also when new blocks have been added to
329 // the function being analyzed. This boolean is used to control the updating
330 // of BlockRPONumber prior to accessing the contents of BlockRPONumber.
331 bool InvalidBlockRPONumbers = true;
332
333 using LoadDepVect = SmallVector<NonLocalDepResult, 64>;
334 using AvailValInBlkVect = SmallVector<AvailableValueInBlock, 64>;
335 using UnavailBlkVect = SmallVector<BasicBlock *, 64>;
336
337 bool run(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
338 const TargetLibraryInfo &RunTLI, AAResults &RunAA,
340 OptimizationRemarkEmitter *ORE, MemorySSA *MSSA = nullptr);
341
342 // List of critical edges to be split between iterations.
344
345 enum class DepKind {
346 Other = 0, // Unknown value.
347 Def, // Exactly overlapping locations.
348 Clobber, // Reaching value superset of needed bits.
349 Select, // Reaching value is a select of two reaching addresses.
350 };
351
352 // Describe a memory location value, such that there exists a path to a point
353 // in the program, along which that memory location is not modified.
354 struct ReachingMemVal {
355 DepKind Kind;
357 const Value *Addr;
358 Instruction *Inst;
359 int32_t Offset;
360 // For DepKind::Select only: the condition and the two addresses referenced
361 // by the "true" and "false" side of the select-dependent load.
362 const Value *SelCond = nullptr;
363 const Value *SelTrueAddr = nullptr;
364 const Value *SelFalseAddr = nullptr;
365
366 static ReachingMemVal getUnknown(BasicBlock *BB, const Value *Addr,
367 Instruction *Inst = nullptr) {
368 return {DepKind::Other, BB, Addr, Inst, -1};
369 }
370
371 static ReachingMemVal getDef(const Value *Addr, Instruction *Inst) {
372 return {DepKind::Def, Inst->getParent(), Addr, Inst, -1};
373 }
374
375 static ReachingMemVal getClobber(const Value *Addr, Instruction *Inst,
376 int32_t Offset = -1) {
377 return {DepKind::Clobber, Inst->getParent(), Addr, Inst, Offset};
378 }
379
380 static ReachingMemVal getSelect(BasicBlock *BB, const Value *Cond,
381 const Value *TrueAddr,
382 const Value *FalseAddr) {
383 return {DepKind::Select, BB, nullptr, nullptr, -1, Cond,
384 TrueAddr, FalseAddr};
385 }
386 };
387
388 struct DependencyBlockInfo {
389 DependencyBlockInfo() = delete;
390 DependencyBlockInfo(const PHITransAddr &Addr, MemoryAccess *ClobberMA)
391 : Addr(Addr), InitialClobberMA(ClobberMA), ClobberMA(ClobberMA),
392 ForceUnknown(false), Visited(false) {}
393 PHITransAddr Addr;
394 MemoryAccess *InitialClobberMA;
395 MemoryAccess *ClobberMA;
396 std::optional<ReachingMemVal> MemVal;
397 bool ForceUnknown : 1;
398 bool Visited : 1;
399 };
400
401 using DependencyBlockSet = DenseMap<BasicBlock *, DependencyBlockInfo>;
402
403 std::optional<GVNPassImpl::ReachingMemVal> scanMemoryAccessesUsers(
404 const MemoryLocation &Loc, bool IsInvariantLoad, BasicBlock *BB,
405 const SmallVectorImpl<MemoryAccess *> &ClobbersList, MemorySSA &MSSA,
406 BatchAAResults &AA, LoadInst *L = nullptr);
407
408 std::optional<GVNPassImpl::ReachingMemVal>
409 accessMayModifyLocation(MemoryAccess *ClobberMA, const MemoryLocation &Loc,
410 Align LoadAlign, bool IsInvariantLoad, BasicBlock *BB,
411 MemorySSA &MSSA, BatchAAResults &AA);
412
413 bool collectPredecessors(BasicBlock *BB, const PHITransAddr &Addr,
414 MemoryAccess *ClobberMA, DependencyBlockSet &Blocks,
415 SmallVectorImpl<BasicBlock *> &Worklist);
416
417 void collectClobberList(SmallVectorImpl<MemoryAccess *> &Clobbers,
418 BasicBlock *BB, const DependencyBlockInfo &StartInfo,
419 const DependencyBlockSet &Blocks, MemorySSA &MSSA);
420
421 bool findReachingValuesForLoad(LoadInst *Inst,
422 SmallVectorImpl<ReachingMemVal> &Values,
423 MemorySSA &MSSA, AAResults &AA);
424
425 // Helper functions of redundant load elimination.
426 bool processLoad(LoadInst *L);
427 bool processMaskedLoad(IntrinsicInst *I);
428 bool processNonLocalLoad(LoadInst *L);
429 bool processNonLocalLoad(LoadInst *L, SmallVectorImpl<ReachingMemVal> &Deps);
430 bool processAssumeIntrinsic(AssumeInst *II);
431
432 /// Given a local dependency (Def or Clobber) determine if a value is
433 /// available for the load.
434 std::optional<AvailableValue>
435 analyzeLoadAvailability(LoadInst *Load, const ReachingMemVal &Dep,
436 Value *Address);
437
438 /// Given a select-dependency for the load (the load address is a select of
439 /// \p TrueAddr and \p FalseAddr guarded by \p Cond), determine whether a
440 /// value is available by finding dominating values for both addresses. If
441 /// so, the load can be rematerialized as a select of those two values.
442 std::optional<AvailableValue>
443 analyzeSelectAvailability(LoadInst *Load, Value *Cond, Value *TrueAddr,
444 Value *FalseAddr, Instruction *From);
445
446 /// Given a list of non-local dependencies, determine if a value is
447 /// available for the load in each specified block. If it is, add it to
448 /// ValuesPerBlock. If not, add it to UnavailableBlocks.
449 void analyzeLoadAvailability(LoadInst *Load,
450 SmallVectorImpl<ReachingMemVal> &Deps,
451 AvailValInBlkVect &ValuesPerBlock,
452 UnavailBlkVect &UnavailableBlocks);
453
454 /// Given a critical edge from Pred to LoadBB, find a load instruction
455 /// which is identical to Load from another successor of Pred.
456 LoadInst *findLoadToHoistIntoPred(BasicBlock *Pred, BasicBlock *LoadBB,
457 LoadInst *Load);
458
459 bool performLoadPRE(LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
460 UnavailBlkVect &UnavailableBlocks);
461
462 /// Try to replace a load which executes on each loop iteraiton with Phi
463 /// translation of load in preheader and load(s) in conditionally executed
464 /// paths.
465 bool performLoopLoadPRE(LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
466 UnavailBlkVect &UnavailableBlocks);
467
468 /// Eliminates partially redundant \p Load, replacing it with \p
469 /// AvailableLoads (connected by Phis if needed).
470 void eliminatePartiallyRedundantLoad(
471 LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
472 MapVector<BasicBlock *, Value *> &AvailableLoads,
473 MapVector<BasicBlock *, LoadInst *> *CriticalEdgePredAndLoad);
474
475 // Other helper routines.
476 bool processInstruction(Instruction *I);
477 bool processBlock(BasicBlock *BB);
478 bool iterateOnFunction(Function &F);
479 bool performPRE(Function &F);
480 bool performScalarPRE(Instruction *I);
481 bool performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
482 BasicBlock *Curr, unsigned int ValNo);
483 Value *findLeader(const BasicBlock *BB, uint32_t Num);
484 void cleanupGlobalSets();
485 void removeInstruction(Instruction *I);
486 void verifyRemoved(const Instruction *I) const;
487 bool splitCriticalEdges();
488 BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
489 bool
490 propagateEquality(Value *LHS, Value *RHS,
491 const std::variant<BasicBlockEdge, Instruction *> &Root);
492 bool processFoldableCondBr(CondBrInst *BI);
493 void addDeadBlock(BasicBlock *BB);
494 void assignValNumForDeadCode();
495 void assignBlockRPONumber(Function &F);
496};
497
498/// Represents a particular available value that we know how to materialize.
499/// Materialization of an AvailableValue never fails. An AvailableValue is
500/// implicitly associated with a rematerialization point which is the
501/// location of the instruction from which it was formed.
503 enum class ValType {
504 SimpleVal, // A simple offsetted value that is accessed.
505 LoadVal, // A value produced by a load.
506 MemIntrin, // A memory intrinsic which is loaded from.
507 UndefVal, // A UndefValue representing a value from dead block (which
508 // is not yet physically removed from the CFG).
509 SelectVal, // A pointer select which is loaded from and for which the load
510 // can be replace by a value select.
511 };
512
513 /// Val - The value that is live out of the block.
515 /// Kind of the live-out value.
517
518 /// Offset - The byte offset in Val that is interesting for the load query.
519 unsigned Offset = 0;
520 /// V1, V2 - The dominating non-clobbered values of SelectVal.
521 Value *V1 = nullptr, *V2 = nullptr;
522
523 static AvailableValue get(Value *V, unsigned Offset = 0) {
524 AvailableValue Res;
525 Res.Val = V;
527 Res.Offset = Offset;
528 return Res;
529 }
530
531 static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) {
532 AvailableValue Res;
533 Res.Val = MI;
535 Res.Offset = Offset;
536 return Res;
537 }
538
539 static AvailableValue getLoad(LoadInst *Load, unsigned Offset = 0) {
540 AvailableValue Res;
541 Res.Val = Load;
543 Res.Offset = Offset;
544 return Res;
545 }
546
548 AvailableValue Res;
549 Res.Val = nullptr;
551 Res.Offset = 0;
552 return Res;
553 }
554
556 AvailableValue Res;
557 Res.Val = Cond;
559 Res.Offset = 0;
560 Res.V1 = V1;
561 Res.V2 = V2;
562 return Res;
563 }
564
565 bool isSimpleValue() const { return Kind == ValType::SimpleVal; }
566 bool isCoercedLoadValue() const { return Kind == ValType::LoadVal; }
567 bool isMemIntrinValue() const { return Kind == ValType::MemIntrin; }
568 bool isUndefValue() const { return Kind == ValType::UndefVal; }
569 bool isSelectValue() const { return Kind == ValType::SelectVal; }
570
572 assert(isSimpleValue() && "Wrong accessor");
573 return Val;
574 }
575
577 assert(isCoercedLoadValue() && "Wrong accessor");
578 return cast<LoadInst>(Val);
579 }
580
582 assert(isMemIntrinValue() && "Wrong accessor");
583 return cast<MemIntrinsic>(Val);
584 }
585
587 assert(isSelectValue() && "Wrong accessor");
588 return Val;
589 }
590
591 /// Emit code at the specified insertion point to adjust the value defined
592 /// here to the specified type. This handles various coercion cases.
594};
595
596/// Represents an AvailableValue which can be rematerialized at the end of
597/// the associated BasicBlock.
599 /// BB - The basic block in question.
600 BasicBlock *BB = nullptr;
601
602 /// AV - The actual available value.
604
607 Res.BB = BB;
608 Res.AV = std::move(AV);
609 return Res;
610 }
611
613 unsigned Offset = 0) {
614 return get(BB, AvailableValue::get(V, Offset));
615 }
616
620
621 /// Emit code at the end of this block to adjust the value defined here to
622 /// the specified type. This handles various coercion cases.
624 return AV.MaterializeAdjustedValue(Load, BB->getTerminator());
625 }
626};
627
628//===----------------------------------------------------------------------===//
629// ValueTable Internal Functions
630//===----------------------------------------------------------------------===//
631
632GVNValueTable::Expression GVNValueTable::createExpr(Instruction *I) {
634 E.Ty = I->getType();
635 E.Opcode = I->getOpcode();
636 if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(I)) {
637 // gc.relocate is 'special' call: its second and third operands are
638 // not real values, but indices into statepoint's argument list.
639 // Use the refered to values for purposes of identity.
640 E.VarArgs.push_back(lookupOrAdd(GCR->getOperand(0)));
641 E.VarArgs.push_back(lookupOrAdd(GCR->getBasePtr()));
642 E.VarArgs.push_back(lookupOrAdd(GCR->getDerivedPtr()));
643 } else {
644 for (Use &Op : I->operands())
645 E.VarArgs.push_back(lookupOrAdd(Op));
646 }
647 if (I->isCommutative()) {
648 // Ensure that commutative instructions that only differ by a permutation
649 // of their operands get the same value number by sorting the operand value
650 // numbers. Since commutative operands are the 1st two operands it is more
651 // efficient to sort by hand rather than using, say, std::sort.
652 assert(I->getNumOperands() >= 2 && "Unsupported commutative instruction!");
653 if (E.VarArgs[0] > E.VarArgs[1])
654 std::swap(E.VarArgs[0], E.VarArgs[1]);
655 E.Commutative = true;
656 }
657
658 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
659 E.VarArgs.append(IVI->idx_begin(), IVI->idx_end());
660 } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
661 ArrayRef<int> ShuffleMask = SVI->getShuffleMask();
662 E.VarArgs.append(ShuffleMask.begin(), ShuffleMask.end());
663 } else if (auto *CB = dyn_cast<CallBase>(I)) {
664 E.Attrs = CB->getAttributes();
665 }
666
667 return E;
668}
669
671GVNValueTable::createCmpExpr(unsigned Opcode, CmpInst::Predicate Predicate,
672 Value *LHS, Value *RHS) {
673 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
674 "Not a comparison!");
677 E.VarArgs.push_back(lookupOrAdd(LHS));
678 E.VarArgs.push_back(lookupOrAdd(RHS));
679
680 // Sort the operand value numbers so x<y and y>x get the same value number.
681 if (E.VarArgs[0] > E.VarArgs[1]) {
682 std::swap(E.VarArgs[0], E.VarArgs[1]);
684 }
685 E.Opcode = (Opcode << 8) | Predicate;
686 E.Commutative = true;
687 return E;
688}
689
691GVNValueTable::createExtractValueExpr(ExtractValueInst *EI) {
692 assert(EI && "Not an ExtractValueInst?");
694 E.Ty = EI->getType();
695 E.Opcode = 0;
696
697 WithOverflowInst *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand());
698 if (WO != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
699 // EI is an extract from one of our with.overflow intrinsics. Synthesize
700 // a semantically equivalent expression instead of an extract value
701 // expression.
702 E.Opcode = WO->getBinaryOp();
703 E.VarArgs.push_back(lookupOrAdd(WO->getLHS()));
704 E.VarArgs.push_back(lookupOrAdd(WO->getRHS()));
705 return E;
706 }
707
708 // Not a recognised intrinsic. Fall back to producing an extract value
709 // expression.
710 E.Opcode = EI->getOpcode();
711 for (Use &Op : EI->operands())
712 E.VarArgs.push_back(lookupOrAdd(Op));
713
714 append_range(E.VarArgs, EI->indices());
715
716 return E;
717}
718
719GVNValueTable::Expression GVNValueTable::createGEPExpr(GetElementPtrInst *GEP) {
721 Type *PtrTy = GEP->getType()->getScalarType();
722 const DataLayout &DL = GEP->getDataLayout();
723 unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy);
724 SmallMapVector<Value *, APInt, 4> VariableOffsets;
725 APInt ConstantOffset(BitWidth, 0);
726 if (GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset)) {
727 // Convert into offset representation, to recognize equivalent address
728 // calculations that use different type encoding.
729 LLVMContext &Context = GEP->getContext();
730 E.Opcode = GEP->getOpcode();
731 E.Ty = nullptr;
732 E.VarArgs.push_back(lookupOrAdd(GEP->getPointerOperand()));
733 for (const auto &[V, Scale] : VariableOffsets) {
734 E.VarArgs.push_back(lookupOrAdd(V));
735 E.VarArgs.push_back(lookupOrAdd(ConstantInt::get(Context, Scale)));
736 }
737 if (!ConstantOffset.isZero())
738 E.VarArgs.push_back(
739 lookupOrAdd(ConstantInt::get(Context, ConstantOffset)));
740 } else {
741 // If converting to offset representation fails (for scalable vectors),
742 // fall back to type-based implementation.
743 E.Opcode = GEP->getOpcode();
744 E.Ty = GEP->getSourceElementType();
745 for (Use &Op : GEP->operands())
746 E.VarArgs.push_back(lookupOrAdd(Op));
747 }
748 return E;
749}
750
751//===----------------------------------------------------------------------===//
752// ValueTable External Functions
753//===----------------------------------------------------------------------===//
754
760
761/// add - Insert a value into the table with a specified value number.
763 ValueNumbering.insert(std::make_pair(V, Num));
764 if (PHINode *PN = dyn_cast<PHINode>(V))
765 NumberingPhi[Num] = PN;
766}
767
768/// Include the incoming memory state into the hash of the expression for the
769/// given instruction. If the incoming memory state is:
770/// * LiveOnEntry, add the value number of the entry block,
771/// * a MemoryPhi, add the value number of the basic block corresponding to that
772/// MemoryPhi,
773/// * a MemoryDef, add the value number of the memory setting instruction.
774void GVNValueTable::addMemoryStateToExp(Instruction *I, Expression &Exp) {
775 assert(MSSA && "addMemoryStateToExp should not be called without MemorySSA");
776 assert(MSSA->getMemoryAccess(I) && "Instruction does not access memory");
778 Exp.VarArgs.push_back(lookupOrAdd(MA));
779}
780
781uint32_t GVNValueTable::lookupOrAddCall(CallInst *C) {
782 // FIXME: Currently the calls which may access the thread id may
783 // be considered as not accessing the memory. But this is
784 // problematic for coroutines, since coroutines may resume in a
785 // different thread. So we disable the optimization here for the
786 // correctness. However, it may block many other correct
787 // optimizations. Revert this one when we detect the memory
788 // accessing kind more precisely.
789 if (C->getFunction()->isPresplitCoroutine()) {
790 ValueNumbering[C] = NextValueNumber;
791 return NextValueNumber++;
792 }
793
794 // Do not combine convergent calls since they implicitly depend on the set of
795 // threads that is currently executing, and they might be in different basic
796 // blocks.
797 if (C->isConvergent()) {
798 ValueNumbering[C] = NextValueNumber;
799 return NextValueNumber++;
800 }
801
802 // Conservatively assign unique value numbers to calls with operand bundles.
803 // TODO: Bundle names could be included in the value numbering expression to
804 // allow combining calls with identical bundles.
805 if (C->hasOperandBundles()) {
806 ValueNumbering[C] = NextValueNumber;
807 return NextValueNumber++;
808 }
809
810 if (AA->doesNotAccessMemory(C)) {
811 Expression Exp = createExpr(C);
812 uint32_t E = assignExpNewValueNum(Exp).first;
813 ValueNumbering[C] = E;
814 return E;
815 }
816
817 if (MD && AA->onlyReadsMemory(C)) {
818 Expression Exp = createExpr(C);
819 auto [E, IsValNumNew] = assignExpNewValueNum(Exp);
820 if (IsValNumNew) {
821 ValueNumbering[C] = E;
822 return E;
823 }
824
825 MemDepResult LocalDep = MD->getDependency(C);
826
827 if (!LocalDep.isDef() && !LocalDep.isNonLocal()) {
828 ValueNumbering[C] = NextValueNumber;
829 return NextValueNumber++;
830 }
831
832 if (LocalDep.isDef()) {
833 // For masked load/store intrinsics, the local_dep may actually be
834 // a normal load or store instruction.
835 CallInst *LocalDepCall = dyn_cast<CallInst>(LocalDep.getInst());
836
837 if (!LocalDepCall || LocalDepCall->arg_size() != C->arg_size()) {
838 ValueNumbering[C] = NextValueNumber;
839 return NextValueNumber++;
840 }
841
842 for (unsigned I = 0, E = C->arg_size(); I < E; ++I) {
843 uint32_t CVN = lookupOrAdd(C->getArgOperand(I));
844 uint32_t LocalDepCallVN = lookupOrAdd(LocalDepCall->getArgOperand(I));
845 if (CVN != LocalDepCallVN) {
846 ValueNumbering[C] = NextValueNumber;
847 return NextValueNumber++;
848 }
849 }
850
851 uint32_t V = lookupOrAdd(LocalDepCall);
852 ValueNumbering[C] = V;
853 return V;
854 }
855
856 // Non-local case.
858 MD->getNonLocalCallDependency(C);
859 // FIXME: Move the checking logic to MemDep!
860 CallInst *CDep = nullptr;
861
862 // Check to see if we have a single dominating call instruction that is
863 // identical to C.
864 for (const NonLocalDepEntry &I : Deps) {
865 if (I.getResult().isNonLocal())
866 continue;
867
868 // We don't handle non-definitions. If we already have a call, reject
869 // instruction dependencies.
870 if (!I.getResult().isDef() || CDep != nullptr) {
871 CDep = nullptr;
872 break;
873 }
874
875 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I.getResult().getInst());
876 // FIXME: All duplicated with non-local case.
877 if (NonLocalDepCall && DT->properlyDominates(I.getBB(), C->getParent())) {
878 CDep = NonLocalDepCall;
879 continue;
880 }
881
882 CDep = nullptr;
883 break;
884 }
885
886 if (!CDep) {
887 ValueNumbering[C] = NextValueNumber;
888 return NextValueNumber++;
889 }
890
891 if (CDep->arg_size() != C->arg_size()) {
892 ValueNumbering[C] = NextValueNumber;
893 return NextValueNumber++;
894 }
895 for (unsigned I = 0, E = C->arg_size(); I < E; ++I) {
896 uint32_t CVN = lookupOrAdd(C->getArgOperand(I));
897 uint32_t CDepVN = lookupOrAdd(CDep->getArgOperand(I));
898 if (CVN != CDepVN) {
899 ValueNumbering[C] = NextValueNumber;
900 return NextValueNumber++;
901 }
902 }
903
904 uint32_t V = lookupOrAdd(CDep);
905 ValueNumbering[C] = V;
906 return V;
907 }
908
909 if (MSSA && IsMSSAEnabled && AA->onlyReadsMemory(C)) {
910 Expression Exp = createExpr(C);
911 addMemoryStateToExp(C, Exp);
912 auto [V, _] = assignExpNewValueNum(Exp);
913 ValueNumbering[C] = V;
914 return V;
915 }
916
917 ValueNumbering[C] = NextValueNumber;
918 return NextValueNumber++;
919}
920
921/// Returns the value number for the specified load or store instruction.
922uint32_t GVNValueTable::computeLoadStoreVN(Instruction *I) {
923 if (!MSSA || !IsMSSAEnabled) {
924 ValueNumbering[I] = NextValueNumber;
925 return NextValueNumber++;
926 }
927
929 Exp.Ty = I->getType();
930 Exp.Opcode = I->getOpcode();
931 for (Use &Op : I->operands())
932 Exp.VarArgs.push_back(lookupOrAdd(Op));
933 addMemoryStateToExp(I, Exp);
934
935 auto [V, _] = assignExpNewValueNum(Exp);
936 ValueNumbering[I] = V;
937 return V;
938}
939
940/// Returns true if a value number exists for the specified value.
942 return ValueNumbering.contains(V);
943}
944
946 return MSSA->isLiveOnEntryDef(MA) || isa<MemoryPhi>(MA)
947 ? lookupOrAdd(MA->getBlock())
948 : lookupOrAdd(cast<MemoryUseOrDef>(MA)->getMemoryInst());
949}
950
951/// lookupOrAdd - Returns the value number for the specified value, assigning
952/// it a new number if it did not have one before.
954 auto VI = ValueNumbering.find(V);
955 if (VI != ValueNumbering.end())
956 return VI->second;
957
958 auto *I = dyn_cast<Instruction>(V);
959 if (!I) {
960 ValueNumbering[V] = NextValueNumber;
961 if (isa<BasicBlock>(V))
962 NumberingBB[NextValueNumber] = cast<BasicBlock>(V);
963 return NextValueNumber++;
964 }
965
966 Expression Exp;
967 switch (I->getOpcode()) {
968 case Instruction::Call:
969 return lookupOrAddCall(cast<CallInst>(I));
970 case Instruction::FNeg:
971 case Instruction::Add:
972 case Instruction::FAdd:
973 case Instruction::Sub:
974 case Instruction::FSub:
975 case Instruction::Mul:
976 case Instruction::FMul:
977 case Instruction::UDiv:
978 case Instruction::SDiv:
979 case Instruction::FDiv:
980 case Instruction::URem:
981 case Instruction::SRem:
982 case Instruction::FRem:
983 case Instruction::Shl:
984 case Instruction::LShr:
985 case Instruction::AShr:
986 case Instruction::And:
987 case Instruction::Or:
988 case Instruction::Xor:
989 case Instruction::Trunc:
990 case Instruction::ZExt:
991 case Instruction::SExt:
992 case Instruction::FPToUI:
993 case Instruction::FPToSI:
994 case Instruction::UIToFP:
995 case Instruction::SIToFP:
996 case Instruction::FPTrunc:
997 case Instruction::FPExt:
998 case Instruction::PtrToInt:
999 case Instruction::PtrToAddr:
1000 case Instruction::IntToPtr:
1001 case Instruction::AddrSpaceCast:
1002 case Instruction::BitCast:
1003 case Instruction::Select:
1004 case Instruction::Freeze:
1005 case Instruction::ExtractElement:
1006 case Instruction::InsertElement:
1007 case Instruction::ShuffleVector:
1008 case Instruction::InsertValue:
1009 Exp = createExpr(I);
1010 break;
1011 case Instruction::ICmp:
1012 case Instruction::FCmp:
1013 Exp = createCmpExpr(I->getOpcode(), cast<CmpInst>(I)->getPredicate(),
1014 I->getOperand(0), I->getOperand(1));
1015 break;
1016 case Instruction::GetElementPtr:
1017 Exp = createGEPExpr(cast<GetElementPtrInst>(I));
1018 break;
1019 case Instruction::ExtractValue:
1020 Exp = createExtractValueExpr(cast<ExtractValueInst>(I));
1021 break;
1022 case Instruction::PHI:
1023 ValueNumbering[V] = NextValueNumber;
1024 NumberingPhi[NextValueNumber] = cast<PHINode>(V);
1025 return NextValueNumber++;
1026 case Instruction::Load:
1027 case Instruction::Store:
1028 return computeLoadStoreVN(I);
1029 default:
1030 ValueNumbering[V] = NextValueNumber;
1031 return NextValueNumber++;
1032 }
1033
1034 uint32_t E = assignExpNewValueNum(Exp).first;
1035 ValueNumbering[V] = E;
1036 return E;
1037}
1038
1039/// Returns the value number of the specified value. Fails if
1040/// the value has not yet been numbered.
1042 auto VI = ValueNumbering.find(V);
1043 if (Verify) {
1044 assert(VI != ValueNumbering.end() && "Value not numbered?");
1045 return VI->second;
1046 }
1047 return (VI != ValueNumbering.end()) ? VI->second : 0;
1048}
1049
1050/// Returns the value number of the given comparison,
1051/// assigning it a new number if it did not have one before. Useful when
1052/// we deduced the result of a comparison, but don't immediately have an
1053/// instruction realizing that comparison to hand.
1055 CmpInst::Predicate Predicate, Value *LHS,
1056 Value *RHS) {
1057 Expression Exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
1058 return assignExpNewValueNum(Exp).first;
1059}
1060
1062 Value *LHS, Value *RHS) {
1063 Expression Exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
1064 return ExpressionNumbering.lookup(Exp);
1065}
1066
1067/// Returns the value number of ptrtoint \p Ptr to \Ty.
1069 Expression Exp(Instruction::PtrToInt);
1070 Exp.Ty = Ty;
1071 Exp.VarArgs.push_back(lookupOrAdd(Ptr));
1072 return ExpressionNumbering.lookup(Exp);
1073}
1074
1075/// Remove all entries from the ValueTable.
1077 ValueNumbering.clear();
1078 ExpressionNumbering.clear();
1079 NumberingPhi.clear();
1080 NumberingBB.clear();
1081 PhiTranslateTable.clear();
1082 NextValueNumber = 1;
1083 Expressions.clear();
1084 ExprIdx.clear();
1085 NextExprNumber = 0;
1086}
1087
1088/// Remove a value from the value numbering.
1090 uint32_t Num = ValueNumbering.lookup(V);
1091 ValueNumbering.erase(V);
1092 // If V is PHINode, V <--> value number is an one-to-one mapping.
1093 if (isa<PHINode>(V))
1094 NumberingPhi.erase(Num);
1095 else if (isa<BasicBlock>(V))
1096 NumberingBB.erase(Num);
1097}
1098
1099/// verifyRemoved - Verify that the value is removed from all internal data
1100/// structures.
1102 assert(!ValueNumbering.contains(V) &&
1103 "Inst still occurs in value numbering map!");
1104}
1105
1106//===----------------------------------------------------------------------===//
1107// LeaderMap External Functions
1108//===----------------------------------------------------------------------===//
1109
1110/// Push a new Value to the LeaderTable onto the list for its value number.
1112 const auto &[It, Inserted] = NumToLeaders.try_emplace(N, V, BB, nullptr);
1113 if (!Inserted) {
1114 // Key already exists: insert new node after the head.
1115 auto *NewSlot = TableAllocator.Allocate<LeaderListNode>();
1116 new (NewSlot) LeaderListNode(V, BB, It->second.Next);
1117 It->second.Next = NewSlot;
1118 }
1119}
1120
1121/// Scan the list of values corresponding to a given
1122/// value number, and remove the given instruction if encountered.
1124 auto It = NumToLeaders.find(N);
1125 if (It == NumToLeaders.end())
1126 return;
1127
1128 LeaderListNode *Prev = nullptr;
1129 LeaderListNode *Curr = &It->second;
1130
1131 while (Curr && (Curr->Entry.Val != I || Curr->Entry.BB != BB)) {
1132 Prev = Curr;
1133 Curr = Curr->Next;
1134 }
1135
1136 if (!Curr)
1137 return;
1138
1139 if (Prev) {
1140 // Non-head node: unlink and destroy.
1141 Prev->Next = Curr->Next;
1142 Curr->~LeaderListNode();
1143 TableAllocator.Deallocate<LeaderListNode>(Curr);
1144 } else {
1145 // Head node (stored by value in DenseMap).
1146 if (!Curr->Next) {
1147 // Only node; erase from map (DenseMap calls the destructor).
1148 NumToLeaders.erase(It);
1149 } else {
1150 // Move second node's data into head, then destroy second node.
1151 LeaderListNode *Next = Curr->Next;
1152 Curr->Entry.Val = std::move(Next->Entry.Val);
1153 Curr->Entry.BB = Next->Entry.BB;
1154 Curr->Next = Next->Next;
1155 Next->~LeaderListNode();
1156 TableAllocator.Deallocate<LeaderListNode>(Next);
1157 }
1158 }
1159}
1160
1161//===----------------------------------------------------------------------===//
1162// GVN Pass
1163//===----------------------------------------------------------------------===//
1164
1166 return Options.AllowScalarPRE.value_or(GVNEnableScalarPRE);
1167}
1168
1170 return Options.AllowLoadPRE.value_or(GVNEnableLoadPRE);
1171}
1172
1174 return Options.AllowLoadInLoopPRE.value_or(GVNEnableLoadInLoopPRE);
1175}
1176
1178 return Options.AllowLoadPRESplitBackedge.value_or(
1180}
1181
1183 // MemDep and MemorySSA are mutually exclusive. parseGVNOptions() enforces
1184 // this for pass parameters, but the -enable-gvn-{memdep,memoryssa} cl::opt
1185 // overrides default independently, so honor MemorySSA winning here too.
1186 if (isMemorySSAEnabled())
1187 return Options.AllowMemDep.value_or(false);
1188 return Options.AllowMemDep.value_or(GVNEnableMemDep);
1189}
1190
1192 return Options.AllowMemorySSA.value_or(GVNEnableMemorySSA);
1193}
1194
1196 GVNPassImpl Impl(Options);
1197
1198 // FIXME: The order of evaluation of these 'getResult' calls is very
1199 // significant! Re-ordering these variables will cause GVN when run alone to
1200 // be less effective! We should fix memdep and basic-aa to not exhibit this
1201 // behavior, but until then don't change the order here.
1202 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1203 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1204 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1205 auto &AA = AM.getResult<AAManager>(F);
1206 auto *MemDep = Impl.isMemDepEnabled()
1208 : nullptr;
1209 auto &LI = AM.getResult<LoopAnalysis>(F);
1210 auto *MSSA = AM.getCachedResult<MemorySSAAnalysis>(F);
1211 if (Impl.isMemorySSAEnabled() && !MSSA) {
1212 assert(!MemDep &&
1213 "On-demand computation of MemSSA implies that MemDep is disabled!");
1214 MSSA = &AM.getResult<MemorySSAAnalysis>(F);
1215 }
1217 bool Changed = Impl.run(F, AC, DT, TLI, AA, MemDep, LI, &ORE,
1218 MSSA ? &MSSA->getMSSA() : nullptr);
1219 if (!Changed)
1220 return PreservedAnalyses::all();
1224 if (MSSA)
1226 PA.preserve<LoopAnalysis>();
1227 return PA;
1228}
1229
1231 salvageKnowledge(I, AC);
1233 removeInstruction(I);
1234}
1235
1237 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1238 static_cast<PassInfoMixin<GVNPass> *>(this)->printPipeline(
1239 OS, MapClassName2PassName);
1240
1241 OS << '<';
1242 if (Options.AllowScalarPRE != std::nullopt)
1243 OS << (*Options.AllowScalarPRE ? "" : "no-") << "scalar-pre;";
1244 if (Options.AllowLoadPRE != std::nullopt)
1245 OS << (*Options.AllowLoadPRE ? "" : "no-") << "load-pre;";
1246 if (Options.AllowLoadPRESplitBackedge != std::nullopt)
1247 OS << (*Options.AllowLoadPRESplitBackedge ? "" : "no-")
1248 << "split-backedge-load-pre;";
1249 if (Options.AllowMemDep != std::nullopt)
1250 OS << (*Options.AllowMemDep ? "" : "no-") << "memdep;";
1251 if (Options.AllowMemorySSA != std::nullopt)
1252 OS << (*Options.AllowMemorySSA ? "" : "no-") << "memoryssa";
1253 OS << '>';
1254}
1255
1256enum class AvailabilityState : char {
1257 /// We know the block *is not* fully available. This is a fixpoint.
1259 /// We know the block *is* fully available. This is a fixpoint.
1261 /// We do not know whether the block is fully available or not,
1262 /// but we are currently speculating that it will be.
1263 /// If it would have turned out that the block was, in fact, not fully
1264 /// available, this would have been cleaned up into an Unavailable.
1266};
1267
1268/// Return true if we can prove that the value
1269/// we're analyzing is fully available in the specified block. As we go, keep
1270/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
1271/// map is actually a tri-state map with the following values:
1272/// 0) we know the block *is not* fully available.
1273/// 1) we know the block *is* fully available.
1274/// 2) we do not know whether the block is fully available or not, but we are
1275/// currently speculating that it will be.
1277 BasicBlock *BB,
1278 DenseMap<BasicBlock *, AvailabilityState> &FullyAvailableBlocks) {
1280 std::optional<BasicBlock *> UnavailableBB;
1281
1282 // The number of times we didn't find an entry for a block in a map and
1283 // optimistically inserted an entry marking block as speculatively available.
1284 unsigned NumNewNewSpeculativelyAvailableBBs = 0;
1285
1286#ifndef NDEBUG
1287 SmallPtrSet<BasicBlock *, 32> NewSpeculativelyAvailableBBs;
1288 SmallVector<BasicBlock *, 32> AvailableBBs;
1289#endif
1290
1291 Worklist.emplace_back(BB);
1292 while (!Worklist.empty()) {
1293 BasicBlock *CurrBB = Worklist.pop_back_val(); // LoadFO - depth-first!
1294 // Optimistically assume that the block is Speculatively Available and check
1295 // to see if we already know about this block in one lookup.
1296 std::pair<DenseMap<BasicBlock *, AvailabilityState>::iterator, bool> IV =
1297 FullyAvailableBlocks.try_emplace(
1299 AvailabilityState &State = IV.first->second;
1300
1301 // Did the entry already exist for this block?
1302 if (!IV.second) {
1303 if (State == AvailabilityState::Unavailable) {
1304 UnavailableBB = CurrBB;
1305 break; // Backpropagate unavailability info.
1306 }
1307
1308#ifndef NDEBUG
1309 AvailableBBs.emplace_back(CurrBB);
1310#endif
1311 continue; // Don't recurse further, but continue processing worklist.
1312 }
1313
1314 // No entry found for block.
1315 ++NumNewNewSpeculativelyAvailableBBs;
1316 bool OutOfBudget = NumNewNewSpeculativelyAvailableBBs > MaxBBSpeculations;
1317
1318 // If we have exhausted our budget, mark this block as unavailable.
1319 // Also, if this block has no predecessors, the value isn't live-in here.
1320 if (OutOfBudget || pred_empty(CurrBB)) {
1321 MaxBBSpeculationCutoffReachedTimes += (int)OutOfBudget;
1323 UnavailableBB = CurrBB;
1324 break; // Backpropagate unavailability info.
1325 }
1326
1327 // Tentatively consider this block as speculatively available.
1328#ifndef NDEBUG
1329 NewSpeculativelyAvailableBBs.insert(CurrBB);
1330#endif
1331 // And further recurse into block's predecessors, in depth-first order!
1332 Worklist.append(pred_begin(CurrBB), pred_end(CurrBB));
1333 }
1334
1335#if LLVM_ENABLE_STATS
1336 IsValueFullyAvailableInBlockNumSpeculationsMax.updateMax(
1337 NumNewNewSpeculativelyAvailableBBs);
1338#endif
1339
1340 // If the block isn't marked as fixpoint yet
1341 // (the Unavailable and Available states are fixpoints).
1342 auto MarkAsFixpointAndEnqueueSuccessors =
1343 [&](BasicBlock *BB, AvailabilityState FixpointState) {
1344 auto It = FullyAvailableBlocks.find(BB);
1345 if (It == FullyAvailableBlocks.end())
1346 return; // Never queried this block, leave as-is.
1347 switch (AvailabilityState &State = It->second) {
1350 return; // Don't backpropagate further, continue processing worklist.
1352 State = FixpointState;
1353#ifndef NDEBUG
1354 assert(NewSpeculativelyAvailableBBs.erase(BB) &&
1355 "Found a speculatively available successor leftover?");
1356#endif
1357 // Queue successors for further processing.
1358 Worklist.append(succ_begin(BB), succ_end(BB));
1359 return;
1360 }
1361 };
1362
1363 if (UnavailableBB) {
1364 // Okay, we have encountered an unavailable block.
1365 // Mark speculatively available blocks reachable from UnavailableBB as
1366 // unavailable as well. Paths are terminated when they reach blocks not in
1367 // FullyAvailableBlocks or they are not marked as speculatively available.
1368 Worklist.clear();
1369 Worklist.append(succ_begin(*UnavailableBB), succ_end(*UnavailableBB));
1370 while (!Worklist.empty())
1371 MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(),
1373 }
1374
1375#ifndef NDEBUG
1376 Worklist.clear();
1377 for (BasicBlock *AvailableBB : AvailableBBs)
1378 Worklist.append(succ_begin(AvailableBB), succ_end(AvailableBB));
1379 while (!Worklist.empty())
1380 MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(),
1382
1383 assert(NewSpeculativelyAvailableBBs.empty() &&
1384 "Must have fixed all the new speculatively available blocks.");
1385#endif
1386
1387 return !UnavailableBB;
1388}
1389
1392
1393/// If the specified OldValue exists in ValuesPerBlock, replace its value with
1394/// NewValue.
1396 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock, Value *OldValue,
1397 Value *NewValue) {
1398 for (AvailableValueInBlock &V : ValuesPerBlock) {
1399 if (V.AV.Val == OldValue)
1400 V.AV.Val = NewValue;
1401 if (V.AV.isSelectValue()) {
1402 if (V.AV.V1 == OldValue)
1403 V.AV.V1 = NewValue;
1404 if (V.AV.V2 == OldValue)
1405 V.AV.V2 = NewValue;
1406 }
1407 }
1408}
1409
1410/// Given a set of loads specified by ValuesPerBlock,
1411/// construct SSA form, allowing us to eliminate Load. This returns the value
1412/// that should be used at Load's definition site.
1413static Value *
1416 DominatorTree &DT) {
1417 // Check for the fully redundant, dominating load case. In this case, we can
1418 // just use the dominating value directly.
1419 if (ValuesPerBlock.size() == 1 &&
1420 DT.properlyDominates(ValuesPerBlock[0].BB, Load->getParent())) {
1421 assert(!ValuesPerBlock[0].AV.isUndefValue() &&
1422 "Dead BB dominate this block");
1423 return ValuesPerBlock[0].MaterializeAdjustedValue(Load);
1424 }
1425
1426 // Otherwise, we have to construct SSA form.
1428 SSAUpdater SSAUpdate(&NewPHIs);
1429 SSAUpdate.Initialize(Load->getType(), Load->getName());
1430
1431 for (const AvailableValueInBlock &AV : ValuesPerBlock) {
1432 BasicBlock *BB = AV.BB;
1433
1434 if (AV.AV.isUndefValue())
1435 continue;
1436
1437 if (SSAUpdate.HasValueForBlock(BB))
1438 continue;
1439
1440 // If the value is the load that we will be eliminating, and the block it's
1441 // available in is the block that the load is in, then don't add it as
1442 // SSAUpdater will resolve the value to the relevant phi which may let it
1443 // avoid phi construction entirely if there's actually only one value.
1444 if (BB == Load->getParent() &&
1445 ((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() == Load) ||
1446 (AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() == Load)))
1447 continue;
1448
1449 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(Load));
1450 }
1451
1452 // Perform PHI construction.
1453 return SSAUpdate.GetValueInMiddleOfBlock(Load->getParent());
1454}
1455
1457 Instruction *InsertPt) const {
1458 Value *Res;
1459 Type *LoadTy = Load->getType();
1460 const DataLayout &DL = Load->getDataLayout();
1461 if (isSimpleValue()) {
1462 Res = getSimpleValue();
1463 if (Res->getType() != LoadTy) {
1464 Res = getValueForLoad(Res, Offset, LoadTy, InsertPt, Load->getFunction());
1465
1466 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset
1467 << " " << *getSimpleValue() << '\n'
1468 << *Res << '\n'
1469 << "\n\n\n");
1470 }
1471 } else if (isCoercedLoadValue()) {
1472 LoadInst *CoercedLoad = getCoercedLoadValue();
1473 if (CoercedLoad->getType() == LoadTy && Offset == 0) {
1474 Res = CoercedLoad;
1475 combineMetadataForCSE(CoercedLoad, Load, false);
1476 } else {
1477 Res = getValueForLoad(CoercedLoad, Offset, LoadTy, InsertPt,
1478 Load->getFunction());
1479 // We are adding a new user for this load, for which the original
1480 // metadata may not hold. Additionally, the new load may have a different
1481 // size and type, so their metadata cannot be combined in any
1482 // straightforward way.
1483 // Drop all metadata that is not known to cause immediate UB on violation,
1484 // unless the load has !noundef, in which case all metadata violations
1485 // will be promoted to UB.
1486 // !noalias and !alias.scope are kept: the load is not moved and still
1487 // accesses the same memory, and these are independent of the load type
1488 // and offset, so they remain valid for the coerced result.
1489 if (!CoercedLoad->hasMetadata(LLVMContext::MD_noundef))
1490 CoercedLoad->dropUnknownNonDebugMetadata(
1491 {LLVMContext::MD_dereferenceable,
1492 LLVMContext::MD_dereferenceable_or_null,
1493 LLVMContext::MD_invariant_load, LLVMContext::MD_invariant_group,
1494 LLVMContext::MD_alias_scope, LLVMContext::MD_noalias});
1495 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset
1496 << " " << *getCoercedLoadValue() << '\n'
1497 << *Res << '\n'
1498 << "\n\n\n");
1499 }
1500 } else if (isMemIntrinValue()) {
1502 InsertPt, DL);
1503 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1504 << " " << *getMemIntrinValue() << '\n'
1505 << *Res << '\n'
1506 << "\n\n\n");
1507 } else if (isSelectValue()) {
1508 // Introduce a new value select for a load from an eligible pointer select.
1510 assert(V1 && V2 && "both value operands of the select must be present");
1511 Res = SelectInst::Create(Cond, V1, V2, "", InsertPt->getIterator());
1512 // We use the DebugLoc from the original load here, as this instruction
1513 // materializes the value that would previously have been loaded.
1514 cast<SelectInst>(Res)->setDebugLoc(Load->getDebugLoc());
1515 } else {
1516 llvm_unreachable("Should not materialize value from dead block");
1517 }
1518 assert(Res && "failed to materialize?");
1519 return Res;
1520}
1521
1522static bool isLifetimeStart(const Instruction *Inst) {
1523 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1524 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1525 return false;
1526}
1527
1528/// Assuming To can be reached from both From and Between, does Between lie on
1529/// every path from From to To?
1530static bool liesBetween(const Instruction *From, Instruction *Between,
1531 const Instruction *To, const DominatorTree *DT) {
1532 if (From->getParent() == Between->getParent())
1533 return DT->dominates(From, Between);
1535 Exclusion.insert(Between->getParent());
1536 return !isPotentiallyReachable(From, To, &Exclusion, DT);
1537}
1538
1540 const DominatorTree *DT) {
1541 Value *PtrOp = Load->getPointerOperand();
1542 if (!PtrOp->hasUseList())
1543 return nullptr;
1544
1545 Instruction *OtherAccess = nullptr;
1546
1547 for (auto *U : PtrOp->users()) {
1548 if (U != Load && (isa<LoadInst>(U) || isa<StoreInst>(U))) {
1549 auto *I = cast<Instruction>(U);
1550 if (I->getFunction() == Load->getFunction() && DT->dominates(I, Load)) {
1551 // Use the most immediately dominating value.
1552 if (OtherAccess) {
1553 if (DT->dominates(OtherAccess, I))
1554 OtherAccess = I;
1555 else
1556 assert(U == OtherAccess || DT->dominates(I, OtherAccess));
1557 } else
1558 OtherAccess = I;
1559 }
1560 }
1561 }
1562
1563 if (OtherAccess)
1564 return OtherAccess;
1565
1566 // There is no dominating use, check if we can find a closest non-dominating
1567 // use that lies between any other potentially available use and Load.
1568 for (auto *U : PtrOp->users()) {
1569 if (U != Load && (isa<LoadInst>(U) || isa<StoreInst>(U))) {
1570 auto *I = cast<Instruction>(U);
1571 if (I->getFunction() == Load->getFunction() &&
1572 isPotentiallyReachable(I, Load, nullptr, DT)) {
1573 if (OtherAccess) {
1574 if (liesBetween(OtherAccess, I, Load, DT)) {
1575 OtherAccess = I;
1576 } else if (!liesBetween(I, OtherAccess, Load, DT)) {
1577 // These uses are both partially available at Load were it not for
1578 // the clobber, but neither lies strictly after the other.
1579 OtherAccess = nullptr;
1580 break;
1581 } // else: keep current OtherAccess since it lies between U and
1582 // Load.
1583 } else {
1584 OtherAccess = I;
1585 }
1586 }
1587 }
1588 }
1589
1590 return OtherAccess;
1591}
1592
1593/// Try to locate the three instruction involved in a missed
1594/// load-elimination case that is due to an intervening store.
1596 const DominatorTree *DT,
1598 using namespace ore;
1599
1600 OptimizationRemarkMissed R(DEBUG_TYPE, "LoadClobbered", Load);
1601 R << "load of type " << NV("Type", Load->getType()) << " not eliminated"
1602 << setExtraArgs();
1603
1604 const Instruction *OtherAccess = findMayClobberedPtrAccess(Load, DT);
1605 if (OtherAccess)
1606 R << " in favor of " << NV("OtherAccess", OtherAccess);
1607
1608 R << " because it is clobbered by " << NV("ClobberedBy", DepInst);
1609
1610 ORE->emit(R);
1611}
1612
1613// Find a dominating value for Loc memory location in the extended basic block
1614// (chain of basic blocks with single predecessors) starting From instruction.
1615// Returns the value from a matching load or a simple store to the same pointer.
1617 Instruction *From, AAResults *AA) {
1618 uint32_t NumVisitedInsts = 0;
1619 BasicBlock *FromBB = From->getParent();
1620 BatchAAResults BatchAA(*AA);
1621 for (BasicBlock *BB = FromBB; BB; BB = BB->getSinglePredecessor())
1622 for (auto *Inst = BB == FromBB ? From : BB->getTerminator();
1623 Inst != nullptr; Inst = Inst->getPrevNode()) {
1624 // Stop the search if limit is reached.
1625 if (++NumVisitedInsts > MaxNumVisitedInsts)
1626 return nullptr;
1627 if (isModSet(BatchAA.getModRefInfo(Inst, Loc))) {
1628 // A simple store to the exact location can forward its value.
1629 if (auto *SI = dyn_cast<StoreInst>(Inst))
1630 if (SI->isSimple() && SI->getPointerOperand() == Loc.Ptr &&
1631 SI->getValueOperand()->getType() == LoadTy)
1632 return SI->getValueOperand();
1633 return nullptr;
1634 }
1635 if (auto *LI = dyn_cast<LoadInst>(Inst))
1636 if (LI->getPointerOperand() == Loc.Ptr && LI->getType() == LoadTy)
1637 return LI;
1638 }
1639 return nullptr;
1640}
1641
1642std::optional<AvailableValue>
1643GVNPassImpl::analyzeSelectAvailability(LoadInst *Load, Value *Cond,
1644 Value *TrueAddr, Value *FalseAddr,
1645 Instruction *From) {
1646 assert(TrueAddr->getType() == Load->getPointerOperandType() &&
1647 "Invalid address type of true side of select dependency");
1648 assert(FalseAddr->getType() == Load->getPointerOperandType() &&
1649 "Invalid address type of false side of select dependency");
1650 // We can convert a load through a select address into a select of the two
1651 // loaded values only if both sides have a dominating, non-clobbered value of
1652 // the right type in the extended basic block ending at From.
1654 Value *V1 = findDominatingValue(Loc.getWithNewPtr(TrueAddr), Load->getType(),
1655 From, getAliasAnalysis());
1656 if (!V1)
1657 return std::nullopt;
1658 Value *V2 = findDominatingValue(Loc.getWithNewPtr(FalseAddr), Load->getType(),
1659 From, getAliasAnalysis());
1660 if (!V2)
1661 return std::nullopt;
1662 return AvailableValue::getSelect(Cond, V1, V2);
1663}
1664
1665std::optional<AvailableValue>
1666GVNPassImpl::analyzeLoadAvailability(LoadInst *Load, const ReachingMemVal &Dep,
1667 Value *Address) {
1668 assert(Load->isUnordered() && "rules below are incorrect for ordered access");
1669 assert((Dep.Kind == DepKind::Def || Dep.Kind == DepKind::Clobber) &&
1670 "expected a local dependence");
1671
1672 Instruction *DepInst = Dep.Inst;
1673
1674 const DataLayout &DL = Load->getDataLayout();
1675 if (Dep.Kind == DepKind::Clobber) {
1676 // If the dependence is to a store that writes to a superset of the bits
1677 // read by the load, we can extract the bits we need for the load from the
1678 // stored value.
1679 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1680 // Can't forward from non-atomic to atomic without violating memory model.
1681 if (Address && Load->isAtomic() <= DepSI->isAtomic()) {
1682 int Offset =
1683 analyzeLoadFromClobberingStore(Load->getType(), Address, DepSI, DL);
1684 if (Offset != -1)
1685 return AvailableValue::get(DepSI->getValueOperand(), Offset);
1686 }
1687 }
1688
1689 // Check to see if we have something like this:
1690 // load i32* P
1691 // load i8* (P+1)
1692 // if we have this, replace the later with an extraction from the former.
1693 if (LoadInst *DepLoad = dyn_cast<LoadInst>(DepInst)) {
1694 // If this is a clobber and L is the first instruction in its block, then
1695 // we have the first instruction in the entry block.
1696 // Can't forward from non-atomic to atomic without violating memory model.
1697 if (DepLoad != Load && Address &&
1698 Load->isAtomic() <= DepLoad->isAtomic()) {
1699 Type *LoadType = Load->getType();
1700 int Offset = Dep.Offset;
1701
1702 if (!isMemorySSAEnabled()) {
1703 // If MD reported clobber, check it was nested.
1704 if (canCoerceMustAliasedValueToLoad(DepLoad, LoadType,
1705 DepLoad->getFunction())) {
1706 const auto ClobberOff = MD->getClobberOffset(DepLoad);
1707 // GVN has no deal with a negative offset.
1708 Offset = (ClobberOff == std::nullopt || *ClobberOff < 0)
1709 ? -1
1710 : *ClobberOff;
1711 }
1712 } else {
1713 if (!canCoerceMustAliasedValueToLoad(DepLoad, LoadType,
1714 DepLoad->getFunction()) ||
1715 Offset < 0)
1716 Offset = -1;
1717 }
1718 if (Offset == -1)
1719 Offset =
1720 analyzeLoadFromClobberingLoad(LoadType, Address, DepLoad, DL);
1721 if (Offset != -1)
1722 return AvailableValue::getLoad(DepLoad, Offset);
1723 }
1724 }
1725
1726 // If the clobbering value is a memset/memcpy/memmove, see if we can
1727 // forward a value on from it.
1728 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1729 if (Address && !Load->isAtomic()) {
1731 DepMI, DL);
1732 if (Offset != -1)
1733 return AvailableValue::getMI(DepMI, Offset);
1734 }
1735 }
1736
1737 // Nothing known about this clobber, have to be conservative.
1738 LLVM_DEBUG(
1739 // fast print dep, using operator<< on instruction is too slow.
1740 dbgs() << "GVN: load "; Load->printAsOperand(dbgs());
1741 dbgs() << " is clobbered by " << *DepInst << '\n';);
1743 reportMayClobberedLoad(Load, DepInst, DT, ORE);
1744
1745 return std::nullopt;
1746 }
1747 assert(Dep.Kind == DepKind::Def && "follows from above");
1748
1749 // Loading the alloca -> undef.
1750 // Loading immediately after lifetime begin -> undef.
1751 if (isa<AllocaInst>(DepInst) || isLifetimeStart(DepInst))
1752 return AvailableValue::get(UndefValue::get(Load->getType()));
1753
1754 if (Constant *InitVal =
1755 getInitialValueOfAllocation(DepInst, TLI, Load->getType()))
1756 return AvailableValue::get(InitVal);
1757
1758 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1759 // Reject loads and stores that are to the same address but are of
1760 // different types if we have to. If the stored value is convertable to
1761 // the loaded value, we can reuse it.
1762 if (!canCoerceMustAliasedValueToLoad(S->getValueOperand(), Load->getType(),
1763 S->getFunction()))
1764 return std::nullopt;
1765
1766 // Can't forward from non-atomic to atomic without violating memory model.
1767 if (S->isAtomic() < Load->isAtomic())
1768 return std::nullopt;
1769
1770 return AvailableValue::get(S->getValueOperand());
1771 }
1772
1773 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1774 // If the types mismatch and we can't handle it, reject reuse of the load.
1775 // If the stored value is larger or equal to the loaded value, we can reuse
1776 // it.
1777 if (!canCoerceMustAliasedValueToLoad(LD, Load->getType(),
1778 LD->getFunction()))
1779 return std::nullopt;
1780
1781 // Can't forward from non-atomic to atomic without violating memory model.
1782 if (LD->isAtomic() < Load->isAtomic())
1783 return std::nullopt;
1784
1785 return AvailableValue::getLoad(LD);
1786 }
1787
1788 // Check if load with Addr dependent from select can be converted to select
1789 // between load values. There must be no instructions between the found
1790 // loads and DepInst that may clobber the loads.
1791 if (auto *Sel = dyn_cast<SelectInst>(DepInst)) {
1792 assert(Sel->getType() == Load->getPointerOperandType());
1793 if (auto AV = analyzeSelectAvailability(Load, Sel->getCondition(),
1794 Sel->getTrueValue(),
1795 Sel->getFalseValue(), DepInst))
1796 return AV;
1797 return std::nullopt;
1798 }
1799
1800 // Unknown def - must be conservative.
1801 LLVM_DEBUG(
1802 // fast print dep, using operator<< on instruction is too slow.
1803 dbgs() << "GVN: load "; Load->printAsOperand(dbgs());
1804 dbgs() << " has unknown def " << *DepInst << '\n';);
1805 return std::nullopt;
1806}
1807
1808void GVNPassImpl::analyzeLoadAvailability(LoadInst *Load,
1810 AvailValInBlkVect &ValuesPerBlock,
1811 UnavailBlkVect &UnavailableBlocks) {
1812 // Filter out useless results (non-locals, etc). Keep track of the blocks
1813 // where we have a value available in repl, also keep track of whether we see
1814 // dependencies that produce an unknown value for the load (such as a call
1815 // that could potentially clobber the load).
1816 for (const auto &Dep : Deps) {
1817 BasicBlock *DepBB = Dep.Block;
1818
1819 if (DeadBlocks.count(DepBB)) {
1820 // Dead dependent mem-op disguise as a load evaluating the same value
1821 // as the load in question.
1822 ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
1823 continue;
1824 }
1825
1826 if (Dep.Kind == DepKind::Other) {
1827 UnavailableBlocks.push_back(DepBB);
1828 continue;
1829 }
1830
1831 // The load address is a select in this block: try to rematerialize the
1832 // load as a select of the two reaching values (one per side). The values
1833 // are searched for at the end of DepBB.
1834 if (Dep.Kind == DepKind::Select) {
1835 if (auto AV = analyzeSelectAvailability(
1836 Load, const_cast<Value *>(Dep.SelCond),
1837 const_cast<Value *>(Dep.SelTrueAddr),
1838 const_cast<Value *>(Dep.SelFalseAddr), DepBB->getTerminator())) {
1839 ValuesPerBlock.push_back(
1840 AvailableValueInBlock::get(DepBB, std::move(*AV)));
1841 } else {
1842 UnavailableBlocks.push_back(DepBB);
1843 }
1844 continue;
1845 }
1846
1847 // The address being loaded in this non-local block may not be the same as
1848 // the pointer operand of the load if PHI translation occurs. Make sure
1849 // to consider the right address.
1850 if (auto AV =
1851 analyzeLoadAvailability(Load, Dep, const_cast<Value *>(Dep.Addr))) {
1852 // subtlety: because we know this was a non-local dependency, we know
1853 // it's safe to materialize anywhere between the instruction within
1854 // DepInfo and the end of it's block.
1855 ValuesPerBlock.push_back(
1856 AvailableValueInBlock::get(DepBB, std::move(*AV)));
1857 } else {
1858 UnavailableBlocks.push_back(DepBB);
1859 }
1860 }
1861
1862 assert(Deps.size() == ValuesPerBlock.size() + UnavailableBlocks.size() &&
1863 "post condition violation");
1864}
1865
1866/// Given the following code, v1 is partially available on some edges, but not
1867/// available on the edge from PredBB. This function tries to find if there is
1868/// another identical load in the other successor of PredBB.
1869///
1870/// v0 = load %addr
1871/// br %LoadBB
1872///
1873/// LoadBB:
1874/// v1 = load %addr
1875/// ...
1876///
1877/// PredBB:
1878/// ...
1879/// br %cond, label %LoadBB, label %SuccBB
1880///
1881/// SuccBB:
1882/// v2 = load %addr
1883/// ...
1884///
1885LoadInst *GVNPassImpl::findLoadToHoistIntoPred(BasicBlock *Pred,
1886 BasicBlock *LoadBB,
1887 LoadInst *Load) {
1888 // For simplicity we handle a Pred has 2 successors only.
1889 auto *Term = Pred->getTerminator();
1890 if (Term->getNumSuccessors() != 2 || Term->isSpecialTerminator())
1891 return nullptr;
1892 auto *SuccBB = Term->getSuccessor(0);
1893 if (SuccBB == LoadBB)
1894 SuccBB = Term->getSuccessor(1);
1895 if (!SuccBB->getSinglePredecessor())
1896 return nullptr;
1897
1898 unsigned int NumInsts = MaxNumInsnsPerBlock;
1899 for (Instruction &Inst : *SuccBB) {
1900 if (Inst.isDebugOrPseudoInst())
1901 continue;
1902 if (--NumInsts == 0)
1903 return nullptr;
1904
1905 if (!Inst.isIdenticalTo(Load))
1906 continue;
1907
1908 bool HasLocalDep = true;
1909 if (!isMemorySSAEnabled()) {
1910 MemDepResult Dep = MD->getDependency(&Inst);
1911 HasLocalDep = !Dep.isNonLocal();
1912 } else {
1913 auto *MSSA = MSSAU->getMemorySSA();
1914 // Do not hoist if the identical load has ordering constraint.
1915 if (auto *MA = MSSA->getMemoryAccess(&Inst); MA && isa<MemoryUse>(MA)) {
1916 auto *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(MA);
1917 HasLocalDep = Clobber->getBlock() == SuccBB;
1918 }
1919 }
1920
1921 // If an identical load doesn't depends on any local instructions, it can
1922 // be safely moved to PredBB.
1923 // Also check for the implicit control flow instructions. See the comments
1924 // in performLoadPRE for details.
1925 if (!HasLocalDep && !ICF->isDominatedByICFIFromSameBlock(&Inst))
1926 return cast<LoadInst>(&Inst);
1927
1928 // Otherwise there is something in the same BB clobbers the memory, we can't
1929 // move this and later load to PredBB.
1930 return nullptr;
1931 }
1932
1933 return nullptr;
1934}
1935
1936void GVNPassImpl::eliminatePartiallyRedundantLoad(
1937 LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
1938 MapVector<BasicBlock *, Value *> &AvailableLoads,
1939 MapVector<BasicBlock *, LoadInst *> *CriticalEdgePredAndLoad) {
1940 for (const auto &AvailableLoad : AvailableLoads) {
1941 BasicBlock *UnavailableBlock = AvailableLoad.first;
1942 Value *LoadPtr = AvailableLoad.second;
1943
1944 auto *NewLoad =
1945 new LoadInst(Load->getType(), LoadPtr, Load->getName() + ".pre",
1946 Load->getProperties(),
1947 UnavailableBlock->getTerminator()->getIterator());
1948 NewLoad->setDebugLoc(Load->getDebugLoc());
1949 if (MSSAU) {
1950 auto *NewAccess = MSSAU->createMemoryAccessInBB(
1951 NewLoad, nullptr, NewLoad->getParent(), MemorySSA::BeforeTerminator);
1952 if (auto *NewDef = dyn_cast<MemoryDef>(NewAccess))
1953 MSSAU->insertDef(NewDef, /*RenameUses=*/true);
1954 else
1955 MSSAU->insertUse(cast<MemoryUse>(NewAccess), /*RenameUses=*/true);
1956 }
1957
1958 // Transfer the old load's AA tags to the new load.
1959 AAMDNodes Tags = Load->getAAMetadata();
1960 if (Tags)
1961 NewLoad->setAAMetadata(Tags);
1962
1963 if (auto *MD = Load->getMetadata(LLVMContext::MD_invariant_load))
1964 NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
1965 if (auto *InvGroupMD = Load->getMetadata(LLVMContext::MD_invariant_group))
1966 NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
1967 if (auto *RangeMD = Load->getMetadata(LLVMContext::MD_range))
1968 NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
1969 if (auto *NoFPClassMD = Load->getMetadata(LLVMContext::MD_nofpclass))
1970 NewLoad->setMetadata(LLVMContext::MD_nofpclass, NoFPClassMD);
1971
1972 if (auto *AccessMD = Load->getMetadata(LLVMContext::MD_access_group))
1973 if (LI->getLoopFor(Load->getParent()) == LI->getLoopFor(UnavailableBlock))
1974 NewLoad->setMetadata(LLVMContext::MD_access_group, AccessMD);
1975
1976 // We do not propagate the old load's debug location, because the new
1977 // load now lives in a different BB, and we want to avoid a jumpy line
1978 // table.
1979 // FIXME: How do we retain source locations without causing poor debugging
1980 // behavior?
1981
1982 // Add the newly created load.
1983 ValuesPerBlock.push_back(
1984 AvailableValueInBlock::get(UnavailableBlock, NewLoad));
1985 if (MD)
1986 MD->invalidateCachedPointerInfo(LoadPtr);
1987 LLVM_DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1988
1989 // For PredBB in CriticalEdgePredAndLoad we need to replace the uses of old
1990 // load instruction with the new created load instruction.
1991 if (CriticalEdgePredAndLoad) {
1992 auto It = CriticalEdgePredAndLoad->find(UnavailableBlock);
1993 if (It != CriticalEdgePredAndLoad->end()) {
1994 ++NumPRELoadMoved2CEPred;
1995 ICF->insertInstructionTo(NewLoad, UnavailableBlock);
1996 LoadInst *OldLoad = It->second;
1997 combineMetadataForCSE(NewLoad, OldLoad, /*DoesKMove=*/true);
1998 OldLoad->replaceAllUsesWith(NewLoad);
1999 replaceValuesPerBlockEntry(ValuesPerBlock, OldLoad, NewLoad);
2000 if (uint32_t ValNo = VN.lookup(OldLoad, false))
2001 LeaderTable.erase(ValNo, OldLoad, OldLoad->getParent());
2002 removeInstruction(OldLoad);
2003 }
2004 }
2005 }
2006
2007 // Perform PHI construction.
2008 Value *V = constructSSAForLoadSet(Load, ValuesPerBlock, getDominatorTree());
2009 // constructSSAForLoadSet is responsible for combining metadata.
2010 ICF->removeUsersOf(Load);
2011 Load->replaceAllUsesWith(V);
2012 if (isa<PHINode>(V))
2013 V->takeName(Load);
2015 I->setDebugLoc(Load->getDebugLoc());
2016 if (MD && V->getType()->isPtrOrPtrVectorTy())
2018 ORE->emit([&]() {
2019 return OptimizationRemark(DEBUG_TYPE, "LoadPRE", Load)
2020 << "load eliminated by PRE";
2021 });
2022 salvageAndRemoveInstruction(Load);
2023}
2024
2025bool GVNPassImpl::performLoadPRE(LoadInst *Load,
2026 AvailValInBlkVect &ValuesPerBlock,
2027 UnavailBlkVect &UnavailableBlocks) {
2028 // Okay, we have *some* definitions of the value. This means that the value
2029 // is available in some of our (transitive) predecessors. Lets think about
2030 // doing PRE of this load. This will involve inserting a new load into the
2031 // predecessor when it's not available. We could do this in general, but
2032 // prefer to not increase code size. As such, we only do this when we know
2033 // that we only have to insert *one* load (which means we're basically moving
2034 // the load, not inserting a new one).
2035
2036 SmallPtrSet<BasicBlock *, 4> Blockers(llvm::from_range, UnavailableBlocks);
2037
2038 // Let's find the first basic block with more than one predecessor. Walk
2039 // backwards through predecessors if needed.
2040 BasicBlock *LoadBB = Load->getParent();
2041 BasicBlock *TmpBB = LoadBB;
2042
2043 // Check that there is no implicit control flow instructions above our load in
2044 // its block. If there is an instruction that doesn't always pass the
2045 // execution to the following instruction, then moving through it may become
2046 // invalid. For example:
2047 //
2048 // int arr[LEN];
2049 // int index = ???;
2050 // ...
2051 // guard(0 <= index && index < LEN);
2052 // use(arr[index]);
2053 //
2054 // It is illegal to move the array access to any point above the guard,
2055 // because if the index is out of bounds we should deoptimize rather than
2056 // access the array.
2057 // Check that there is no guard in this block above our instruction.
2058 bool MustEnsureSafetyOfSpeculativeExecution =
2060
2061 while (TmpBB->getSinglePredecessor()) {
2062 TmpBB = TmpBB->getSinglePredecessor();
2063 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
2064 return false;
2065 if (Blockers.count(TmpBB))
2066 return false;
2067
2068 // If any of these blocks has more than one successor (i.e. if the edge we
2069 // just traversed was critical), then there are other paths through this
2070 // block along which the load may not be anticipated. Hoisting the load
2071 // above this block would be adding the load to execution paths along
2072 // which it was not previously executed.
2073 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
2074 return false;
2075
2076 // Check that there is no implicit control flow in a block above.
2077 MustEnsureSafetyOfSpeculativeExecution =
2078 MustEnsureSafetyOfSpeculativeExecution || ICF->hasICF(TmpBB);
2079 }
2080
2081 assert(TmpBB);
2082 LoadBB = TmpBB;
2083
2084 // Check to see how many predecessors have the loaded value fully
2085 // available.
2087 DenseMap<BasicBlock *, AvailabilityState> FullyAvailableBlocks;
2088 for (const AvailableValueInBlock &AV : ValuesPerBlock)
2089 FullyAvailableBlocks[AV.BB] = AvailabilityState::Available;
2090 for (BasicBlock *UnavailableBB : UnavailableBlocks)
2091 FullyAvailableBlocks[UnavailableBB] = AvailabilityState::Unavailable;
2092
2093 // The edge from Pred to LoadBB is a critical edge will be splitted.
2094 SmallVector<BasicBlock *, 4> CriticalEdgePredSplit;
2095 // The edge from Pred to LoadBB is a critical edge, another successor of Pred
2096 // contains a load can be moved to Pred. This data structure maps the Pred to
2097 // the movable load.
2098 MapVector<BasicBlock *, LoadInst *> CriticalEdgePredAndLoad;
2099 for (BasicBlock *Pred : predecessors(LoadBB)) {
2100 // If any predecessor block is an EH pad that does not allow non-PHI
2101 // instructions before the terminator, we can't PRE the load.
2102 if (Pred->getTerminator()->isEHPad()) {
2103 LLVM_DEBUG(
2104 dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
2105 << Pred->getName() << "': " << *Load << '\n');
2106 return false;
2107 }
2108
2109 if (isValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
2110 continue;
2111 }
2112
2113 if (Pred->getTerminator()->getNumSuccessors() != 1) {
2114 if (isa<IndirectBrInst>(Pred->getTerminator())) {
2115 LLVM_DEBUG(
2116 dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
2117 << Pred->getName() << "': " << *Load << '\n');
2118 return false;
2119 }
2120
2121 if (LoadBB->isEHPad()) {
2122 LLVM_DEBUG(
2123 dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
2124 << Pred->getName() << "': " << *Load << '\n');
2125 return false;
2126 }
2127
2128 // Do not split backedge as it will break the canonical loop form.
2129 if (!isLoadPRESplitBackedgeEnabled())
2130 if (DT->dominates(LoadBB, Pred)) {
2131 LLVM_DEBUG(
2132 dbgs()
2133 << "COULD NOT PRE LOAD BECAUSE OF A BACKEDGE CRITICAL EDGE '"
2134 << Pred->getName() << "': " << *Load << '\n');
2135 return false;
2136 }
2137
2138 if (LoadInst *LI = findLoadToHoistIntoPred(Pred, LoadBB, Load))
2139 CriticalEdgePredAndLoad[Pred] = LI;
2140 else
2141 CriticalEdgePredSplit.push_back(Pred);
2142 } else {
2143 // Only add the predecessors that will not be split for now.
2144 PredLoads[Pred] = nullptr;
2145 }
2146 }
2147
2148 // Decide whether PRE is profitable for this load.
2149 unsigned NumInsertPreds = PredLoads.size() + CriticalEdgePredSplit.size();
2150 unsigned NumUnavailablePreds = NumInsertPreds +
2151 CriticalEdgePredAndLoad.size();
2152 assert(NumUnavailablePreds != 0 &&
2153 "Fully available value should already be eliminated!");
2154 (void)NumUnavailablePreds;
2155
2156 // If we need to insert new load in multiple predecessors, reject it.
2157 // FIXME: If we could restructure the CFG, we could make a common pred with
2158 // all the preds that don't have an available Load and insert a new load into
2159 // that one block.
2160 if (NumInsertPreds > 1)
2161 return false;
2162
2163 // Now we know where we will insert load. We must ensure that it is safe
2164 // to speculatively execute the load at that points.
2165 if (MustEnsureSafetyOfSpeculativeExecution) {
2166 if (CriticalEdgePredSplit.size())
2168 DT))
2169 return false;
2170 for (auto &PL : PredLoads)
2171 if (!isSafeToSpeculativelyExecute(Load, PL.first->getTerminator(), AC,
2172 DT))
2173 return false;
2174 for (auto &CEP : CriticalEdgePredAndLoad)
2175 if (!isSafeToSpeculativelyExecute(Load, CEP.first->getTerminator(), AC,
2176 DT))
2177 return false;
2178 }
2179
2180 // Split critical edges, and update the unavailable predecessors accordingly.
2181 for (BasicBlock *OrigPred : CriticalEdgePredSplit) {
2182 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
2183 assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
2184 PredLoads[NewPred] = nullptr;
2185 LLVM_DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
2186 << LoadBB->getName() << '\n');
2187 }
2188
2189 for (auto &CEP : CriticalEdgePredAndLoad)
2190 PredLoads[CEP.first] = nullptr;
2191
2192 // Check if the load can safely be moved to all the unavailable predecessors.
2193 bool CanDoPRE = true;
2194 const DataLayout &DL = Load->getDataLayout();
2196 for (auto &PredLoad : PredLoads) {
2197 BasicBlock *UnavailablePred = PredLoad.first;
2198
2199 // Do PHI translation to get its value in the predecessor if necessary. The
2200 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
2201 // We do the translation for each edge we skipped by going from Load's block
2202 // to LoadBB, otherwise we might miss pieces needing translation.
2203
2204 // If all preds have a single successor, then we know it is safe to insert
2205 // the load on the pred (?!?), so we can insert code to materialize the
2206 // pointer if it is not available.
2207 Value *LoadPtr = Load->getPointerOperand();
2208 BasicBlock *Cur = Load->getParent();
2209 while (Cur != LoadBB) {
2210 PHITransAddr Address(LoadPtr, DL, AC);
2211 LoadPtr = Address.translateWithInsertion(Cur, Cur->getSinglePredecessor(),
2212 *DT, NewInsts);
2213 if (!LoadPtr) {
2214 CanDoPRE = false;
2215 break;
2216 }
2217 Cur = Cur->getSinglePredecessor();
2218 }
2219
2220 if (LoadPtr) {
2221 PHITransAddr Address(LoadPtr, DL, AC);
2222 LoadPtr = Address.translateWithInsertion(LoadBB, UnavailablePred, *DT,
2223 NewInsts);
2224 }
2225 // If we couldn't find or insert a computation of this phi translated value,
2226 // we fail PRE.
2227 if (!LoadPtr) {
2228 LLVM_DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
2229 << *Load->getPointerOperand() << "\n");
2230 CanDoPRE = false;
2231 break;
2232 }
2233
2234 PredLoad.second = LoadPtr;
2235 }
2236
2237 if (!CanDoPRE) {
2238 while (!NewInsts.empty()) {
2239 // Erase instructions generated by the failed PHI translation before
2240 // trying to number them. PHI translation might insert instructions
2241 // in basic blocks other than the current one, and we delete them
2242 // directly, as salvageAndRemoveInstruction only allows removing from the
2243 // current basic block.
2244 NewInsts.pop_back_val()->eraseFromParent();
2245 }
2246 // HINT: Don't revert the edge-splitting as following transformation may
2247 // also need to split these critical edges.
2248 return !CriticalEdgePredSplit.empty();
2249 }
2250
2251 // Okay, we can eliminate this load by inserting a reload in the predecessor
2252 // and using PHI construction to get the value in the other predecessors, do
2253 // it.
2254 LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *Load << '\n');
2255 LLVM_DEBUG(if (!NewInsts.empty()) dbgs() << "INSERTED " << NewInsts.size()
2256 << " INSTS: " << *NewInsts.back()
2257 << '\n');
2258
2259 // Assign value numbers to the new instructions.
2260 for (Instruction *I : NewInsts) {
2261 // Instructions that have been inserted in predecessor(s) to materialize
2262 // the load address do not retain their original debug locations. Doing
2263 // so could lead to confusing (but correct) source attributions.
2264 I->updateLocationAfterHoist();
2265
2266 // FIXME: We really _ought_ to insert these value numbers into their
2267 // parent's availability map. However, in doing so, we risk getting into
2268 // ordering issues. If a block hasn't been processed yet, we would be
2269 // marking a value as AVAIL-IN, which isn't what we intend.
2270 VN.lookupOrAdd(I);
2271 }
2272
2273 eliminatePartiallyRedundantLoad(Load, ValuesPerBlock, PredLoads,
2274 &CriticalEdgePredAndLoad);
2275 ++NumPRELoad;
2276 return true;
2277}
2278
2279bool GVNPassImpl::performLoopLoadPRE(LoadInst *Load,
2280 AvailValInBlkVect &ValuesPerBlock,
2281 UnavailBlkVect &UnavailableBlocks) {
2282 const Loop *L = LI->getLoopFor(Load->getParent());
2283 // TODO: Generalize to other loop blocks that dominate the latch.
2284 if (!L || L->getHeader() != Load->getParent())
2285 return false;
2286
2287 BasicBlock *Preheader = L->getLoopPreheader();
2288 BasicBlock *Latch = L->getLoopLatch();
2289 if (!Preheader || !Latch)
2290 return false;
2291
2292 Value *LoadPtr = Load->getPointerOperand();
2293 // Must be available in preheader.
2294 if (!L->isLoopInvariant(LoadPtr))
2295 return false;
2296
2297 // We plan to hoist the load to preheader without introducing a new fault.
2298 // In order to do it, we need to prove that we cannot side-exit the loop
2299 // once loop header is first entered before execution of the load.
2301 return false;
2302
2303 BasicBlock *LoopBlock = nullptr;
2304 for (auto *Blocker : UnavailableBlocks) {
2305 // Blockers from outside the loop are handled in preheader.
2306 if (!L->contains(Blocker))
2307 continue;
2308
2309 // Only allow one loop block. Loop header is not less frequently executed
2310 // than each loop block, and likely it is much more frequently executed. But
2311 // in case of multiple loop blocks, we need extra information (such as block
2312 // frequency info) to understand whether it is profitable to PRE into
2313 // multiple loop blocks.
2314 if (LoopBlock)
2315 return false;
2316
2317 // Do not sink into inner loops. This may be non-profitable.
2318 if (L != LI->getLoopFor(Blocker))
2319 return false;
2320
2321 // Blocks that dominate the latch execute on every single iteration, maybe
2322 // except the last one. So PREing into these blocks doesn't make much sense
2323 // in most cases. But the blocks that do not necessarily execute on each
2324 // iteration are sometimes much colder than the header, and this is when
2325 // PRE is potentially profitable.
2326 if (DT->dominates(Blocker, Latch))
2327 return false;
2328
2329 // Make sure that the terminator itself doesn't clobber.
2330 if (Blocker->getTerminator()->mayWriteToMemory())
2331 return false;
2332
2333 LoopBlock = Blocker;
2334 }
2335
2336 if (!LoopBlock)
2337 return false;
2338
2339 // Make sure the memory at this pointer cannot be freed, therefore we can
2340 // safely reload from it after clobber.
2341 if (LoadPtr->canBeFreed())
2342 return false;
2343
2344 // TODO: Support critical edge splitting if blocker has more than 1 successor.
2345 MapVector<BasicBlock *, Value *> AvailableLoads;
2346 AvailableLoads[LoopBlock] = LoadPtr;
2347 AvailableLoads[Preheader] = LoadPtr;
2348
2349 LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOOP LOAD: " << *Load << '\n');
2350 eliminatePartiallyRedundantLoad(Load, ValuesPerBlock, AvailableLoads,
2351 /*CriticalEdgePredAndLoad*/ nullptr);
2352 ++NumPRELoopLoad;
2353 return true;
2354}
2355
2358 using namespace ore;
2359
2360 ORE->emit([&]() {
2361 return OptimizationRemark(DEBUG_TYPE, "LoadElim", Load)
2362 << "load of type " << NV("Type", Load->getType()) << " eliminated"
2363 << setExtraArgs() << " in favor of "
2364 << NV("InfavorOfValue", AvailableValue);
2365 });
2366}
2367
2368/// Attempt to eliminate a load whose dependencies are
2369/// non-local by performing PHI construction.
2370bool GVNPassImpl::processNonLocalLoad(LoadInst *Load) {
2371 // Non-local speculations are not allowed under asan.
2372 if (Load->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
2373 Load->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
2374 return false;
2375
2376 // Find the non-local dependencies of the load.
2377 LoadDepVect Deps;
2379
2380 // If we had to process more than one hundred blocks to find the
2381 // dependencies, this load isn't worth worrying about. Optimizing
2382 // it will be too expensive.
2383 unsigned NumDeps = Deps.size();
2384 if (NumDeps > MaxNumDeps)
2385 return false;
2386
2388 MemVals.reserve(Deps.size());
2389
2390 for (const NonLocalDepResult &Dep : Deps) {
2391 const auto &R = Dep.getResult();
2392 SelectAddr SelAddr = Dep.getAddress();
2393 BasicBlock *BB = Dep.getBB();
2394 Instruction *Inst = R.getInst();
2395 if (R.isSelect()) {
2396 auto [Cond, Addrs] = SelAddr.getSelectCondAndAddrs();
2397 MemVals.emplace_back(
2398 ReachingMemVal::getSelect(BB, Cond, Addrs.first, Addrs.second));
2399 continue;
2400 }
2401 Value *Address = SelAddr.getAddr();
2402 if (R.isClobber())
2403 MemVals.emplace_back(ReachingMemVal::getClobber(Address, Inst));
2404 else if (R.isDef())
2405 MemVals.emplace_back(ReachingMemVal::getDef(Address, Inst));
2406 else
2407 MemVals.emplace_back(ReachingMemVal::getUnknown(BB, Address, Inst));
2408 }
2409
2410 return processNonLocalLoad(Load, MemVals);
2411}
2412
2413bool GVNPassImpl::processNonLocalLoad(LoadInst *Load,
2415 // If we had a phi translation failure, we'll have a single entry which is a
2416 // clobber in the current block. Reject this early.
2417 if (Deps.size() == 1 && Deps[0].Kind == DepKind::Other) {
2418 LLVM_DEBUG(dbgs() << "GVN: non-local load "; Load->printAsOperand(dbgs());
2419 dbgs() << " has unknown dependencies\n";);
2420 return false;
2421 }
2422
2423 bool Changed = false;
2424 // This is a limited form of scalar PRE for load indices. If this load follows
2425 // a GEP, see if we can PRE the indices before analyzing.
2426 if (isScalarPREEnabled()) {
2427 if (GetElementPtrInst *GEP =
2428 dyn_cast<GetElementPtrInst>(Load->getOperand(0))) {
2429 for (Use &U : GEP->indices())
2430 // Instructions inserted by GVN during this iteration (e.g. coercion
2431 // casts from MaterializeAdjustedValue) may not have value numbers yet,
2432 // so they are skipped.
2433 if (Instruction *I = dyn_cast<Instruction>(U.get()); I && VN.exists(I))
2434 Changed |= performScalarPRE(I);
2435 }
2436 }
2437
2438 // Step 1: Analyze the availability of the load.
2439 AvailValInBlkVect ValuesPerBlock;
2440 UnavailBlkVect UnavailableBlocks;
2441 analyzeLoadAvailability(Load, Deps, ValuesPerBlock, UnavailableBlocks);
2442
2443 // If we have no predecessors that produce a known value for this load, exit
2444 // early.
2445 if (ValuesPerBlock.empty())
2446 return Changed;
2447
2448 // Step 2: Eliminate fully redundancy.
2449 //
2450 // If all of the instructions we depend on produce a known value for this
2451 // load, then it is fully redundant and we can use PHI insertion to compute
2452 // its value. Insert PHIs and remove the fully redundant value now.
2453 if (UnavailableBlocks.empty()) {
2454 LLVM_DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *Load << '\n');
2455
2456 // Perform PHI construction.
2457 Value *V = constructSSAForLoadSet(Load, ValuesPerBlock, getDominatorTree());
2458 // constructSSAForLoadSet is responsible for combining metadata.
2459 ICF->removeUsersOf(Load);
2460 Load->replaceAllUsesWith(V);
2461
2462 if (isa<PHINode>(V))
2463 V->takeName(Load);
2465 // If instruction I has debug info, then we should not update it.
2466 // Also, if I has a null DebugLoc, then it is still potentially incorrect
2467 // to propagate Load's DebugLoc because Load may not post-dominate I.
2468 if (Load->getDebugLoc() && Load->getParent() == I->getParent())
2469 I->setDebugLoc(Load->getDebugLoc());
2470 if (MD && V->getType()->isPtrOrPtrVectorTy())
2472 ++NumGVNLoad;
2473 reportLoadElim(Load, V, ORE);
2474 salvageAndRemoveInstruction(Load);
2475 return true;
2476 }
2477
2478 // Step 3: Eliminate partial redundancy.
2479 if (!isLoadPREEnabled())
2480 return Changed;
2481 if (!isLoadInLoopPREEnabled() && LI->getLoopFor(Load->getParent()))
2482 return Changed;
2483
2484 if (performLoopLoadPRE(Load, ValuesPerBlock, UnavailableBlocks) ||
2485 performLoadPRE(Load, ValuesPerBlock, UnavailableBlocks))
2486 return true;
2487
2488 return Changed;
2489}
2490
2491bool GVNPassImpl::processAssumeIntrinsic(AssumeInst *IntrinsicI) {
2492 Value *V = IntrinsicI->getArgOperand(0);
2493
2495 if (Cond->isZero()) {
2496 Type *Int8Ty = Type::getInt8Ty(V->getContext());
2497 Type *PtrTy = PointerType::get(V->getContext(), 0);
2498 // Insert a new store to null instruction before the load to indicate that
2499 // this code is not reachable. FIXME: We could insert unreachable
2500 // instruction directly because we can modify the CFG.
2501 auto *NewS =
2503 IntrinsicI->getIterator());
2504 if (MSSAU) {
2505 const MemoryUseOrDef *FirstNonDom = nullptr;
2506 const auto *AL =
2507 MSSAU->getMemorySSA()->getBlockAccesses(IntrinsicI->getParent());
2508
2509 // If there are accesses in the current basic block, find the first one
2510 // that does not come before NewS. The new memory access is inserted
2511 // after the found access or before the terminator if no such access is
2512 // found.
2513 if (AL) {
2514 for (const auto &Acc : *AL) {
2515 if (auto *Current = dyn_cast<MemoryUseOrDef>(&Acc))
2516 if (!Current->getMemoryInst()->comesBefore(NewS)) {
2517 FirstNonDom = Current;
2518 break;
2519 }
2520 }
2521 }
2522
2523 auto *NewDef =
2524 FirstNonDom ? MSSAU->createMemoryAccessBefore(
2525 NewS, nullptr,
2526 const_cast<MemoryUseOrDef *>(FirstNonDom))
2527 : MSSAU->createMemoryAccessInBB(
2528 NewS, nullptr,
2529 NewS->getParent(), MemorySSA::BeforeTerminator);
2530
2531 MSSAU->insertDef(cast<MemoryDef>(NewDef), /*RenameUses=*/false);
2532 }
2533 }
2534 if (isAssumeWithEmptyBundle(*IntrinsicI)) {
2535 salvageAndRemoveInstruction(IntrinsicI);
2536 return true;
2537 }
2538 return false;
2539 }
2540
2541 if (isa<Constant>(V)) {
2542 // If it's not false, and constant, it must evaluate to true. This means our
2543 // assume is assume(true), and thus, pointless, and we don't want to do
2544 // anything more here.
2545 return false;
2546 }
2547
2548 Constant *True = ConstantInt::getTrue(V->getContext());
2549 return propagateEquality(V, True, IntrinsicI);
2550}
2551
2554 I->replaceAllUsesWith(Repl);
2555}
2556
2557/// If a load has !invariant.group, try to find the most-dominating instruction
2558/// with the same metadata and equivalent pointer (modulo bitcasts and zero
2559/// GEPs). If one is found that dominates the load, its value can be reused.
2561 Value *PointerOperand = L->getPointerOperand()->stripPointerCasts();
2562
2563 // It's not safe to walk the use list of a global value because function
2564 // passes aren't allowed to look outside their functions.
2565 // FIXME: this could be fixed by filtering instructions from outside of
2566 // current function.
2567 if (isa<Constant>(PointerOperand))
2568 return nullptr;
2569
2570 // Queue to process all pointers that are equivalent to load operand.
2571 SmallVector<Value *, 8> PointerUsesQueue;
2572 PointerUsesQueue.push_back(PointerOperand);
2573
2574 Instruction *MostDominatingInstruction = L;
2575
2576 // FIXME: This loop is potentially O(n^2) due to repeated dominates checks.
2577 while (!PointerUsesQueue.empty()) {
2578 Value *Ptr = PointerUsesQueue.pop_back_val();
2579 assert(Ptr && !isa<GlobalValue>(Ptr) &&
2580 "Null or GlobalValue should not be inserted");
2581
2582 for (User *U : Ptr->users()) {
2583 auto *I = dyn_cast<Instruction>(U);
2584 if (!I || I == L || !DT.dominates(I, MostDominatingInstruction))
2585 continue;
2586
2587 // Add bitcasts and zero GEPs to queue.
2588 // TODO: Should drop bitcast?
2589 if (isa<BitCastInst>(I) ||
2591 cast<GetElementPtrInst>(I)->hasAllZeroIndices())) {
2592 PointerUsesQueue.push_back(I);
2593 continue;
2594 }
2595
2596 // If we hit a load/store with an invariant.group metadata and the same
2597 // pointer operand, we can assume that value pointed to by the pointer
2598 // operand didn't change.
2599 if (I->hasMetadata(LLVMContext::MD_invariant_group) &&
2600 Ptr == getLoadStorePointerOperand(I) && !I->isVolatile())
2601 MostDominatingInstruction = I;
2602 }
2603 }
2604
2605 return MostDominatingInstruction != L ? MostDominatingInstruction : nullptr;
2606}
2607
2608/// Return the memory location accessed by the (masked) load/store instruction
2609/// `I`, if the instruction could potentially provide a useful value for
2610/// eliminating the load.
2611static std::optional<MemoryLocation>
2613 const TargetLibraryInfo *TLI) {
2614 if (auto *LI = dyn_cast<LoadInst>(I))
2615 return MemoryLocation::get(LI);
2616
2617 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2618 switch (II->getIntrinsicID()) {
2619 case Intrinsic::masked_load:
2620 return MemoryLocation::getForArgument(II, 0, TLI);
2621 case Intrinsic::masked_store:
2622 if (AllowStores)
2623 return MemoryLocation::getForArgument(II, 1, TLI);
2624 return std::nullopt;
2625 default:
2626 break;
2627 }
2628 }
2629
2630 if (!AllowStores)
2631 return std::nullopt;
2632
2633 if (auto *SI = dyn_cast<StoreInst>(I))
2634 return MemoryLocation::get(SI);
2635 return std::nullopt;
2636}
2637
2638/// Scan the users of each MemoryAccess in `ClobbersList` that belong to `BB`,
2639/// looking for memory reads whose location aliases `Loc` and dominates our
2640/// load.
2641std::optional<GVNPassImpl::ReachingMemVal> GVNPassImpl::scanMemoryAccessesUsers(
2642 const MemoryLocation &Loc, bool IsInvariantLoad, BasicBlock *BB,
2643 const SmallVectorImpl<MemoryAccess *> &ClobbersList, MemorySSA &MSSA,
2644 BatchAAResults &AA, LoadInst *L) {
2645
2646 // Prefer a candidate that is closer to the load within the same block.
2647 auto UpdateChoice = [&](std::optional<ReachingMemVal> &Choice,
2648 AliasResult &AR, Instruction *Candidate) {
2649 if (!Choice) {
2650 if (AR == AliasResult::PartialAlias)
2651 Choice = ReachingMemVal::getClobber(Loc.Ptr, Candidate, AR.getOffset());
2652 else
2653 Choice = ReachingMemVal::getDef(Loc.Ptr, Candidate);
2654 return;
2655 }
2656 if (!MSSA.locallyDominates(MSSA.getMemoryAccess(Choice->Inst),
2657 MSSA.getMemoryAccess(Candidate)))
2658 return;
2659
2660 if (AR == AliasResult::PartialAlias) {
2661 Choice->Kind = DepKind::Clobber;
2662 Choice->Offset = AR.getOffset();
2663 } else {
2664 Choice->Kind = DepKind::Def;
2665 Choice->Offset = -1;
2666 }
2667
2668 Choice->Inst = Candidate;
2669 Choice->Block = Candidate->getParent();
2670 };
2671
2672 std::optional<ReachingMemVal> ReachingVal;
2673 for (MemoryAccess *MA : ClobbersList) {
2674 unsigned Scanned = 0;
2675 for (User *U : MA->users()) {
2676 if (++Scanned >= ScanUsersLimit)
2677 return ReachingMemVal::getUnknown(BB, Loc.Ptr);
2678
2679 auto *UseOrDef = dyn_cast<MemoryUseOrDef>(U);
2680 if (!UseOrDef || UseOrDef->getBlock() != BB)
2681 continue;
2682
2683 Instruction *MemI = UseOrDef->getMemoryInst();
2684 if (MemI == L ||
2685 (L && !MSSA.locallyDominates(UseOrDef, MSSA.getMemoryAccess(L))))
2686 continue;
2687
2688 if (auto MaybeLoc = maybeLoadStoreLocation(MemI, IsInvariantLoad, TLI)) {
2689 AliasResult AR = AA.alias(*MaybeLoc, Loc);
2690 // If the locations do not certainly alias, we cannot possibly infer the
2691 // following load loads the same value.
2693 continue;
2694
2695 // Locations partially overlap, but neither is a subset of the other, or
2696 // the second location is before the first.
2697 if (AR == AliasResult::PartialAlias &&
2698 (!AR.hasOffset() || AR.getOffset() < 0))
2699 continue;
2700
2701 // Found candidate, the new load memory location and the given location
2702 // must alias: precise overlap, or subset with non-negative offset.
2703 UpdateChoice(ReachingVal, AR, MemI);
2704 }
2705 }
2706 if (ReachingVal)
2707 break;
2708 }
2709
2710 return ReachingVal;
2711}
2712
2713/// Check if a given MemoryAccess (usually a MemoryDef) actually modifies a
2714/// given location. Returns a ReachingMemVal describing the dependency.
2715std::optional<GVNPassImpl::ReachingMemVal> GVNPassImpl::accessMayModifyLocation(
2716 MemoryAccess *ClobberMA, const MemoryLocation &Loc, Align LoadAlign,
2717 bool IsInvariantLoad, BasicBlock *BB, MemorySSA &MSSA, BatchAAResults &AA) {
2718 assert(ClobberMA->getBlock() == BB);
2719
2720 // If the clobbering access is the entry memory state, we cannot say anything
2721 // about the content of the memory, except when we are accessing a local
2722 // object, which can be turned later into producing `undef`.
2723 if (MSSA.isLiveOnEntryDef(ClobberMA)) {
2725 if (Alloc->getParent() == BB)
2726 return ReachingMemVal::getDef(Loc.Ptr, const_cast<AllocaInst *>(Alloc));
2727 return ReachingMemVal::getUnknown(BB, Loc.Ptr);
2728 }
2729
2730 // Loads from "constant" memory can't be clobbered.
2731 if (IsInvariantLoad || AA.pointsToConstantMemory(Loc))
2732 return std::nullopt;
2733
2734 auto GetOrdering = [](const Instruction *I) {
2735 if (auto *L = dyn_cast<LoadInst>(I))
2736 return L->getOrdering();
2737 return cast<StoreInst>(I)->getOrdering();
2738 };
2739 Instruction *ClobberI = cast<MemoryDef>(ClobberMA)->getMemoryInst();
2740
2741 // Check if the clobbering access is a load or a store that we can reuse.
2742 if (auto MaybeLoc = maybeLoadStoreLocation(ClobberI, true, TLI)) {
2743 AliasResult AR = AA.alias(*MaybeLoc, Loc);
2744 if (AR == AliasResult::MustAlias)
2745 return ReachingMemVal::getDef(Loc.Ptr, ClobberI);
2746
2747 if (AR == AliasResult::NoAlias) {
2748 // If the locations do not alias we may still be able to skip over the
2749 // clobbering instruction, even if it is atomic.
2750 // The original load is either non-atomic or unordered. We can reorder
2751 // these across non-atomic, unordered or monotonic loads or across any
2752 // store.
2753 if (!ClobberI->isAtomic() ||
2754 !isStrongerThan(GetOrdering(ClobberI), AtomicOrdering::Monotonic) ||
2755 isa<StoreInst>(ClobberI))
2756 return std::nullopt;
2757 return ReachingMemVal::getClobber(Loc.Ptr, ClobberI);
2758 }
2759
2760 // Skip over volatile loads (the original load is non-volatile, non-atomic).
2761 if (!ClobberI->isAtomic() && isa<LoadInst>(ClobberI))
2762 return std::nullopt;
2763
2764 // A store that writes back a value already at the memory location leaves
2765 // the latter unchanged.
2766 if (auto *SI = dyn_cast<StoreInst>(ClobberI))
2767 if (isStorePreservingMemoryLocation(SI, Loc, LoadAlign, AA,
2769 return std::nullopt;
2770
2771 if (AR == AliasResult::MayAlias ||
2773 (!AR.hasOffset() || AR.getOffset() < 0)))
2774 return ReachingMemVal::getClobber(Loc.Ptr, ClobberI);
2775
2776 // The only option left is a store of the superset of the required bits.
2778 AR.getOffset() > 0 &&
2779 "Must be the superset/partial overlap case with positive offset");
2780 return ReachingMemVal::getClobber(Loc.Ptr, ClobberI, AR.getOffset());
2781 }
2782
2783 if (auto *II = dyn_cast<IntrinsicInst>(ClobberI)) {
2785 return std::nullopt;
2786 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
2788 if (AA.isMustAlias(IIObjLoc, Loc))
2789 return ReachingMemVal::getDef(Loc.Ptr, ClobberI);
2790 return std::nullopt;
2791 }
2792 }
2793
2794 // If we are at a malloc-like function call, we can turn the load into `undef`
2795 // or zero.
2796 if (isNoAliasCall(ClobberI)) {
2797 const Value *Obj = getUnderlyingObject(Loc.Ptr);
2798 if (Obj == ClobberI || AA.isMustAlias(ClobberI, Loc.Ptr))
2799 return ReachingMemVal::getDef(Loc.Ptr, ClobberI);
2800 }
2801
2802 // Can reorder loads across a release fence.
2803 if (auto *FI = dyn_cast<FenceInst>(ClobberI))
2804 if (FI->getOrdering() == AtomicOrdering::Release)
2805 return std::nullopt;
2806
2807 // See if the clobber instruction (e.g., a generic call) may modify the
2808 // location.
2809 ModRefInfo MR = AA.getModRefInfo(ClobberI, Loc);
2810 // If may modify the location, analyze deeper, to exclude accesses to
2811 // non-escaping local allocations.
2812 if (MR == ModRefInfo::NoModRef || MR == ModRefInfo::Ref)
2813 return std::nullopt;
2814
2815 // Conservatively assume the clobbering memory access may overwrite the
2816 // location.
2817 return ReachingMemVal::getClobber(Loc.Ptr, ClobberI);
2818}
2819
2820/// Collect the predecessors of block, while doing phi-translation of the memory
2821/// address and the memory clobber. Return false if the block should be marked
2822/// as clobbering the memory location in an unknown way.
2823bool GVNPassImpl::collectPredecessors(BasicBlock *BB, const PHITransAddr &Addr,
2824 MemoryAccess *ClobberMA,
2825 DependencyBlockSet &Blocks,
2827 if (Addr.needsPHITranslationFromBlock(BB) &&
2829 return false;
2830
2831 auto *MPhi =
2832 ClobberMA->getBlock() == BB ? dyn_cast<MemoryPhi>(ClobberMA) : nullptr;
2834 for (BasicBlock *Pred : predecessors(BB)) {
2835 // Skip unreachable predecessors.
2836 if (!DT->isReachableFromEntry(Pred))
2837 continue;
2838
2839 // Skip already visited predecessors.
2840 if (llvm::any_of(Preds, [Pred](const auto &P) { return P.first == Pred; }))
2841 continue;
2842
2843 PHITransAddr TransAddr = Addr;
2844 if (TransAddr.needsPHITranslationFromBlock(BB))
2845 TransAddr.translateValue(BB, Pred, DT, false);
2846
2847 auto It = Blocks.find(Pred);
2848 if (It != Blocks.end()) {
2849 // If we reach a visited block with a different address, set the
2850 // current block as clobbering the memory location in an unknown way
2851 // (by returning false).
2852 if (It->second.Addr.getAddr() != TransAddr.getAddr())
2853 return false;
2854 // Otherwise, just stop the traversal.
2855 continue;
2856 }
2857
2858 Preds.emplace_back(
2859 Pred, DependencyBlockInfo(TransAddr,
2860 MPhi ? MPhi->getIncomingValueForBlock(Pred)
2861 : ClobberMA));
2862 }
2863
2864 // We collected the predecessors and stored them in Preds. Now, populate the
2865 // worklist with the predecessors found, and cache the eventual translated
2866 // address for each block.
2867 for (auto &P : Preds) {
2868 [[maybe_unused]] auto It =
2869 Blocks.try_emplace(P.first, std::move(P.second)).first;
2870 Worklist.push_back(P.first);
2871 }
2872
2873 return true;
2874}
2875
2876/// Build a list of MemoryAccesses whose users could potentially alias the
2877/// memory location being queried. Starts from StartInfo's initial clobber,
2878/// walk the use-def chain to the final clobber. If the chain extends beyond
2879/// `BB`, continue into that block but only if it is in the previously collected
2880/// set.
2881void GVNPassImpl::collectClobberList(SmallVectorImpl<MemoryAccess *> &Clobbers,
2882 BasicBlock *BB,
2883 const DependencyBlockInfo &StartInfo,
2884 const DependencyBlockSet &Blocks,
2885 MemorySSA &MSSA) {
2886 MemoryAccess *MA = StartInfo.InitialClobberMA;
2887 MemoryAccess *LastMA = StartInfo.ClobberMA;
2888
2889 for (;;) {
2890 while (MA != LastMA) {
2891 Clobbers.push_back(MA);
2892 MA = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
2893 }
2894 Clobbers.push_back(MA);
2895
2896 if (MSSA.isLiveOnEntryDef(MA) ||
2897 (MA->getBlock() == BB && !isa<MemoryPhi>(MA)))
2898 break;
2899
2900 // If the final clobber in the current block is a MemoryPhi, go to the
2901 // immediate dominator; otherwise, just get to the block containing the
2902 // final clobber.
2903 if (MA->getBlock() == BB)
2904 BB = DT->getNode(BB)->getIDom()->getBlock();
2905 else
2906 BB = MA->getBlock();
2907
2908 auto It = Blocks.find(BB);
2909 if (It == Blocks.end())
2910 break;
2911
2912 MA = It->second.InitialClobberMA;
2913 LastMA = It->second.ClobberMA;
2914 if (MA == Clobbers.back())
2915 Clobbers.pop_back();
2916 }
2917}
2918
2919/// Entrypoint for the MemorySSA-based redundant load elimination algorithm.
2920/// Given as input a load instruction, the function computes the set of reaching
2921/// memory values, one per predecessor path, that analyzeLoadAvailability can
2922/// later use to establish whether the load may be eliminated. A reaching value
2923/// may be of the following descriptor kind:
2924/// * Def: a precise instruction that produces the exact bits the load would
2925/// read (e.g., an equivalent load or a MustAlias store);
2926/// * Clobber: a write that clobbers a superset of the bits the load would read
2927/// (e.g., a memset over a larger region);
2928/// * Other: we know which block defines the memory location in some way, but
2929/// could not identify a precise instruction (e.g., memory already live at
2930/// function entry).
2931bool GVNPassImpl::findReachingValuesForLoad(
2933 AAResults &AAR) {
2934 EarliestEscapeAnalysis EA(*DT, LI);
2935 BatchAAResults AA(AAR, &EA);
2936 BasicBlock *StartBlock = L->getParent();
2937 bool IsInvariantLoad = L->hasMetadata(LLVMContext::MD_invariant_load);
2938 // TODO: Simplify later work by just getClobberingMemoryAccess().
2939 MemoryAccess *ClobberMA = MSSA.getMemoryAccess(L)->getDefiningAccess();
2941
2942 // Fast path for load tagged with !invariant.group.
2943 if (L->hasMetadata(LLVMContext::MD_invariant_group)) {
2944 if (Instruction *G = findInvariantGroupValue(L, *DT)) {
2945 Values.emplace_back(
2946 ReachingMemVal::getDef(getLoadStorePointerOperand(G), G));
2947 return true;
2948 }
2949 }
2950
2951 // Phase 1. First off, look for a local dependency to avoid having to
2952 // disambiguate between before the load and after the load of the starting
2953 // block (as the load may be visited from a backedge).
2954 do {
2955 // Scan users of the clobbering memory access.
2956 if (auto RMV = scanMemoryAccessesUsers(
2957 Loc, IsInvariantLoad, StartBlock,
2958 SmallVector<MemoryAccess *, 1>{ClobberMA}, MSSA, AA, L)) {
2959 Values.emplace_back(*RMV);
2960 return true;
2961 }
2962
2963 // Exit from here, and proceed visiting predecessors if the clobbering
2964 // access is non-local or is a MemoryPhi.
2965 if (ClobberMA->getBlock() != StartBlock || isa<MemoryPhi>(ClobberMA))
2966 break;
2967
2968 // Check if the clobber actually aliases the load location.
2969 if (auto RMV =
2970 accessMayModifyLocation(ClobberMA, Loc, L->getAlign(),
2971 IsInvariantLoad, StartBlock, MSSA, AA)) {
2972 Values.emplace_back(*RMV);
2973 return true;
2974 }
2975
2976 // It may happen that the clobbering memory access does not actually
2977 // clobber our load location, transition to its defining memory access.
2978 ClobberMA = cast<MemoryUseOrDef>(ClobberMA)->getDefiningAccess();
2979 } while (ClobberMA->getBlock() == StartBlock);
2980
2981 // Non-local speculations are not allowed under ASan.
2982 if (L->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
2983 L->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
2984 return false;
2985
2986 // Phase 2. Walk backwards through the CFG, collecting all the blocks that
2987 // contain an instruction that modifies the load memory location, or that lie
2988 // on a path between a clobbering block and our load. Start off by collecting
2989 // the predecessors of `StartBlock`. All the visited blocks are stored in a
2990 // the set `Blocks`. If possible, the memory address maintained for the block
2991 // visited does get phi-translated.
2992 DependencyBlockSet Blocks;
2993 SmallVector<BasicBlock *, 16> InitialWorklist;
2994 const DataLayout &DL = L->getModule()->getDataLayout();
2995 if (!collectPredecessors(StartBlock,
2996 PHITransAddr(L->getPointerOperand(), DL, AC),
2997 ClobberMA, Blocks, InitialWorklist))
2998 return false;
2999
3000 // Do a bottom-up DFS.
3001 auto Worklist = InitialWorklist;
3002 while (!Worklist.empty()) {
3003 // Match MemDep's cutoff for expensive non-local queries.
3004 if (Blocks.size() > MaxNumReachingBlocks)
3005 return false;
3006 auto *BB = Worklist.pop_back_val();
3007 DependencyBlockInfo &Info = Blocks.find(BB)->second;
3008
3009 // Phi-translation may have failed.
3010 if (!Info.Addr.getAddr())
3011 continue;
3012
3013 // If the clobbering memory access is in the current block and it indeed
3014 // clobbers our load location, record the dependency and do not visit the
3015 // predecessors of this block further, continue with the blocks in the
3016 // worklist.
3017 if (Info.ClobberMA->getBlock() == BB && !isa<MemoryPhi>(Info.ClobberMA)) {
3018 const MemoryLocation BBLoc = Loc.getWithNewPtr(Info.Addr.getAddr());
3019 if (auto RMV =
3020 accessMayModifyLocation(Info.ClobberMA, BBLoc, L->getAlign(),
3021 IsInvariantLoad, BB, MSSA, AA)) {
3022 Info.MemVal = RMV;
3023 continue;
3024 }
3025 assert(!MSSA.isLiveOnEntryDef(Info.ClobberMA) &&
3026 "LiveOnEntry aliases everything");
3027
3028 // If, however, the clobbering memory access does not actually clobber
3029 // our load location, transition to its defining memory access, but
3030 // keep examining the same basic block.
3031 Info.ClobberMA =
3032 cast<MemoryUseOrDef>(Info.ClobberMA)->getDefiningAccess();
3033 Worklist.emplace_back(BB);
3034 continue;
3035 }
3036
3037 // At this point we know the current block is "transparent", i.e. the memory
3038 // location is not modified when execution goes through this block.
3039 // Continue to its predecessors, unless a predecessor has already been
3040 // visited with a different address. We currently cannot represent such a
3041 // dependency.
3042 if (BB == StartBlock && Info.Addr.getAddr() != L->getPointerOperand()) {
3043 Info.ForceUnknown = true;
3044 continue;
3045 }
3046 if (BB != StartBlock &&
3047 !collectPredecessors(BB, Info.Addr, Info.ClobberMA, Blocks, Worklist))
3048 Info.ForceUnknown = true;
3049 }
3050
3051 // Phase 3. We have collected all the blocks that either write a value to the
3052 // memory location of the load, or there exists a path to the load, along
3053 // which the memory location is not modified. Perform a second DFS to find
3054 // load-to-load dependencies; namely, look at the dominating memory reads,
3055 // that alias our load. These are the MemoryUses that are users of the
3056 // MemoryDefs we previously identified. If no memory read is encountered,
3057 // either confirm the clobbering write found before or set to unknown.
3058 Worklist = InitialWorklist;
3059 for (BasicBlock *BB : Worklist) {
3060 DependencyBlockInfo &Info = Blocks.find(BB)->second;
3061 Info.Visited = true;
3062 }
3063
3065 while (!Worklist.empty()) {
3066 auto *BB = Worklist.pop_back_val();
3067 DependencyBlockInfo &Info = Blocks.find(BB)->second;
3068
3069 // If phi-translation failed, assume the memory location is modified in
3070 // unknown way.
3071 if (!Info.Addr.getAddr()) {
3072 Values.push_back(ReachingMemVal::getUnknown(BB, nullptr));
3073 continue;
3074 }
3075
3076 Clobbers.clear();
3077 collectClobberList(Clobbers, BB, Info, Blocks, MSSA);
3078 if (auto RMV =
3079 scanMemoryAccessesUsers(Loc.getWithNewPtr(Info.Addr.getAddr()),
3080 IsInvariantLoad, BB, Clobbers, MSSA, AA)) {
3081 Values.push_back(*RMV);
3082 continue;
3083 }
3084
3085 // If no reusable memory use was found, and the current block is not
3086 // transparent, use the already established memory def.
3087 if (Info.MemVal) {
3088 Values.push_back(*Info.MemVal);
3089 continue;
3090 }
3091
3092 if (Info.ForceUnknown) {
3093 Values.push_back(ReachingMemVal::getUnknown(BB, Info.Addr.getAddr()));
3094 continue;
3095 }
3096
3097 // If the current block is transparent, continue to its predecessors.
3098 for (BasicBlock *Pred : predecessors(BB)) {
3099 auto It = Blocks.find(Pred);
3100 if (It == Blocks.end())
3101 continue;
3102 DependencyBlockInfo &PredInfo = It->second;
3103 if (PredInfo.Visited)
3104 continue;
3105 PredInfo.Visited = true;
3106 Worklist.push_back(Pred);
3107 }
3108 }
3109
3110 return true;
3111}
3112
3113/// Attempt to eliminate a load, first by eliminating it
3114/// locally, and then attempting non-local elimination if that fails.
3115bool GVNPassImpl::processLoad(LoadInst *L) {
3116 if (!MD && !isMemorySSAEnabled())
3117 return false;
3118
3119 // This code hasn't been audited for ordered or volatile memory access.
3120 if (!L->isUnordered())
3121 return false;
3122
3123 if (L->getType()->isTokenLikeTy())
3124 return false;
3125
3126 if (L->use_empty()) {
3127 salvageAndRemoveInstruction(L);
3128 return true;
3129 }
3130
3131 ReachingMemVal MemVal = ReachingMemVal::getUnknown(nullptr, nullptr);
3132 if (!isMemorySSAEnabled()) {
3133 // ... to a pointer that has been loaded from before...
3134 MemDepResult Dep = MD->getDependency(L);
3135
3136 // If it is defined in another block, try harder.
3137 if (Dep.isNonLocal())
3138 return processNonLocalLoad(L);
3139
3140 // Only handle the local case below.
3141 if (Dep.isDef())
3142 MemVal = ReachingMemVal::getDef(L->getPointerOperand(), Dep.getInst());
3143 else if (Dep.isClobber())
3144 MemVal =
3145 ReachingMemVal::getClobber(L->getPointerOperand(), Dep.getInst());
3146 } else {
3148 if (!findReachingValuesForLoad(L, MemVals, *MSSAU->getMemorySSA(), *AA))
3149 return false; // Too many dependencies.
3150 assert(MemVals.size() && "Expected at least an unknown value");
3151 if (MemVals.size() > 1 || MemVals[0].Block != L->getParent())
3152 return processNonLocalLoad(L, MemVals);
3153
3154 MemVal = MemVals[0];
3155 }
3156
3157 if (MemVal.Kind == DepKind::Other) {
3158 // This might be a NonFuncLocal or an Unknown.
3159 LLVM_DEBUG(
3160 // fast print dep, using operator<< on instruction is too slow.
3161 dbgs() << "GVN: load "; L->printAsOperand(dbgs());
3162 dbgs() << " has unknown dependence\n";);
3163 return false;
3164 }
3165
3166 auto AV = analyzeLoadAvailability(L, MemVal, L->getPointerOperand());
3167 if (!AV)
3168 return false;
3169
3171
3172 // MaterializeAdjustedValue is responsible for combining metadata.
3173 ICF->removeUsersOf(L);
3174 L->replaceAllUsesWith(AvailableValue);
3175 if (MSSAU)
3176 MSSAU->removeMemoryAccess(L);
3177 ++NumGVNLoad;
3179 salvageAndRemoveInstruction(L);
3180 // Tell MDA to reexamine the reused pointer since we might have more
3181 // information after forwarding it.
3182 if (MD && AvailableValue->getType()->isPtrOrPtrVectorTy())
3184 return true;
3185}
3186
3187// Attempt to process masked loads which have loaded from
3188// masked stores with the same mask
3189bool GVNPassImpl::processMaskedLoad(IntrinsicInst *I) {
3190 if (!MD)
3191 return false;
3192 MemDepResult Dep = MD->getDependency(I);
3193 Instruction *DepInst = Dep.getInst();
3194 if (!DepInst || !Dep.isLocal() || !Dep.isDef())
3195 return false;
3196
3197 Value *Mask = I->getOperand(1);
3198 Value *Passthrough = I->getOperand(2);
3199 Value *StoreVal;
3200 if (!match(DepInst,
3201 m_MaskedStore(m_Value(StoreVal), m_Value(), m_Specific(Mask))) ||
3202 StoreVal->getType() != I->getType())
3203 return false;
3204
3205 // Remove the load but generate a select for the passthrough
3206 Value *OpToForward = llvm::SelectInst::Create(Mask, StoreVal, Passthrough, "",
3207 I->getIterator());
3208
3209 ICF->removeUsersOf(I);
3210 I->replaceAllUsesWith(OpToForward);
3211 salvageAndRemoveInstruction(I);
3212 ++NumGVNLoad;
3213 return true;
3214}
3215
3216/// Return a pair the first field showing the value number of \p Exp and the
3217/// second field showing whether it is a value number newly created.
3218std::pair<uint32_t, bool> GVNValueTable::assignExpNewValueNum(Expression &Exp) {
3219 uint32_t &E = ExpressionNumbering[Exp];
3220 bool CreateNewValNum = !E;
3221 if (CreateNewValNum) {
3222 Expressions.push_back(Exp);
3223 if (ExprIdx.size() < NextValueNumber + 1)
3224 ExprIdx.resize(NextValueNumber * 2);
3225 E = NextValueNumber;
3226 ExprIdx[NextValueNumber++] = NextExprNumber++;
3227 }
3228 return {E, CreateNewValNum};
3229}
3230
3231/// Return whether all the values related with the same \p num are
3232/// defined in \p BB.
3233bool GVNValueTable::areAllValsInBB(uint32_t Num, const BasicBlock *BB,
3234 GVNLeaderMap &LeaderTable) {
3235 return all_of(
3236 LeaderTable.getLeaders(Num),
3237 [=](const GVNLeaderMap::LeaderTableEntry &L) { return L.BB == BB; });
3238}
3239
3240/// Wrap phiTranslateImpl to provide caching functionality.
3242 const BasicBlock *PhiBlock, uint32_t Num,
3243 GVNLeaderMap &LeaderTable) {
3244 auto FindRes = PhiTranslateTable.find({Num, Pred});
3245 if (FindRes != PhiTranslateTable.end())
3246 return FindRes->second;
3247 uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, LeaderTable);
3248 PhiTranslateTable.insert({{Num, Pred}, NewNum});
3249 return NewNum;
3250}
3251
3252// Return true if the value number \p Num and NewNum have equal value.
3253// Return false if the result is unknown.
3254bool GVNValueTable::areCallValsEqual(uint32_t Num, uint32_t NewNum,
3255 const BasicBlock *Pred,
3256 const BasicBlock *PhiBlock,
3257 GVNLeaderMap &LeaderTable) {
3258 CallInst *Call = nullptr;
3259 auto Leaders = LeaderTable.getLeaders(Num);
3260 for (const auto &Entry : Leaders) {
3261 Call = dyn_cast<CallInst>(&*Entry.Val);
3262 if (Call && Call->getParent() == PhiBlock)
3263 break;
3264 }
3265
3266 if (AA->doesNotAccessMemory(Call))
3267 return true;
3268
3269 if (!MD || !AA->onlyReadsMemory(Call))
3270 return false;
3271
3272 MemDepResult LocalDep = MD->getDependency(Call);
3273 if (!LocalDep.isNonLocal())
3274 return false;
3275
3278
3279 // Check to see if the Call has no function local clobber.
3280 for (const NonLocalDepEntry &D : Deps) {
3281 if (D.getResult().isNonFuncLocal())
3282 return true;
3283 }
3284 return false;
3285}
3286
3287/// Translate value number \p Num using phis, so that it has the values of
3288/// the phis in BB.
3289uint32_t GVNValueTable::phiTranslateImpl(const BasicBlock *Pred,
3290 const BasicBlock *PhiBlock,
3291 uint32_t Num,
3292 GVNLeaderMap &LeaderTable) {
3293 // See if we can refine the value number by looking at the PN incoming value
3294 // for the given predecessor.
3295 if (PHINode *PN = NumberingPhi[Num]) {
3296 if (PN->getParent() != PhiBlock)
3297 return Num;
3298 for (unsigned I = 0; I != PN->getNumIncomingValues(); ++I) {
3299 if (PN->getIncomingBlock(I) != Pred)
3300 continue;
3301 if (uint32_t TransVal = lookup(PN->getIncomingValue(I), false))
3302 return TransVal;
3303 }
3304 return Num;
3305 }
3306
3307 if (BasicBlock *BB = NumberingBB[Num]) {
3308 assert(MSSA && "NumberingBB is non-empty only when using MemorySSA");
3309 // Value numbers of basic blocks are used to represent memory state in
3310 // load/store instructions and read-only function calls when said state is
3311 // set by a MemoryPhi.
3312 if (BB != PhiBlock)
3313 return Num;
3314 MemoryPhi *MPhi = MSSA->getMemoryAccess(BB);
3315 for (unsigned i = 0, N = MPhi->getNumIncomingValues(); i != N; ++i) {
3316 if (MPhi->getIncomingBlock(i) != Pred)
3317 continue;
3318 MemoryAccess *MA = MPhi->getIncomingValue(i);
3319 if (auto *PredPhi = dyn_cast<MemoryPhi>(MA))
3320 return lookupOrAdd(PredPhi->getBlock());
3321 if (MSSA->isLiveOnEntryDef(MA))
3322 return lookupOrAdd(&BB->getParent()->getEntryBlock());
3323 return lookupOrAdd(cast<MemoryUseOrDef>(MA)->getMemoryInst());
3324 }
3326 "CFG/MemorySSA mismatch: predecessor not found among incoming blocks");
3327 }
3328
3329 // If there is any value related with Num is defined in a BB other than
3330 // PhiBlock, it cannot depend on a phi in PhiBlock without going through
3331 // a backedge. We can do an early exit in that case to save compile time.
3332 if (!areAllValsInBB(Num, PhiBlock, LeaderTable))
3333 return Num;
3334
3335 if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
3336 return Num;
3337 Expression Exp = Expressions[ExprIdx[Num]];
3338
3339 for (unsigned I = 0; I < Exp.VarArgs.size(); I++) {
3340 // For InsertValue and ExtractValue, some varargs are index numbers
3341 // instead of value numbers. Those index numbers should not be
3342 // translated.
3343 if ((I > 1 && Exp.Opcode == Instruction::InsertValue) ||
3344 (I > 0 && Exp.Opcode == Instruction::ExtractValue) ||
3345 (I > 1 && Exp.Opcode == Instruction::ShuffleVector))
3346 continue;
3347 Exp.VarArgs[I] = phiTranslate(Pred, PhiBlock, Exp.VarArgs[I], LeaderTable);
3348 }
3349
3350 if (Exp.Commutative) {
3351 assert(Exp.VarArgs.size() >= 2 && "Unsupported commutative instruction!");
3352 if (Exp.VarArgs[0] > Exp.VarArgs[1]) {
3353 std::swap(Exp.VarArgs[0], Exp.VarArgs[1]);
3354 uint32_t Opcode = Exp.Opcode >> 8;
3355 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)
3356 Exp.Opcode = (Opcode << 8) |
3358 static_cast<CmpInst::Predicate>(Exp.Opcode & 255));
3359 }
3360 }
3361
3362 if (uint32_t NewNum = ExpressionNumbering[Exp]) {
3363 if (Exp.Opcode == Instruction::Call && NewNum != Num)
3364 return areCallValsEqual(Num, NewNum, Pred, PhiBlock, LeaderTable) ? NewNum
3365 : Num;
3366 return NewNum;
3367 }
3368 return Num;
3369}
3370
3371/// Erase stale entry from phiTranslate cache so phiTranslate can be computed
3372/// again.
3374 const BasicBlock &CurrBlock) {
3375 for (const BasicBlock *Pred : predecessors(&CurrBlock))
3376 PhiTranslateTable.erase({Num, Pred});
3377}
3378
3379// In order to find a leader for a given value number at a
3380// specific basic block, we first obtain the list of all Values for that number,
3381// and then scan the list to find one whose block dominates the block in
3382// question. This is fast because dominator tree queries consist of only
3383// a few comparisons of DFS numbers.
3384Value *GVNPassImpl::findLeader(const BasicBlock *BB, uint32_t Num) {
3385 auto Leaders = LeaderTable.getLeaders(Num);
3386 if (Leaders.empty())
3387 return nullptr;
3388
3389 Value *Val = nullptr;
3390 for (const auto &Entry : Leaders) {
3391 if (DT->dominates(Entry.BB, BB)) {
3392 Val = Entry.Val;
3393 if (isa<Constant>(Val))
3394 return Val;
3395 }
3396 }
3397
3398 return Val;
3399}
3400
3401/// There is an edge from 'Src' to 'Dst'. Return
3402/// true if every path from the entry block to 'Dst' passes via this edge. In
3403/// particular 'Dst' must not be reachable via another edge from 'Src'.
3405 DominatorTree *DT) {
3406 // While in theory it is interesting to consider the case in which Dst has
3407 // more than one predecessor, because Dst might be part of a loop which is
3408 // only reachable from Src, in practice it is pointless since at the time
3409 // GVN runs all such loops have preheaders, which means that Dst will have
3410 // been changed to have only one predecessor, namely Src.
3411 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
3412 assert((!Pred || Pred == E.getStart()) &&
3413 "No edge between these basic blocks!");
3414 return Pred != nullptr;
3415}
3416
3417void GVNPassImpl::assignBlockRPONumber(Function &F) {
3418 BlockRPONumber.clear();
3419 uint32_t NextBlockNumber = 1;
3421 for (BasicBlock *BB : RPOT)
3422 BlockRPONumber[BB] = NextBlockNumber++;
3423 InvalidBlockRPONumbers = false;
3424}
3425
3426/// The given values are known to be equal in every use
3427/// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
3428/// 'RHS' everywhere in the scope. Returns whether a change was made.
3429/// The Root may either be a basic block edge (for conditions) or an
3430/// instruction (for assumes).
3431bool GVNPassImpl::propagateEquality(
3432 Value *LHS, Value *RHS,
3433 const std::variant<BasicBlockEdge, Instruction *> &Root) {
3436 Worklist.push_back(std::make_pair(LHS, RHS));
3437 bool Changed = false;
3438 SmallVector<const BasicBlock *> DominatedBlocks;
3439 if (const BasicBlockEdge *Edge = std::get_if<BasicBlockEdge>(&Root)) {
3440 // For speed, compute a conservative fast approximation to
3441 // DT->dominates(Root, Root.getEnd());
3443 DominatedBlocks.push_back(Edge->getEnd());
3444 } else {
3445 Instruction *I = std::get<Instruction *>(Root);
3446 for (const auto *Node : DT->getNode(I->getParent())->children())
3447 DominatedBlocks.push_back(Node->getBlock());
3448 }
3449
3450 while (!Worklist.empty()) {
3451 std::pair<Value*, Value*> Item = Worklist.pop_back_val();
3452 LHS = Item.first; RHS = Item.second;
3453
3454 if (LHS == RHS)
3455 continue;
3456 assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
3457
3458 // Don't try to propagate equalities between constants.
3460 continue;
3461
3462 // Prefer a constant on the right-hand side, or an Argument if no constants.
3464 std::swap(LHS, RHS);
3465 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
3466 const DataLayout &DL =
3468 ? cast<Argument>(LHS)->getParent()->getDataLayout()
3469 : cast<Instruction>(LHS)->getDataLayout();
3470
3471 // If there is no obvious reason to prefer the left-hand side over the
3472 // right-hand side, ensure the longest lived term is on the right-hand side,
3473 // so the shortest lived term will be replaced by the longest lived.
3474 // This tends to expose more simplifications.
3475 uint32_t LVN = VN.lookupOrAdd(LHS);
3476 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
3478 // Move the 'oldest' value to the right-hand side, using the value number
3479 // as a proxy for age.
3480 uint32_t RVN = VN.lookupOrAdd(RHS);
3481 if (LVN < RVN) {
3482 std::swap(LHS, RHS);
3483 LVN = RVN;
3484 }
3485 }
3486
3487 if (!Visited.insert({LHS, RHS}).second)
3488 continue;
3489
3490 // If value numbering later sees that an instruction in the scope is equal
3491 // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
3492 // the invariant that instructions only occur in the leader table for their
3493 // own value number (this is used by removeFromLeaderTable), do not do this
3494 // if RHS is an instruction (if an instruction in the scope is morphed into
3495 // LHS then it will be turned into RHS by the next GVN iteration anyway, so
3496 // using the leader table is about compiling faster, not optimizing better).
3497 // The leader table only tracks basic blocks, not edges. Only add to if we
3498 // have the simple case where the edge dominates the end.
3500 for (const BasicBlock *BB : DominatedBlocks)
3501 LeaderTable.insert(LVN, RHS, BB);
3502
3503 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
3504 // LHS always has at least one use that is not dominated by Root, this will
3505 // never do anything if LHS has only one use.
3506 if (!LHS->hasOneUse()) {
3507 // Create a callback that captures the DL.
3508 auto CanReplacePointersCallBack = [&DL](const Use &U, const Value *To) {
3509 return canReplacePointersInUseIfEqual(U, To, DL);
3510 };
3511 unsigned NumReplacements;
3512 if (const BasicBlockEdge *Edge = std::get_if<BasicBlockEdge>(&Root))
3513 NumReplacements = replaceDominatedUsesWithIf(
3514 LHS, RHS, *DT, *Edge, CanReplacePointersCallBack);
3515 else
3516 NumReplacements = replaceDominatedUsesWithIf(
3517 LHS, RHS, *DT, std::get<Instruction *>(Root),
3518 CanReplacePointersCallBack);
3519
3520 if (NumReplacements > 0) {
3521 Changed = true;
3522 NumGVNEqProp += NumReplacements;
3523 // Cached information for anything that uses LHS will be invalid.
3524 if (MD)
3526 }
3527 }
3528
3529 // Now try to deduce additional equalities from this one. For example, if
3530 // the known equality was "(A != B)" == "false" then it follows that A and B
3531 // are equal in the scope. Only boolean equalities with an explicit true or
3532 // false RHS are currently supported.
3533 if (!RHS->getType()->isIntegerTy(1))
3534 // Not a boolean equality - bail out.
3535 continue;
3537 if (!CI)
3538 // RHS neither 'true' nor 'false' - bail out.
3539 continue;
3540 // Whether RHS equals 'true'. Otherwise it equals 'false'.
3541 bool IsKnownTrue = CI->isMinusOne();
3542 bool IsKnownFalse = !IsKnownTrue;
3543
3544 // If "A && B" is known true then both A and B are known true. If "A || B"
3545 // is known false then both A and B are known false.
3546 Value *A, *B;
3547 if ((IsKnownTrue && match(LHS, m_LogicalAnd(m_Value(A), m_Value(B)))) ||
3548 (IsKnownFalse && match(LHS, m_LogicalOr(m_Value(A), m_Value(B))))) {
3549 Worklist.push_back(std::make_pair(A, RHS));
3550 Worklist.push_back(std::make_pair(B, RHS));
3551 continue;
3552 }
3553
3554 // If we are propagating an equality like "(A == B)" == "true" then also
3555 // propagate the equality A == B. When propagating a comparison such as
3556 // "(A >= B)" == "true", replace all instances of "A < B" with "false".
3557 if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
3558 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
3559
3560 // If "A == B" is known true, or "A != B" is known false, then replace
3561 // A with B everywhere in the scope. For floating point operations, we
3562 // have to be careful since equality does not always imply equivalance.
3563 if (Cmp->isEquivalence(IsKnownFalse))
3564 Worklist.push_back(std::make_pair(Op0, Op1));
3565
3566 // If "A >= B" is known true, replace "A < B" with false everywhere.
3567 CmpInst::Predicate NotPred = Cmp->getInversePredicate();
3568 Constant *NotVal = ConstantInt::get(Cmp->getType(), IsKnownFalse);
3569 // Since we don't have the instruction "A < B" immediately to hand, work
3570 // out the value number that it would have and use that to find an
3571 // appropriate instruction (if any).
3572 uint32_t NextNum = VN.getNextUnusedValueNumber();
3573 uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
3574 // If the number we were assigned was brand new then there is no point in
3575 // looking for an instruction realizing it: there cannot be one!
3576 if (Num < NextNum) {
3577 for (const auto &Entry : LeaderTable.getLeaders(Num)) {
3578 // Only look at leaders that either dominate the start of the edge,
3579 // or are dominated by the end. This check is not necessary for
3580 // correctness, it only discards cases for which the following
3581 // use replacement will not work anyway.
3582 if (const BasicBlockEdge *Edge = std::get_if<BasicBlockEdge>(&Root)) {
3583 if (!DT->dominates(Entry.BB, Edge->getStart()) &&
3584 !DT->dominates(Edge->getEnd(), Entry.BB))
3585 continue;
3586 } else {
3587 auto *InstBB = std::get<Instruction *>(Root)->getParent();
3588 if (!DT->dominates(Entry.BB, InstBB) &&
3589 !DT->dominates(InstBB, Entry.BB))
3590 continue;
3591 }
3592
3593 Value *NotCmp = Entry.Val;
3594 if (NotCmp && isa<Instruction>(NotCmp)) {
3595 unsigned NumReplacements;
3596 if (const BasicBlockEdge *Edge = std::get_if<BasicBlockEdge>(&Root))
3597 NumReplacements =
3598 replaceDominatedUsesWith(NotCmp, NotVal, *DT, *Edge);
3599 else
3600 NumReplacements = replaceDominatedUsesWith(
3601 NotCmp, NotVal, *DT, std::get<Instruction *>(Root));
3602 Changed |= NumReplacements > 0;
3603 NumGVNEqProp += NumReplacements;
3604 // Cached information for anything that uses NotCmp will be invalid.
3605 if (MD)
3606 MD->invalidateCachedPointerInfo(NotCmp);
3607 }
3608 }
3609 }
3610 // Ensure that any instruction in scope that gets the "A < B" value number
3611 // is replaced with false.
3612 // The leader table only tracks basic blocks, not edges. Only add to if we
3613 // have the simple case where the edge dominates the end.
3614 for (const BasicBlock *BB : DominatedBlocks)
3615 LeaderTable.insert(Num, NotVal, BB);
3616
3617 continue;
3618 }
3619
3620 // Propagate equalities that results from truncation with no unsigned wrap
3621 // like (trunc nuw i64 %v to i1) == "true" or (trunc nuw i64 %v to i1) ==
3622 // "false"
3623 if (match(LHS, m_NUWTrunc(m_Value(A)))) {
3624 Worklist.emplace_back(A, ConstantInt::get(A->getType(), IsKnownTrue));
3625 continue;
3626 }
3627
3628 if (match(LHS, m_Not(m_Value(A)))) {
3629 Worklist.emplace_back(A, ConstantInt::get(A->getType(), !IsKnownTrue));
3630 continue;
3631 }
3632 }
3633
3634 return Changed;
3635}
3636
3637/// When calculating availability, handle an instruction
3638/// by inserting it into the appropriate sets.
3639bool GVNPassImpl::processInstruction(Instruction *I) {
3640 // If the instruction can be easily simplified then do so now in preference
3641 // to value numbering it. Value numbering often exposes redundancies, for
3642 // example if it determines that %y is equal to %x then the instruction
3643 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
3644 const DataLayout &DL = I->getDataLayout();
3645 if (Value *V = simplifyInstruction(I, {DL, TLI, DT, AC})) {
3646 bool Changed = false;
3647 if (!I->use_empty()) {
3648 // Simplification can cause a special instruction to become not special.
3649 // For example, devirtualization to a willreturn function.
3650 ICF->removeUsersOf(I);
3651 I->replaceAllUsesWith(V);
3652 Changed = true;
3653 }
3654 if (isInstructionTriviallyDead(I, TLI)) {
3655 salvageAndRemoveInstruction(I);
3656 Changed = true;
3657 }
3658 if (Changed) {
3659 if (MD && V->getType()->isPtrOrPtrVectorTy())
3661 ++NumGVNSimpl;
3662 return true;
3663 }
3664 }
3665
3666 if (auto *Assume = dyn_cast<AssumeInst>(I))
3667 return processAssumeIntrinsic(Assume);
3668
3670 if (processLoad(Load))
3671 return true;
3672
3673 unsigned Num = VN.lookupOrAdd(Load);
3674 LeaderTable.insert(Num, Load, Load->getParent());
3675 return false;
3676 }
3677
3679 processMaskedLoad(cast<IntrinsicInst>(I)))
3680 return true;
3681
3682 // For conditional branches, we can perform simple conditional propagation on
3683 // the condition value itself.
3684 if (CondBrInst *BI = dyn_cast<CondBrInst>(I)) {
3685 if (isa<Constant>(BI->getCondition()))
3686 return processFoldableCondBr(BI);
3687
3688 Value *BranchCond = BI->getCondition();
3689 BasicBlock *TrueSucc = BI->getSuccessor(0);
3690 BasicBlock *FalseSucc = BI->getSuccessor(1);
3691 // Avoid multiple edges early.
3692 if (TrueSucc == FalseSucc)
3693 return false;
3694
3695 BasicBlock *Parent = BI->getParent();
3696 bool Changed = false;
3697
3699 BasicBlockEdge TrueE(Parent, TrueSucc);
3700 Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
3701
3703 BasicBlockEdge FalseE(Parent, FalseSucc);
3704 Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
3705
3706 return Changed;
3707 }
3708
3709 // For switches, propagate the case values into the case destinations.
3711 Value *SwitchCond = SI->getCondition();
3712 BasicBlock *Parent = SI->getParent();
3713 bool Changed = false;
3714
3715 // Remember how many outgoing edges there are to every successor.
3717 for (BasicBlock *Succ : successors(Parent))
3718 ++SwitchEdges[Succ];
3719
3720 for (const auto &Case : SI->cases()) {
3721 BasicBlock *Dst = Case.getCaseSuccessor();
3722 // If there is only a single edge, propagate the case value into it.
3723 if (SwitchEdges.lookup(Dst) == 1) {
3724 BasicBlockEdge E(Parent, Dst);
3725 Changed |= propagateEquality(SwitchCond, Case.getCaseValue(), E);
3726 }
3727 }
3728 return Changed;
3729 }
3730
3731 // Instructions with void type don't return a value, so there's
3732 // no point in trying to find redundancies in them.
3733 if (I->getType()->isVoidTy())
3734 return false;
3735
3736 uint32_t NextNum = VN.getNextUnusedValueNumber();
3737 unsigned Num = VN.lookupOrAdd(I);
3738
3739 // Allocations are always uniquely numbered, so we can save time and memory
3740 // by fast failing them.
3741 if (isa<AllocaInst>(I) || I->isTerminator() || isa<PHINode>(I)) {
3742 LeaderTable.insert(Num, I, I->getParent());
3743 return false;
3744 }
3745
3746 // A ptrtoaddr and a ptrtoint of the same pointer compute the same value when
3747 // the address width equals the pointer representation width.
3748 if (auto *PTA = dyn_cast<PtrToAddrInst>(I)) {
3749 const DataLayout &DL = I->getDataLayout();
3750 unsigned AS = PTA->getPointerAddressSpace();
3751 if (DL.getAddressSizeInBits(AS) == DL.getPointerSizeInBits(AS) &&
3752 !DL.hasUnstableRepresentation(AS)) {
3753 uint32_t PTINum =
3754 VN.lookupPtrToInt(PTA->getPointerOperand(), PTA->getType());
3755 if (Value *PTI = findLeader(I->getParent(), PTINum)) {
3757 salvageAndRemoveInstruction(I);
3758 return true;
3759 }
3760 }
3761 }
3762
3763 // Perform fast-path value-number based elimination of values inherited from
3764 // dominators, unless the number we were assigned was a brand new VN, then
3765 // we don't need to do a lookup to see if the number already exists somewhere
3766 // in the domtree: it can't!
3767 Value *Repl = Num < NextNum ? findLeader(I->getParent(), Num) : nullptr;
3768 if (!Repl) {
3769 // Substitute cmp instruction with not if possible.
3770 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
3771 uint32_t NotNum =
3772 VN.lookupCmp(Cmp->getOpcode(), Cmp->getInversePredicate(),
3773 Cmp->getOperand(0), Cmp->getOperand(1));
3774 if (NotNum != 0) {
3775 Value *NotRepl = findLeader(I->getParent(), NotNum);
3776 if (NotRepl) {
3779 NotRepl, NotRepl->getName() + ".not", I->getIterator());
3780 Not->setDebugLoc(I->getDebugLoc());
3781 I->replaceAllUsesWith(Not);
3782 salvageAndRemoveInstruction(I);
3783 return true;
3784 }
3785 }
3786 auto *ICmp = dyn_cast<ICmpInst>(Cmp);
3787 if (ICmp && ICmp->hasSameSign() && !ICmp->isEquality()) {
3788 uint32_t SameSignNum = VN.lookupCmp(
3789 ICmp->getOpcode(),
3790 ICmpInst::getFlippedSignednessPredicate(ICmp->getPredicate()),
3791 ICmp->getOperand(0), ICmp->getOperand(1));
3792 if (SameSignNum != 0) {
3793 Repl = findLeader(I->getParent(), SameSignNum);
3794 if (Repl) {
3796 salvageAndRemoveInstruction(I);
3797 return true;
3798 }
3799 }
3800 }
3801 }
3802 // Failure, just remember this instance for future use.
3803 LeaderTable.insert(Num, I, I->getParent());
3804 return false;
3805 }
3806
3807 if (Repl == I) {
3808 // If I was the result of a shortcut PRE, it might already be in the table
3809 // and the best replacement for itself. Nothing to do.
3810 return false;
3811 }
3812
3813 // Remove it!
3815 if (MD && Repl->getType()->isPtrOrPtrVectorTy())
3817 salvageAndRemoveInstruction(I);
3818 return true;
3819}
3820
3821/// runOnFunction - This is the main transformation entry point for a function.
3822bool GVNPassImpl::run(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
3823 const TargetLibraryInfo &RunTLI, AAResults &RunAA,
3825 OptimizationRemarkEmitter *RunORE, MemorySSA *MSSA) {
3826 // MemDep and MemorySSA are mutually exclusive. isMemDepEnabled() silently
3827 // lets MemorySSA win for the common single-flag case, but an explicit
3828 // request for both via -enable-gvn-{memdep,memoryssa} is a contradiction we
3829 // reject rather than resolve arbitrarily.
3832 report_fatal_error("GVN: -enable-gvn-memdep and -enable-gvn-memoryssa are "
3833 "mutually exclusive",
3834 /*gen_crash_diag=*/false);
3835 AC = &RunAC;
3836 DT = &RunDT;
3837 VN.setDomTree(DT);
3838 TLI = &RunTLI;
3839 AA = &RunAA;
3840 VN.setAliasAnalysis(&RunAA);
3841 MD = RunMD;
3842 ImplicitControlFlowTracking ImplicitCFT;
3843 ICF = &ImplicitCFT;
3844 this->LI = &LI;
3845 VN.setMemDep(MD);
3846 // Propagate the MSSA-enabled flag so the value-numbering paths in
3847 // lookupOrAddCall() and computeLoadStoreVN(), which depends on whether
3848 // IsMSSAEnabled is turned on.
3849 VN.setMemorySSA(MSSA, isMemorySSAEnabled());
3850 ORE = RunORE;
3851 InvalidBlockRPONumbers = true;
3852 MemorySSAUpdater Updater(MSSA);
3853 MSSAU = MSSA ? &Updater : nullptr;
3854
3855 bool Changed = false;
3856 bool ShouldContinue = true;
3857
3858 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
3859 // Merge unconditional branches, allowing PRE to catch more
3860 // optimization opportunities.
3861 for (BasicBlock &BB : make_early_inc_range(F)) {
3862 bool RemovedBlock = MergeBlockIntoPredecessor(&BB, &DTU, &LI, MSSAU, MD);
3863 if (RemovedBlock)
3864 ++NumGVNBlocks;
3865
3866 Changed |= RemovedBlock;
3867 }
3868 DTU.flush();
3869
3870 unsigned Iteration = 0;
3871 while (ShouldContinue) {
3872 LLVM_DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
3873 (void) Iteration;
3874 ShouldContinue = iterateOnFunction(F);
3875 Changed |= ShouldContinue;
3876 ++Iteration;
3877 }
3878
3879 if (isScalarPREEnabled()) {
3880 // Fabricate val-num for dead-code in order to suppress assertion in
3881 // performPRE().
3882 assignValNumForDeadCode();
3883 bool PREChanged = true;
3884 while (PREChanged) {
3885 PREChanged = performPRE(F);
3886 Changed |= PREChanged;
3887 }
3888 }
3889
3890 // FIXME: Should perform GVN again after PRE does something. PRE can move
3891 // computations into blocks where they become fully redundant. Note that
3892 // we can't do this until PRE's critical edge splitting updates memdep.
3893 // Actually, when this happens, we should just fully integrate PRE into GVN.
3894
3895 cleanupGlobalSets();
3896 // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
3897 // iteration.
3898 DeadBlocks.clear();
3899
3900 if (MSSA && VerifyMemorySSA)
3901 MSSA->verifyMemorySSA();
3902
3903 return Changed;
3904}
3905
3906bool GVNPassImpl::processBlock(BasicBlock *BB) {
3907 if (DeadBlocks.count(BB))
3908 return false;
3909
3910 bool ChangedFunction = false;
3911
3912 // Since we may not have visited the input blocks of the phis, we can't
3913 // use our normal hash approach for phis. Instead, simply look for
3914 // obvious duplicates. The first pass of GVN will tend to create
3915 // identical phis, and the second or later passes can eliminate them.
3916 SmallPtrSet<PHINode *, 8> PHINodesToRemove;
3917 ChangedFunction |= EliminateDuplicatePHINodes(BB, PHINodesToRemove);
3918 for (PHINode *PN : PHINodesToRemove) {
3919 removeInstruction(PN);
3920 }
3921 for (Instruction &Inst : make_early_inc_range(*BB))
3922 ChangedFunction |= processInstruction(&Inst);
3923 return ChangedFunction;
3924}
3925
3926// Instantiate an expression in a predecessor that lacked it.
3927bool GVNPassImpl::performScalarPREInsertion(Instruction *Instr,
3928 BasicBlock *Pred, BasicBlock *Curr,
3929 unsigned int ValNo) {
3930 // Because we are going top-down through the block, all value numbers
3931 // will be available in the predecessor by the time we need them. Any
3932 // that weren't originally present will have been instantiated earlier
3933 // in this loop.
3934 bool Success = true;
3935 for (unsigned I = 0, E = Instr->getNumOperands(); I != E; ++I) {
3936 Value *Op = Instr->getOperand(I);
3938 continue;
3939 // This could be a newly inserted instruction, in which case, we won't
3940 // find a value number, and should give up before we hurt ourselves.
3941 // FIXME: Rewrite the infrastructure to let it easier to value number
3942 // and process newly inserted instructions.
3943 if (!VN.exists(Op)) {
3944 Success = false;
3945 break;
3946 }
3947 uint32_t TValNo = VN.phiTranslate(Pred, Curr, VN.lookup(Op), LeaderTable);
3948 if (Value *V = findLeader(Pred, TValNo)) {
3949 Instr->setOperand(I, V);
3950 } else {
3951 Success = false;
3952 break;
3953 }
3954 }
3955
3956 // Fail out if we encounter an operand that is not available in
3957 // the PRE predecessor. This is typically because of loads which
3958 // are not value numbered precisely.
3959 if (!Success)
3960 return false;
3961
3962 Instr->insertBefore(Pred->getTerminator()->getIterator());
3963 Instr->setName(Instr->getName() + ".pre");
3964 Instr->setDebugLoc(Instr->getDebugLoc());
3965
3966 ICF->insertInstructionTo(Instr, Pred);
3967
3968 unsigned Num = VN.lookupOrAdd(Instr);
3969 VN.add(Instr, Num);
3970
3971 // Update the availability map to include the new instruction.
3972 LeaderTable.insert(Num, Instr, Pred);
3973 return true;
3974}
3975
3976bool GVNPassImpl::performScalarPRE(Instruction *CurInst) {
3977 if (isa<AllocaInst>(CurInst) || CurInst->isTerminator() ||
3978 isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
3979 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
3980 CurInst->getType()->isTokenLikeTy())
3981 return false;
3982
3983 // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
3984 // sinking the compare again, and it would force the code generator to
3985 // move the i1 from processor flags or predicate registers into a general
3986 // purpose register.
3987 if (isa<CmpInst>(CurInst))
3988 return false;
3989
3990 // Don't do PRE on GEPs. The inserted PHI would prevent CodeGenPrepare from
3991 // sinking the addressing mode computation back to its uses. Extending the
3992 // GEP's live range increases the register pressure, and therefore it can
3993 // introduce unnecessary spills.
3994 //
3995 // This doesn't prevent Load PRE. PHI translation will make the GEP available
3996 // to the load by moving it to the predecessor block if necessary.
3997 if (isa<GetElementPtrInst>(CurInst))
3998 return false;
3999
4000 if (auto *CallB = dyn_cast<CallBase>(CurInst)) {
4001 // We don't currently value number ANY inline asm calls.
4002 if (CallB->isInlineAsm())
4003 return false;
4004 }
4005
4006 uint32_t ValNo = VN.lookup(CurInst);
4007
4008 // Look for the predecessors for PRE opportunities. We're
4009 // only trying to solve the basic diamond case, where
4010 // a value is computed in the successor and one predecessor,
4011 // but not the other. We also explicitly disallow cases
4012 // where the successor is its own predecessor, because they're
4013 // more complicated to get right.
4014 unsigned NumWith = 0;
4015 unsigned NumWithout = 0;
4016 BasicBlock *PREPred = nullptr;
4017 BasicBlock *CurrentBlock = CurInst->getParent();
4018
4019 // Update the RPO numbers for this function.
4020 if (InvalidBlockRPONumbers)
4021 assignBlockRPONumber(*CurrentBlock->getParent());
4022
4024 for (BasicBlock *P : predecessors(CurrentBlock)) {
4025 // We're not interested in PRE where blocks with predecessors that are
4026 // not reachable.
4027 if (!DT->isReachableFromEntry(P)) {
4028 NumWithout = 2;
4029 break;
4030 }
4031 // It is not safe to do PRE when P->CurrentBlock is a loop backedge.
4032 assert(BlockRPONumber.count(P) && BlockRPONumber.count(CurrentBlock) &&
4033 "Invalid BlockRPONumber map.");
4034 if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock]) {
4035 NumWithout = 2;
4036 break;
4037 }
4038
4039 uint32_t TValNo = VN.phiTranslate(P, CurrentBlock, ValNo, LeaderTable);
4040 Value *PredV = findLeader(P, TValNo);
4041 if (!PredV) {
4042 PredMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
4043 PREPred = P;
4044 ++NumWithout;
4045 } else if (PredV == CurInst) {
4046 // CurInst dominates this predecessor.
4047 NumWithout = 2;
4048 break;
4049 } else {
4050 PredMap.push_back(std::make_pair(PredV, P));
4051 ++NumWith;
4052 }
4053 }
4054
4055 // Don't do PRE when it might increase code size, i.e. when
4056 // we would need to insert instructions in more than one pred.
4057 if (NumWithout > 1 || NumWith == 0)
4058 return false;
4059
4060 // We may have a case where all predecessors have the instruction,
4061 // and we just need to insert a phi node. Otherwise, perform
4062 // insertion.
4063 Instruction *PREInstr = nullptr;
4064
4065 if (NumWithout != 0) {
4066 if (!isSafeToSpeculativelyExecute(CurInst)) {
4067 // It is only valid to insert a new instruction if the current instruction
4068 // is always executed. An instruction with implicit control flow could
4069 // prevent us from doing it. If we cannot speculate the execution, then
4070 // PRE should be prohibited.
4071 if (ICF->isDominatedByICFIFromSameBlock(CurInst))
4072 return false;
4073 }
4074
4075 // Don't do PRE across indirect branch.
4076 if (isa<IndirectBrInst>(PREPred->getTerminator()))
4077 return false;
4078
4079 // We can't do PRE safely on a critical edge, so instead we schedule
4080 // the edge to be split and perform the PRE the next time we iterate
4081 // on the function.
4082 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
4083 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
4084 ToSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
4085 return false;
4086 }
4087 // We need to insert somewhere, so let's give it a shot.
4088 PREInstr = CurInst->clone();
4089 if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
4090 // If we failed insertion, make sure we remove the instruction.
4091#ifndef NDEBUG
4092 verifyRemoved(PREInstr);
4093#endif
4094 PREInstr->deleteValue();
4095 return false;
4096 }
4097 }
4098
4099 // Either we should have filled in the PRE instruction, or we should
4100 // not have needed insertions.
4101 assert(PREInstr != nullptr || NumWithout == 0);
4102
4103 ++NumGVNPRE;
4104
4105 // Create a PHI to make the value available in this block.
4106 PHINode *Phi = PHINode::Create(CurInst->getType(), PredMap.size(),
4107 CurInst->getName() + ".pre-phi");
4108 Phi->insertBefore(CurrentBlock->begin());
4109 for (auto &[V, BB] : PredMap) {
4110 if (V) {
4111 // If we use an existing value in this phi, we have to patch the original
4112 // value because the phi will be used to replace a later value.
4113 patchReplacementInstruction(CurInst, V);
4114 Phi->addIncoming(V, BB);
4115 } else
4116 Phi->addIncoming(PREInstr, PREPred);
4117 }
4118
4119 VN.add(Phi, ValNo);
4120 // After creating a new PHI for ValNo, the phi translate result for ValNo will
4121 // be changed, so erase the related stale entries in phi translate cache.
4122 VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock);
4123 LeaderTable.insert(ValNo, Phi, CurrentBlock);
4124 Phi->setDebugLoc(CurInst->getDebugLoc());
4125 CurInst->replaceAllUsesWith(Phi);
4126 if (MD && Phi->getType()->isPtrOrPtrVectorTy())
4128 LeaderTable.erase(ValNo, CurInst, CurrentBlock);
4129
4130 LLVM_DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
4131 removeInstruction(CurInst);
4132
4133 return true;
4134}
4135
4136/// Perform a purely local form of PRE that looks for diamond
4137/// control flow patterns and attempts to perform simple PRE at the join point.
4138bool GVNPassImpl::performPRE(Function &F) {
4139 bool Changed = false;
4140 for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
4141 // Nothing to PRE in the entry block.
4142 if (CurrentBlock == &F.getEntryBlock())
4143 continue;
4144
4145 // Don't perform PRE on an EH pad.
4146 if (CurrentBlock->isEHPad())
4147 continue;
4148
4149 for (BasicBlock::iterator BI = CurrentBlock->begin(),
4150 BE = CurrentBlock->end();
4151 BI != BE;) {
4152 Instruction *CurInst = &*BI++;
4153 Changed |= performScalarPRE(CurInst);
4154 }
4155 }
4156
4157 if (splitCriticalEdges())
4158 Changed = true;
4159
4160 return Changed;
4161}
4162
4163/// Split the critical edge connecting the given two blocks, and return
4164/// the block inserted to the critical edge.
4165BasicBlock *GVNPassImpl::splitCriticalEdges(BasicBlock *Pred,
4166 BasicBlock *Succ) {
4167 // GVN does not require loop-simplify, do not try to preserve it if it is not
4168 // possible.
4170 Pred, Succ,
4171 CriticalEdgeSplittingOptions(DT, LI, MSSAU).unsetPreserveLoopSimplify());
4172 if (BB) {
4173 if (MD)
4175 InvalidBlockRPONumbers = true;
4176 }
4177 return BB;
4178}
4179
4180/// Split critical edges found during the previous
4181/// iteration that may enable further optimization.
4182bool GVNPassImpl::splitCriticalEdges() {
4183 if (ToSplit.empty())
4184 return false;
4185
4186 bool Changed = false;
4187 do {
4188 std::pair<Instruction *, unsigned> Edge = ToSplit.pop_back_val();
4189 Changed |= SplitCriticalEdge(Edge.first, Edge.second,
4190 CriticalEdgeSplittingOptions(DT, LI, MSSAU)) !=
4191 nullptr;
4192 } while (!ToSplit.empty());
4193 if (Changed) {
4194 if (MD)
4196 InvalidBlockRPONumbers = true;
4197 }
4198 return Changed;
4199}
4200
4201/// Executes one iteration of GVN.
4202bool GVNPassImpl::iterateOnFunction(Function &F) {
4203 cleanupGlobalSets();
4204
4205 // Top-down walk of the dominator tree.
4206 bool Changed = false;
4207 // Needed for value numbering with phi construction to work.
4208 // RPOT walks the graph in its constructor and will not be invalidated during
4209 // processBlock.
4211
4212 for (BasicBlock *BB : RPOT)
4213 Changed |= processBlock(BB);
4214
4215 return Changed;
4216}
4217
4218void GVNPassImpl::cleanupGlobalSets() {
4219 VN.clear();
4220 LeaderTable.clear();
4221 BlockRPONumber.clear();
4222 ICF->clear();
4223 InvalidBlockRPONumbers = true;
4224}
4225
4226void GVNPassImpl::removeInstruction(Instruction *I) {
4227 VN.erase(I);
4228 if (MD) MD->removeInstruction(I);
4229 if (MSSAU)
4230 MSSAU->removeMemoryAccess(I);
4231#ifndef NDEBUG
4232 verifyRemoved(I);
4233#endif
4234 ICF->removeInstruction(I);
4235 I->eraseFromParent();
4236 ++NumGVNInstr;
4237}
4238
4239/// Verify that the specified instruction does not occur in our
4240/// internal data structures.
4241void GVNPassImpl::verifyRemoved(const Instruction *Inst) const {
4242 VN.verifyRemoved(Inst);
4243}
4244
4245/// BB is declared dead, which implied other blocks become dead as well. This
4246/// function is to add all these blocks to "DeadBlocks". For the dead blocks'
4247/// live successors, update their phi nodes by replacing the operands
4248/// corresponding to dead blocks with UndefVal.
4249void GVNPassImpl::addDeadBlock(BasicBlock *BB) {
4252
4253 NewDead.push_back(BB);
4254 while (!NewDead.empty()) {
4255 BasicBlock *D = NewDead.pop_back_val();
4256 if (DeadBlocks.count(D))
4257 continue;
4258
4259 // All blocks dominated by D are dead.
4261 DT->getDescendants(D, Dom);
4262 DeadBlocks.insert_range(Dom);
4263
4264 // Figure out the dominance-frontier(D).
4265 for (BasicBlock *B : Dom) {
4266 for (BasicBlock *S : successors(B)) {
4267 if (DeadBlocks.count(S))
4268 continue;
4269
4270 bool AllPredDead = true;
4271 for (BasicBlock *P : predecessors(S))
4272 if (!DeadBlocks.count(P)) {
4273 AllPredDead = false;
4274 break;
4275 }
4276
4277 if (!AllPredDead) {
4278 // S could be proved dead later on. That is why we don't update phi
4279 // operands at this moment.
4280 DF.insert(S);
4281 } else {
4282 // While S is not dominated by D, it is dead by now. This could take
4283 // place if S already have a dead predecessor before D is declared
4284 // dead.
4285 NewDead.push_back(S);
4286 }
4287 }
4288 }
4289 }
4290
4291 // For the dead blocks' live successors, update their phi nodes by replacing
4292 // the operands corresponding to dead blocks with UndefVal.
4293 for (BasicBlock *B : DF) {
4294 if (DeadBlocks.count(B))
4295 continue;
4296
4297 // First, split the critical edges. This might also create additional blocks
4298 // to preserve LoopSimplify form and adjust edges accordingly.
4300 for (BasicBlock *P : Preds) {
4301 if (!DeadBlocks.count(P))
4302 continue;
4303
4304 if (is_contained(successors(P), B) &&
4305 isCriticalEdge(P->getTerminator(), B)) {
4306 if (BasicBlock *S = splitCriticalEdges(P, B))
4307 DeadBlocks.insert(P = S);
4308 }
4309 }
4310
4311 // Now poison the incoming values from the dead predecessors.
4312 for (BasicBlock *P : predecessors(B)) {
4313 if (!DeadBlocks.count(P))
4314 continue;
4315 for (PHINode &Phi : B->phis()) {
4316 Phi.setIncomingValueForBlock(P, PoisonValue::get(Phi.getType()));
4317 if (MD)
4319 }
4320 }
4321 }
4322}
4323
4324// If the given branch is recognized as a foldable branch (i.e. conditional
4325// branch with constant condition), it will perform following analyses and
4326// transformation.
4327// 1) If the dead out-coming edge is a critical-edge, split it. Let
4328// R be the target of the dead out-coming edge.
4329// 1) Identify the set of dead blocks implied by the branch's dead outcoming
4330// edge. The result of this step will be {X| X is dominated by R}
4331// 2) Identify those blocks which haves at least one dead predecessor. The
4332// result of this step will be dominance-frontier(R).
4333// 3) Update the PHIs in DF(R) by replacing the operands corresponding to
4334// dead blocks with "UndefVal" in an hope these PHIs will optimized away.
4335//
4336// Return true iff *NEW* dead code are found.
4337bool GVNPassImpl::processFoldableCondBr(CondBrInst *BI) {
4338 // If a branch has two identical successors, we cannot declare either dead.
4339 if (BI->getSuccessor(0) == BI->getSuccessor(1))
4340 return false;
4341
4343 if (!Cond)
4344 return false;
4345
4346 BasicBlock *DeadRoot =
4347 Cond->getZExtValue() ? BI->getSuccessor(1) : BI->getSuccessor(0);
4348 if (DeadBlocks.count(DeadRoot))
4349 return false;
4350
4351 if (!DeadRoot->getSinglePredecessor())
4352 DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
4353
4354 addDeadBlock(DeadRoot);
4355 return true;
4356}
4357
4358// performPRE() will trigger assert if it comes across an instruction without
4359// associated val-num. As it normally has far more live instructions than dead
4360// instructions, it makes more sense just to "fabricate" a val-number for the
4361// dead code than checking if instruction involved is dead or not.
4362void GVNPassImpl::assignValNumForDeadCode() {
4363 for (BasicBlock *BB : DeadBlocks) {
4364 for (Instruction &Inst : *BB) {
4365 unsigned ValNum = VN.lookupOrAdd(&Inst);
4366 LeaderTable.insert(ValNum, &Inst, BB);
4367 }
4368 }
4369}
4370
4372public:
4373 static char ID; // Pass identification, replacement for typeid.
4374
4375 explicit GVNLegacyPass(bool MemDepAnalysis = GVNEnableMemDep,
4376 bool MemSSAAnalysis = GVNEnableMemorySSA,
4377 bool ScalarPRE = true)
4378 : FunctionPass(ID), Impl(GVNOptions()
4379 .setMemDep(MemDepAnalysis)
4380 .setMemorySSA(MemSSAAnalysis)
4381 .setScalarPRE(ScalarPRE)) {
4383 }
4384
4385 bool runOnFunction(Function &F) override {
4386 if (skipFunction(F))
4387 return false;
4388
4390 if (Impl.isMemorySSAEnabled() && !MSSAWP)
4392
4393 return Impl.run(
4394 F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
4397 getAnalysis<AAResultsWrapperPass>().getAAResults(),
4398 Impl.isMemDepEnabled()
4400 : nullptr,
4401 getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
4403 MSSAWP ? &MSSAWP->getMSSA() : nullptr);
4404 }
4405
4423
4424private:
4425 GVNPassImpl Impl;
4426};
4427
4428char GVNLegacyPass::ID = 0;
4429
4430INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
4439INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
4440
4441// The public interface to this file...
4444 return new GVNLegacyPass(GVNEnableMemDep, GVNEnableMemorySSA, ScalarPRE);
4445}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
early cse Early CSE w MemorySSA
This file provides a data structure for mapping values and expressions to congruence class IDs.
static void reportMayClobberedLoad(LoadInst *Load, Instruction *DepInst, const DominatorTree *DT, OptimizationRemarkEmitter *ORE)
Try to locate the three instruction involved in a missed load-elimination case that is due to an inte...
Definition GVN.cpp:1595
static bool isValueFullyAvailableInBlock(BasicBlock *BB, DenseMap< BasicBlock *, AvailabilityState > &FullyAvailableBlocks)
Return true if we can prove that the value we're analyzing is fully available in the specified block.
Definition GVN.cpp:1276
static Instruction * findInvariantGroupValue(LoadInst *L, DominatorTree &DT)
If a load has !invariant.group, try to find the most-dominating instruction with the same metadata an...
Definition GVN.cpp:2560
static void reportLoadElim(LoadInst *Load, Value *AvailableValue, OptimizationRemarkEmitter *ORE)
Definition GVN.cpp:2356
static cl::opt< uint32_t > MaxNumInsnsPerBlock("gvn-max-num-insns", cl::Hidden, cl::init(100), cl::desc("Max number of instructions to scan in each basic block in GVN " "(default = 100)"))
static cl::opt< bool > GVNEnableMemDep("enable-gvn-memdep", cl::init(true))
static cl::opt< bool > GVNEnableLoadInLoopPRE("enable-load-in-loop-pre", cl::init(true))
static const Instruction * findMayClobberedPtrAccess(LoadInst *Load, const DominatorTree *DT)
Definition GVN.cpp:1539
static cl::opt< uint32_t > MaxNumDeps("gvn-max-num-deps", cl::Hidden, cl::init(100), cl::desc("Max number of dependences to attempt Load PRE (default = 100)"))
static std::optional< MemoryLocation > maybeLoadStoreLocation(Instruction *I, bool AllowStores, const TargetLibraryInfo *TLI)
Return the memory location accessed by the (masked) load/store instruction I, if the instruction coul...
Definition GVN.cpp:2612
static cl::opt< uint32_t > MaxNumReachingBlocks("gvn-max-num-reaching-blocks", cl::Hidden, cl::init(200), cl::desc("Max number of blocks scanned per load in the MemorySSA " "reaching-value analysis (default = 200)"))
static cl::opt< bool > GVNEnableMemorySSA("enable-gvn-memoryssa", cl::init(false))
GVNPassImpl::AvailableValue AvailableValue
Definition GVN.cpp:1390
static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E, DominatorTree *DT)
There is an edge from 'Src' to 'Dst'.
Definition GVN.cpp:3404
static cl::opt< bool > GVNEnableScalarPRE("enable-scalar-pre", cl::init(true), cl::Hidden)
static Value * findDominatingValue(const MemoryLocation &Loc, Type *LoadTy, Instruction *From, AAResults *AA)
Definition GVN.cpp:1616
static bool liesBetween(const Instruction *From, Instruction *Between, const Instruction *To, const DominatorTree *DT)
Assuming To can be reached from both From and Between, does Between lie on every path from From to To...
Definition GVN.cpp:1530
static bool isLifetimeStart(const Instruction *Inst)
Definition GVN.cpp:1522
static cl::opt< bool > GVNEnableSplitBackedgeInLoadPRE("enable-split-backedge-in-load-pre", cl::init(false))
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl)
Definition GVN.cpp:2552
static void replaceValuesPerBlockEntry(SmallVectorImpl< AvailableValueInBlock > &ValuesPerBlock, Value *OldValue, Value *NewValue)
If the specified OldValue exists in ValuesPerBlock, replace its value with NewValue.
Definition GVN.cpp:1395
GVNPassImpl::AvailableValueInBlock AvailableValueInBlock
Definition GVN.cpp:1391
static cl::opt< unsigned > ScanUsersLimit("gvn-scan-users-limit", cl::Hidden, cl::init(100), cl::desc("The number of memory accesses to scan in a block in reaching " "memory values analysis (default = 100)"))
AvailabilityState
Definition GVN.cpp:1256
@ Unavailable
We know the block is not fully available. This is a fixpoint.
Definition GVN.cpp:1258
@ Available
We know the block is fully available. This is a fixpoint.
Definition GVN.cpp:1260
@ SpeculativelyAvailable
We do not know whether the block is fully available or not, but we are currently speculating that it ...
Definition GVN.cpp:1265
static Value * constructSSAForLoadSet(LoadInst *Load, SmallVectorImpl< AvailableValueInBlock > &ValuesPerBlock, DominatorTree &DT)
Given a set of loads specified by ValuesPerBlock, construct SSA form, allowing us to eliminate Load.
Definition GVN.cpp:1414
static cl::opt< uint32_t > MaxNumVisitedInsts("gvn-max-num-visited-insts", cl::Hidden, cl::init(100), cl::desc("Max number of visited instructions when trying to find " "dominating value of select dependency (default = 100)"))
static cl::opt< uint32_t > MaxBBSpeculations("gvn-max-block-speculations", cl::Hidden, cl::init(600), cl::desc("Max number of blocks we're willing to speculate on (and recurse " "into) when deducing if a value is fully available or not in GVN " "(default = 600)"))
static cl::opt< bool > GVNEnableLoadPRE("enable-load-pre", cl::init(true))
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static bool splitCriticalEdges(CallBrInst *CBR, DominatorTree *DT)
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file implements a map that provides insertion order iteration.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops PowerPC CTR Loops Verify
#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
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
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
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition GVN.cpp:4406
static char ID
Definition GVN.cpp:4373
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
Definition GVN.cpp:4385
GVNLegacyPass(bool MemDepAnalysis=GVNEnableMemDep, bool MemSSAAnalysis=GVNEnableMemorySSA, bool ScalarPRE=true)
Definition GVN.cpp:4375
The core GVN pass object.
Definition GVN.cpp:281
bool isMemDepEnabled() const
Definition GVN.cpp:1182
bool isScalarPREEnabled() const
Definition GVN.cpp:1165
bool isLoadPRESplitBackedgeEnabled() const
Definition GVN.cpp:1177
void salvageAndRemoveInstruction(Instruction *I)
This removes the specified instruction from our various maps and marks it for deletion.
Definition GVN.cpp:1230
DominatorTree & getDominatorTree() const
Definition GVN.cpp:294
bool isLoadInLoopPREEnabled() const
Definition GVN.cpp:1173
GVNPassImpl(llvm::GVNOptions Options={})
Definition GVN.cpp:288
bool isLoadPREEnabled() const
Definition GVN.cpp:1169
bool isMemorySSAEnabled() const
Definition GVN.cpp:1191
MemoryDependenceResults & getMemDep() const
Definition GVN.cpp:296
AAResults * getAliasAnalysis() const
Definition GVN.cpp:295
friend class GVNLegacyPass
Definition GVN.cpp:307
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
The possible results of an alias query.
@ MayAlias
The two locations may or may not alias.
@ NoAlias
The two locations do not alias at all.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
constexpr int32_t getOffset() const
constexpr bool hasOffset() const
an instruction to allocate memory on the stack
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
iterator end() const
Definition ArrayRef.h:130
iterator begin() const
Definition ArrayRef.h:129
Value handle that asserts if the Value is deleted.
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:689
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Value * getArgOperand(unsigned i) const
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:778
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:782
iterator end()
Definition DenseMap.h:702
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:809
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:872
iterator_range< iterator > children()
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
void getDescendants(NodeT *R, SmallVectorImpl< NodeT * > &Result) const
Get all nodes dominated by R, including R itself.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Context-sensitive CaptureAnalysis provider, which computes and caches the earliest common dominator c...
Class representing an expression and its matching format.
This instruction extracts a struct member or array element value from an aggregate value.
unsigned getNumIndices() const
iterator_range< idx_iterator > indices() const
idx_iterator idx_begin() const
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
FunctionPass(char &pid)
Definition Pass.h:316
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition Pass.cpp:196
const BasicBlock & getEntryBlock() const
Definition Function.h:794
Represents calls to the gc.relocate intrinsic.
leader_iterator & operator++()
Definition GVN.cpp:234
bool operator!=(const leader_iterator &Other) const
Definition GVN.cpp:242
leader_iterator(const LeaderListNode *C)
Definition GVN.cpp:233
reference operator*() const
Definition GVN.cpp:245
const LeaderTableEntry value_type
Definition GVN.cpp:228
std::forward_iterator_tag iterator_category
Definition GVN.cpp:227
bool operator==(const leader_iterator &Other) const
Definition GVN.cpp:239
A mapping from value numbers to lists of Value*'s that have that value number.
Definition GVN.cpp:201
LLVM_ABI void insert(uint32_t N, Value *V, const BasicBlock *BB)
Push a new Value to the LeaderTable onto the list for its value number.
Definition GVN.cpp:1111
LLVM_ABI void erase(uint32_t N, Instruction *I, const BasicBlock *BB)
Scan the list of values corresponding to a given value number, and remove the given instruction if en...
Definition GVN.cpp:1123
iterator_range< leader_iterator > getLeaders(uint32_t N)
Definition GVN.cpp:248
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Definition GVN.cpp:1195
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition GVN.cpp:1236
This class holds the mapping between values and value numbers.
LLVM_ABI uint32_t lookupOrAddCmp(unsigned Opcode, CmpInst::Predicate Pred, Value *LHS, Value *RHS)
Returns the value number of the given comparison, assigning it a new number if it did not have one be...
Definition GVN.cpp:1054
LLVM_ABI void erase(Value *V)
Remove a value from the value numbering.
Definition GVN.cpp:1089
LLVM_ABI uint32_t lookup(Value *V, bool Verify=true) const
Returns the value number of the specified value.
Definition GVN.cpp:1041
LLVM_ABI void add(Value *V, uint32_t Num)
add - Insert a value into the table with a specified value number.
Definition GVN.cpp:762
LLVM_ABI void eraseTranslateCacheEntry(uint32_t Num, const BasicBlock &CurrBlock)
Erase stale entry from phiTranslate cache so phiTranslate can be computed again.
Definition GVN.cpp:3373
LLVM_ABI void verifyRemoved(const Value *) const
verifyRemoved - Verify that the value is removed from all internal data structures.
Definition GVN.cpp:1101
void setAliasAnalysis(AAResults *A)
LLVM_ABI uint32_t phiTranslate(const BasicBlock *BB, const BasicBlock *PhiBlock, uint32_t Num, GVNLeaderMap &LeaderTable)
Wrap phiTranslateImpl to provide caching functionality.
Definition GVN.cpp:3241
LLVM_ABI GVNValueTable()
LLVM_ABI uint32_t lookupCmp(unsigned Opcode, CmpInst::Predicate Pred, Value *LHS, Value *RHS)
Definition GVN.cpp:1061
LLVM_ABI uint32_t lookupOrAdd(MemoryAccess *MA)
Definition GVN.cpp:945
void setMemDep(MemoryDependenceResults *M, bool MDEnabled=true)
LLVM_ABI void clear()
Remove all entries from the ValueTable.
Definition GVN.cpp:1076
LLVM_ABI bool exists(Value *V) const
Returns true if a value number exists for the specified value.
Definition GVN.cpp:941
uint32_t getNextUnusedValueNumber()
LLVM_ABI GVNValueTable & operator=(const GVNValueTable &Arg)
LLVM_ABI uint32_t lookupPtrToInt(Value *Ptr, Type *Ty)
Returns the value number of ptrtoint Ptr to \Ty.
Definition GVN.cpp:1068
void setDomTree(DominatorTree *D)
LLVM_ABI ~GVNValueTable()
void setMemorySSA(MemorySSA *M, bool MSSAEnabled=false)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Legacy wrapper pass to provide the GlobalsAAResult object.
static LLVM_ABI Predicate getFlippedSignednessPredicate(Predicate Pred)
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
This class allows to keep track on instructions with implicit control flow.
bool isDominatedByICFIFromSameBlock(const Instruction *Insn)
Returns true if the first ICFI of Insn's block exists and dominates Insn.
bool hasICF(const BasicBlock *BB)
Returns true if at least one instruction from the given basic block has implicit control flow.
LLVM_ABI void clear()
Invalidates all information from this tracking.
LLVM_ABI void removeUsersOf(const Instruction *Inst)
Notifies this tracking that we are going to replace all uses of Inst.
LLVM_ABI void insertInstructionTo(const Instruction *Inst, const BasicBlock *BB)
Notifies this tracking that we are going to insert a new instruction Inst to the basic block BB.
LLVM_ABI void removeInstruction(const Instruction *Inst)
Notifies this tracking that we are going to remove the instruction Inst It makes all necessary update...
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI bool isDebugOrPseudoInst() const LLVM_READONLY
Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool isTerminator() const
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
LLVM_ABI void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI bool isIdenticalTo(const Instruction *I) const LLVM_READONLY
Return true if the specified instruction is exactly identical to the current one.
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
size_type size() const
Definition MapVector.h:58
A memory dependence query can return one of three different answers.
bool isClobber() const
Tests if this MemDepResult represents a query that is an instruction clobber dependency.
bool isNonLocal() const
Tests if this MemDepResult represents a query that is transparent to the start of the block,...
bool isDef() const
Tests if this MemDepResult represents a query that is an instruction definition dependency.
bool isLocal() const
Tests if this MemDepResult represents a valid local query (Clobber/Def).
Instruction * getInst() const
If this is a normal dependency, returns the instruction that is depended on.
This is the common base class for memset/memcpy/memmove.
BasicBlock * getBlock() const
Definition MemorySSA.h:162
An analysis that produces MemoryDependenceResults for a function.
Provides a lazy, caching interface for making common memory aliasing information queries,...
std::vector< NonLocalDepEntry > NonLocalDepInfo
LLVM_ABI void invalidateCachedPredecessors()
Clears the PredIteratorCache info.
LLVM_ABI void invalidateCachedPointerInfo(Value *Ptr)
Invalidates cached information about the specified pointer, because it may be too conservative in mem...
std::optional< int32_t > getClobberOffset(LoadInst *DepInst) const
Return the clobber offset to dependent instruction.
LLVM_ABI void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
LLVM_ABI MemDepResult getDependency(Instruction *QueryInst)
Returns the instruction on which a memory operation depends.
LLVM_ABI const NonLocalDepInfo & getNonLocalCallDependency(CallBase *QueryCall)
Perform a full dependency query for the specified call, returning the set of blocks that the value is...
LLVM_ABI void getNonLocalPointerDependency(Instruction *QueryInst, SmallVectorImpl< NonLocalDepResult > &Result)
Perform a full dependency query for an access to the QueryInst's specified memory location,...
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance.
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Definition MemorySSA.h:529
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
Definition MemorySSA.h:542
MemoryAccess * getIncomingValue(unsigned I) const
Return incoming value number x.
Definition MemorySSA.h:532
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI MemoryUseOrDef * createMemoryAccessBefore(Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt)
Create a MemoryAccess in MemorySSA before an existing MemoryAccess.
LLVM_ABI void insertDef(MemoryDef *Def, bool RenameUses=false)
Insert a definition into the MemorySSA IR.
LLVM_ABI void insertUse(MemoryUse *Use, bool RenameUses=false)
LLVM_ABI MemoryAccess * createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, MemorySSA::InsertionPlace Point, bool CreationMustSucceed=true)
Create a MemoryAccess in MemorySSA at a specified point in a block.
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
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
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Definition MemorySSA.h:758
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:720
LLVM_ABI bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:740
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:250
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Definition MemorySSA.h:260
This is an entry in the NonLocalDepInfo cache.
This is a result from a NonLocal dependence query.
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
bool allowExtraAnalysis(StringRef PassName) const
Whether we allow for extra compile-time budget to perform more analysis to produce fewer false positi...
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PHITransAddr - An address value which tracks and handles phi translation.
LLVM_ABI Value * translateValue(BasicBlock *CurBB, BasicBlock *PredBB, const DominatorTree *DT, bool MustDominate)
translateValue - PHI translate the current address up the CFG from CurBB to Pred, updating our state ...
LLVM_ABI bool isPotentiallyPHITranslatable() const
isPotentiallyPHITranslatable - If this needs PHI translation, return true if we have some hope of doi...
bool needsPHITranslationFromBlock(BasicBlock *BB) const
needsPHITranslationFromBlock - Return true if moving from the specified BasicBlock to its predecessor...
Value * getAddr() const
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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 & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
LLVM_ABI void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
LLVM_ABI Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block.
LLVM_ABI bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
LLVM_ABI void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
Storage of either a normal Value address, or a select condition together with a pair of addresses for...
std::pair< Value *, SelectAddrs > getSelectCondAndAddrs() const
Value * getAddr() const
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
A vector that has set insertion semantics.
Definition SetVector.h:57
void insert_range(Range &&R)
Definition SetVector.h:182
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
bool erase(PtrType Ptr)
Remove pointer from the set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
Definition Type.cpp:1115
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:428
bool hasUseList() const
Check if this Value has a use-list.
Definition Value.h:346
LLVM_ABI bool canBeFreed() const
Return true if the memory object referred to by V can by freed in the scope for which the SSA value d...
Definition Value.cpp:832
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:108
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
int getNumOccurrences() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
An efficient, type-erasing, non-owning reference to a callable.
An opaque object representing a hash code.
Definition Hashing.h:77
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
@ 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.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_MaskedStore(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
Matches MaskedStore Intrinsic.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
Not(const Pred &P) -> Not< Pred >
LLVM_ABI int analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr, StoreInst *DepSI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the store at D...
LLVM_ABI Value * getMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, Type *LoadTy, Instruction *InsertPt, const DataLayout &DL)
If analyzeLoadFromClobberingMemInst returned an offset, this function can be used to actually perform...
LLVM_ABI int analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr, LoadInst *DepLI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the load at De...
LLVM_ABI Value * getValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy, Instruction *InsertPt, Function *F)
If analyzeLoadFromClobberingStore/Load returned an offset, this function can be used to actually perf...
LLVM_ABI int analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr, MemIntrinsic *DepMI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the memory int...
LLVM_ABI bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy, Function *F)
Return true if CoerceAvailableValueToLoadType would succeed if it was called.
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
hash_code hash_value(const FixedPointSemantics &Val)
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, const TargetLibraryInfo *TLI, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
LLVM_ABI unsigned replaceDominatedUsesWithIf(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge, function_ref< bool(const Use &U, const Value *To)> ShouldReplace)
Replace each use of 'From' with 'To' if that use is dominated by the given edge and the callback Shou...
Definition Local.cpp:3294
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
LLVM_ABI unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition CFG.cpp:90
auto pred_end(const MachineBasicBlock *BB)
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 FunctionPass * createGVNPass(bool ScalarPRE)
Create a legacy GVN pass.
Definition GVN.cpp:4443
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
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
constexpr from_range_t from_range
LLVM_ABI bool isStorePreservingMemoryLocation(const StoreInst *SI, const MemoryLocation &MemLoc, Align MemLocAlign, BatchAAResults &AA, unsigned ScanLimit)
Check whether SI, which may alias MemLoc, can be safely skipped.
Definition Loads.cpp:843
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
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
LLVM_ABI bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
LLVM_ABI bool isAssumeWithEmptyBundle(const AssumeInst &Assume)
Return true iff the operand bundles of the provided llvm.assume doesn't contain any valuable informat...
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
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:402
LLVM_ABI bool canReplacePointersInUseIfEqual(const Use &U, const Value *To, const DataLayout &DL)
Definition Loads.cpp:924
LLVM_ABI bool canReplacePointersIfEqual(const Value *From, const Value *To, const DataLayout &DL)
Returns true if a pointer value From can be replaced with another pointer value \To if they are deeme...
Definition Loads.cpp:944
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
Definition Local.cpp:3194
LLVM_ABI void initializeGVNLegacyPassPass(PassRegistry &)
LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge)
Replace each use of 'From' with 'To' if that use is dominated by the given edge.
Definition Local.cpp:3273
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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
@ Success
The lock was released successfully.
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
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:3122
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
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.
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI FunctionPass * createGVNPass()
Definition GVN.cpp:4442
LLVM_ABI bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
Definition CFG.cpp:335
DWARFExpression::Operation Op
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition CFG.cpp:106
constexpr unsigned BitWidth
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
iterator_range< df_iterator< T > > depth_first(const T &G)
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:390
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
Definition Local.cpp:1501
bool isStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice,...
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
#define N
Represents an AvailableValue which can be rematerialized at the end of the associated BasicBlock.
Definition GVN.cpp:598
BasicBlock * BB
BB - The basic block in question.
Definition GVN.cpp:600
static AvailableValueInBlock getUndef(BasicBlock *BB)
Definition GVN.cpp:617
Value * MaterializeAdjustedValue(LoadInst *Load) const
Emit code at the end of this block to adjust the value defined here to the specified type.
Definition GVN.cpp:623
static AvailableValueInBlock get(BasicBlock *BB, Value *V, unsigned Offset=0)
Definition GVN.cpp:612
AvailableValue AV
AV - The actual available value.
Definition GVN.cpp:603
static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV)
Definition GVN.cpp:605
Represents a particular available value that we know how to materialize.
Definition GVN.cpp:502
Value * getSimpleValue() const
Definition GVN.cpp:571
ValType Kind
Kind of the live-out value.
Definition GVN.cpp:516
Value * getSelectCondition() const
Definition GVN.cpp:586
static AvailableValue get(Value *V, unsigned Offset=0)
Definition GVN.cpp:523
bool isUndefValue() const
Definition GVN.cpp:568
static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset=0)
Definition GVN.cpp:531
bool isSimpleValue() const
Definition GVN.cpp:565
Value * V1
V1, V2 - The dominating non-clobbered values of SelectVal.
Definition GVN.cpp:521
MemIntrinsic * getMemIntrinValue() const
Definition GVN.cpp:581
LoadInst * getCoercedLoadValue() const
Definition GVN.cpp:576
static AvailableValue getUndef()
Definition GVN.cpp:547
static AvailableValue getSelect(Value *Cond, Value *V1, Value *V2)
Definition GVN.cpp:555
static AvailableValue getLoad(LoadInst *Load, unsigned Offset=0)
Definition GVN.cpp:539
bool isSelectValue() const
Definition GVN.cpp:569
unsigned Offset
Offset - The byte offset in Val that is interesting for the load query.
Definition GVN.cpp:519
Value * MaterializeAdjustedValue(LoadInst *Load, Instruction *InsertPt) const
Emit code at the specified insertion point to adjust the value defined here to the specified type.
Definition GVN.cpp:1456
Value * Val
Val - The value that is live out of the block.
Definition GVN.cpp:514
bool isMemIntrinValue() const
Definition GVN.cpp:567
bool isCoercedLoadValue() const
Definition GVN.cpp:566
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:774
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Option class for critical edge splitting.
static unsigned getHashValue(const GVNValueTable::Expression &E)
Definition GVN.cpp:187
static bool isEqual(const GVNValueTable::Expression &LHS, const GVNValueTable::Expression &RHS)
Definition GVN.cpp:193
An information struct used to provide DenseMap with the various necessary components for a given valu...
AssertingVH< Value > Val
Definition GVN.cpp:207
LeaderTableEntry(Value *V, const BasicBlock *BB)
Definition GVN.cpp:209
A set of parameters to control various transforms performed by GVN pass.
Definition GVN.h:32
Expression(uint32_t Op=~2U)
Definition GVN.cpp:163
SmallVector< uint32_t, 4 > VarArgs
Definition GVN.cpp:159
bool operator==(const Expression &Other) const
Definition GVN.cpp:165
friend hash_code hash_value(const Expression &Value)
Definition GVN.cpp:180