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