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