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