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