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