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