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