1//===- NewGVN.cpp - Global Value Numbering Pass ---------------------------===//
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/// \file
10/// This file implements the new LLVM's Global Value Numbering pass.
11/// GVN partitions values computed by a function into congruence classes.
12/// Values ending up in the same congruence class are guaranteed to be the same
13/// for every execution of the program. In that respect, congruency is a
14/// compile-time approximation of equivalence of values at runtime.
15/// The algorithm implemented here uses a sparse formulation and it's based
16/// on the ideas described in the paper:
17/// "A Sparse Algorithm for Predicated Global Value Numbering" from
18/// Karthik Gargi.
19///
20/// A brief overview of the algorithm: The algorithm is essentially the same as
21/// the standard RPO value numbering algorithm (a good reference is the paper
22/// "SCC based value numbering" by L. Taylor Simpson) with one major difference:
23/// The RPO algorithm proceeds, on every iteration, to process every reachable
24/// block and every instruction in that block. This is because the standard RPO
25/// algorithm does not track what things have the same value number, it only
26/// tracks what the value number of a given operation is (the mapping is
27/// operation -> value number). Thus, when a value number of an operation
28/// changes, it must reprocess everything to ensure all uses of a value number
29/// get updated properly. In constrast, the sparse algorithm we use *also*
30/// tracks what operations have a given value number (IE it also tracks the
31/// reverse mapping from value number -> operations with that value number), so
32/// that it only needs to reprocess the instructions that are affected when
33/// something's value number changes. The vast majority of complexity and code
34/// in this file is devoted to tracking what value numbers could change for what
35/// instructions when various things happen. The rest of the algorithm is
36/// devoted to performing symbolic evaluation, forward propagation, and
37/// simplification of operations based on the value numbers deduced so far
38///
39/// In order to make the GVN mostly-complete, we use a technique derived from
40/// "Detection of Redundant Expressions: A Complete and Polynomial-time
41/// Algorithm in SSA" by R.R. Pai. The source of incompleteness in most SSA
42/// based GVN algorithms is related to their inability to detect equivalence
43/// between phi of ops (IE phi(a+b, c+d)) and op of phis (phi(a,c) + phi(b, d)).
44/// We resolve this issue by generating the equivalent "phi of ops" form for
45/// each op of phis we see, in a way that only takes polynomial time to resolve.
46///
47/// We also do not perform elimination by using any published algorithm. All
48/// published algorithms are O(Instructions). Instead, we use a technique that
49/// is O(number of operations with the same value number), enabling us to skip
50/// trying to eliminate things that have unique value numbers.
51//
52//===----------------------------------------------------------------------===//
53
54#include "llvm/Transforms/Scalar/NewGVN.h"
55#include "llvm/ADT/ArrayRef.h"
56#include "llvm/ADT/BitVector.h"
57#include "llvm/ADT/DenseMap.h"
58#include "llvm/ADT/DenseMapInfo.h"
59#include "llvm/ADT/DenseSet.h"
60#include "llvm/ADT/GraphTraits.h"
61#include "llvm/ADT/Hashing.h"
62#include "llvm/ADT/PointerIntPair.h"
63#include "llvm/ADT/PostOrderIterator.h"
64#include "llvm/ADT/SetOperations.h"
65#include "llvm/ADT/SmallPtrSet.h"
66#include "llvm/ADT/SmallVector.h"
67#include "llvm/ADT/SparseBitVector.h"
68#include "llvm/ADT/Statistic.h"
69#include "llvm/ADT/iterator_range.h"
70#include "llvm/Analysis/AliasAnalysis.h"
71#include "llvm/Analysis/AssumptionCache.h"
72#include "llvm/Analysis/CFGPrinter.h"
73#include "llvm/Analysis/ConstantFolding.h"
74#include "llvm/Analysis/GlobalsModRef.h"
75#include "llvm/Analysis/InstructionSimplify.h"
76#include "llvm/Analysis/MemoryBuiltins.h"
77#include "llvm/Analysis/MemorySSA.h"
78#include "llvm/Analysis/TargetLibraryInfo.h"
79#include "llvm/Analysis/ValueTracking.h"
80#include "llvm/IR/Argument.h"
81#include "llvm/IR/BasicBlock.h"
82#include "llvm/IR/Constant.h"
83#include "llvm/IR/Constants.h"
84#include "llvm/IR/DebugInfo.h"
85#include "llvm/IR/Dominators.h"
86#include "llvm/IR/Function.h"
87#include "llvm/IR/InstrTypes.h"
88#include "llvm/IR/Instruction.h"
89#include "llvm/IR/Instructions.h"
90#include "llvm/IR/IntrinsicInst.h"
91#include "llvm/IR/PatternMatch.h"
92#include "llvm/IR/Type.h"
93#include "llvm/IR/Use.h"
94#include "llvm/IR/User.h"
95#include "llvm/IR/Value.h"
96#include "llvm/Support/Allocator.h"
97#include "llvm/Support/ArrayRecycler.h"
98#include "llvm/Support/Casting.h"
99#include "llvm/Support/CommandLine.h"
100#include "llvm/Support/Debug.h"
101#include "llvm/Support/DebugCounter.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/raw_ostream.h"
104#include "llvm/Transforms/Scalar/GVNExpression.h"
105#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
106#include "llvm/Transforms/Utils/Local.h"
107#include "llvm/Transforms/Utils/PredicateInfo.h"
108#include "llvm/Transforms/Utils/VNCoercion.h"
109#include <algorithm>
110#include <cassert>
111#include <cstdint>
112#include <iterator>
113#include <map>
114#include <memory>
115#include <set>
116#include <string>
117#include <tuple>
118#include <utility>
119#include <vector>
120
121using namespace llvm;
122using namespace llvm::GVNExpression;
123using namespace llvm::VNCoercion;
124using namespace llvm::PatternMatch;
125
126#define DEBUG_TYPE "newgvn"
127
128STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
129STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
130STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
131STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
132STATISTIC(NumGVNMaxIterations,
133 "Maximum Number of iterations it took to converge GVN");
134STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
135STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
136STATISTIC(NumGVNAvoidedSortedLeaderChanges,
137 "Number of avoided sorted leader changes");
138STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
139STATISTIC(NumGVNPHIOfOpsCreated, "Number of PHI of ops created");
140STATISTIC(NumGVNPHIOfOpsEliminations,
141 "Number of things eliminated using PHI of ops");
142DEBUG_COUNTER(VNCounter, "newgvn-vn",
143 "Controls which instructions are value numbered");
144DEBUG_COUNTER(PHIOfOpsCounter, "newgvn-phi",
145 "Controls which instructions we create phi of ops for");
146// Currently store defining access refinement is too slow due to basicaa being
147// egregiously slow. This flag lets us keep it working while we work on this
148// issue.
149static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
150 cl::init(Val: false), cl::Hidden);
151
152/// Currently, the generation "phi of ops" can result in correctness issues.
153static cl::opt<bool> EnablePhiOfOps("enable-phi-of-ops", cl::init(Val: true),
154 cl::Hidden);
155
156//===----------------------------------------------------------------------===//
157// GVN Pass
158//===----------------------------------------------------------------------===//
159
160// Anchor methods.
161Expression::~Expression() = default;
162BasicExpression::~BasicExpression() = default;
163CallExpression::~CallExpression() = default;
164LoadExpression::~LoadExpression() = default;
165StoreExpression::~StoreExpression() = default;
166AggregateValueExpression::~AggregateValueExpression() = default;
167PHIExpression::~PHIExpression() = default;
168
169namespace {
170
171// Tarjan's SCC finding algorithm with Nuutila's improvements
172// SCCIterator is actually fairly complex for the simple thing we want.
173// It also wants to hand us SCC's that are unrelated to the phi node we ask
174// about, and have us process them there or risk redoing work.
175// Graph traits over a filter iterator also doesn't work that well here.
176// This SCC finder is specialized to walk use-def chains, and only follows
177// instructions,
178// not generic values (arguments, etc).
179struct TarjanSCC {
180 TarjanSCC() : Components(1) {}
181
182 void Start(const Instruction *Start) {
183 if (Root.lookup(Val: Start) == 0)
184 FindSCC(I: Start);
185 }
186
187 const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
188 unsigned ComponentID = ValueToComponent.lookup(Val: V);
189
190 assert(ComponentID > 0 &&
191 "Asking for a component for a value we never processed");
192 return Components[ComponentID];
193 }
194
195private:
196 void FindSCC(const Instruction *I) {
197 Root[I] = ++DFSNum;
198 // Store the DFS Number we had before it possibly gets incremented.
199 unsigned int OurDFS = DFSNum;
200 for (const auto &Op : I->operands()) {
201 if (auto *InstOp = dyn_cast<Instruction>(Val: Op)) {
202 if (Root.lookup(Val: Op) == 0)
203 FindSCC(I: InstOp);
204 if (!InComponent.count(Ptr: Op))
205 Root[I] = std::min(a: Root.lookup(Val: I), b: Root.lookup(Val: Op));
206 }
207 }
208 // See if we really were the root of a component, by seeing if we still have
209 // our DFSNumber. If we do, we are the root of the component, and we have
210 // completed a component. If we do not, we are not the root of a component,
211 // and belong on the component stack.
212 if (Root.lookup(Val: I) == OurDFS) {
213 unsigned ComponentID = Components.size();
214 Components.resize(N: Components.size() + 1);
215 auto &Component = Components.back();
216 Component.insert(Ptr: I);
217 LLVM_DEBUG(dbgs() << "Component root is " << *I << "\n");
218 InComponent.insert(Ptr: I);
219 ValueToComponent[I] = ComponentID;
220 // Pop a component off the stack and label it.
221 while (!Stack.empty() && Root.lookup(Val: Stack.back()) >= OurDFS) {
222 auto *Member = Stack.back();
223 LLVM_DEBUG(dbgs() << "Component member is " << *Member << "\n");
224 Component.insert(Ptr: Member);
225 InComponent.insert(Ptr: Member);
226 ValueToComponent[Member] = ComponentID;
227 Stack.pop_back();
228 }
229 } else {
230 // Part of a component, push to stack
231 Stack.push_back(Elt: I);
232 }
233 }
234
235 unsigned int DFSNum = 1;
236 SmallPtrSet<const Value *, 8> InComponent;
237 DenseMap<const Value *, unsigned int> Root;
238 SmallVector<const Value *, 8> Stack;
239
240 // Store the components as vector of ptr sets, because we need the topo order
241 // of SCC's, but not individual member order
242 SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
243
244 DenseMap<const Value *, unsigned> ValueToComponent;
245};
246
247// Congruence classes represent the set of expressions/instructions
248// that are all the same *during some scope in the function*.
249// That is, because of the way we perform equality propagation, and
250// because of memory value numbering, it is not correct to assume
251// you can willy-nilly replace any member with any other at any
252// point in the function.
253//
254// For any Value in the Member set, it is valid to replace any dominated member
255// with that Value.
256//
257// Every congruence class has a leader, and the leader is used to symbolize
258// instructions in a canonical way (IE every operand of an instruction that is a
259// member of the same congruence class will always be replaced with leader
260// during symbolization). To simplify symbolization, we keep the leader as a
261// constant if class can be proved to be a constant value. Otherwise, the
262// leader is the member of the value set with the smallest DFS number. Each
263// congruence class also has a defining expression, though the expression may be
264// null. If it exists, it can be used for forward propagation and reassociation
265// of values.
266
267// For memory, we also track a representative MemoryAccess, and a set of memory
268// members for MemoryPhis (which have no real instructions). Note that for
269// memory, it seems tempting to try to split the memory members into a
270// MemoryCongruenceClass or something. Unfortunately, this does not work
271// easily. The value numbering of a given memory expression depends on the
272// leader of the memory congruence class, and the leader of memory congruence
273// class depends on the value numbering of a given memory expression. This
274// leads to wasted propagation, and in some cases, missed optimization. For
275// example: If we had value numbered two stores together before, but now do not,
276// we move them to a new value congruence class. This in turn will move at one
277// of the memorydefs to a new memory congruence class. Which in turn, affects
278// the value numbering of the stores we just value numbered (because the memory
279// congruence class is part of the value number). So while theoretically
280// possible to split them up, it turns out to be *incredibly* complicated to get
281// it to work right, because of the interdependency. While structurally
282// slightly messier, it is algorithmically much simpler and faster to do what we
283// do here, and track them both at once in the same class.
284// Note: The default iterators for this class iterate over values
285class CongruenceClass {
286public:
287 using MemberType = Value;
288 using MemberSet = SmallPtrSet<MemberType *, 4>;
289 using MemoryMemberType = MemoryPhi;
290 using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
291
292 explicit CongruenceClass(unsigned ID) : ID(ID) {}
293 CongruenceClass(unsigned ID, std::pair<Value *, unsigned int> Leader,
294 const Expression *E)
295 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
296
297 unsigned getID() const { return ID; }
298
299 // True if this class has no members left. This is mainly used for assertion
300 // purposes, and for skipping empty classes.
301 bool isDead() const {
302 // If it's both dead from a value perspective, and dead from a memory
303 // perspective, it's really dead.
304 return empty() && memory_empty();
305 }
306
307 // Leader functions
308 Value *getLeader() const { return RepLeader.first; }
309 void setLeader(std::pair<Value *, unsigned int> Leader) {
310 RepLeader = std::move(Leader);
311 }
312 const std::pair<Value *, unsigned int> &getNextLeader() const {
313 return NextLeader;
314 }
315 void resetNextLeader() { NextLeader = {nullptr, ~0}; }
316 bool addPossibleLeader(std::pair<Value *, unsigned int> LeaderPair) {
317 if (LeaderPair.second < RepLeader.second) {
318 NextLeader = RepLeader;
319 RepLeader = std::move(LeaderPair);
320 return true;
321 } else if (LeaderPair.second < NextLeader.second) {
322 NextLeader = std::move(LeaderPair);
323 }
324 return false;
325 }
326
327 Value *getStoredValue() const { return RepStoredValue; }
328 void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
329 const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
330 void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
331
332 // Forward propagation info
333 const Expression *getDefiningExpr() const { return DefiningExpr; }
334
335 // Value member set
336 bool empty() const { return Members.empty(); }
337 unsigned size() const { return Members.size(); }
338 MemberSet::const_iterator begin() const { return Members.begin(); }
339 MemberSet::const_iterator end() const { return Members.end(); }
340 void insert(MemberType *M) { Members.insert(Ptr: M); }
341 void erase(MemberType *M) { Members.erase(Ptr: M); }
342 void swap(MemberSet &Other) { Members.swap(RHS&: Other); }
343
344 // Memory member set
345 bool memory_empty() const { return MemoryMembers.empty(); }
346 unsigned memory_size() const { return MemoryMembers.size(); }
347 MemoryMemberSet::const_iterator memory_begin() const {
348 return MemoryMembers.begin();
349 }
350 MemoryMemberSet::const_iterator memory_end() const {
351 return MemoryMembers.end();
352 }
353 iterator_range<MemoryMemberSet::const_iterator> memory() const {
354 return make_range(x: memory_begin(), y: memory_end());
355 }
356
357 void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(Ptr: M); }
358 void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(Ptr: M); }
359
360 // Store count
361 unsigned getStoreCount() const { return StoreCount; }
362 void incStoreCount() { ++StoreCount; }
363 void decStoreCount() {
364 assert(StoreCount != 0 && "Store count went negative");
365 --StoreCount;
366 }
367
368 // True if this class has no memory members.
369 bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
370
371 // Return true if two congruence classes are equivalent to each other. This
372 // means that every field but the ID number and the dead field are equivalent.
373 bool isEquivalentTo(const CongruenceClass *Other) const {
374 if (!Other)
375 return false;
376 if (this == Other)
377 return true;
378
379 if (std::tie(args: StoreCount, args: RepLeader, args: RepStoredValue, args: RepMemoryAccess) !=
380 std::tie(args: Other->StoreCount, args: Other->RepLeader, args: Other->RepStoredValue,
381 args: Other->RepMemoryAccess))
382 return false;
383 if (DefiningExpr != Other->DefiningExpr)
384 if (!DefiningExpr || !Other->DefiningExpr ||
385 *DefiningExpr != *Other->DefiningExpr)
386 return false;
387
388 if (Members.size() != Other->Members.size())
389 return false;
390
391 return llvm::set_is_subset(S1: Members, S2: Other->Members);
392 }
393
394private:
395 unsigned ID;
396
397 // Representative leader and its corresponding RPO number.
398 // The leader must have the lowest RPO number.
399 std::pair<Value *, unsigned int> RepLeader = {nullptr, ~0U};
400
401 // The most dominating leader after our current leader (given by the RPO
402 // number), because the member set is not sorted and is expensive to keep
403 // sorted all the time.
404 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
405
406 // If this is represented by a store, the value of the store.
407 Value *RepStoredValue = nullptr;
408
409 // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
410 // access.
411 const MemoryAccess *RepMemoryAccess = nullptr;
412
413 // Defining Expression.
414 const Expression *DefiningExpr = nullptr;
415
416 // Actual members of this class.
417 MemberSet Members;
418
419 // This is the set of MemoryPhis that exist in the class. MemoryDefs and
420 // MemoryUses have real instructions representing them, so we only need to
421 // track MemoryPhis here.
422 MemoryMemberSet MemoryMembers;
423
424 // Number of stores in this congruence class.
425 // This is used so we can detect store equivalence changes properly.
426 int StoreCount = 0;
427};
428
429struct ExactEqualsExpression {
430 const Expression &E;
431
432 explicit ExactEqualsExpression(const Expression &E) : E(E) {}
433
434 hash_code getComputedHash() const { return E.getComputedHash(); }
435
436 bool operator==(const Expression &Other) const {
437 return E.exactlyEquals(Other);
438 }
439};
440} // end anonymous namespace
441
442template <> struct llvm::DenseMapInfo<const Expression *> {
443 static unsigned getHashValue(const Expression *E) {
444 return E->getComputedHash();
445 }
446
447 static unsigned getHashValue(const ExactEqualsExpression &E) {
448 return E.getComputedHash();
449 }
450
451 static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS) {
452 return LHS == *RHS;
453 }
454
455 static bool isEqual(const Expression *LHS, const Expression *RHS) {
456 if (LHS == RHS)
457 return true;
458 // Compare hashes before equality. This is *not* what the hashtable does,
459 // since it is computing it modulo the number of buckets, whereas we are
460 // using the full hash keyspace. Since the hashes are precomputed, this
461 // check is *much* faster than equality.
462 if (LHS->getComputedHash() != RHS->getComputedHash())
463 return false;
464 return *LHS == *RHS;
465 }
466};
467
468namespace {
469
470class NewGVN {
471 Function &F;
472 DominatorTree *DT = nullptr;
473 const TargetLibraryInfo *TLI = nullptr;
474 AliasAnalysis *AA = nullptr;
475 MemorySSA *MSSA = nullptr;
476 MemorySSAWalker *MSSAWalker = nullptr;
477 AssumptionCache *AC = nullptr;
478 const DataLayout &DL;
479
480 // These are the only two things the create* functions should have
481 // side-effects on due to allocating memory.
482 mutable BumpPtrAllocator ExpressionAllocator;
483 mutable ArrayRecycler<Value *> ArgRecycler;
484 mutable TarjanSCC SCCFinder;
485
486 std::unique_ptr<PredicateInfo> PredInfo;
487 const SimplifyQuery SQ;
488
489 // Number of function arguments, used by ranking
490 unsigned int NumFuncArgs = 0;
491
492 // RPOOrdering of basic blocks
493 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
494
495 // Congruence class info.
496
497 // This class is called INITIAL in the paper. It is the class everything
498 // startsout in, and represents any value. Being an optimistic analysis,
499 // anything in the TOP class has the value TOP, which is indeterminate and
500 // equivalent to everything.
501 CongruenceClass *TOPClass = nullptr;
502 std::vector<CongruenceClass *> CongruenceClasses;
503 unsigned NextCongruenceNum = 0;
504
505 // Value Mappings.
506 DenseMap<Value *, CongruenceClass *> ValueToClass;
507 DenseMap<Value *, const Expression *> ValueToExpression;
508
509 // Value PHI handling, used to make equivalence between phi(op, op) and
510 // op(phi, phi).
511 // These mappings just store various data that would normally be part of the
512 // IR.
513 SmallPtrSet<const Instruction *, 8> PHINodeUses;
514
515 // The cached results, in general, are only valid for the specific block where
516 // they were computed. The unsigned part of the key is a unique block
517 // identifier
518 DenseMap<std::pair<const Value *, unsigned>, bool> OpSafeForPHIOfOps;
519 unsigned CacheIdx;
520
521 // Map a temporary instruction we created to a parent block.
522 DenseMap<const Value *, BasicBlock *> TempToBlock;
523
524 // Map between the already in-program instructions and the temporary phis we
525 // created that they are known equivalent to.
526 DenseMap<const Value *, PHINode *> RealToTemp;
527
528 // In order to know when we should re-process instructions that have
529 // phi-of-ops, we track the set of expressions that they needed as
530 // leaders. When we discover new leaders for those expressions, we process the
531 // associated phi-of-op instructions again in case they have changed. The
532 // other way they may change is if they had leaders, and those leaders
533 // disappear. However, at the point they have leaders, there are uses of the
534 // relevant operands in the created phi node, and so they will get reprocessed
535 // through the normal user marking we perform.
536 mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
537 DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
538 ExpressionToPhiOfOps;
539
540 // Map from temporary operation to MemoryAccess.
541 DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
542
543 // Set of all temporary instructions we created.
544 // Note: This will include instructions that were just created during value
545 // numbering. The way to test if something is using them is to check
546 // RealToTemp.
547 DenseSet<Instruction *> AllTempInstructions;
548
549 // This is the set of instructions to revisit on a reachability change. At
550 // the end of the main iteration loop it will contain at least all the phi of
551 // ops instructions that will be changed to phis, as well as regular phis.
552 // During the iteration loop, it may contain other things, such as phi of ops
553 // instructions that used edge reachability to reach a result, and so need to
554 // be revisited when the edge changes, independent of whether the phi they
555 // depended on changes.
556 DenseMap<BasicBlock *, SparseBitVector<>> RevisitOnReachabilityChange;
557
558 // Mapping from predicate info we used to the instructions we used it with.
559 // In order to correctly ensure propagation, we must keep track of what
560 // comparisons we used, so that when the values of the comparisons change, we
561 // propagate the information to the places we used the comparison.
562 mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
563 PredicateToUsers;
564
565 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
566 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
567 mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
568 MemoryToUsers;
569
570 // A table storing which memorydefs/phis represent a memory state provably
571 // equivalent to another memory state.
572 // We could use the congruence class machinery, but the MemoryAccess's are
573 // abstract memory states, so they can only ever be equivalent to each other,
574 // and not to constants, etc.
575 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
576
577 // We could, if we wanted, build MemoryPhiExpressions and
578 // MemoryVariableExpressions, etc, and value number them the same way we value
579 // number phi expressions. For the moment, this seems like overkill. They
580 // can only exist in one of three states: they can be TOP (equal to
581 // everything), Equivalent to something else, or unique. Because we do not
582 // create expressions for them, we need to simulate leader change not just
583 // when they change class, but when they change state. Note: We can do the
584 // same thing for phis, and avoid having phi expressions if we wanted, We
585 // should eventually unify in one direction or the other, so this is a little
586 // bit of an experiment in which turns out easier to maintain.
587 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
588 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
589
590 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
591 mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
592
593 // Expression to class mapping.
594 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
595 ExpressionClassMap ExpressionToClass;
596
597 // We have a single expression that represents currently DeadExpressions.
598 // For dead expressions we can prove will stay dead, we mark them with
599 // DFS number zero. However, it's possible in the case of phi nodes
600 // for us to assume/prove all arguments are dead during fixpointing.
601 // We use DeadExpression for that case.
602 DeadExpression *SingletonDeadExpression = nullptr;
603
604 // Which values have changed as a result of leader changes.
605 SmallPtrSet<Value *, 8> LeaderChanges;
606
607 // Reachability info.
608 using BlockEdge = BasicBlockEdge;
609 DenseSet<BlockEdge> ReachableEdges;
610 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
611
612 // This is a bitvector because, on larger functions, we may have
613 // thousands of touched instructions at once (entire blocks,
614 // instructions with hundreds of uses, etc). Even with optimization
615 // for when we mark whole blocks as touched, when this was a
616 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
617 // the time in GVN just managing this list. The bitvector, on the
618 // other hand, efficiently supports test/set/clear of both
619 // individual and ranges, as well as "find next element" This
620 // enables us to use it as a worklist with essentially 0 cost.
621 BitVector TouchedInstructions;
622
623 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
624 mutable DenseMap<const BitCastInst *, const Value *> PredicateSwapChoice;
625
626#ifndef NDEBUG
627 // Debugging for how many times each block and instruction got processed.
628 DenseMap<const Value *, unsigned> ProcessedCount;
629#endif
630
631 // DFS info.
632 // This contains a mapping from Instructions to DFS numbers.
633 // The numbering starts at 1. An instruction with DFS number zero
634 // means that the instruction is dead.
635 DenseMap<const Value *, unsigned> InstrDFS;
636
637 // This contains the mapping DFS numbers to instructions.
638 SmallVector<Value *, 32> DFSToInstr;
639
640 // Deletion info.
641 SmallPtrSet<Instruction *, 8> InstructionsToErase;
642
643public:
644 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
645 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
646 const DataLayout &DL)
647 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), AC(AC), DL(DL),
648 // Reuse ExpressionAllocator for PredicateInfo as well.
649 PredInfo(
650 std::make_unique<PredicateInfo>(args&: F, args&: *DT, args&: *AC, args&: ExpressionAllocator)),
651 SQ(DL, TLI, DT, AC, /*CtxI=*/nullptr, /*UseInstrInfo=*/false,
652 /*CanUseUndef=*/false) {}
653
654 bool runGVN();
655
656private:
657 /// Helper struct return a Expression with an optional extra dependency.
658 struct ExprResult {
659 const Expression *Expr;
660 Value *ExtraDep;
661 const PredicateBase *PredDep;
662
663 ExprResult(const Expression *Expr, Value *ExtraDep = nullptr,
664 const PredicateBase *PredDep = nullptr)
665 : Expr(Expr), ExtraDep(ExtraDep), PredDep(PredDep) {}
666 ExprResult(const ExprResult &) = delete;
667 ExprResult(ExprResult &&Other)
668 : Expr(Other.Expr), ExtraDep(Other.ExtraDep), PredDep(Other.PredDep) {
669 Other.Expr = nullptr;
670 Other.ExtraDep = nullptr;
671 Other.PredDep = nullptr;
672 }
673 ExprResult &operator=(const ExprResult &Other) = delete;
674 ExprResult &operator=(ExprResult &&Other) = delete;
675
676 ~ExprResult() { assert(!ExtraDep && "unhandled ExtraDep"); }
677
678 operator bool() const { return Expr; }
679
680 static ExprResult none() { return {nullptr, nullptr, nullptr}; }
681 static ExprResult some(const Expression *Expr, Value *ExtraDep = nullptr) {
682 return {Expr, ExtraDep, nullptr};
683 }
684 static ExprResult some(const Expression *Expr,
685 const PredicateBase *PredDep) {
686 return {Expr, nullptr, PredDep};
687 }
688 static ExprResult some(const Expression *Expr, Value *ExtraDep,
689 const PredicateBase *PredDep) {
690 return {Expr, ExtraDep, PredDep};
691 }
692 };
693
694 // Expression handling.
695 ExprResult createExpression(Instruction *) const;
696 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
697 Instruction *) const;
698
699 // Our canonical form for phi arguments is a pair of incoming value, incoming
700 // basic block.
701 using ValPair = std::pair<Value *, BasicBlock *>;
702
703 PHIExpression *createPHIExpression(ArrayRef<ValPair>, const Instruction *,
704 BasicBlock *, bool &HasBackEdge,
705 bool &OriginalOpsConstant) const;
706 const DeadExpression *createDeadExpression() const;
707 const VariableExpression *createVariableExpression(Value *) const;
708 const ConstantExpression *createConstantExpression(Constant *) const;
709 const Expression *createVariableOrConstant(Value *V) const;
710 const UnknownExpression *createUnknownExpression(Instruction *) const;
711 const StoreExpression *createStoreExpression(StoreInst *,
712 const MemoryAccess *) const;
713 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
714 const MemoryAccess *) const;
715 const CallExpression *createCallExpression(CallInst *,
716 const MemoryAccess *) const;
717 const AggregateValueExpression *
718 createAggregateValueExpression(Instruction *) const;
719 bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
720
721 // Congruence class handling.
722 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
723 // Set RPO to 0 for values that are always available (constants and function
724 // args). These should always be made leader.
725 unsigned LeaderDFS = 0;
726
727 // If Leader is not specified, either we have a memory class or the leader
728 // will be set later. Otherwise, if Leader is an Instruction, set LeaderDFS
729 // to its RPO number.
730 if (!Leader)
731 LeaderDFS = ~0;
732 else if (auto *I = dyn_cast<Instruction>(Val: Leader))
733 LeaderDFS = InstrToDFSNum(V: I);
734 auto *result =
735 new CongruenceClass(NextCongruenceNum++, {Leader, LeaderDFS}, E);
736 CongruenceClasses.emplace_back(args&: result);
737 return result;
738 }
739
740 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
741 auto *CC = createCongruenceClass(Leader: nullptr, E: nullptr);
742 CC->setMemoryLeader(MA);
743 return CC;
744 }
745
746 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
747 auto *CC = getMemoryClass(MA);
748 if (CC->getMemoryLeader() != MA)
749 CC = createMemoryClass(MA);
750 return CC;
751 }
752
753 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
754 CongruenceClass *CClass = createCongruenceClass(Leader: Member, E: nullptr);
755 CClass->insert(M: Member);
756 ValueToClass[Member] = CClass;
757 return CClass;
758 }
759
760 void initializeCongruenceClasses(Function &F);
761 const Expression *makePossiblePHIOfOps(Instruction *,
762 SmallPtrSetImpl<Value *> &);
763 Value *findLeaderForInst(Instruction *ValueOp,
764 SmallPtrSetImpl<Value *> &Visited,
765 MemoryAccess *MemAccess, Instruction *OrigInst,
766 BasicBlock *PredBB);
767 bool OpIsSafeForPHIOfOps(Value *Op, const BasicBlock *PHIBlock,
768 SmallPtrSetImpl<const Value *> &);
769 void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
770 void removePhiOfOps(Instruction *I, PHINode *PHITemp);
771
772 // Value number an Instruction or MemoryPhi.
773 void valueNumberMemoryPhi(MemoryPhi *);
774 void valueNumberInstruction(Instruction *);
775
776 // Symbolic evaluation.
777 ExprResult checkExprResults(Expression *, Instruction *, Value *) const;
778 ExprResult performSymbolicEvaluation(Instruction *,
779 SmallPtrSetImpl<Value *> &) const;
780 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
781 Instruction *,
782 MemoryAccess *) const;
783 const Expression *performSymbolicLoadEvaluation(Instruction *) const;
784 const Expression *performSymbolicStoreEvaluation(Instruction *) const;
785 ExprResult performSymbolicCallEvaluation(Instruction *) const;
786 void sortPHIOps(MutableArrayRef<ValPair> Ops) const;
787 const Expression *performSymbolicPHIEvaluation(ArrayRef<ValPair>,
788 Instruction *I,
789 BasicBlock *PHIBlock) const;
790 const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
791 ExprResult performSymbolicCmpEvaluation(Instruction *) const;
792 ExprResult performSymbolicPredicateInfoEvaluation(BitCastInst *) const;
793
794 // Congruence finding.
795 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
796 Value *lookupOperandLeader(Value *) const;
797 CongruenceClass *getClassForExpression(const Expression *E) const;
798 void performCongruenceFinding(Instruction *, const Expression *);
799 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
800 CongruenceClass *, CongruenceClass *);
801 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
802 CongruenceClass *, CongruenceClass *);
803 Value *getNextValueLeader(CongruenceClass *) const;
804 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
805 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
806 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
807 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
808 bool isMemoryAccessTOP(const MemoryAccess *) const;
809
810 // Ranking
811 unsigned int getRank(const Value *) const;
812 bool shouldSwapOperands(const Value *, const Value *) const;
813 bool shouldSwapOperandsForPredicate(const Value *, const Value *,
814 const BitCastInst *I) const;
815
816 // Reachability handling.
817 void updateReachableEdge(BasicBlock *, BasicBlock *);
818 void processOutgoingEdges(Instruction *, BasicBlock *);
819 Value *findConditionEquivalence(Value *) const;
820
821 // Elimination.
822 struct ValueDFS;
823 void convertClassToDFSOrdered(const CongruenceClass &,
824 SmallVectorImpl<ValueDFS> &,
825 DenseMap<const Value *, unsigned int> &,
826 SmallPtrSetImpl<Instruction *> &) const;
827 void convertClassToLoadsAndStores(const CongruenceClass &,
828 SmallVectorImpl<ValueDFS> &) const;
829
830 bool eliminateInstructions(Function &);
831 void replaceInstruction(Instruction *, Value *);
832 void markInstructionForDeletion(Instruction *);
833 void deleteInstructionsInBlock(BasicBlock *);
834 Value *findPHIOfOpsLeader(const Expression *, const Instruction *,
835 const BasicBlock *) const;
836
837 // Various instruction touch utilities
838 template <typename Map, typename KeyType>
839 void touchAndErase(Map &, const KeyType &);
840 void markUsersTouched(Value *);
841 void markMemoryUsersTouched(const MemoryAccess *);
842 void markMemoryDefTouched(const MemoryAccess *);
843 void markPredicateUsersTouched(Instruction *);
844 void markValueLeaderChangeTouched(CongruenceClass *CC);
845 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
846 void markPhiOfOpsChanged(const Expression *E);
847 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
848 void addAdditionalUsers(Value *To, Value *User) const;
849 void addAdditionalUsers(ExprResult &Res, Instruction *User) const;
850
851 // Main loop of value numbering
852 void iterateTouchedInstructions();
853
854 // Utilities.
855 void cleanupTables();
856 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
857 void updateProcessedCount(const Value *V);
858 void verifyMemoryCongruency() const;
859 void verifyIterationSettled(Function &F);
860 void verifyStoreExpressions() const;
861 bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
862 const MemoryAccess *, const MemoryAccess *) const;
863 BasicBlock *getBlockForValue(Value *V) const;
864 void deleteExpression(const Expression *E) const;
865 MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
866 MemoryPhi *getMemoryAccess(const BasicBlock *) const;
867 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
868
869 unsigned InstrToDFSNum(const Value *V) const {
870 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
871 return InstrDFS.lookup(Val: V);
872 }
873
874 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
875 return MemoryToDFSNum(MA);
876 }
877
878 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
879
880 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
881 // This deliberately takes a value so it can be used with Use's, which will
882 // auto-convert to Value's but not to MemoryAccess's.
883 unsigned MemoryToDFSNum(const Value *MA) const {
884 assert(isa<MemoryAccess>(MA) &&
885 "This should not be used with instructions");
886 return isa<MemoryUseOrDef>(Val: MA)
887 ? InstrToDFSNum(V: cast<MemoryUseOrDef>(Val: MA)->getMemoryInst())
888 : InstrDFS.lookup(Val: MA);
889 }
890
891 bool isCycleFree(const Instruction *) const;
892 bool isBackedge(BasicBlock *From, BasicBlock *To) const;
893
894 // Debug counter info. When verifying, we have to reset the value numbering
895 // debug counter to the same state it started in to get the same results.
896 DebugCounter::CounterState StartingVNCounter;
897};
898
899} // end anonymous namespace
900
901template <typename T>
902static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
903 if (!isa<LoadExpression>(Val: RHS) && !isa<StoreExpression>(Val: RHS))
904 return false;
905 return LHS.MemoryExpression::equals(RHS);
906}
907
908bool LoadExpression::equals(const Expression &Other) const {
909 return equalsLoadStoreHelper(LHS: *this, RHS: Other);
910}
911
912bool StoreExpression::equals(const Expression &Other) const {
913 if (!equalsLoadStoreHelper(LHS: *this, RHS: Other))
914 return false;
915 // Make sure that store vs store includes the value operand.
916 if (const auto *S = dyn_cast<StoreExpression>(Val: &Other))
917 if (getStoredValue() != S->getStoredValue())
918 return false;
919 return true;
920}
921
922bool CallExpression::equals(const Expression &Other) const {
923 if (!MemoryExpression::equals(Other))
924 return false;
925
926 if (auto *RHS = dyn_cast<CallExpression>(Val: &Other))
927 return Call->getAttributes()
928 .intersectWith(C&: Call->getContext(), Other: RHS->Call->getAttributes())
929 .has_value();
930
931 return false;
932}
933
934// Determine if the edge From->To is a backedge
935bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
936 return From == To ||
937 RPOOrdering.lookup(Val: DT->getNode(BB: From)) >=
938 RPOOrdering.lookup(Val: DT->getNode(BB: To));
939}
940
941#ifndef NDEBUG
942static std::string getBlockName(const BasicBlock *B) {
943 return DOTGraphTraits<DOTFuncInfo *>::getSimpleNodeLabel(B, nullptr);
944}
945#endif
946
947// Get a MemoryAccess for an instruction, fake or real.
948MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
949 auto *Result = MSSA->getMemoryAccess(I);
950 return Result ? Result : TempToMemory.lookup(Val: I);
951}
952
953// Get a MemoryPhi for a basic block. These are all real.
954MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
955 return MSSA->getMemoryAccess(BB);
956}
957
958// Get the basic block from an instruction/memory value.
959BasicBlock *NewGVN::getBlockForValue(Value *V) const {
960 if (auto *I = dyn_cast<Instruction>(Val: V)) {
961 auto *Parent = I->getParent();
962 if (Parent)
963 return Parent;
964 Parent = TempToBlock.lookup(Val: V);
965 assert(Parent && "Every fake instruction should have a block");
966 return Parent;
967 }
968
969 auto *MP = dyn_cast<MemoryPhi>(Val: V);
970 assert(MP && "Should have been an instruction or a MemoryPhi");
971 return MP->getBlock();
972}
973
974// Delete a definitely dead expression, so it can be reused by the expression
975// allocator. Some of these are not in creation functions, so we have to accept
976// const versions.
977void NewGVN::deleteExpression(const Expression *E) const {
978 assert(isa<BasicExpression>(E));
979 auto *BE = cast<BasicExpression>(Val: E);
980 const_cast<BasicExpression *>(BE)->deallocateOperands(Recycler&: ArgRecycler);
981 ExpressionAllocator.Deallocate(Ptr: E);
982}
983
984// If V is a predicateinfo copy, get the thing it is a copy of.
985static Value *getCopyOf(const Value *V) {
986 if (auto *BC = dyn_cast<BitCastInst>(Val: V))
987 if (BC->getType() == BC->getOperand(i_nocapture: 0)->getType())
988 return BC->getOperand(i_nocapture: 0);
989 return nullptr;
990}
991
992// Return true if V is really PN, even accounting for predicateinfo copies.
993static bool isCopyOfPHI(const Value *V, const PHINode *PN) {
994 return V == PN || getCopyOf(V) == PN;
995}
996
997static bool isCopyOfAPHI(const Value *V) {
998 auto *CO = getCopyOf(V);
999 return CO && isa<PHINode>(Val: CO);
1000}
1001
1002// Sort PHI Operands into a canonical order. What we use here is an RPO
1003// order. The BlockInstRange numbers are generated in an RPO walk of the basic
1004// blocks.
1005void NewGVN::sortPHIOps(MutableArrayRef<ValPair> Ops) const {
1006 llvm::sort(C&: Ops, Comp: [&](const ValPair &P1, const ValPair &P2) {
1007 return BlockInstRange.lookup(Val: P1.second).first <
1008 BlockInstRange.lookup(Val: P2.second).first;
1009 });
1010}
1011
1012// Return true if V is a value that will always be available (IE can
1013// be placed anywhere) in the function. We don't do globals here
1014// because they are often worse to put in place.
1015static bool alwaysAvailable(Value *V) {
1016 return isa<Constant>(Val: V) || isa<Argument>(Val: V);
1017}
1018
1019// Create a PHIExpression from an array of {incoming edge, value} pairs. I is
1020// the original instruction we are creating a PHIExpression for (but may not be
1021// a phi node). We require, as an invariant, that all the PHIOperands in the
1022// same block are sorted the same way. sortPHIOps will sort them into a
1023// canonical order.
1024PHIExpression *NewGVN::createPHIExpression(ArrayRef<ValPair> PHIOperands,
1025 const Instruction *I,
1026 BasicBlock *PHIBlock,
1027 bool &HasBackedge,
1028 bool &OriginalOpsConstant) const {
1029 unsigned NumOps = PHIOperands.size();
1030 auto *E = new (ExpressionAllocator) PHIExpression(NumOps, PHIBlock);
1031
1032 E->allocateOperands(Recycler&: ArgRecycler, Allocator&: ExpressionAllocator);
1033 E->setType(PHIOperands.begin()->first->getType());
1034 E->setOpcode(Instruction::PHI);
1035
1036 // Filter out unreachable phi operands.
1037 auto Filtered = make_filter_range(Range&: PHIOperands, Pred: [&](const ValPair &P) {
1038 auto *BB = P.second;
1039 if (auto *PHIOp = dyn_cast<PHINode>(Val: I))
1040 if (isCopyOfPHI(V: P.first, PN: PHIOp))
1041 return false;
1042 if (!ReachableEdges.count(V: {BB, PHIBlock}))
1043 return false;
1044 // Things in TOPClass are equivalent to everything.
1045 if (ValueToClass.lookup(Val: P.first) == TOPClass)
1046 return false;
1047 OriginalOpsConstant = OriginalOpsConstant && isa<Constant>(Val: P.first);
1048 HasBackedge = HasBackedge || isBackedge(From: BB, To: PHIBlock);
1049 return lookupOperandLeader(P.first) != I;
1050 });
1051 llvm::transform(Range&: Filtered, d_first: op_inserter(E), F: [&](const ValPair &P) -> Value * {
1052 return lookupOperandLeader(P.first);
1053 });
1054 return E;
1055}
1056
1057// Set basic expression info (Arguments, type, opcode) for Expression
1058// E from Instruction I in block B.
1059bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
1060 bool AllConstant = true;
1061 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: I))
1062 E->setType(GEP->getSourceElementType());
1063 else
1064 E->setType(I->getType());
1065 E->setOpcode(I->getOpcode());
1066 E->allocateOperands(Recycler&: ArgRecycler, Allocator&: ExpressionAllocator);
1067
1068 // Transform the operand array into an operand leader array, and keep track of
1069 // whether all members are constant.
1070 std::transform(first: I->op_begin(), last: I->op_end(), result: op_inserter(E), unary_op: [&](Value *O) {
1071 auto Operand = lookupOperandLeader(O);
1072 AllConstant = AllConstant && isa<Constant>(Val: Operand);
1073 return Operand;
1074 });
1075
1076 return AllConstant;
1077}
1078
1079const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
1080 Value *Arg1, Value *Arg2,
1081 Instruction *I) const {
1082 auto *E = new (ExpressionAllocator) BasicExpression(2);
1083 // TODO: we need to remove context instruction after Value Tracking
1084 // can run without context instruction
1085 const SimplifyQuery Q = SQ.getWithInstruction(I);
1086
1087 E->setType(T);
1088 E->setOpcode(Opcode);
1089 E->allocateOperands(Recycler&: ArgRecycler, Allocator&: ExpressionAllocator);
1090 if (Instruction::isCommutative(Opcode)) {
1091 // Ensure that commutative instructions that only differ by a permutation
1092 // of their operands get the same value number by sorting the operand value
1093 // numbers. Since all commutative instructions have two operands it is more
1094 // efficient to sort by hand rather than using, say, std::sort.
1095 if (shouldSwapOperands(Arg1, Arg2))
1096 std::swap(a&: Arg1, b&: Arg2);
1097 }
1098 E->op_push_back(Arg: lookupOperandLeader(Arg1));
1099 E->op_push_back(Arg: lookupOperandLeader(Arg2));
1100
1101 Value *V = simplifyBinOp(Opcode, LHS: E->getOperand(N: 0), RHS: E->getOperand(N: 1), Q);
1102 if (auto Simplified = checkExprResults(E, I, V)) {
1103 addAdditionalUsers(Res&: Simplified, User: I);
1104 return Simplified.Expr;
1105 }
1106 return E;
1107}
1108
1109// Take a Value returned by simplification of Expression E/Instruction
1110// I, and see if it resulted in a simpler expression. If so, return
1111// that expression.
1112NewGVN::ExprResult NewGVN::checkExprResults(Expression *E, Instruction *I,
1113 Value *V) const {
1114 if (!V)
1115 return ExprResult::none();
1116
1117 if (auto *C = dyn_cast<Constant>(Val: V)) {
1118 if (I)
1119 LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
1120 << " constant " << *C << "\n");
1121 NumGVNOpsSimplified++;
1122 assert(isa<BasicExpression>(E) &&
1123 "We should always have had a basic expression here");
1124 deleteExpression(E);
1125 return ExprResult::some(Expr: createConstantExpression(C));
1126 } else if (isa<Argument>(Val: V) || isa<GlobalVariable>(Val: V)) {
1127 if (I)
1128 LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
1129 << " variable " << *V << "\n");
1130 deleteExpression(E);
1131 return ExprResult::some(Expr: createVariableExpression(V));
1132 }
1133
1134 CongruenceClass *CC = ValueToClass.lookup(Val: V);
1135 if (CC) {
1136 if (CC->getLeader() && CC->getLeader() != I) {
1137 return ExprResult::some(Expr: createVariableOrConstant(V: CC->getLeader()), ExtraDep: V);
1138 }
1139 if (CC->getDefiningExpr()) {
1140 if (I)
1141 LLVM_DEBUG(dbgs() << "Simplified " << *I << " to "
1142 << " expression " << *CC->getDefiningExpr() << "\n");
1143 NumGVNOpsSimplified++;
1144 deleteExpression(E);
1145 return ExprResult::some(Expr: CC->getDefiningExpr(), ExtraDep: V);
1146 }
1147 }
1148
1149 return ExprResult::none();
1150}
1151
1152// Create a value expression from the instruction I, replacing operands with
1153// their leaders.
1154
1155NewGVN::ExprResult NewGVN::createExpression(Instruction *I) const {
1156 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
1157 // TODO: we need to remove context instruction after Value Tracking
1158 // can run without context instruction
1159 const SimplifyQuery Q = SQ.getWithInstruction(I);
1160
1161 bool AllConstant = setBasicExpressionInfo(I, E);
1162
1163 if (I->isCommutative()) {
1164 // Ensure that commutative instructions that only differ by a permutation
1165 // of their operands get the same value number by sorting the operand value
1166 // numbers. Since all commutative instructions have two operands it is more
1167 // efficient to sort by hand rather than using, say, std::sort.
1168 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
1169 if (shouldSwapOperands(E->getOperand(N: 0), E->getOperand(N: 1)))
1170 E->swapOperands(First: 0, Second: 1);
1171 }
1172 // Perform simplification.
1173 if (auto *CI = dyn_cast<CmpInst>(Val: I)) {
1174 // Sort the operand value numbers so x<y and y>x get the same value
1175 // number.
1176 CmpInst::Predicate Predicate = CI->getPredicate();
1177 if (shouldSwapOperands(E->getOperand(N: 0), E->getOperand(N: 1))) {
1178 E->swapOperands(First: 0, Second: 1);
1179 Predicate = CmpInst::getSwappedPredicate(pred: Predicate);
1180 }
1181 E->setOpcode((CI->getOpcode() << 8) | Predicate);
1182 // TODO: 25% of our time is spent in simplifyCmpInst with pointer operands
1183 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
1184 "Wrong types on cmp instruction");
1185 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
1186 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
1187 Value *V =
1188 simplifyCmpInst(Predicate, LHS: E->getOperand(N: 0), RHS: E->getOperand(N: 1), Q);
1189 if (auto Simplified = checkExprResults(E, I, V))
1190 return Simplified;
1191 } else if (isa<SelectInst>(Val: I)) {
1192 if (isa<Constant>(Val: E->getOperand(N: 0)) ||
1193 E->getOperand(N: 1) == E->getOperand(N: 2)) {
1194 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
1195 E->getOperand(2)->getType() == I->getOperand(2)->getType());
1196 Value *V = simplifySelectInst(Cond: E->getOperand(N: 0), TrueVal: E->getOperand(N: 1),
1197 FalseVal: E->getOperand(N: 2), FMF: FastMathFlags(), Q);
1198 if (auto Simplified = checkExprResults(E, I, V))
1199 return Simplified;
1200 }
1201 } else if (I->isBinaryOp()) {
1202 Value *V =
1203 simplifyBinOp(Opcode: E->getOpcode(), LHS: E->getOperand(N: 0), RHS: E->getOperand(N: 1), Q);
1204 if (auto Simplified = checkExprResults(E, I, V))
1205 return Simplified;
1206 } else if (auto *CI = dyn_cast<CastInst>(Val: I)) {
1207 Value *V =
1208 simplifyCastInst(CastOpc: CI->getOpcode(), Op: E->getOperand(N: 0), Ty: CI->getType(), Q);
1209 if (auto Simplified = checkExprResults(E, I, V))
1210 return Simplified;
1211 } else if (auto *GEPI = dyn_cast<GetElementPtrInst>(Val: I)) {
1212 Value *V = simplifyGEPInst(SrcTy: GEPI->getSourceElementType(), Ptr: *E->op_begin(),
1213 Indices: ArrayRef(std::next(x: E->op_begin()), E->op_end()),
1214 NW: GEPI->getNoWrapFlags(), Q);
1215 if (auto Simplified = checkExprResults(E, I, V))
1216 return Simplified;
1217 } else if (AllConstant) {
1218 // We don't bother trying to simplify unless all of the operands
1219 // were constant.
1220 // TODO: There are a lot of Simplify*'s we could call here, if we
1221 // wanted to. The original motivating case for this code was a
1222 // zext i1 false to i8, which we don't have an interface to
1223 // simplify (IE there is no SimplifyZExt).
1224
1225 SmallVector<Constant *, 8> C;
1226 for (Value *Arg : E->operands())
1227 C.emplace_back(Args: cast<Constant>(Val: Arg));
1228
1229 if (Value *V = ConstantFoldInstOperands(I, Ops: C, DL, TLI))
1230 if (auto Simplified = checkExprResults(E, I, V))
1231 return Simplified;
1232 }
1233 return ExprResult::some(Expr: E);
1234}
1235
1236const AggregateValueExpression *
1237NewGVN::createAggregateValueExpression(Instruction *I) const {
1238 if (auto *II = dyn_cast<InsertValueInst>(Val: I)) {
1239 auto *E = new (ExpressionAllocator)
1240 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
1241 setBasicExpressionInfo(I, E);
1242 E->allocateIntOperands(Allocator&: ExpressionAllocator);
1243 llvm::copy(Range: II->indices(), Out: int_op_inserter(E));
1244 return E;
1245 } else if (auto *EI = dyn_cast<ExtractValueInst>(Val: I)) {
1246 auto *E = new (ExpressionAllocator)
1247 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
1248 setBasicExpressionInfo(I: EI, E);
1249 E->allocateIntOperands(Allocator&: ExpressionAllocator);
1250 llvm::copy(Range: EI->indices(), Out: int_op_inserter(E));
1251 return E;
1252 }
1253 llvm_unreachable("Unhandled type of aggregate value operation");
1254}
1255
1256const DeadExpression *NewGVN::createDeadExpression() const {
1257 // DeadExpression has no arguments and all DeadExpression's are the same,
1258 // so we only need one of them.
1259 return SingletonDeadExpression;
1260}
1261
1262const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
1263 auto *E = new (ExpressionAllocator) VariableExpression(V);
1264 E->setOpcode(V->getValueID());
1265 return E;
1266}
1267
1268const Expression *NewGVN::createVariableOrConstant(Value *V) const {
1269 if (auto *C = dyn_cast<Constant>(Val: V))
1270 return createConstantExpression(C);
1271 return createVariableExpression(V);
1272}
1273
1274const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
1275 auto *E = new (ExpressionAllocator) ConstantExpression(C);
1276 E->setOpcode(C->getValueID());
1277 return E;
1278}
1279
1280const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
1281 auto *E = new (ExpressionAllocator) UnknownExpression(I);
1282 E->setOpcode(I->getOpcode());
1283 return E;
1284}
1285
1286const CallExpression *
1287NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
1288 // FIXME: Add operand bundles for calls.
1289 auto *E =
1290 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
1291 setBasicExpressionInfo(I: CI, E);
1292 if (CI->isCommutative()) {
1293 // Ensure that commutative intrinsics that only differ by a permutation
1294 // of their operands get the same value number by sorting the operand value
1295 // numbers.
1296 assert(CI->getNumOperands() >= 2 && "Unsupported commutative intrinsic!");
1297 if (shouldSwapOperands(E->getOperand(N: 0), E->getOperand(N: 1)))
1298 E->swapOperands(First: 0, Second: 1);
1299 }
1300 return E;
1301}
1302
1303// Return true if some equivalent of instruction Inst dominates instruction U.
1304bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1305 const Instruction *U) const {
1306 auto *CC = ValueToClass.lookup(Val: Inst);
1307 // This must be an instruction because we are only called from phi nodes
1308 // in the case that the value it needs to check against is an instruction.
1309
1310 // The most likely candidates for dominance are the leader and the next leader.
1311 // The leader or nextleader will dominate in all cases where there is an
1312 // equivalent that is higher up in the dom tree.
1313 // We can't *only* check them, however, because the
1314 // dominator tree could have an infinite number of non-dominating siblings
1315 // with instructions that are in the right congruence class.
1316 // A
1317 // B C D E F G
1318 // |
1319 // H
1320 // Instruction U could be in H, with equivalents in every other sibling.
1321 // Depending on the rpo order picked, the leader could be the equivalent in
1322 // any of these siblings.
1323 if (!CC)
1324 return false;
1325 if (alwaysAvailable(V: CC->getLeader()))
1326 return true;
1327 if (DT->dominates(Def: cast<Instruction>(Val: CC->getLeader()), User: U))
1328 return true;
1329 if (CC->getNextLeader().first &&
1330 DT->dominates(Def: cast<Instruction>(Val: CC->getNextLeader().first), User: U))
1331 return true;
1332 return llvm::any_of(Range&: *CC, P: [&](const Value *Member) {
1333 return Member != CC->getLeader() &&
1334 DT->dominates(Def: cast<Instruction>(Val: Member), User: U);
1335 });
1336}
1337
1338// See if we have a congruence class and leader for this operand, and if so,
1339// return it. Otherwise, return the operand itself.
1340Value *NewGVN::lookupOperandLeader(Value *V) const {
1341 CongruenceClass *CC = ValueToClass.lookup(Val: V);
1342 if (CC) {
1343 // Everything in TOP is represented by poison, as it can be any value.
1344 // We do have to make sure we get the type right though, so we can't set the
1345 // RepLeader to poison.
1346 if (CC == TOPClass)
1347 return PoisonValue::get(T: V->getType());
1348 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
1349 }
1350
1351 return V;
1352}
1353
1354const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1355 auto *CC = getMemoryClass(MA);
1356 assert(CC->getMemoryLeader() &&
1357 "Every MemoryAccess should be mapped to a congruence class with a "
1358 "representative memory access");
1359 return CC->getMemoryLeader();
1360}
1361
1362// Return true if the MemoryAccess is really equivalent to everything. This is
1363// equivalent to the lattice value "TOP" in most lattices. This is the initial
1364// state of all MemoryAccesses.
1365bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
1366 return getMemoryClass(MA) == TOPClass;
1367}
1368
1369LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
1370 LoadInst *LI,
1371 const MemoryAccess *MA) const {
1372 auto *E =
1373 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
1374 E->allocateOperands(Recycler&: ArgRecycler, Allocator&: ExpressionAllocator);
1375 E->setType(LoadType);
1376
1377 // Give store and loads same opcode so they value number together.
1378 E->setOpcode(0);
1379 E->op_push_back(Arg: PointerOp);
1380
1381 // TODO: Value number heap versions. We may be able to discover
1382 // things alias analysis can't on it's own (IE that a store and a
1383 // load have the same value, and thus, it isn't clobbering the load).
1384 return E;
1385}
1386
1387const StoreExpression *
1388NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
1389 auto *StoredValueLeader = lookupOperandLeader(V: SI->getValueOperand());
1390 auto *E = new (ExpressionAllocator)
1391 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
1392 E->allocateOperands(Recycler&: ArgRecycler, Allocator&: ExpressionAllocator);
1393 E->setType(SI->getValueOperand()->getType());
1394
1395 // Give store and loads same opcode so they value number together.
1396 E->setOpcode(0);
1397 E->op_push_back(Arg: lookupOperandLeader(V: SI->getPointerOperand()));
1398
1399 // TODO: Value number heap versions. We may be able to discover
1400 // things alias analysis can't on it's own (IE that a store and a
1401 // load have the same value, and thus, it isn't clobbering the load).
1402 return E;
1403}
1404
1405const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
1406 // Unlike loads, we never try to eliminate stores, so we do not check if they
1407 // are simple and avoid value numbering them.
1408 auto *SI = cast<StoreInst>(Val: I);
1409 auto *StoreAccess = getMemoryAccess(I: SI);
1410 // Get the expression, if any, for the RHS of the MemoryDef.
1411 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1412 if (EnableStoreRefinement)
1413 StoreRHS = MSSAWalker->getClobberingMemoryAccess(MA: StoreAccess);
1414 // If we bypassed the use-def chains, make sure we add a use.
1415 StoreRHS = lookupMemoryLeader(MA: StoreRHS);
1416 if (StoreRHS != StoreAccess->getDefiningAccess())
1417 addMemoryUsers(To: StoreRHS, U: StoreAccess);
1418 // If we are defined by ourselves, use the live on entry def.
1419 if (StoreRHS == StoreAccess)
1420 StoreRHS = MSSA->getLiveOnEntryDef();
1421
1422 if (SI->isSimple()) {
1423 // See if we are defined by a previous store expression, it already has a
1424 // value, and it's the same value as our current store. FIXME: Right now, we
1425 // only do this for simple stores, we should expand to cover memcpys, etc.
1426 const auto *LastStore = createStoreExpression(SI, MA: StoreRHS);
1427 const auto *LastCC = ExpressionToClass.lookup(Val: LastStore);
1428 // We really want to check whether the expression we matched was a store. No
1429 // easy way to do that. However, we can check that the class we found has a
1430 // store, which, assuming the value numbering state is not corrupt, is
1431 // sufficient, because we must also be equivalent to that store's expression
1432 // for it to be in the same class as the load.
1433 if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
1434 return LastStore;
1435 // Also check if our value operand is defined by a load of the same memory
1436 // location, and the memory state is the same as it was then (otherwise, it
1437 // could have been overwritten later. See test32 in
1438 // transforms/DeadStoreElimination/simple.ll).
1439 if (auto *LI = dyn_cast<LoadInst>(Val: LastStore->getStoredValue()))
1440 if ((lookupOperandLeader(V: LI->getPointerOperand()) ==
1441 LastStore->getOperand(N: 0)) &&
1442 (lookupMemoryLeader(MA: getMemoryAccess(I: LI)->getDefiningAccess()) ==
1443 StoreRHS))
1444 return LastStore;
1445 deleteExpression(E: LastStore);
1446 }
1447
1448 // If the store is not equivalent to anything, value number it as a store that
1449 // produces a unique memory state (instead of using it's MemoryUse, we use
1450 // it's MemoryDef).
1451 return createStoreExpression(SI, MA: StoreAccess);
1452}
1453
1454// See if we can extract the value of a loaded pointer from a load, a store, or
1455// a memory instruction.
1456const Expression *
1457NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1458 LoadInst *LI, Instruction *DepInst,
1459 MemoryAccess *DefiningAccess) const {
1460 assert((!LI || LI->isSimple()) && "Not a simple load");
1461 if (auto *DepSI = dyn_cast<StoreInst>(Val: DepInst)) {
1462 // Can't forward from non-atomic to atomic without violating memory model.
1463 // Also don't need to coerce if they are the same type, we will just
1464 // propagate.
1465 if (LI->isAtomic() > DepSI->isAtomic() ||
1466 LoadType == DepSI->getValueOperand()->getType())
1467 return nullptr;
1468 int Offset = analyzeLoadFromClobberingStore(LoadTy: LoadType, LoadPtr, DepSI, DL);
1469 if (Offset >= 0) {
1470 if (auto *C = dyn_cast<Constant>(
1471 Val: lookupOperandLeader(V: DepSI->getValueOperand()))) {
1472 if (Constant *Res = getConstantValueForLoad(SrcVal: C, Offset, LoadTy: LoadType, DL)) {
1473 LLVM_DEBUG(dbgs() << "Coercing load from store " << *DepSI
1474 << " to constant " << *Res << "\n");
1475 return createConstantExpression(C: Res);
1476 }
1477 }
1478 }
1479 } else if (auto *DepLI = dyn_cast<LoadInst>(Val: DepInst)) {
1480 // Can't forward from non-atomic to atomic without violating memory model.
1481 if (LI->isAtomic() > DepLI->isAtomic())
1482 return nullptr;
1483 int Offset = analyzeLoadFromClobberingLoad(LoadTy: LoadType, LoadPtr, DepLI, DL);
1484 if (Offset >= 0) {
1485 // We can coerce a constant load into a load.
1486 if (auto *C = dyn_cast<Constant>(Val: lookupOperandLeader(V: DepLI)))
1487 if (auto *PossibleConstant =
1488 getConstantValueForLoad(SrcVal: C, Offset, LoadTy: LoadType, DL)) {
1489 LLVM_DEBUG(dbgs() << "Coercing load from load " << *LI
1490 << " to constant " << *PossibleConstant << "\n");
1491 return createConstantExpression(C: PossibleConstant);
1492 }
1493 }
1494 } else if (auto *DepMI = dyn_cast<MemIntrinsic>(Val: DepInst)) {
1495 int Offset = analyzeLoadFromClobberingMemInst(LoadTy: LoadType, LoadPtr, DepMI, DL);
1496 if (Offset >= 0) {
1497 if (auto *PossibleConstant =
1498 getConstantMemInstValueForLoad(SrcInst: DepMI, Offset, LoadTy: LoadType, DL)) {
1499 LLVM_DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1500 << " to constant " << *PossibleConstant << "\n");
1501 return createConstantExpression(C: PossibleConstant);
1502 }
1503 }
1504 }
1505
1506 if (auto *II = dyn_cast<IntrinsicInst>(Val: DepInst)) {
1507 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1508 auto *LifetimePtr = II->getOperand(i_nocapture: 0);
1509 if (LoadPtr == lookupOperandLeader(V: LifetimePtr) ||
1510 AA->isMustAlias(V1: LoadPtr, V2: LifetimePtr))
1511 return createConstantExpression(C: UndefValue::get(T: LoadType));
1512 }
1513 }
1514
1515 // All of the below are only true if the loaded pointer is produced
1516 // by the dependent instruction.
1517 if (!DepInst->getType()->isPointerTy() ||
1518 (LoadPtr != lookupOperandLeader(V: DepInst) &&
1519 !AA->isMustAlias(V1: LoadPtr, V2: DepInst)))
1520 return nullptr;
1521 // If this load really doesn't depend on anything, then we must be loading an
1522 // undef value. This can happen when loading for a fresh allocation with no
1523 // intervening stores, for example. Note that this is only true in the case
1524 // that the result of the allocation is pointer equal to the load ptr.
1525 if (isa<AllocaInst>(Val: DepInst)) {
1526 return createConstantExpression(C: UndefValue::get(T: LoadType));
1527 } else if (auto *InitVal =
1528 getInitialValueOfAllocation(V: DepInst, TLI, Ty: LoadType))
1529 return createConstantExpression(C: InitVal);
1530
1531 return nullptr;
1532}
1533
1534const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
1535 auto *LI = cast<LoadInst>(Val: I);
1536
1537 // We can eliminate in favor of non-simple loads, but we won't be able to
1538 // eliminate the loads themselves.
1539 if (!LI->isSimple())
1540 return nullptr;
1541
1542 Value *LoadAddressLeader = lookupOperandLeader(V: LI->getPointerOperand());
1543 // Load of undef is UB.
1544 if (isa<UndefValue>(Val: LoadAddressLeader))
1545 return createConstantExpression(C: PoisonValue::get(T: LI->getType()));
1546 MemoryAccess *OriginalAccess = getMemoryAccess(I);
1547 MemoryAccess *DefiningAccess =
1548 MSSAWalker->getClobberingMemoryAccess(MA: OriginalAccess);
1549
1550 if (!MSSA->isLiveOnEntryDef(MA: DefiningAccess)) {
1551 if (auto *MD = dyn_cast<MemoryDef>(Val: DefiningAccess)) {
1552 Instruction *DefiningInst = MD->getMemoryInst();
1553 // If the defining instruction is not reachable, replace with poison.
1554 if (!ReachableBlocks.count(Ptr: DefiningInst->getParent()))
1555 return createConstantExpression(C: PoisonValue::get(T: LI->getType()));
1556 // This will handle stores and memory insts. We only do if it the
1557 // defining access has a different type, or it is a pointer produced by
1558 // certain memory operations that cause the memory to have a fixed value
1559 // (IE things like calloc).
1560 if (const auto *CoercionResult =
1561 performSymbolicLoadCoercion(LoadType: LI->getType(), LoadPtr: LoadAddressLeader, LI,
1562 DepInst: DefiningInst, DefiningAccess))
1563 return CoercionResult;
1564 }
1565 }
1566
1567 const auto *LE = createLoadExpression(LoadType: LI->getType(), PointerOp: LoadAddressLeader, LI,
1568 MA: DefiningAccess);
1569 // If our MemoryLeader is not our defining access, add a use to the
1570 // MemoryLeader, so that we get reprocessed when it changes.
1571 if (LE->getMemoryLeader() != DefiningAccess)
1572 addMemoryUsers(To: LE->getMemoryLeader(), U: OriginalAccess);
1573 return LE;
1574}
1575
1576NewGVN::ExprResult
1577NewGVN::performSymbolicPredicateInfoEvaluation(BitCastInst *I) const {
1578 auto *PI = PredInfo->getPredicateInfoFor(V: I);
1579 if (!PI)
1580 return ExprResult::none();
1581
1582 LLVM_DEBUG(dbgs() << "Found predicate info from instruction !\n");
1583
1584 const std::optional<PredicateConstraint> &Constraint = PI->getConstraint();
1585 if (!Constraint)
1586 return ExprResult::none();
1587
1588 CmpInst::Predicate Predicate = Constraint->Predicate;
1589 Value *CmpOp0 = I->getOperand(i_nocapture: 0);
1590 Value *CmpOp1 = Constraint->OtherOp;
1591
1592 Value *FirstOp = lookupOperandLeader(V: CmpOp0);
1593 Value *SecondOp = lookupOperandLeader(V: CmpOp1);
1594 Value *AdditionallyUsedValue = CmpOp0;
1595
1596 // Sort the ops.
1597 if (shouldSwapOperandsForPredicate(FirstOp, SecondOp, I)) {
1598 std::swap(a&: FirstOp, b&: SecondOp);
1599 Predicate = CmpInst::getSwappedPredicate(pred: Predicate);
1600 AdditionallyUsedValue = CmpOp1;
1601 }
1602
1603 if (Predicate == CmpInst::ICMP_EQ)
1604 return ExprResult::some(Expr: createVariableOrConstant(V: FirstOp),
1605 ExtraDep: AdditionallyUsedValue, PredDep: PI);
1606
1607 // Handle the special case of floating point.
1608 if (Predicate == CmpInst::FCMP_OEQ && isa<ConstantFP>(Val: FirstOp) &&
1609 !cast<ConstantFP>(Val: FirstOp)->isZero())
1610 return ExprResult::some(Expr: createConstantExpression(C: cast<Constant>(Val: FirstOp)),
1611 ExtraDep: AdditionallyUsedValue, PredDep: PI);
1612
1613 return ExprResult::none();
1614}
1615
1616// Evaluate read only and pure calls, and create an expression result.
1617NewGVN::ExprResult NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
1618 auto *CI = cast<CallInst>(Val: I);
1619
1620 // FIXME: Currently the calls which may access the thread id may
1621 // be considered as not accessing the memory. But this is
1622 // problematic for coroutines, since coroutines may resume in a
1623 // different thread. So we disable the optimization here for the
1624 // correctness. However, it may block many other correct
1625 // optimizations. Revert this one when we detect the memory
1626 // accessing kind more precisely.
1627 if (CI->getFunction()->isPresplitCoroutine())
1628 return ExprResult::none();
1629
1630 // Do not combine convergent calls since they implicitly depend on the set of
1631 // threads that is currently executing, and they might be in different basic
1632 // blocks.
1633 if (CI->isConvergent())
1634 return ExprResult::none();
1635
1636 if (AA->doesNotAccessMemory(Call: CI)) {
1637 return ExprResult::some(
1638 Expr: createCallExpression(CI, MA: TOPClass->getMemoryLeader()));
1639 } else if (AA->onlyReadsMemory(Call: CI)) {
1640 if (auto *MA = MSSA->getMemoryAccess(I: CI)) {
1641 auto *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(MA);
1642 return ExprResult::some(Expr: createCallExpression(CI, MA: DefiningAccess));
1643 } else // MSSA determined that CI does not access memory.
1644 return ExprResult::some(
1645 Expr: createCallExpression(CI, MA: TOPClass->getMemoryLeader()));
1646 }
1647 return ExprResult::none();
1648}
1649
1650// Retrieve the memory class for a given MemoryAccess.
1651CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1652 auto *Result = MemoryAccessToClass.lookup(Val: MA);
1653 assert(Result && "Should have found memory class");
1654 return Result;
1655}
1656
1657// Update the MemoryAccess equivalence table to say that From is equal to To,
1658// and return true if this is different from what already existed in the table.
1659bool NewGVN::setMemoryClass(const MemoryAccess *From,
1660 CongruenceClass *NewClass) {
1661 assert(NewClass &&
1662 "Every MemoryAccess should be getting mapped to a non-null class");
1663 LLVM_DEBUG(dbgs() << "Setting " << *From);
1664 LLVM_DEBUG(dbgs() << " equivalent to congruence class ");
1665 LLVM_DEBUG(dbgs() << NewClass->getID()
1666 << " with current MemoryAccess leader ");
1667 LLVM_DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
1668
1669 auto LookupResult = MemoryAccessToClass.find(Val: From);
1670 bool Changed = false;
1671 // If it's already in the table, see if the value changed.
1672 if (LookupResult != MemoryAccessToClass.end()) {
1673 auto *OldClass = LookupResult->second;
1674 if (OldClass != NewClass) {
1675 // If this is a phi, we have to handle memory member updates.
1676 if (auto *MP = dyn_cast<MemoryPhi>(Val: From)) {
1677 OldClass->memory_erase(M: MP);
1678 NewClass->memory_insert(M: MP);
1679 // This may have killed the class if it had no non-memory members
1680 if (OldClass->getMemoryLeader() == From) {
1681 if (OldClass->definesNoMemory()) {
1682 OldClass->setMemoryLeader(nullptr);
1683 } else {
1684 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1685 LLVM_DEBUG(dbgs() << "Memory class leader change for class "
1686 << OldClass->getID() << " to "
1687 << *OldClass->getMemoryLeader()
1688 << " due to removal of a memory member " << *From
1689 << "\n");
1690 markMemoryLeaderChangeTouched(CC: OldClass);
1691 }
1692 }
1693 }
1694 // It wasn't equivalent before, and now it is.
1695 LookupResult->second = NewClass;
1696 Changed = true;
1697 }
1698 }
1699
1700 return Changed;
1701}
1702
1703// Determine if a instruction is cycle-free. That means the values in the
1704// instruction don't depend on any expressions that can change value as a result
1705// of the instruction. For example, a non-cycle free instruction would be v =
1706// phi(0, v+1).
1707bool NewGVN::isCycleFree(const Instruction *I) const {
1708 // In order to compute cycle-freeness, we do SCC finding on the instruction,
1709 // and see what kind of SCC it ends up in. If it is a singleton, it is
1710 // cycle-free. If it is not in a singleton, it is only cycle free if the
1711 // other members are all phi nodes (as they do not compute anything, they are
1712 // copies).
1713 auto ICS = InstCycleState.lookup(Val: I);
1714 if (ICS == ICS_Unknown) {
1715 SCCFinder.Start(Start: I);
1716 auto &SCC = SCCFinder.getComponentFor(V: I);
1717 // It's cycle free if it's size 1 or the SCC is *only* phi nodes.
1718 if (SCC.size() == 1)
1719 InstCycleState.insert(KV: {I, ICS_CycleFree});
1720 else {
1721 bool AllPhis = llvm::all_of(Range: SCC, P: [](const Value *V) {
1722 return isa<PHINode>(Val: V) || isCopyOfAPHI(V);
1723 });
1724 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
1725 for (const auto *Member : SCC)
1726 if (auto *MemberPhi = dyn_cast<PHINode>(Val: Member))
1727 InstCycleState.insert(KV: {MemberPhi, ICS});
1728 }
1729 }
1730 if (ICS == ICS_Cycle)
1731 return false;
1732 return true;
1733}
1734
1735// Evaluate PHI nodes symbolically and create an expression result.
1736const Expression *
1737NewGVN::performSymbolicPHIEvaluation(ArrayRef<ValPair> PHIOps,
1738 Instruction *I,
1739 BasicBlock *PHIBlock) const {
1740 // True if one of the incoming phi edges is a backedge.
1741 bool HasBackedge = false;
1742 // All constant tracks the state of whether all the *original* phi operands
1743 // This is really shorthand for "this phi cannot cycle due to forward
1744 // change in value of the phi is guaranteed not to later change the value of
1745 // the phi. IE it can't be v = phi(undef, v+1)
1746 bool OriginalOpsConstant = true;
1747 auto *E = cast<PHIExpression>(Val: createPHIExpression(
1748 PHIOperands: PHIOps, I, PHIBlock, HasBackedge, OriginalOpsConstant));
1749 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1750 // See if all arguments are the same.
1751 // We track if any were undef because they need special handling.
1752 bool HasUndef = false, HasPoison = false;
1753 auto Filtered = make_filter_range(Range: E->operands(), Pred: [&](Value *Arg) {
1754 if (isa<PoisonValue>(Val: Arg)) {
1755 HasPoison = true;
1756 return false;
1757 }
1758 if (isa<UndefValue>(Val: Arg)) {
1759 HasUndef = true;
1760 return false;
1761 }
1762 return true;
1763 });
1764 // If we are left with no operands, it's dead.
1765 if (Filtered.empty()) {
1766 // If it has undef or poison at this point, it means there are no-non-undef
1767 // arguments, and thus, the value of the phi node must be undef.
1768 if (HasUndef) {
1769 LLVM_DEBUG(
1770 dbgs() << "PHI Node " << *I
1771 << " has no non-undef arguments, valuing it as undef\n");
1772 return createConstantExpression(C: UndefValue::get(T: I->getType()));
1773 }
1774 if (HasPoison) {
1775 LLVM_DEBUG(
1776 dbgs() << "PHI Node " << *I
1777 << " has no non-poison arguments, valuing it as poison\n");
1778 return createConstantExpression(C: PoisonValue::get(T: I->getType()));
1779 }
1780
1781 LLVM_DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
1782 deleteExpression(E);
1783 return createDeadExpression();
1784 }
1785 Value *AllSameValue = *(Filtered.begin());
1786 ++Filtered.begin();
1787 // Can't use std::equal here, sadly, because filter.begin moves.
1788 if (llvm::all_of(Range&: Filtered, P: equal_to(Arg&: AllSameValue))) {
1789 // Can't fold phi(undef, X) -> X unless X can't be poison (thus X is undef
1790 // in the worst case).
1791 if (HasUndef && !isGuaranteedNotToBePoison(V: AllSameValue, AC, CtxI: nullptr, DT))
1792 return E;
1793
1794 // In LLVM's non-standard representation of phi nodes, it's possible to have
1795 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1796 // on the original phi node), especially in weird CFG's where some arguments
1797 // are unreachable, or uninitialized along certain paths. This can cause
1798 // infinite loops during evaluation. We work around this by not trying to
1799 // really evaluate them independently, but instead using a variable
1800 // expression to say if one is equivalent to the other.
1801 // We also special case undef/poison, so that if we have an undef, we can't
1802 // use the common value unless it dominates the phi block.
1803 if (HasPoison || HasUndef) {
1804 // If we have undef and at least one other value, this is really a
1805 // multivalued phi, and we need to know if it's cycle free in order to
1806 // evaluate whether we can ignore the undef. The other parts of this are
1807 // just shortcuts. If there is no backedge, or all operands are
1808 // constants, it also must be cycle free.
1809 if (HasBackedge && !OriginalOpsConstant &&
1810 !isa<UndefValue>(Val: AllSameValue) && !isCycleFree(I))
1811 return E;
1812
1813 // Only have to check for instructions
1814 if (auto *AllSameInst = dyn_cast<Instruction>(Val: AllSameValue))
1815 if (!someEquivalentDominates(Inst: AllSameInst, U: I))
1816 return E;
1817 }
1818 // Can't simplify to something that comes later in the iteration.
1819 // Otherwise, when and if it changes congruence class, we will never catch
1820 // up. We will always be a class behind it.
1821 if (isa<Instruction>(Val: AllSameValue) &&
1822 InstrToDFSNum(V: AllSameValue) > InstrToDFSNum(V: I))
1823 return E;
1824 NumGVNPhisAllSame++;
1825 LLVM_DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1826 << "\n");
1827 deleteExpression(E);
1828 return createVariableOrConstant(V: AllSameValue);
1829 }
1830 return E;
1831}
1832
1833const Expression *
1834NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
1835 if (auto *EI = dyn_cast<ExtractValueInst>(Val: I)) {
1836 auto *WO = dyn_cast<WithOverflowInst>(Val: EI->getAggregateOperand());
1837 if (WO && EI->getNumIndices() == 1 && *EI->idx_begin() == 0)
1838 // EI is an extract from one of our with.overflow intrinsics. Synthesize
1839 // a semantically equivalent expression instead of an extract value
1840 // expression.
1841 return createBinaryExpression(Opcode: WO->getBinaryOp(), T: EI->getType(),
1842 Arg1: WO->getLHS(), Arg2: WO->getRHS(), I);
1843 }
1844
1845 return createAggregateValueExpression(I);
1846}
1847
1848NewGVN::ExprResult NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
1849 assert(isa<CmpInst>(I) && "Expected a cmp instruction.");
1850
1851 auto *CI = cast<CmpInst>(Val: I);
1852 // See if our operands are equal to those of a previous predicate, and if so,
1853 // if it implies true or false.
1854 auto Op0 = lookupOperandLeader(V: CI->getOperand(i_nocapture: 0));
1855 auto Op1 = lookupOperandLeader(V: CI->getOperand(i_nocapture: 1));
1856 auto OurPredicate = CI->getPredicate();
1857 if (shouldSwapOperands(Op0, Op1)) {
1858 std::swap(a&: Op0, b&: Op1);
1859 OurPredicate = CI->getSwappedPredicate();
1860 }
1861
1862 // Avoid processing the same info twice.
1863 const PredicateBase *LastPredInfo = nullptr;
1864 // See if we know something about the comparison itself, like it is the target
1865 // of an assume.
1866 auto *CmpPI = PredInfo->getPredicateInfoFor(V: I);
1867 if (isa_and_nonnull<PredicateAssume>(Val: CmpPI))
1868 return ExprResult::some(
1869 Expr: createConstantExpression(C: ConstantInt::getTrue(Ty: CI->getType())));
1870
1871 if (Op0 == Op1) {
1872 // This condition does not depend on predicates, no need to add users
1873 if (CI->isTrueWhenEqual())
1874 return ExprResult::some(
1875 Expr: createConstantExpression(C: ConstantInt::getTrue(Ty: CI->getType())));
1876 else if (CI->isFalseWhenEqual())
1877 return ExprResult::some(
1878 Expr: createConstantExpression(C: ConstantInt::getFalse(Ty: CI->getType())));
1879 }
1880
1881 // NOTE: Because we are comparing both operands here and below, and using
1882 // previous comparisons, we rely on fact that predicateinfo knows to mark
1883 // comparisons that use renamed operands as users of the earlier comparisons.
1884 // It is *not* enough to just mark predicateinfo renamed operands as users of
1885 // the earlier comparisons, because the *other* operand may have changed in a
1886 // previous iteration.
1887 // Example:
1888 // icmp slt %a, %b
1889 // %b.0 = ssa.copy(%b)
1890 // false branch:
1891 // icmp slt %c, %b.0
1892
1893 // %c and %a may start out equal, and thus, the code below will say the second
1894 // %icmp is false. c may become equal to something else, and in that case the
1895 // %second icmp *must* be reexamined, but would not if only the renamed
1896 // %operands are considered users of the icmp.
1897
1898 // *Currently* we only check one level of comparisons back, and only mark one
1899 // level back as touched when changes happen. If you modify this code to look
1900 // back farther through comparisons, you *must* mark the appropriate
1901 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1902 // we know something just from the operands themselves
1903
1904 // See if our operands have predicate info, so that we may be able to derive
1905 // something from a previous comparison.
1906 for (const auto &Op : CI->operands()) {
1907 auto *PI = PredInfo->getPredicateInfoFor(V: Op);
1908 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(Val: PI)) {
1909 if (PI == LastPredInfo)
1910 continue;
1911 LastPredInfo = PI;
1912 // In phi of ops cases, we may have predicate info that we are evaluating
1913 // in a different context.
1914 if (!DT->dominates(A: PBranch->To, B: I->getParent()))
1915 continue;
1916 // TODO: Along the false edge, we may know more things too, like
1917 // icmp of
1918 // same operands is false.
1919 // TODO: We only handle actual comparison conditions below, not
1920 // and/or.
1921 auto *BranchCond = dyn_cast<CmpInst>(Val: PBranch->Condition);
1922 if (!BranchCond)
1923 continue;
1924 auto *BranchOp0 = lookupOperandLeader(V: BranchCond->getOperand(i_nocapture: 0));
1925 auto *BranchOp1 = lookupOperandLeader(V: BranchCond->getOperand(i_nocapture: 1));
1926 auto BranchPredicate = BranchCond->getPredicate();
1927 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
1928 std::swap(a&: BranchOp0, b&: BranchOp1);
1929 BranchPredicate = BranchCond->getSwappedPredicate();
1930 }
1931 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1932 if (PBranch->TrueEdge) {
1933 // If we know the previous predicate is true and we are in the true
1934 // edge then we may be implied true or false.
1935 if (auto R = ICmpInst::isImpliedByMatchingCmp(Pred1: BranchPredicate,
1936 Pred2: OurPredicate)) {
1937 auto *C = ConstantInt::getBool(Ty: CI->getType(), V: *R);
1938 return ExprResult::some(Expr: createConstantExpression(C), PredDep: PI);
1939 }
1940 } else {
1941 // Just handle the ne and eq cases, where if we have the same
1942 // operands, we may know something.
1943 if (BranchPredicate == OurPredicate) {
1944 // Same predicate, same ops,we know it was false, so this is false.
1945 return ExprResult::some(
1946 Expr: createConstantExpression(C: ConstantInt::getFalse(Ty: CI->getType())),
1947 PredDep: PI);
1948 } else if (BranchPredicate ==
1949 CmpInst::getInversePredicate(pred: OurPredicate)) {
1950 // Inverse predicate, we know the other was false, so this is true.
1951 return ExprResult::some(
1952 Expr: createConstantExpression(C: ConstantInt::getTrue(Ty: CI->getType())),
1953 PredDep: PI);
1954 }
1955 }
1956 }
1957 }
1958 }
1959 // Create expression will take care of simplifyCmpInst
1960 return createExpression(I);
1961}
1962
1963// Substitute and symbolize the instruction before value numbering.
1964NewGVN::ExprResult
1965NewGVN::performSymbolicEvaluation(Instruction *I,
1966 SmallPtrSetImpl<Value *> &Visited) const {
1967
1968 const Expression *E = nullptr;
1969 // TODO: memory intrinsics.
1970 // TODO: Some day, we should do the forward propagation and reassociation
1971 // parts of the algorithm.
1972 switch (I->getOpcode()) {
1973 case Instruction::ExtractValue:
1974 case Instruction::InsertValue:
1975 E = performSymbolicAggrValueEvaluation(I);
1976 break;
1977 case Instruction::PHI: {
1978 SmallVector<ValPair, 3> Ops;
1979 auto *PN = cast<PHINode>(Val: I);
1980 for (unsigned i = 0; i < PN->getNumOperands(); ++i)
1981 Ops.push_back(Elt: {PN->getIncomingValue(i), PN->getIncomingBlock(i)});
1982 // Sort to ensure the invariant createPHIExpression requires is met.
1983 sortPHIOps(Ops);
1984 E = performSymbolicPHIEvaluation(PHIOps: Ops, I, PHIBlock: getBlockForValue(V: I));
1985 } break;
1986 case Instruction::Call:
1987 return performSymbolicCallEvaluation(I);
1988 break;
1989 case Instruction::Store:
1990 E = performSymbolicStoreEvaluation(I);
1991 break;
1992 case Instruction::Load:
1993 E = performSymbolicLoadEvaluation(I);
1994 break;
1995 case Instruction::BitCast:
1996 // Intrinsics with the returned attribute are copies of arguments.
1997 if (I->getType() == I->getOperand(i: 0)->getType())
1998 if (auto Res =
1999 performSymbolicPredicateInfoEvaluation(I: cast<BitCastInst>(Val: I)))
2000 return Res;
2001 [[fallthrough]];
2002 case Instruction::AddrSpaceCast:
2003 case Instruction::Freeze:
2004 return createExpression(I);
2005 break;
2006 case Instruction::ICmp:
2007 case Instruction::FCmp:
2008 return performSymbolicCmpEvaluation(I);
2009 break;
2010 case Instruction::FNeg:
2011 case Instruction::Add:
2012 case Instruction::FAdd:
2013 case Instruction::Sub:
2014 case Instruction::FSub:
2015 case Instruction::Mul:
2016 case Instruction::FMul:
2017 case Instruction::UDiv:
2018 case Instruction::SDiv:
2019 case Instruction::FDiv:
2020 case Instruction::URem:
2021 case Instruction::SRem:
2022 case Instruction::FRem:
2023 case Instruction::Shl:
2024 case Instruction::LShr:
2025 case Instruction::AShr:
2026 case Instruction::And:
2027 case Instruction::Or:
2028 case Instruction::Xor:
2029 case Instruction::Trunc:
2030 case Instruction::ZExt:
2031 case Instruction::SExt:
2032 case Instruction::FPToUI:
2033 case Instruction::FPToSI:
2034 case Instruction::UIToFP:
2035 case Instruction::SIToFP:
2036 case Instruction::FPTrunc:
2037 case Instruction::FPExt:
2038 case Instruction::PtrToInt:
2039 case Instruction::PtrToAddr:
2040 case Instruction::IntToPtr:
2041 case Instruction::Select:
2042 case Instruction::ExtractElement:
2043 case Instruction::InsertElement:
2044 case Instruction::GetElementPtr:
2045 return createExpression(I);
2046 break;
2047 case Instruction::ShuffleVector:
2048 // FIXME: Add support for shufflevector to createExpression.
2049 return ExprResult::none();
2050 default:
2051 return ExprResult::none();
2052 }
2053 return ExprResult::some(Expr: E);
2054}
2055
2056// Look up a container of values/instructions in a map, and touch all the
2057// instructions in the container. Then erase value from the map.
2058template <typename Map, typename KeyType>
2059void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
2060 const auto Result = M.find_as(Key);
2061 if (Result != M.end()) {
2062 for (const typename Map::mapped_type::value_type Mapped : Result->second)
2063 TouchedInstructions.set(InstrToDFSNum(Mapped));
2064 M.erase(Result);
2065 }
2066}
2067
2068void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
2069 assert(User && To != User);
2070 if (isa<Instruction>(Val: To))
2071 AdditionalUsers[To].insert(Ptr: User);
2072}
2073
2074void NewGVN::addAdditionalUsers(ExprResult &Res, Instruction *User) const {
2075 if (Res.ExtraDep && Res.ExtraDep != User)
2076 addAdditionalUsers(To: Res.ExtraDep, User);
2077 Res.ExtraDep = nullptr;
2078
2079 if (Res.PredDep) {
2080 if (const auto *PBranch = dyn_cast<PredicateBranch>(Val: Res.PredDep))
2081 PredicateToUsers[PBranch->Condition].insert(Ptr: User);
2082 else if (const auto *PAssume =
2083 dyn_cast<PredicateConditionAssume>(Val: Res.PredDep))
2084 PredicateToUsers[PAssume->Condition].insert(Ptr: User);
2085 }
2086 Res.PredDep = nullptr;
2087}
2088
2089void NewGVN::markUsersTouched(Value *V) {
2090 // Now mark the users as touched.
2091 for (auto *User : V->users()) {
2092 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
2093 TouchedInstructions.set(InstrToDFSNum(V: User));
2094 }
2095 touchAndErase(M&: AdditionalUsers, Key: V);
2096}
2097
2098void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
2099 LLVM_DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
2100 MemoryToUsers[To].insert(Ptr: U);
2101}
2102
2103void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
2104 TouchedInstructions.set(MemoryToDFSNum(MA));
2105}
2106
2107void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
2108 if (isa<MemoryUse>(Val: MA))
2109 return;
2110 for (const auto *U : MA->users())
2111 TouchedInstructions.set(MemoryToDFSNum(MA: U));
2112 touchAndErase(M&: MemoryToUsers, Key: MA);
2113}
2114
2115// Touch all the predicates that depend on this instruction.
2116void NewGVN::markPredicateUsersTouched(Instruction *I) {
2117 touchAndErase(M&: PredicateToUsers, Key: I);
2118}
2119
2120// Mark users affected by a memory leader change.
2121void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
2122 for (const auto *M : CC->memory())
2123 markMemoryDefTouched(MA: M);
2124}
2125
2126// Touch the instructions that need to be updated after a congruence class has a
2127// leader change, and mark changed values.
2128void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
2129 for (auto *M : *CC) {
2130 if (auto *I = dyn_cast<Instruction>(Val: M))
2131 TouchedInstructions.set(InstrToDFSNum(V: I));
2132 LeaderChanges.insert(Ptr: M);
2133 }
2134}
2135
2136// Give a range of things that have instruction DFS numbers, this will return
2137// the member of the range with the smallest dfs number.
2138template <class T, class Range>
2139T *NewGVN::getMinDFSOfRange(const Range &R) const {
2140 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
2141 for (const auto X : R) {
2142 auto DFSNum = InstrToDFSNum(X);
2143 if (DFSNum < MinDFS.second)
2144 MinDFS = {X, DFSNum};
2145 }
2146 return MinDFS.first;
2147}
2148
2149// This function returns the MemoryAccess that should be the next leader of
2150// congruence class CC, under the assumption that the current leader is going to
2151// disappear.
2152const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
2153 // TODO: If this ends up to slow, we can maintain a next memory leader like we
2154 // do for regular leaders.
2155 // Make sure there will be a leader to find.
2156 assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
2157 if (CC->getStoreCount() > 0) {
2158 if (auto *NL = dyn_cast_or_null<StoreInst>(Val: CC->getNextLeader().first))
2159 return getMemoryAccess(I: NL);
2160 // Find the store with the minimum DFS number.
2161 auto *V = getMinDFSOfRange<Value>(R: make_filter_range(
2162 Range&: *CC, Pred: [&](const Value *V) { return isa<StoreInst>(Val: V); }));
2163 return getMemoryAccess(I: cast<StoreInst>(Val: V));
2164 }
2165 assert(CC->getStoreCount() == 0);
2166
2167 // Given our assertion, hitting this part must mean
2168 // !OldClass->memory_empty()
2169 if (CC->memory_size() == 1)
2170 return *CC->memory_begin();
2171 return getMinDFSOfRange<const MemoryPhi>(R: CC->memory());
2172}
2173
2174// This function returns the next value leader of a congruence class, under the
2175// assumption that the current leader is going away. This should end up being
2176// the next most dominating member.
2177Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
2178 // We don't need to sort members if there is only 1, and we don't care about
2179 // sorting the TOP class because everything either gets out of it or is
2180 // unreachable.
2181
2182 if (CC->size() == 1 || CC == TOPClass) {
2183 return *(CC->begin());
2184 } else if (CC->getNextLeader().first) {
2185 ++NumGVNAvoidedSortedLeaderChanges;
2186 return CC->getNextLeader().first;
2187 } else {
2188 ++NumGVNSortedLeaderChanges;
2189 // NOTE: If this ends up to slow, we can maintain a dual structure for
2190 // member testing/insertion, or keep things mostly sorted, and sort only
2191 // here, or use SparseBitVector or ....
2192 return getMinDFSOfRange<Value>(R: *CC);
2193 }
2194}
2195
2196// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
2197// the memory members, etc for the move.
2198//
2199// The invariants of this function are:
2200//
2201// - I must be moving to NewClass from OldClass
2202// - The StoreCount of OldClass and NewClass is expected to have been updated
2203// for I already if it is a store.
2204// - The OldClass memory leader has not been updated yet if I was the leader.
2205void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
2206 MemoryAccess *InstMA,
2207 CongruenceClass *OldClass,
2208 CongruenceClass *NewClass) {
2209 // If the leader is I, and we had a representative MemoryAccess, it should
2210 // be the MemoryAccess of OldClass.
2211 assert((!InstMA || !OldClass->getMemoryLeader() ||
2212 OldClass->getLeader() != I ||
2213 MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
2214 MemoryAccessToClass.lookup(InstMA)) &&
2215 "Representative MemoryAccess mismatch");
2216 // First, see what happens to the new class
2217 if (!NewClass->getMemoryLeader()) {
2218 // Should be a new class, or a store becoming a leader of a new class.
2219 assert(NewClass->size() == 1 ||
2220 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
2221 NewClass->setMemoryLeader(InstMA);
2222 // Mark it touched if we didn't just create a singleton
2223 LLVM_DEBUG(dbgs() << "Memory class leader change for class "
2224 << NewClass->getID()
2225 << " due to new memory instruction becoming leader\n");
2226 markMemoryLeaderChangeTouched(CC: NewClass);
2227 }
2228 setMemoryClass(From: InstMA, NewClass);
2229 // Now, fixup the old class if necessary
2230 if (OldClass->getMemoryLeader() == InstMA) {
2231 if (!OldClass->definesNoMemory()) {
2232 OldClass->setMemoryLeader(getNextMemoryLeader(CC: OldClass));
2233 LLVM_DEBUG(dbgs() << "Memory class leader change for class "
2234 << OldClass->getID() << " to "
2235 << *OldClass->getMemoryLeader()
2236 << " due to removal of old leader " << *InstMA << "\n");
2237 markMemoryLeaderChangeTouched(CC: OldClass);
2238 } else
2239 OldClass->setMemoryLeader(nullptr);
2240 }
2241}
2242
2243// Move a value, currently in OldClass, to be part of NewClass
2244// Update OldClass and NewClass for the move (including changing leaders, etc).
2245void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
2246 CongruenceClass *OldClass,
2247 CongruenceClass *NewClass) {
2248 if (I == OldClass->getNextLeader().first)
2249 OldClass->resetNextLeader();
2250
2251 OldClass->erase(M: I);
2252 NewClass->insert(M: I);
2253
2254 // Ensure that the leader has the lowest RPO. If the leader changed notify all
2255 // members of the class.
2256 if (NewClass->getLeader() != I &&
2257 NewClass->addPossibleLeader(LeaderPair: {I, InstrToDFSNum(V: I)})) {
2258 markValueLeaderChangeTouched(CC: NewClass);
2259 }
2260
2261 // Handle our special casing of stores.
2262 if (auto *SI = dyn_cast<StoreInst>(Val: I)) {
2263 OldClass->decStoreCount();
2264 // Okay, so when do we want to make a store a leader of a class?
2265 // If we have a store defined by an earlier load, we want the earlier load
2266 // to lead the class.
2267 // If we have a store defined by something else, we want the store to lead
2268 // the class so everything else gets the "something else" as a value.
2269 // If we have a store as the single member of the class, we want the store
2270 // as the leader
2271 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
2272 // If it's a store expression we are using, it means we are not equivalent
2273 // to something earlier.
2274 if (auto *SE = dyn_cast<StoreExpression>(Val: E)) {
2275 NewClass->setStoredValue(SE->getStoredValue());
2276 markValueLeaderChangeTouched(CC: NewClass);
2277 // Shift the new class leader to be the store
2278 LLVM_DEBUG(dbgs() << "Changing leader of congruence class "
2279 << NewClass->getID() << " from "
2280 << *NewClass->getLeader() << " to " << *SI
2281 << " because store joined class\n");
2282 // If we changed the leader, we have to mark it changed because we don't
2283 // know what it will do to symbolic evaluation.
2284 NewClass->setLeader({SI, InstrToDFSNum(V: SI)});
2285 }
2286 // We rely on the code below handling the MemoryAccess change.
2287 }
2288 NewClass->incStoreCount();
2289 }
2290 // True if there is no memory instructions left in a class that had memory
2291 // instructions before.
2292
2293 // If it's not a memory use, set the MemoryAccess equivalence
2294 auto *InstMA = dyn_cast_or_null<MemoryDef>(Val: getMemoryAccess(I));
2295 if (InstMA)
2296 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
2297 ValueToClass[I] = NewClass;
2298 // See if we destroyed the class or need to swap leaders.
2299 if (OldClass->empty() && OldClass != TOPClass) {
2300 if (OldClass->getDefiningExpr()) {
2301 LLVM_DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
2302 << " from table\n");
2303 // We erase it as an exact expression to make sure we don't just erase an
2304 // equivalent one.
2305 auto Iter = ExpressionToClass.find_as(
2306 Val: ExactEqualsExpression(*OldClass->getDefiningExpr()));
2307 if (Iter != ExpressionToClass.end())
2308 ExpressionToClass.erase(I: Iter);
2309#ifdef EXPENSIVE_CHECKS
2310 assert(
2311 (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
2312 "We erased the expression we just inserted, which should not happen");
2313#endif
2314 }
2315 } else if (OldClass->getLeader() == I) {
2316 // When the leader changes, the value numbering of
2317 // everything may change due to symbolization changes, so we need to
2318 // reprocess.
2319 LLVM_DEBUG(dbgs() << "Value class leader change for class "
2320 << OldClass->getID() << "\n");
2321 ++NumGVNLeaderChanges;
2322 // Destroy the stored value if there are no more stores to represent it.
2323 // Note that this is basically clean up for the expression removal that
2324 // happens below. If we remove stores from a class, we may leave it as a
2325 // class of equivalent memory phis.
2326 if (OldClass->getStoreCount() == 0) {
2327 if (OldClass->getStoredValue())
2328 OldClass->setStoredValue(nullptr);
2329 }
2330 OldClass->setLeader({getNextValueLeader(CC: OldClass),
2331 InstrToDFSNum(V: getNextValueLeader(CC: OldClass))});
2332 OldClass->resetNextLeader();
2333 markValueLeaderChangeTouched(CC: OldClass);
2334 }
2335}
2336
2337// For a given expression, mark the phi of ops instructions that could have
2338// changed as a result.
2339void NewGVN::markPhiOfOpsChanged(const Expression *E) {
2340 touchAndErase(M&: ExpressionToPhiOfOps, Key: E);
2341}
2342
2343// Perform congruence finding on a given value numbering expression.
2344void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
2345 // This is guaranteed to return something, since it will at least find
2346 // TOP.
2347
2348 CongruenceClass *IClass = ValueToClass.lookup(Val: I);
2349 assert(IClass && "Should have found a IClass");
2350 // Dead classes should have been eliminated from the mapping.
2351 assert(!IClass->isDead() && "Found a dead class");
2352
2353 CongruenceClass *EClass = nullptr;
2354 if (const auto *VE = dyn_cast<VariableExpression>(Val: E)) {
2355 EClass = ValueToClass.lookup(Val: VE->getVariableValue());
2356 } else if (isa<DeadExpression>(Val: E)) {
2357 EClass = TOPClass;
2358 }
2359 if (!EClass) {
2360 auto lookupResult = ExpressionToClass.try_emplace(Key: E);
2361
2362 // If it's not in the value table, create a new congruence class.
2363 if (lookupResult.second) {
2364 CongruenceClass *NewClass = createCongruenceClass(Leader: nullptr, E);
2365 auto place = lookupResult.first;
2366 place->second = NewClass;
2367
2368 // Constants and variables should always be made the leader.
2369 if (const auto *CE = dyn_cast<ConstantExpression>(Val: E)) {
2370 NewClass->setLeader({CE->getConstantValue(), 0});
2371 } else if (const auto *SE = dyn_cast<StoreExpression>(Val: E)) {
2372 StoreInst *SI = SE->getStoreInst();
2373 NewClass->setLeader({SI, InstrToDFSNum(V: SI)});
2374 NewClass->setStoredValue(SE->getStoredValue());
2375 // The RepMemoryAccess field will be filled in properly by the
2376 // moveValueToNewCongruenceClass call.
2377 } else {
2378 NewClass->setLeader({I, InstrToDFSNum(V: I)});
2379 }
2380 assert(!isa<VariableExpression>(E) &&
2381 "VariableExpression should have been handled already");
2382
2383 EClass = NewClass;
2384 LLVM_DEBUG(dbgs() << "Created new congruence class for " << *I
2385 << " using expression " << *E << " at "
2386 << NewClass->getID() << " and leader "
2387 << *(NewClass->getLeader()));
2388 if (NewClass->getStoredValue())
2389 LLVM_DEBUG(dbgs() << " and stored value "
2390 << *(NewClass->getStoredValue()));
2391 LLVM_DEBUG(dbgs() << "\n");
2392 } else {
2393 EClass = lookupResult.first->second;
2394 if (isa<ConstantExpression>(Val: E))
2395 assert((isa<Constant>(EClass->getLeader()) ||
2396 (EClass->getStoredValue() &&
2397 isa<Constant>(EClass->getStoredValue()))) &&
2398 "Any class with a constant expression should have a "
2399 "constant leader");
2400
2401 assert(EClass && "Somehow don't have an eclass");
2402
2403 assert(!EClass->isDead() && "We accidentally looked up a dead class");
2404 }
2405 }
2406 bool ClassChanged = IClass != EClass;
2407 bool LeaderChanged = LeaderChanges.erase(Ptr: I);
2408 if (ClassChanged || LeaderChanged) {
2409 LLVM_DEBUG(dbgs() << "New class " << EClass->getID() << " for expression "
2410 << *E << "\n");
2411 if (ClassChanged) {
2412 moveValueToNewCongruenceClass(I, E, OldClass: IClass, NewClass: EClass);
2413 markPhiOfOpsChanged(E);
2414 }
2415
2416 markUsersTouched(V: I);
2417 if (MemoryAccess *MA = getMemoryAccess(I))
2418 markMemoryUsersTouched(MA);
2419 if (auto *CI = dyn_cast<CmpInst>(Val: I))
2420 markPredicateUsersTouched(I: CI);
2421 }
2422 // If we changed the class of the store, we want to ensure nothing finds the
2423 // old store expression. In particular, loads do not compare against stored
2424 // value, so they will find old store expressions (and associated class
2425 // mappings) if we leave them in the table.
2426 if (ClassChanged && isa<StoreInst>(Val: I)) {
2427 auto *OldE = ValueToExpression.lookup(Val: I);
2428 // It could just be that the old class died. We don't want to erase it if we
2429 // just moved classes.
2430 if (OldE && isa<StoreExpression>(Val: OldE) && *E != *OldE) {
2431 // Erase this as an exact expression to ensure we don't erase expressions
2432 // equivalent to it.
2433 auto Iter = ExpressionToClass.find_as(Val: ExactEqualsExpression(*OldE));
2434 if (Iter != ExpressionToClass.end())
2435 ExpressionToClass.erase(I: Iter);
2436 }
2437 }
2438 ValueToExpression[I] = E;
2439}
2440
2441// Process the fact that Edge (from, to) is reachable, including marking
2442// any newly reachable blocks and instructions for processing.
2443void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2444 // Check if the Edge was reachable before.
2445 if (ReachableEdges.insert(V: {From, To}).second) {
2446 // If this block wasn't reachable before, all instructions are touched.
2447 if (ReachableBlocks.insert(Ptr: To).second) {
2448 LLVM_DEBUG(dbgs() << "Block " << getBlockName(To)
2449 << " marked reachable\n");
2450 const auto &InstRange = BlockInstRange.lookup(Val: To);
2451 TouchedInstructions.set(I: InstRange.first, E: InstRange.second);
2452 } else {
2453 LLVM_DEBUG(dbgs() << "Block " << getBlockName(To)
2454 << " was reachable, but new edge {"
2455 << getBlockName(From) << "," << getBlockName(To)
2456 << "} to it found\n");
2457
2458 // We've made an edge reachable to an existing block, which may
2459 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2460 // they are the only thing that depend on new edges. Anything using their
2461 // values will get propagated to if necessary.
2462 if (MemoryAccess *MemPhi = getMemoryAccess(BB: To))
2463 TouchedInstructions.set(InstrToDFSNum(MA: MemPhi));
2464
2465 // FIXME: We should just add a union op on a Bitvector and
2466 // SparseBitVector. We can do it word by word faster than we are doing it
2467 // here.
2468 for (auto InstNum : RevisitOnReachabilityChange[To])
2469 TouchedInstructions.set(InstNum);
2470 }
2471 }
2472}
2473
2474// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2475// see if we know some constant value for it already.
2476Value *NewGVN::findConditionEquivalence(Value *Cond) const {
2477 auto Result = lookupOperandLeader(V: Cond);
2478 return isa<Constant>(Val: Result) ? Result : nullptr;
2479}
2480
2481// Process the outgoing edges of a block for reachability.
2482void NewGVN::processOutgoingEdges(Instruction *TI, BasicBlock *B) {
2483 // Evaluate reachability of terminator instruction.
2484 Value *Cond;
2485 BasicBlock *TrueSucc, *FalseSucc;
2486 if (match(V: TI, P: m_Br(C: m_Value(V&: Cond), T&: TrueSucc, F&: FalseSucc))) {
2487 Value *CondEvaluated = findConditionEquivalence(Cond);
2488 if (!CondEvaluated) {
2489 if (auto *I = dyn_cast<Instruction>(Val: Cond)) {
2490 SmallPtrSet<Value *, 4> Visited;
2491 auto Res = performSymbolicEvaluation(I, Visited);
2492 if (const auto *CE = dyn_cast_or_null<ConstantExpression>(Val: Res.Expr)) {
2493 CondEvaluated = CE->getConstantValue();
2494 addAdditionalUsers(Res, User: I);
2495 } else {
2496 // Did not use simplification result, no need to add the extra
2497 // dependency.
2498 Res.ExtraDep = nullptr;
2499 }
2500 } else if (isa<ConstantInt>(Val: Cond)) {
2501 CondEvaluated = Cond;
2502 }
2503 }
2504 ConstantInt *CI;
2505 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(Val: CondEvaluated))) {
2506 if (CI->isOne()) {
2507 LLVM_DEBUG(dbgs() << "Condition for Terminator " << *TI
2508 << " evaluated to true\n");
2509 updateReachableEdge(From: B, To: TrueSucc);
2510 } else if (CI->isZero()) {
2511 LLVM_DEBUG(dbgs() << "Condition for Terminator " << *TI
2512 << " evaluated to false\n");
2513 updateReachableEdge(From: B, To: FalseSucc);
2514 }
2515 } else {
2516 updateReachableEdge(From: B, To: TrueSucc);
2517 updateReachableEdge(From: B, To: FalseSucc);
2518 }
2519 } else if (auto *SI = dyn_cast<SwitchInst>(Val: TI)) {
2520 // For switches, propagate the case values into the case
2521 // destinations.
2522
2523 Value *SwitchCond = SI->getCondition();
2524 Value *CondEvaluated = findConditionEquivalence(Cond: SwitchCond);
2525 // See if we were able to turn this switch statement into a constant.
2526 if (CondEvaluated && isa<ConstantInt>(Val: CondEvaluated)) {
2527 auto *CondVal = cast<ConstantInt>(Val: CondEvaluated);
2528 // We should be able to get case value for this.
2529 auto Case = *SI->findCaseValue(C: CondVal);
2530 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
2531 // We proved the value is outside of the range of the case.
2532 // We can't do anything other than mark the default dest as reachable,
2533 // and go home.
2534 updateReachableEdge(From: B, To: SI->getDefaultDest());
2535 return;
2536 }
2537 // Now get where it goes and mark it reachable.
2538 BasicBlock *TargetBlock = Case.getCaseSuccessor();
2539 updateReachableEdge(From: B, To: TargetBlock);
2540 } else {
2541 for (BasicBlock *TargetBlock : successors(BB: SI->getParent()))
2542 updateReachableEdge(From: B, To: TargetBlock);
2543 }
2544 } else {
2545 // Otherwise this is either unconditional, or a type we have no
2546 // idea about. Just mark successors as reachable.
2547 for (BasicBlock *TargetBlock : successors(BB: TI->getParent()))
2548 updateReachableEdge(From: B, To: TargetBlock);
2549
2550 // This also may be a memory defining terminator, in which case, set it
2551 // equivalent only to itself.
2552 //
2553 auto *MA = getMemoryAccess(I: TI);
2554 if (MA && !isa<MemoryUse>(Val: MA)) {
2555 auto *CC = ensureLeaderOfMemoryClass(MA);
2556 if (setMemoryClass(From: MA, NewClass: CC))
2557 markMemoryUsersTouched(MA);
2558 }
2559 }
2560}
2561
2562// Remove the PHI of Ops PHI for I
2563void NewGVN::removePhiOfOps(Instruction *I, PHINode *PHITemp) {
2564 InstrDFS.erase(Val: PHITemp);
2565 // It's still a temp instruction. We keep it in the array so it gets erased.
2566 // However, it's no longer used by I, or in the block
2567 TempToBlock.erase(Val: PHITemp);
2568 RealToTemp.erase(Val: I);
2569 // We don't remove the users from the phi node uses. This wastes a little
2570 // time, but such is life. We could use two sets to track which were there
2571 // are the start of NewGVN, and which were added, but right nowt he cost of
2572 // tracking is more than the cost of checking for more phi of ops.
2573}
2574
2575// Add PHI Op in BB as a PHI of operations version of ExistingValue.
2576void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
2577 Instruction *ExistingValue) {
2578 InstrDFS[Op] = InstrToDFSNum(V: ExistingValue);
2579 AllTempInstructions.insert(V: Op);
2580 TempToBlock[Op] = BB;
2581 RealToTemp[ExistingValue] = Op;
2582 // Add all users to phi node use, as they are now uses of the phi of ops phis
2583 // and may themselves be phi of ops.
2584 for (auto *U : ExistingValue->users())
2585 if (auto *UI = dyn_cast<Instruction>(Val: U))
2586 PHINodeUses.insert(Ptr: UI);
2587}
2588
2589static bool okayForPHIOfOps(const Instruction *I) {
2590 if (!EnablePhiOfOps)
2591 return false;
2592 return isa<BinaryOperator>(Val: I) || isa<SelectInst>(Val: I) || isa<CmpInst>(Val: I) ||
2593 isa<LoadInst>(Val: I);
2594}
2595
2596// Return true if this operand will be safe to use for phi of ops.
2597//
2598// The reason some operands are unsafe is that we are not trying to recursively
2599// translate everything back through phi nodes. We actually expect some lookups
2600// of expressions to fail. In particular, a lookup where the expression cannot
2601// exist in the predecessor. This is true even if the expression, as shown, can
2602// be determined to be constant.
2603bool NewGVN::OpIsSafeForPHIOfOps(Value *V, const BasicBlock *PHIBlock,
2604 SmallPtrSetImpl<const Value *> &Visited) {
2605 SmallVector<Value *, 4> Worklist;
2606 Worklist.push_back(Elt: V);
2607 while (!Worklist.empty()) {
2608 auto *I = Worklist.pop_back_val();
2609 if (!isa<Instruction>(Val: I))
2610 continue;
2611
2612 auto OISIt = OpSafeForPHIOfOps.find(Val: {I, CacheIdx});
2613 if (OISIt != OpSafeForPHIOfOps.end())
2614 return OISIt->second;
2615
2616 // Keep walking until we either dominate the phi block, or hit a phi, or run
2617 // out of things to check.
2618 if (DT->properlyDominates(A: getBlockForValue(V: I), B: PHIBlock)) {
2619 OpSafeForPHIOfOps.insert(KV: {{I, CacheIdx}, true});
2620 continue;
2621 }
2622 // PHI in the same block.
2623 if (isa<PHINode>(Val: I) && getBlockForValue(V: I) == PHIBlock) {
2624 OpSafeForPHIOfOps.insert(KV: {{I, CacheIdx}, false});
2625 return false;
2626 }
2627
2628 auto *OrigI = cast<Instruction>(Val: I);
2629 // When we hit an instruction that reads memory (load, call, etc), we must
2630 // consider any store that may happen in the loop. For now, we assume the
2631 // worst: there is a store in the loop that alias with this read.
2632 // The case where the load is outside the loop is already covered by the
2633 // dominator check above.
2634 // TODO: relax this condition
2635 if (OrigI->mayReadFromMemory())
2636 return false;
2637
2638 // Check the operands of the current instruction.
2639 for (auto *Op : OrigI->operand_values()) {
2640 if (!isa<Instruction>(Val: Op))
2641 continue;
2642 // Stop now if we find an unsafe operand.
2643 auto OISIt = OpSafeForPHIOfOps.find(Val: {OrigI, CacheIdx});
2644 if (OISIt != OpSafeForPHIOfOps.end()) {
2645 if (!OISIt->second) {
2646 OpSafeForPHIOfOps.insert(KV: {{I, CacheIdx}, false});
2647 return false;
2648 }
2649 continue;
2650 }
2651 if (!Visited.insert(Ptr: Op).second)
2652 continue;
2653 Worklist.push_back(Elt: cast<Instruction>(Val: Op));
2654 }
2655 }
2656 OpSafeForPHIOfOps.insert(KV: {{V, CacheIdx}, true});
2657 return true;
2658}
2659
2660// Try to find a leader for instruction TransInst, which is a phi translated
2661// version of something in our original program. Visited is used to ensure we
2662// don't infinite loop during translations of cycles. OrigInst is the
2663// instruction in the original program, and PredBB is the predecessor we
2664// translated it through.
2665Value *NewGVN::findLeaderForInst(Instruction *TransInst,
2666 SmallPtrSetImpl<Value *> &Visited,
2667 MemoryAccess *MemAccess, Instruction *OrigInst,
2668 BasicBlock *PredBB) {
2669 unsigned IDFSNum = InstrToDFSNum(V: OrigInst);
2670 // Make sure it's marked as a temporary instruction.
2671 AllTempInstructions.insert(V: TransInst);
2672 // and make sure anything that tries to add it's DFS number is
2673 // redirected to the instruction we are making a phi of ops
2674 // for.
2675 TempToBlock.insert(KV: {TransInst, PredBB});
2676 InstrDFS.insert(KV: {TransInst, IDFSNum});
2677
2678 auto Res = performSymbolicEvaluation(I: TransInst, Visited);
2679 const Expression *E = Res.Expr;
2680 addAdditionalUsers(Res, User: OrigInst);
2681 InstrDFS.erase(Val: TransInst);
2682 AllTempInstructions.erase(V: TransInst);
2683 TempToBlock.erase(Val: TransInst);
2684 if (MemAccess)
2685 TempToMemory.erase(Val: TransInst);
2686 if (!E)
2687 return nullptr;
2688 auto *FoundVal = findPHIOfOpsLeader(E, OrigInst, PredBB);
2689 if (!FoundVal) {
2690 ExpressionToPhiOfOps[E].insert(Ptr: OrigInst);
2691 LLVM_DEBUG(dbgs() << "Cannot find phi of ops operand for " << *TransInst
2692 << " in block " << getBlockName(PredBB) << "\n");
2693 return nullptr;
2694 }
2695 if (auto *SI = dyn_cast<StoreInst>(Val: FoundVal))
2696 FoundVal = SI->getValueOperand();
2697 return FoundVal;
2698}
2699
2700// When we see an instruction that is an op of phis, generate the equivalent phi
2701// of ops form.
2702const Expression *
2703NewGVN::makePossiblePHIOfOps(Instruction *I,
2704 SmallPtrSetImpl<Value *> &Visited) {
2705 if (!okayForPHIOfOps(I))
2706 return nullptr;
2707
2708 if (!Visited.insert(Ptr: I).second)
2709 return nullptr;
2710 // For now, we require the instruction be cycle free because we don't
2711 // *always* create a phi of ops for instructions that could be done as phi
2712 // of ops, we only do it if we think it is useful. If we did do it all the
2713 // time, we could remove the cycle free check.
2714 if (!isCycleFree(I))
2715 return nullptr;
2716
2717 // TODO: We don't do phi translation on memory accesses because it's
2718 // complicated. For a load, we'd need to be able to simulate a new memoryuse,
2719 // which we don't have a good way of doing ATM.
2720 auto *MemAccess = getMemoryAccess(I);
2721 // If the memory operation is defined by a memory operation this block that
2722 // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
2723 // can't help, as it would still be killed by that memory operation.
2724 if (MemAccess && !isa<MemoryPhi>(Val: MemAccess->getDefiningAccess()) &&
2725 MemAccess->getDefiningAccess()->getBlock() == I->getParent())
2726 return nullptr;
2727
2728 // Convert op of phis to phi of ops
2729 SmallPtrSet<const Value *, 10> VisitedOps;
2730 SmallVector<Value *, 4> Ops(I->operand_values());
2731 BasicBlock *SamePHIBlock = nullptr;
2732 PHINode *OpPHI = nullptr;
2733 if (!DebugCounter::shouldExecute(Counter&: PHIOfOpsCounter))
2734 return nullptr;
2735 for (auto *Op : Ops) {
2736 if (!isa<PHINode>(Val: Op)) {
2737 auto *ValuePHI = RealToTemp.lookup(Val: Op);
2738 if (!ValuePHI)
2739 continue;
2740 LLVM_DEBUG(dbgs() << "Found possible dependent phi of ops\n");
2741 Op = ValuePHI;
2742 }
2743 OpPHI = cast<PHINode>(Val: Op);
2744 if (!SamePHIBlock) {
2745 SamePHIBlock = getBlockForValue(V: OpPHI);
2746 } else if (SamePHIBlock != getBlockForValue(V: OpPHI)) {
2747 LLVM_DEBUG(
2748 dbgs()
2749 << "PHIs for operands are not all in the same block, aborting\n");
2750 return nullptr;
2751 }
2752 // No point in doing this for one-operand phis.
2753 // Since all PHIs for operands must be in the same block, then they must
2754 // have the same number of operands so we can just abort.
2755 if (OpPHI->getNumOperands() == 1)
2756 return nullptr;
2757 }
2758
2759 if (!OpPHI)
2760 return nullptr;
2761
2762 SmallVector<ValPair, 4> PHIOps;
2763 SmallPtrSet<Value *, 4> Deps;
2764 auto *PHIBlock = getBlockForValue(V: OpPHI);
2765 RevisitOnReachabilityChange[PHIBlock].reset(Idx: InstrToDFSNum(V: I));
2766 for (unsigned PredNum = 0; PredNum < OpPHI->getNumOperands(); ++PredNum) {
2767 auto *PredBB = OpPHI->getIncomingBlock(i: PredNum);
2768 Value *FoundVal = nullptr;
2769 SmallPtrSet<Value *, 4> CurrentDeps;
2770 // We could just skip unreachable edges entirely but it's tricky to do
2771 // with rewriting existing phi nodes.
2772 if (ReachableEdges.count(V: {PredBB, PHIBlock})) {
2773 // Clone the instruction, create an expression from it that is
2774 // translated back into the predecessor, and see if we have a leader.
2775 Instruction *ValueOp = I->clone();
2776 // Emit the temporal instruction in the predecessor basic block where the
2777 // corresponding value is defined.
2778 ValueOp->insertBefore(InsertPos: PredBB->getTerminator()->getIterator());
2779 if (MemAccess)
2780 TempToMemory.insert(KV: {ValueOp, MemAccess});
2781 bool SafeForPHIOfOps = true;
2782 VisitedOps.clear();
2783 for (auto &Op : ValueOp->operands()) {
2784 auto *OrigOp = &*Op;
2785 // When these operand changes, it could change whether there is a
2786 // leader for us or not, so we have to add additional users.
2787 if (isa<PHINode>(Val: Op)) {
2788 Op = Op->DoPHITranslation(CurBB: PHIBlock, PredBB);
2789 if (Op != OrigOp && Op != I)
2790 CurrentDeps.insert(Ptr: Op);
2791 } else if (auto *ValuePHI = RealToTemp.lookup(Val: Op)) {
2792 if (getBlockForValue(V: ValuePHI) == PHIBlock)
2793 Op = ValuePHI->getIncomingValueForBlock(BB: PredBB);
2794 }
2795 // If we phi-translated the op, it must be safe.
2796 SafeForPHIOfOps =
2797 SafeForPHIOfOps &&
2798 (Op != OrigOp || OpIsSafeForPHIOfOps(V: Op, PHIBlock, Visited&: VisitedOps));
2799 }
2800 // FIXME: For those things that are not safe we could generate
2801 // expressions all the way down, and see if this comes out to a
2802 // constant. For anything where that is true, and unsafe, we should
2803 // have made a phi-of-ops (or value numbered it equivalent to something)
2804 // for the pieces already.
2805 FoundVal = !SafeForPHIOfOps ? nullptr
2806 : findLeaderForInst(TransInst: ValueOp, Visited,
2807 MemAccess, OrigInst: I, PredBB);
2808 ValueOp->eraseFromParent();
2809 if (!FoundVal) {
2810 // We failed to find a leader for the current ValueOp, but this might
2811 // change in case of the translated operands change.
2812 if (SafeForPHIOfOps)
2813 for (auto *Dep : CurrentDeps)
2814 addAdditionalUsers(To: Dep, User: I);
2815
2816 return nullptr;
2817 }
2818 Deps.insert_range(R&: CurrentDeps);
2819 } else {
2820 LLVM_DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
2821 << getBlockName(PredBB)
2822 << " because the block is unreachable\n");
2823 FoundVal = PoisonValue::get(T: I->getType());
2824 RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(V: I));
2825 }
2826
2827 PHIOps.push_back(Elt: {FoundVal, PredBB});
2828 LLVM_DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
2829 << getBlockName(PredBB) << "\n");
2830 }
2831 for (auto *Dep : Deps)
2832 addAdditionalUsers(To: Dep, User: I);
2833 sortPHIOps(Ops: PHIOps);
2834 auto *E = performSymbolicPHIEvaluation(PHIOps, I, PHIBlock);
2835 if (isa<ConstantExpression>(Val: E) || isa<VariableExpression>(Val: E)) {
2836 LLVM_DEBUG(
2837 dbgs()
2838 << "Not creating real PHI of ops because it simplified to existing "
2839 "value or constant\n");
2840 // We have leaders for all operands, but do not create a real PHI node with
2841 // those leaders as operands, so the link between the operands and the
2842 // PHI-of-ops is not materialized in the IR. If any of those leaders
2843 // changes, the PHI-of-op may change also, so we need to add the operands as
2844 // additional users.
2845 for (auto &O : PHIOps)
2846 addAdditionalUsers(To: O.first, User: I);
2847
2848 return E;
2849 }
2850 auto *ValuePHI = RealToTemp.lookup(Val: I);
2851 bool NewPHI = false;
2852 if (!ValuePHI) {
2853 ValuePHI =
2854 PHINode::Create(Ty: I->getType(), NumReservedValues: OpPHI->getNumOperands(), NameStr: "phiofops");
2855 addPhiOfOps(Op: ValuePHI, BB: PHIBlock, ExistingValue: I);
2856 NewPHI = true;
2857 NumGVNPHIOfOpsCreated++;
2858 }
2859 if (NewPHI) {
2860 for (auto PHIOp : PHIOps)
2861 ValuePHI->addIncoming(V: PHIOp.first, BB: PHIOp.second);
2862 } else {
2863 TempToBlock[ValuePHI] = PHIBlock;
2864 unsigned int i = 0;
2865 for (auto PHIOp : PHIOps) {
2866 ValuePHI->setIncomingValue(i, V: PHIOp.first);
2867 ValuePHI->setIncomingBlock(i, BB: PHIOp.second);
2868 ++i;
2869 }
2870 }
2871 RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(V: I));
2872 LLVM_DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
2873 << "\n");
2874
2875 return E;
2876}
2877
2878// The algorithm initially places the values of the routine in the TOP
2879// congruence class. The leader of TOP is the undetermined value `poison`.
2880// When the algorithm has finished, values still in TOP are unreachable.
2881void NewGVN::initializeCongruenceClasses(Function &F) {
2882 NextCongruenceNum = 0;
2883
2884 // Note that even though we use the live on entry def as a representative
2885 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2886 // have no real equivalent to poison for MemoryAccesses, and so we really
2887 // should be checking whether the MemoryAccess is top if we want to know if it
2888 // is equivalent to everything. Otherwise, what this really signifies is that
2889 // the access "it reaches all the way back to the beginning of the function"
2890
2891 // Initialize all other instructions to be in TOP class.
2892 TOPClass = createCongruenceClass(Leader: nullptr, E: nullptr);
2893 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
2894 // The live on entry def gets put into it's own class
2895 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2896 createMemoryClass(MA: MSSA->getLiveOnEntryDef());
2897
2898 for (auto *DTN : nodes(G: DT)) {
2899 BasicBlock *BB = DTN->getBlock();
2900 // All MemoryAccesses are equivalent to live on entry to start. They must
2901 // be initialized to something so that initial changes are noticed. For
2902 // the maximal answer, we initialize them all to be the same as
2903 // liveOnEntry.
2904 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
2905 if (MemoryBlockDefs)
2906 for (const auto &Def : *MemoryBlockDefs) {
2907 MemoryAccessToClass[&Def] = TOPClass;
2908 auto *MD = dyn_cast<MemoryDef>(Val: &Def);
2909 // Insert the memory phis into the member list.
2910 if (!MD) {
2911 const MemoryPhi *MP = cast<MemoryPhi>(Val: &Def);
2912 TOPClass->memory_insert(M: MP);
2913 MemoryPhiState.insert(KV: {MP, MPS_TOP});
2914 }
2915
2916 if (MD && isa<StoreInst>(Val: MD->getMemoryInst()))
2917 TOPClass->incStoreCount();
2918 }
2919
2920 // FIXME: This is trying to discover which instructions are uses of phi
2921 // nodes. We should move this into one of the myriad of places that walk
2922 // all the operands already.
2923 for (auto &I : *BB) {
2924 if (isa<PHINode>(Val: &I))
2925 for (auto *U : I.users())
2926 if (auto *UInst = dyn_cast<Instruction>(Val: U))
2927 if (InstrToDFSNum(V: UInst) != 0 && okayForPHIOfOps(I: UInst))
2928 PHINodeUses.insert(Ptr: UInst);
2929 // Don't insert void terminators into the class. We don't value number
2930 // them, and they just end up sitting in TOP.
2931 if (I.isTerminator() && I.getType()->isVoidTy())
2932 continue;
2933 TOPClass->insert(M: &I);
2934 ValueToClass[&I] = TOPClass;
2935 }
2936 }
2937
2938 // Initialize arguments to be in their own unique congruence classes
2939 for (auto &FA : F.args())
2940 createSingletonCongruenceClass(Member: &FA);
2941}
2942
2943void NewGVN::cleanupTables() {
2944 for (CongruenceClass *&CC : CongruenceClasses) {
2945 LLVM_DEBUG(dbgs() << "Congruence class " << CC->getID() << " has "
2946 << CC->size() << " members\n");
2947 // Make sure we delete the congruence class (probably worth switching to
2948 // a unique_ptr at some point.
2949 delete CC;
2950 CC = nullptr;
2951 }
2952
2953 // Destroy the value expressions
2954 SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
2955 AllTempInstructions.end());
2956 AllTempInstructions.clear();
2957
2958 // We have to drop all references for everything first, so there are no uses
2959 // left as we delete them.
2960 for (auto *I : TempInst) {
2961 I->dropAllReferences();
2962 }
2963
2964 while (!TempInst.empty()) {
2965 auto *I = TempInst.pop_back_val();
2966 I->deleteValue();
2967 }
2968
2969 ValueToClass.clear();
2970 ArgRecycler.clear(ExpressionAllocator);
2971 ExpressionAllocator.Reset();
2972 CongruenceClasses.clear();
2973 ExpressionToClass.clear();
2974 ValueToExpression.clear();
2975 RealToTemp.clear();
2976 AdditionalUsers.clear();
2977 ExpressionToPhiOfOps.clear();
2978 TempToBlock.clear();
2979 TempToMemory.clear();
2980 PHINodeUses.clear();
2981 OpSafeForPHIOfOps.clear();
2982 ReachableBlocks.clear();
2983 ReachableEdges.clear();
2984#ifndef NDEBUG
2985 ProcessedCount.clear();
2986#endif
2987 InstrDFS.clear();
2988 InstructionsToErase.clear();
2989 DFSToInstr.clear();
2990 BlockInstRange.clear();
2991 TouchedInstructions.clear();
2992 MemoryAccessToClass.clear();
2993 PredicateToUsers.clear();
2994 MemoryToUsers.clear();
2995 RevisitOnReachabilityChange.clear();
2996 PredicateSwapChoice.clear();
2997}
2998
2999// Assign local DFS number mapping to instructions, and leave space for Value
3000// PHI's.
3001std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
3002 unsigned Start) {
3003 unsigned End = Start;
3004 if (MemoryAccess *MemPhi = getMemoryAccess(BB: B)) {
3005 InstrDFS[MemPhi] = End++;
3006 DFSToInstr.emplace_back(Args&: MemPhi);
3007 }
3008
3009 // Then the real block goes next.
3010 for (auto &I : *B) {
3011 // There's no need to call isInstructionTriviallyDead more than once on
3012 // an instruction. Therefore, once we know that an instruction is dead
3013 // we change its DFS number so that it doesn't get value numbered.
3014 if (isInstructionTriviallyDead(I: &I, TLI)) {
3015 InstrDFS[&I] = 0;
3016 LLVM_DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
3017 salvageDebugInfo(I);
3018 markInstructionForDeletion(&I);
3019 continue;
3020 }
3021 if (isa<PHINode>(Val: &I))
3022 RevisitOnReachabilityChange[B].set(End);
3023 InstrDFS[&I] = End++;
3024 DFSToInstr.emplace_back(Args: &I);
3025 }
3026
3027 // All of the range functions taken half-open ranges (open on the end side).
3028 // So we do not subtract one from count, because at this point it is one
3029 // greater than the last instruction.
3030 return std::make_pair(x&: Start, y&: End);
3031}
3032
3033void NewGVN::updateProcessedCount(const Value *V) {
3034#ifndef NDEBUG
3035 assert(++ProcessedCount[V] < 100 &&
3036 "Seem to have processed the same Value a lot");
3037#endif
3038}
3039
3040// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
3041void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
3042 // If all the arguments are the same, the MemoryPhi has the same value as the
3043 // argument. Filter out unreachable blocks and self phis from our operands.
3044 // TODO: We could do cycle-checking on the memory phis to allow valueizing for
3045 // self-phi checking.
3046 const BasicBlock *PHIBlock = MP->getBlock();
3047 auto Filtered = make_filter_range(Range: MP->operands(), Pred: [&](const Use &U) {
3048 return cast<MemoryAccess>(Val: U) != MP &&
3049 !isMemoryAccessTOP(MA: cast<MemoryAccess>(Val: U)) &&
3050 ReachableEdges.count(V: {MP->getIncomingBlock(U), PHIBlock});
3051 });
3052 // If all that is left is nothing, our memoryphi is poison. We keep it as
3053 // InitialClass. Note: The only case this should happen is if we have at
3054 // least one self-argument.
3055 if (Filtered.begin() == Filtered.end()) {
3056 if (setMemoryClass(From: MP, NewClass: TOPClass))
3057 markMemoryUsersTouched(MA: MP);
3058 return;
3059 }
3060
3061 // Transform the remaining operands into operand leaders.
3062 // FIXME: mapped_iterator should have a range version.
3063 auto LookupFunc = [&](const Use &U) {
3064 return lookupMemoryLeader(MA: cast<MemoryAccess>(Val: U));
3065 };
3066 auto MappedBegin = map_iterator(I: Filtered.begin(), F: LookupFunc);
3067 auto MappedEnd = map_iterator(I: Filtered.end(), F: LookupFunc);
3068
3069 // and now check if all the elements are equal.
3070 // Sadly, we can't use std::equals since these are random access iterators.
3071 const auto *AllSameValue = *MappedBegin;
3072 ++MappedBegin;
3073 bool AllEqual = std::all_of(
3074 first: MappedBegin, last: MappedEnd,
3075 pred: [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
3076
3077 if (AllEqual)
3078 LLVM_DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue
3079 << "\n");
3080 else
3081 LLVM_DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
3082 // If it's equal to something, it's in that class. Otherwise, it has to be in
3083 // a class where it is the leader (other things may be equivalent to it, but
3084 // it needs to start off in its own class, which means it must have been the
3085 // leader, and it can't have stopped being the leader because it was never
3086 // removed).
3087 CongruenceClass *CC =
3088 AllEqual ? getMemoryClass(MA: AllSameValue) : ensureLeaderOfMemoryClass(MA: MP);
3089 auto OldState = MemoryPhiState.lookup(Val: MP);
3090 assert(OldState != MPS_Invalid && "Invalid memory phi state");
3091 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
3092 MemoryPhiState[MP] = NewState;
3093 if (setMemoryClass(From: MP, NewClass: CC) || OldState != NewState)
3094 markMemoryUsersTouched(MA: MP);
3095}
3096
3097// Value number a single instruction, symbolically evaluating, performing
3098// congruence finding, and updating mappings.
3099void NewGVN::valueNumberInstruction(Instruction *I) {
3100 LLVM_DEBUG(dbgs() << "Processing instruction " << *I << "\n");
3101 if (!I->isTerminator()) {
3102 const Expression *Symbolized = nullptr;
3103 SmallPtrSet<Value *, 2> Visited;
3104 if (DebugCounter::shouldExecute(Counter&: VNCounter)) {
3105 auto Res = performSymbolicEvaluation(I, Visited);
3106 Symbolized = Res.Expr;
3107 addAdditionalUsers(Res, User: I);
3108
3109 // Make a phi of ops if necessary
3110 if (Symbolized && !isa<ConstantExpression>(Val: Symbolized) &&
3111 !isa<VariableExpression>(Val: Symbolized) && PHINodeUses.count(Ptr: I)) {
3112 auto *PHIE = makePossiblePHIOfOps(I, Visited);
3113 // If we created a phi of ops, use it.
3114 // If we couldn't create one, make sure we don't leave one lying around
3115 if (PHIE) {
3116 Symbolized = PHIE;
3117 } else if (auto *Op = RealToTemp.lookup(Val: I)) {
3118 removePhiOfOps(I, PHITemp: Op);
3119 }
3120 }
3121 } else {
3122 // Mark the instruction as unused so we don't value number it again.
3123 InstrDFS[I] = 0;
3124 }
3125 // If we couldn't come up with a symbolic expression, use the unknown
3126 // expression
3127 if (Symbolized == nullptr)
3128 Symbolized = createUnknownExpression(I);
3129 performCongruenceFinding(I, E: Symbolized);
3130 } else {
3131 // Handle terminators that return values. All of them produce values we
3132 // don't currently understand. We don't place non-value producing
3133 // terminators in a class.
3134 if (!I->getType()->isVoidTy()) {
3135 auto *Symbolized = createUnknownExpression(I);
3136 performCongruenceFinding(I, E: Symbolized);
3137 }
3138 processOutgoingEdges(TI: I, B: I->getParent());
3139 }
3140}
3141
3142// Check if there is a path, using single or equal argument phi nodes, from
3143// First to Second.
3144bool NewGVN::singleReachablePHIPath(
3145 SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
3146 const MemoryAccess *Second) const {
3147 if (First == Second)
3148 return true;
3149 if (MSSA->isLiveOnEntryDef(MA: First))
3150 return false;
3151
3152 // This is not perfect, but as we're just verifying here, we can live with
3153 // the loss of precision. The real solution would be that of doing strongly
3154 // connected component finding in this routine, and it's probably not worth
3155 // the complexity for the time being. So, we just keep a set of visited
3156 // MemoryAccess and return true when we hit a cycle.
3157 if (!Visited.insert(Ptr: First).second)
3158 return true;
3159
3160 const auto *EndDef = First;
3161 for (const auto *ChainDef : optimized_def_chain(MA: First)) {
3162 if (ChainDef == Second)
3163 return true;
3164 if (MSSA->isLiveOnEntryDef(MA: ChainDef))
3165 return false;
3166 EndDef = ChainDef;
3167 }
3168 auto *MP = cast<MemoryPhi>(Val: EndDef);
3169 auto ReachableOperandPred = [&](const Use &U) {
3170 return ReachableEdges.count(V: {MP->getIncomingBlock(U), MP->getBlock()});
3171 };
3172 auto FilteredPhiArgs =
3173 make_filter_range(Range: MP->operands(), Pred: ReachableOperandPred);
3174 SmallVector<const Value *, 32> OperandList(FilteredPhiArgs);
3175 bool Okay = all_equal(Range&: OperandList);
3176 if (Okay)
3177 return singleReachablePHIPath(Visited, First: cast<MemoryAccess>(Val: OperandList[0]),
3178 Second);
3179 return false;
3180}
3181
3182// Verify the that the memory equivalence table makes sense relative to the
3183// congruence classes. Note that this checking is not perfect, and is currently
3184// subject to very rare false negatives. It is only useful for
3185// testing/debugging.
3186void NewGVN::verifyMemoryCongruency() const {
3187#ifndef NDEBUG
3188 // Verify that the memory table equivalence and memory member set match
3189 for (const auto *CC : CongruenceClasses) {
3190 if (CC == TOPClass || CC->isDead())
3191 continue;
3192 if (CC->getStoreCount() != 0) {
3193 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
3194 "Any class with a store as a leader should have a "
3195 "representative stored value");
3196 assert(CC->getMemoryLeader() &&
3197 "Any congruence class with a store should have a "
3198 "representative access");
3199 }
3200
3201 if (CC->getMemoryLeader())
3202 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
3203 "Representative MemoryAccess does not appear to be reverse "
3204 "mapped properly");
3205 for (const auto *M : CC->memory())
3206 assert(MemoryAccessToClass.lookup(M) == CC &&
3207 "Memory member does not appear to be reverse mapped properly");
3208 }
3209
3210 // Anything equivalent in the MemoryAccess table should be in the same
3211 // congruence class.
3212
3213 // Filter out the unreachable and trivially dead entries, because they may
3214 // never have been updated if the instructions were not processed.
3215 auto ReachableAccessPred =
3216 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
3217 bool Result = ReachableBlocks.count(Pair.first->getBlock());
3218 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
3219 MemoryToDFSNum(Pair.first) == 0)
3220 return false;
3221 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
3222 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
3223
3224 // We could have phi nodes which operands are all trivially dead,
3225 // so we don't process them.
3226 if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
3227 for (const auto &U : MemPHI->incoming_values()) {
3228 if (auto *I = dyn_cast<Instruction>(&*U)) {
3229 if (!isInstructionTriviallyDead(I))
3230 return true;
3231 }
3232 }
3233 return false;
3234 }
3235
3236 return true;
3237 };
3238
3239 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
3240 for (auto KV : Filtered) {
3241 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
3242 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
3243 if (FirstMUD && SecondMUD) {
3244 SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
3245 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
3246 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
3247 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
3248 "The instructions for these memory operations should have "
3249 "been in the same congruence class or reachable through"
3250 "a single argument phi");
3251 }
3252 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
3253 // We can only sanely verify that MemoryDefs in the operand list all have
3254 // the same class.
3255 auto ReachableOperandPred = [&](const Use &U) {
3256 return ReachableEdges.count(
3257 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
3258 isa<MemoryDef>(U);
3259 };
3260 // All arguments should in the same class, ignoring unreachable arguments
3261 auto FilteredPhiArgs =
3262 make_filter_range(FirstMP->operands(), ReachableOperandPred);
3263 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
3264 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
3265 std::back_inserter(PhiOpClasses), [&](const Use &U) {
3266 const MemoryDef *MD = cast<MemoryDef>(U);
3267 return ValueToClass.lookup(MD->getMemoryInst());
3268 });
3269 assert(all_equal(PhiOpClasses) &&
3270 "All MemoryPhi arguments should be in the same class");
3271 }
3272 }
3273#endif
3274}
3275
3276// Verify that the sparse propagation we did actually found the maximal fixpoint
3277// We do this by storing the value to class mapping, touching all instructions,
3278// and redoing the iteration to see if anything changed.
3279void NewGVN::verifyIterationSettled(Function &F) {
3280#ifndef NDEBUG
3281 LLVM_DEBUG(dbgs() << "Beginning iteration verification\n");
3282 if (DebugCounter::isCounterSet(VNCounter))
3283 DebugCounter::setCounterState(VNCounter, StartingVNCounter);
3284
3285 // Note that we have to store the actual classes, as we may change existing
3286 // classes during iteration. This is because our memory iteration propagation
3287 // is not perfect, and so may waste a little work. But it should generate
3288 // exactly the same congruence classes we have now, with different IDs.
3289 std::map<const Value *, CongruenceClass> BeforeIteration;
3290
3291 for (auto &KV : ValueToClass) {
3292 if (auto *I = dyn_cast<Instruction>(KV.first))
3293 // Skip unused/dead instructions.
3294 if (InstrToDFSNum(I) == 0)
3295 continue;
3296 BeforeIteration.insert({KV.first, *KV.second});
3297 }
3298
3299 TouchedInstructions.set();
3300 TouchedInstructions.reset(0);
3301 OpSafeForPHIOfOps.clear();
3302 CacheIdx = 0;
3303 iterateTouchedInstructions();
3304 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
3305 EqualClasses;
3306 for (const auto &KV : ValueToClass) {
3307 if (auto *I = dyn_cast<Instruction>(KV.first))
3308 // Skip unused/dead instructions.
3309 if (InstrToDFSNum(I) == 0)
3310 continue;
3311 // We could sink these uses, but i think this adds a bit of clarity here as
3312 // to what we are comparing.
3313 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
3314 auto *AfterCC = KV.second;
3315 // Note that the classes can't change at this point, so we memoize the set
3316 // that are equal.
3317 if (!EqualClasses.count({BeforeCC, AfterCC})) {
3318 assert(BeforeCC->isEquivalentTo(AfterCC) &&
3319 "Value number changed after main loop completed!");
3320 EqualClasses.insert({BeforeCC, AfterCC});
3321 }
3322 }
3323#endif
3324}
3325
3326// Verify that for each store expression in the expression to class mapping,
3327// only the latest appears, and multiple ones do not appear.
3328// Because loads do not use the stored value when doing equality with stores,
3329// if we don't erase the old store expressions from the table, a load can find
3330// a no-longer valid StoreExpression.
3331void NewGVN::verifyStoreExpressions() const {
3332#ifndef NDEBUG
3333 // This is the only use of this, and it's not worth defining a complicated
3334 // densemapinfo hash/equality function for it.
3335 std::set<
3336 std::pair<const Value *,
3337 std::tuple<const Value *, const CongruenceClass *, Value *>>>
3338 StoreExpressionSet;
3339 for (const auto &KV : ExpressionToClass) {
3340 if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3341 // Make sure a version that will conflict with loads is not already there
3342 auto Res = StoreExpressionSet.insert(
3343 {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
3344 SE->getStoredValue())});
3345 bool Okay = Res.second;
3346 // It's okay to have the same expression already in there if it is
3347 // identical in nature.
3348 // This can happen when the leader of the stored value changes over time.
3349 if (!Okay)
3350 Okay = (std::get<1>(Res.first->second) == KV.second) &&
3351 (lookupOperandLeader(std::get<2>(Res.first->second)) ==
3352 lookupOperandLeader(SE->getStoredValue()));
3353 assert(Okay && "Stored expression conflict exists in expression table");
3354 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3355 assert(ValueExpr && ValueExpr->equals(*SE) &&
3356 "StoreExpression in ExpressionToClass is not latest "
3357 "StoreExpression for value");
3358 }
3359 }
3360#endif
3361}
3362
3363// This is the main value numbering loop, it iterates over the initial touched
3364// instruction set, propagating value numbers, marking things touched, etc,
3365// until the set of touched instructions is completely empty.
3366void NewGVN::iterateTouchedInstructions() {
3367 uint64_t Iterations = 0;
3368 // Figure out where touchedinstructions starts
3369 int FirstInstr = TouchedInstructions.find_first();
3370 // Nothing set, nothing to iterate, just return.
3371 if (FirstInstr == -1)
3372 return;
3373 const BasicBlock *LastBlock = getBlockForValue(V: InstrFromDFSNum(DFSNum: FirstInstr));
3374 while (TouchedInstructions.any()) {
3375 ++Iterations;
3376 // Walk through all the instructions in all the blocks in RPO.
3377 // TODO: As we hit a new block, we should push and pop equalities into a
3378 // table lookupOperandLeader can use, to catch things PredicateInfo
3379 // might miss, like edge-only equivalences.
3380 for (unsigned InstrNum : TouchedInstructions.set_bits()) {
3381
3382 // This instruction was found to be dead. We don't bother looking
3383 // at it again.
3384 if (InstrNum == 0) {
3385 TouchedInstructions.reset(Idx: InstrNum);
3386 continue;
3387 }
3388
3389 Value *V = InstrFromDFSNum(DFSNum: InstrNum);
3390 const BasicBlock *CurrBlock = getBlockForValue(V);
3391
3392 // If we hit a new block, do reachability processing.
3393 if (CurrBlock != LastBlock) {
3394 LastBlock = CurrBlock;
3395 bool BlockReachable = ReachableBlocks.count(Ptr: CurrBlock);
3396 const auto &CurrInstRange = BlockInstRange.lookup(Val: CurrBlock);
3397
3398 // If it's not reachable, erase any touched instructions and move on.
3399 if (!BlockReachable) {
3400 TouchedInstructions.reset(I: CurrInstRange.first, E: CurrInstRange.second);
3401 LLVM_DEBUG(dbgs() << "Skipping instructions in block "
3402 << getBlockName(CurrBlock)
3403 << " because it is unreachable\n");
3404 continue;
3405 }
3406 // Use the appropriate cache for "OpIsSafeForPHIOfOps".
3407 CacheIdx = RPOOrdering.lookup(Val: DT->getNode(BB: CurrBlock)) - 1;
3408 updateProcessedCount(V: CurrBlock);
3409 }
3410 // Reset after processing (because we may mark ourselves as touched when
3411 // we propagate equalities).
3412 TouchedInstructions.reset(Idx: InstrNum);
3413
3414 if (auto *MP = dyn_cast<MemoryPhi>(Val: V)) {
3415 LLVM_DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
3416 valueNumberMemoryPhi(MP);
3417 } else if (auto *I = dyn_cast<Instruction>(Val: V)) {
3418 valueNumberInstruction(I);
3419 } else {
3420 llvm_unreachable("Should have been a MemoryPhi or Instruction");
3421 }
3422 updateProcessedCount(V);
3423 }
3424 }
3425 NumGVNMaxIterations = std::max(a: NumGVNMaxIterations.getValue(), b: Iterations);
3426}
3427
3428// This is the main transformation entry point.
3429bool NewGVN::runGVN() {
3430 if (DebugCounter::isCounterSet(Info&: VNCounter))
3431 StartingVNCounter = DebugCounter::getCounterState(Info&: VNCounter);
3432 bool Changed = false;
3433 NumFuncArgs = F.arg_size();
3434 MSSAWalker = MSSA->getWalker();
3435 SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
3436
3437 // Count number of instructions for sizing of hash tables, and come
3438 // up with a global dfs numbering for instructions.
3439 unsigned ICount = 1;
3440 // Add an empty instruction to account for the fact that we start at 1
3441 DFSToInstr.emplace_back(Args: nullptr);
3442 // Note: Number the blocks in RPO to put every definition before its uses,
3443 // except for a PHI operand arriving along a back edge. A wrong order costs
3444 // iterations.
3445 ReversePostOrderTraversal<Function *> RPOT(&F);
3446 unsigned Counter = 0;
3447 for (BasicBlock *B : RPOT) {
3448 auto *Node = DT->getNode(BB: B);
3449 assert(Node && "RPO and Dominator tree should have same reachability");
3450 RPOOrdering[Node] = ++Counter;
3451 const auto &BlockRange = assignDFSNumbers(B, Start: ICount);
3452 BlockInstRange.insert(KV: {B, BlockRange});
3453 ICount += BlockRange.second - BlockRange.first;
3454 }
3455 initializeCongruenceClasses(F);
3456
3457 TouchedInstructions.resize(N: ICount);
3458 // Ensure we don't end up resizing the expressionToClass map, as
3459 // that can be quite expensive. At most, we have one expression per
3460 // instruction.
3461 ExpressionToClass.reserve(NumEntries: ICount);
3462
3463 // Initialize the touched instructions to include the entry block.
3464 const auto &InstRange = BlockInstRange.lookup(Val: &F.getEntryBlock());
3465 TouchedInstructions.set(I: InstRange.first, E: InstRange.second);
3466 LLVM_DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
3467 << " marked reachable\n");
3468 ReachableBlocks.insert(Ptr: &F.getEntryBlock());
3469 // Use index corresponding to entry block.
3470 CacheIdx = 0;
3471
3472 iterateTouchedInstructions();
3473 verifyMemoryCongruency();
3474 verifyIterationSettled(F);
3475 verifyStoreExpressions();
3476
3477 Changed |= eliminateInstructions(F);
3478
3479 // Delete all instructions marked for deletion.
3480 for (Instruction *ToErase : InstructionsToErase) {
3481 if (!ToErase->use_empty())
3482 ToErase->replaceAllUsesWith(V: PoisonValue::get(T: ToErase->getType()));
3483
3484 assert(ToErase->getParent() &&
3485 "BB containing ToErase deleted unexpectedly!");
3486 ToErase->eraseFromParent();
3487 }
3488 Changed |= !InstructionsToErase.empty();
3489
3490 // Delete all unreachable blocks.
3491 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
3492 return !ReachableBlocks.count(Ptr: &BB);
3493 };
3494
3495 for (auto &BB : make_filter_range(Range&: F, Pred: UnreachableBlockPred)) {
3496 LLVM_DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
3497 << " is unreachable\n");
3498 deleteInstructionsInBlock(&BB);
3499 Changed = true;
3500 }
3501
3502 cleanupTables();
3503 return Changed;
3504}
3505
3506struct NewGVN::ValueDFS {
3507 int DFSIn = 0;
3508 int DFSOut = 0;
3509 int LocalNum = 0;
3510
3511 // Only one of Def and U will be set.
3512 // The bool in the Def tells us whether the Def is the stored value of a
3513 // store.
3514 PointerIntPair<Value *, 1, bool> Def;
3515 Use *U = nullptr;
3516
3517 bool operator<(const ValueDFS &Other) const {
3518 // It's not enough that any given field be less than - we have sets
3519 // of fields that need to be evaluated together to give a proper ordering.
3520 // For example, if you have;
3521 // DFS (1, 3)
3522 // Val 0
3523 // DFS (1, 2)
3524 // Val 50
3525 // We want the second to be less than the first, but if we just go field
3526 // by field, we will get to Val 0 < Val 50 and say the first is less than
3527 // the second. We only want it to be less than if the DFS orders are equal.
3528 //
3529 // Each LLVM instruction only produces one value, and thus the lowest-level
3530 // differentiator that really matters for the stack (and what we use as a
3531 // replacement) is the local dfs number.
3532 // Everything else in the structure is instruction level, and only affects
3533 // the order in which we will replace operands of a given instruction.
3534 //
3535 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
3536 // the order of replacement of uses does not matter.
3537 // IE given,
3538 // a = 5
3539 // b = a + a
3540 // When you hit b, you will have two valuedfs with the same dfsin, out, and
3541 // localnum.
3542 // The .val will be the same as well.
3543 // The .u's will be different.
3544 // You will replace both, and it does not matter what order you replace them
3545 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
3546 // operand 2).
3547 // Similarly for the case of same dfsin, dfsout, localnum, but different
3548 // .val's
3549 // a = 5
3550 // b = 6
3551 // c = a + b
3552 // in c, we will a valuedfs for a, and one for b,with everything the same
3553 // but .val and .u.
3554 // It does not matter what order we replace these operands in.
3555 // You will always end up with the same IR, and this is guaranteed.
3556 return std::tie(args: DFSIn, args: DFSOut, args: LocalNum, args: Def, args: U) <
3557 std::tie(args: Other.DFSIn, args: Other.DFSOut, args: Other.LocalNum, args: Other.Def,
3558 args: Other.U);
3559 }
3560};
3561
3562// This function converts the set of members for a congruence class from values,
3563// to sets of defs and uses with associated DFS info. The total number of
3564// reachable uses for each value is stored in UseCount, and instructions that
3565// seem
3566// dead (have no non-dead uses) are stored in ProbablyDead.
3567void NewGVN::convertClassToDFSOrdered(
3568 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
3569 DenseMap<const Value *, unsigned int> &UseCounts,
3570 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
3571 for (auto *D : Dense) {
3572 // First add the value.
3573 BasicBlock *BB = getBlockForValue(V: D);
3574 // Constants are handled prior to ever calling this function, so
3575 // we should only be left with instructions as members.
3576 assert(BB && "Should have figured out a basic block for value");
3577 ValueDFS VDDef;
3578 DomTreeNode *DomNode = DT->getNode(BB);
3579 VDDef.DFSIn = DomNode->getDFSNumIn();
3580 VDDef.DFSOut = DomNode->getDFSNumOut();
3581 // If it's a store, use the leader of the value operand, if it's always
3582 // available, or the value operand. TODO: We could do dominance checks to
3583 // find a dominating leader, but not worth it ATM.
3584 if (auto *SI = dyn_cast<StoreInst>(Val: D)) {
3585 auto Leader = lookupOperandLeader(V: SI->getValueOperand());
3586 if (alwaysAvailable(V: Leader)) {
3587 VDDef.Def.setPointer(Leader);
3588 } else {
3589 VDDef.Def.setPointer(SI->getValueOperand());
3590 VDDef.Def.setInt(true);
3591 }
3592 } else {
3593 VDDef.Def.setPointer(D);
3594 }
3595 assert(isa<Instruction>(D) &&
3596 "The dense set member should always be an instruction");
3597 Instruction *Def = cast<Instruction>(Val: D);
3598 VDDef.LocalNum = InstrToDFSNum(V: D);
3599 DFSOrderedSet.push_back(Elt: VDDef);
3600 // If there is a phi node equivalent, add it
3601 if (auto *PN = RealToTemp.lookup(Val: Def)) {
3602 auto *PHIE =
3603 dyn_cast_or_null<PHIExpression>(Val: ValueToExpression.lookup(Val: Def));
3604 if (PHIE) {
3605 VDDef.Def.setInt(false);
3606 VDDef.Def.setPointer(PN);
3607 VDDef.LocalNum = 0;
3608 DFSOrderedSet.push_back(Elt: VDDef);
3609 }
3610 }
3611
3612 unsigned int UseCount = 0;
3613 // Now add the uses.
3614 for (auto &U : Def->uses()) {
3615 if (auto *I = dyn_cast<Instruction>(Val: U.getUser())) {
3616 // Don't try to replace into dead uses
3617 if (InstructionsToErase.count(Ptr: I))
3618 continue;
3619 ValueDFS VDUse;
3620 // Put the phi node uses in the incoming block.
3621 BasicBlock *IBlock;
3622 if (auto *P = dyn_cast<PHINode>(Val: I)) {
3623 IBlock = P->getIncomingBlock(U);
3624 // Make phi node users appear last in the incoming block
3625 // they are from.
3626 VDUse.LocalNum = InstrDFS.size() + 1;
3627 } else {
3628 IBlock = getBlockForValue(V: I);
3629 VDUse.LocalNum = InstrToDFSNum(V: I);
3630 }
3631
3632 // Skip uses in unreachable blocks, as we're going
3633 // to delete them.
3634 if (!ReachableBlocks.contains(Ptr: IBlock))
3635 continue;
3636
3637 DomTreeNode *DomNode = DT->getNode(BB: IBlock);
3638 VDUse.DFSIn = DomNode->getDFSNumIn();
3639 VDUse.DFSOut = DomNode->getDFSNumOut();
3640 VDUse.U = &U;
3641 ++UseCount;
3642 DFSOrderedSet.emplace_back(Args&: VDUse);
3643 }
3644 }
3645
3646 // If there are no uses, it's probably dead (but it may have side-effects,
3647 // so not definitely dead. Otherwise, store the number of uses so we can
3648 // track if it becomes dead later).
3649 if (UseCount == 0)
3650 ProbablyDead.insert(Ptr: Def);
3651 else
3652 UseCounts[Def] = UseCount;
3653 }
3654}
3655
3656// This function converts the set of members for a congruence class from values,
3657// to the set of defs for loads and stores, with associated DFS info.
3658void NewGVN::convertClassToLoadsAndStores(
3659 const CongruenceClass &Dense,
3660 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
3661 for (auto *D : Dense) {
3662 if (!isa<LoadInst>(Val: D) && !isa<StoreInst>(Val: D))
3663 continue;
3664
3665 BasicBlock *BB = getBlockForValue(V: D);
3666 ValueDFS VD;
3667 DomTreeNode *DomNode = DT->getNode(BB);
3668 VD.DFSIn = DomNode->getDFSNumIn();
3669 VD.DFSOut = DomNode->getDFSNumOut();
3670 VD.Def.setPointer(D);
3671
3672 // If it's an instruction, use the real local dfs number.
3673 if (auto *I = dyn_cast<Instruction>(Val: D))
3674 VD.LocalNum = InstrToDFSNum(V: I);
3675 else
3676 llvm_unreachable("Should have been an instruction");
3677
3678 LoadsAndStores.emplace_back(Args&: VD);
3679 }
3680}
3681
3682static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3683 patchReplacementInstruction(I, Repl);
3684 I->replaceAllUsesWith(V: Repl);
3685}
3686
3687void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
3688 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
3689 ++NumGVNBlocksDeleted;
3690
3691 // Delete the instructions backwards, as it has a reduced likelihood of having
3692 // to update as many def-use and use-def chains. Start after the terminator.
3693 auto StartPoint = BB->rbegin();
3694 ++StartPoint;
3695 // Note that we explicitly recalculate BB->rend() on each iteration,
3696 // as it may change when we remove the first instruction.
3697 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3698 Instruction &Inst = *I++;
3699 if (!Inst.use_empty())
3700 Inst.replaceAllUsesWith(V: PoisonValue::get(T: Inst.getType()));
3701 if (isa<LandingPadInst>(Val: Inst))
3702 continue;
3703 salvageKnowledge(I: &Inst, AC);
3704
3705 Inst.eraseFromParent();
3706 ++NumGVNInstrDeleted;
3707 }
3708 // Now insert something that simplifycfg will turn into an unreachable.
3709 Type *Int8Ty = Type::getInt8Ty(C&: BB->getContext());
3710 new StoreInst(
3711 PoisonValue::get(T: Int8Ty),
3712 Constant::getNullValue(Ty: PointerType::getUnqual(C&: BB->getContext())),
3713 BB->getTerminator()->getIterator());
3714}
3715
3716void NewGVN::markInstructionForDeletion(Instruction *I) {
3717 LLVM_DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3718 InstructionsToErase.insert(Ptr: I);
3719}
3720
3721void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3722 LLVM_DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3723 patchAndReplaceAllUsesWith(I, Repl: V);
3724 // We save the actual erasing to avoid invalidating memory
3725 // dependencies until we are done with everything.
3726 markInstructionForDeletion(I);
3727}
3728
3729namespace {
3730
3731// This is a stack that contains both the value and dfs info of where
3732// that value is valid.
3733class ValueDFSStack {
3734public:
3735 Value *back() const { return ValueStack.back(); }
3736 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3737
3738 void push_back(Value *V, int DFSIn, int DFSOut) {
3739 ValueStack.emplace_back(Args&: V);
3740 DFSStack.emplace_back(Args&: DFSIn, Args&: DFSOut);
3741 }
3742
3743 bool empty() const { return DFSStack.empty(); }
3744
3745 bool isInScope(int DFSIn, int DFSOut) const {
3746 if (empty())
3747 return false;
3748 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3749 }
3750
3751 void popUntilDFSScope(int DFSIn, int DFSOut) {
3752
3753 // These two should always be in sync at this point.
3754 assert(ValueStack.size() == DFSStack.size() &&
3755 "Mismatch between ValueStack and DFSStack");
3756 while (
3757 !DFSStack.empty() &&
3758 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3759 DFSStack.pop_back();
3760 ValueStack.pop_back();
3761 }
3762 }
3763
3764private:
3765 SmallVector<Value *, 8> ValueStack;
3766 SmallVector<std::pair<int, int>, 8> DFSStack;
3767};
3768
3769} // end anonymous namespace
3770
3771// Given an expression, get the congruence class for it.
3772CongruenceClass *NewGVN::getClassForExpression(const Expression *E) const {
3773 if (auto *VE = dyn_cast<VariableExpression>(Val: E))
3774 return ValueToClass.lookup(Val: VE->getVariableValue());
3775 else if (isa<DeadExpression>(Val: E))
3776 return TOPClass;
3777 return ExpressionToClass.lookup(Val: E);
3778}
3779
3780// Given a value and a basic block we are trying to see if it is available in,
3781// see if the value has a leader available in that block.
3782Value *NewGVN::findPHIOfOpsLeader(const Expression *E,
3783 const Instruction *OrigInst,
3784 const BasicBlock *BB) const {
3785 // It would already be constant if we could make it constant
3786 if (auto *CE = dyn_cast<ConstantExpression>(Val: E))
3787 return CE->getConstantValue();
3788 if (auto *VE = dyn_cast<VariableExpression>(Val: E)) {
3789 auto *V = VE->getVariableValue();
3790 if (alwaysAvailable(V) || DT->dominates(A: getBlockForValue(V), B: BB))
3791 return VE->getVariableValue();
3792 }
3793
3794 auto *CC = getClassForExpression(E);
3795 if (!CC)
3796 return nullptr;
3797 if (alwaysAvailable(V: CC->getLeader()))
3798 return CC->getLeader();
3799
3800 for (auto *Member : *CC) {
3801 auto *MemberInst = dyn_cast<Instruction>(Val: Member);
3802 if (MemberInst == OrigInst)
3803 continue;
3804 // Anything that isn't an instruction is always available.
3805 if (!MemberInst)
3806 return Member;
3807 if (DT->dominates(A: getBlockForValue(V: MemberInst), B: BB))
3808 return Member;
3809 }
3810 return nullptr;
3811}
3812
3813bool NewGVN::eliminateInstructions(Function &F) {
3814 // This is a non-standard eliminator. The normal way to eliminate is
3815 // to walk the dominator tree in order, keeping track of available
3816 // values, and eliminating them. However, this is mildly
3817 // pointless. It requires doing lookups on every instruction,
3818 // regardless of whether we will ever eliminate it. For
3819 // instructions part of most singleton congruence classes, we know we
3820 // will never eliminate them.
3821
3822 // Instead, this eliminator looks at the congruence classes directly, sorts
3823 // them into a DFS ordering of the dominator tree, and then we just
3824 // perform elimination straight on the sets by walking the congruence
3825 // class member uses in order, and eliminate the ones dominated by the
3826 // last member. This is worst case O(E log E) where E = number of
3827 // instructions in a single congruence class. In theory, this is all
3828 // instructions. In practice, it is much faster, as most instructions are
3829 // either in singleton congruence classes or can't possibly be eliminated
3830 // anyway (if there are no overlapping DFS ranges in class).
3831 // When we find something not dominated, it becomes the new leader
3832 // for elimination purposes.
3833 // TODO: If we wanted to be faster, We could remove any members with no
3834 // overlapping ranges while sorting, as we will never eliminate anything
3835 // with those members, as they don't dominate anything else in our set.
3836
3837 bool AnythingReplaced = false;
3838
3839 // Since we are going to walk the domtree anyway, and we can't guarantee the
3840 // DFS numbers are updated, we compute some ourselves.
3841 DT->updateDFSNumbers();
3842
3843 // Go through all of our phi nodes, and kill the arguments associated with
3844 // unreachable edges.
3845 auto ReplaceUnreachablePHIArgs = [&](PHINode *PHI, BasicBlock *BB) {
3846 for (auto &Operand : PHI->incoming_values())
3847 if (!ReachableEdges.count(V: {PHI->getIncomingBlock(U: Operand), BB})) {
3848 LLVM_DEBUG(dbgs() << "Replacing incoming value of " << PHI
3849 << " for block "
3850 << getBlockName(PHI->getIncomingBlock(Operand))
3851 << " with poison due to it being unreachable\n");
3852 Operand.set(PoisonValue::get(T: PHI->getType()));
3853 }
3854 };
3855 // Replace unreachable phi arguments.
3856 // At this point, RevisitOnReachabilityChange only contains:
3857 //
3858 // 1. PHIs
3859 // 2. Temporaries that will convert to PHIs
3860 // 3. Operations that are affected by an unreachable edge but do not fit into
3861 // 1 or 2 (rare).
3862 // So it is a slight overshoot of what we want. We could make it exact by
3863 // using two SparseBitVectors per block.
3864 DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
3865 for (auto &KV : ReachableEdges)
3866 ReachablePredCount[KV.getEnd()]++;
3867 for (auto &BBPair : RevisitOnReachabilityChange) {
3868 for (auto InstNum : BBPair.second) {
3869 auto *Inst = InstrFromDFSNum(DFSNum: InstNum);
3870 auto *PHI = dyn_cast<PHINode>(Val: Inst);
3871 PHI = PHI ? PHI : dyn_cast_or_null<PHINode>(Val: RealToTemp.lookup(Val: Inst));
3872 if (!PHI)
3873 continue;
3874 auto *BB = BBPair.first;
3875 if (ReachablePredCount.lookup(Val: BB) != PHI->getNumIncomingValues())
3876 ReplaceUnreachablePHIArgs(PHI, BB);
3877 }
3878 }
3879
3880 // Map to store the use counts
3881 DenseMap<const Value *, unsigned int> UseCounts;
3882 for (auto *CC : reverse(C&: CongruenceClasses)) {
3883 LLVM_DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
3884 << "\n");
3885 // Track the equivalent store info so we can decide whether to try
3886 // dead store elimination.
3887 SmallVector<ValueDFS, 8> PossibleDeadStores;
3888 SmallPtrSet<Instruction *, 8> ProbablyDead;
3889 if (CC->isDead() || CC->empty())
3890 continue;
3891 // Everything still in the TOP class is unreachable or dead.
3892 if (CC == TOPClass) {
3893 for (auto *M : *CC) {
3894 auto *VTE = ValueToExpression.lookup(Val: M);
3895 if (VTE && isa<DeadExpression>(Val: VTE))
3896 markInstructionForDeletion(I: cast<Instruction>(Val: M));
3897 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3898 InstructionsToErase.count(cast<Instruction>(M))) &&
3899 "Everything in TOP should be unreachable or dead at this "
3900 "point");
3901 }
3902 continue;
3903 }
3904
3905 assert(CC->getLeader() && "We should have had a leader");
3906 // If this is a leader that is always available, and it's a
3907 // constant or has no equivalences, just replace everything with
3908 // it. We then update the congruence class with whatever members
3909 // are left.
3910 Value *Leader =
3911 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
3912 if (alwaysAvailable(V: Leader)) {
3913 CongruenceClass::MemberSet MembersLeft;
3914 for (auto *M : *CC) {
3915 Value *Member = M;
3916 // Void things have no uses we can replace.
3917 if (Member == Leader || !isa<Instruction>(Val: Member) ||
3918 Member->getType()->isVoidTy()) {
3919 MembersLeft.insert(Ptr: Member);
3920 continue;
3921 }
3922
3923 LLVM_DEBUG(dbgs() << "Found replacement " << *(Leader) << " for "
3924 << *Member << "\n");
3925 auto *I = cast<Instruction>(Val: Member);
3926 assert(Leader != I && "About to accidentally remove our leader");
3927 replaceInstruction(I, V: Leader);
3928 AnythingReplaced = true;
3929 }
3930 CC->swap(Other&: MembersLeft);
3931 } else {
3932 // If this is a singleton, we can skip it.
3933 if (CC->size() != 1 || RealToTemp.count(Val: Leader)) {
3934 // This is a stack because equality replacement/etc may place
3935 // constants in the middle of the member list, and we want to use
3936 // those constant values in preference to the current leader, over
3937 // the scope of those constants.
3938 ValueDFSStack EliminationStack;
3939
3940 // Convert the members to DFS ordered sets and then merge them.
3941 SmallVector<ValueDFS, 8> DFSOrderedSet;
3942 convertClassToDFSOrdered(Dense: *CC, DFSOrderedSet, UseCounts, ProbablyDead);
3943
3944 // Sort the whole thing.
3945 llvm::sort(C&: DFSOrderedSet);
3946 for (auto &VD : DFSOrderedSet) {
3947 int MemberDFSIn = VD.DFSIn;
3948 int MemberDFSOut = VD.DFSOut;
3949 Value *Def = VD.Def.getPointer();
3950 bool FromStore = VD.Def.getInt();
3951 Use *U = VD.U;
3952 // We ignore void things because we can't get a value from them.
3953 if (Def && Def->getType()->isVoidTy())
3954 continue;
3955 auto *DefInst = dyn_cast_or_null<Instruction>(Val: Def);
3956 if (DefInst && AllTempInstructions.count(V: DefInst)) {
3957 auto *PN = cast<PHINode>(Val: DefInst);
3958
3959 // If this is a value phi and that's the expression we used, insert
3960 // it into the program
3961 // remove from temp instruction list.
3962 AllTempInstructions.erase(V: PN);
3963 auto *DefBlock = getBlockForValue(V: Def);
3964 LLVM_DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
3965 << " into block "
3966 << getBlockName(getBlockForValue(Def)) << "\n");
3967 PN->insertBefore(InsertPos: DefBlock->begin());
3968 Def = PN;
3969 NumGVNPHIOfOpsEliminations++;
3970 }
3971
3972 if (EliminationStack.empty()) {
3973 LLVM_DEBUG(dbgs() << "Elimination Stack is empty\n");
3974 } else {
3975 LLVM_DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3976 << EliminationStack.dfs_back().first << ","
3977 << EliminationStack.dfs_back().second << ")\n");
3978 }
3979
3980 LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3981 << MemberDFSOut << ")\n");
3982 // First, we see if we are out of scope or empty. If so,
3983 // and there equivalences, we try to replace the top of
3984 // stack with equivalences (if it's on the stack, it must
3985 // not have been eliminated yet).
3986 // Then we synchronize to our current scope, by
3987 // popping until we are back within a DFS scope that
3988 // dominates the current member.
3989 // Then, what happens depends on a few factors
3990 // If the stack is now empty, we need to push
3991 // If we have a constant or a local equivalence we want to
3992 // start using, we also push.
3993 // Otherwise, we walk along, processing members who are
3994 // dominated by this scope, and eliminate them.
3995 bool ShouldPush = Def && EliminationStack.empty();
3996 bool OutOfScope =
3997 !EliminationStack.isInScope(DFSIn: MemberDFSIn, DFSOut: MemberDFSOut);
3998
3999 if (OutOfScope || ShouldPush) {
4000 // Sync to our current scope.
4001 EliminationStack.popUntilDFSScope(DFSIn: MemberDFSIn, DFSOut: MemberDFSOut);
4002 bool ShouldPush = Def && EliminationStack.empty();
4003 if (ShouldPush) {
4004 EliminationStack.push_back(V: Def, DFSIn: MemberDFSIn, DFSOut: MemberDFSOut);
4005 }
4006 }
4007
4008 // Skip the Def's, we only want to eliminate on their uses. But mark
4009 // dominated defs as dead.
4010 if (Def) {
4011 // For anything in this case, what and how we value number
4012 // guarantees that any side-effects that would have occurred (ie
4013 // throwing, etc) can be proven to either still occur (because it's
4014 // dominated by something that has the same side-effects), or never
4015 // occur. Otherwise, we would not have been able to prove it value
4016 // equivalent to something else. For these things, we can just mark
4017 // it all dead. Note that this is different from the "ProbablyDead"
4018 // set, which may not be dominated by anything, and thus, are only
4019 // easy to prove dead if they are also side-effect free. Note that
4020 // because stores are put in terms of the stored value, we skip
4021 // stored values here. If the stored value is really dead, it will
4022 // still be marked for deletion when we process it in its own class.
4023 auto *DefI = dyn_cast<Instruction>(Val: Def);
4024 if (!EliminationStack.empty() && DefI && !FromStore) {
4025 Value *DominatingLeader = EliminationStack.back();
4026 if (DominatingLeader != Def) {
4027 // Even if the instruction is removed, we still need to update
4028 // flags/metadata due to downstreams users of the leader.
4029 patchReplacementInstruction(I: DefI, Repl: DominatingLeader);
4030
4031 SmallVector<DbgVariableRecord *> DVRUsers;
4032 findDbgUsers(V: DefI, DbgVariableRecords&: DVRUsers);
4033
4034 for (auto *DVR : DVRUsers)
4035 DVR->replaceVariableLocationOp(OldValue: DefI, NewValue: DominatingLeader);
4036
4037 markInstructionForDeletion(I: DefI);
4038 }
4039 }
4040 continue;
4041 }
4042 // At this point, we know it is a Use we are trying to possibly
4043 // replace.
4044
4045 assert(isa<Instruction>(U->get()) &&
4046 "Current def should have been an instruction");
4047 assert(isa<Instruction>(U->getUser()) &&
4048 "Current user should have been an instruction");
4049
4050 // If the thing we are replacing into is already marked to be dead,
4051 // this use is dead. Note that this is true regardless of whether
4052 // we have anything dominating the use or not. We do this here
4053 // because we are already walking all the uses anyway.
4054 Instruction *InstUse = cast<Instruction>(Val: U->getUser());
4055 if (InstructionsToErase.count(Ptr: InstUse)) {
4056 auto &UseCount = UseCounts[U->get()];
4057 if (--UseCount == 0) {
4058 ProbablyDead.insert(Ptr: cast<Instruction>(Val: U->get()));
4059 }
4060 }
4061
4062 // If we get to this point, and the stack is empty we must have a use
4063 // with nothing we can use to eliminate this use, so just skip it.
4064 if (EliminationStack.empty())
4065 continue;
4066
4067 Value *DominatingLeader = EliminationStack.back();
4068
4069 Instruction *SSACopy = nullptr;
4070 if (auto *BC = dyn_cast<BitCastInst>(Val: DominatingLeader)) {
4071 if (BC->getType() == BC->getOperand(i_nocapture: 0)->getType() &&
4072 PredInfo->getPredicateInfoFor(V: DominatingLeader)) {
4073 SSACopy = BC;
4074 DominatingLeader = BC->getOperand(i_nocapture: 0);
4075 }
4076 }
4077
4078 // Don't replace our existing users with ourselves.
4079 if (U->get() == DominatingLeader)
4080 continue;
4081
4082 // If we replaced something in an instruction, handle the patching of
4083 // metadata. Skip this if we are replacing predicateinfo with its
4084 // original operand, as we already know we can just drop it.
4085 auto *ReplacedInst = cast<Instruction>(Val: U->get());
4086 auto *PI = PredInfo->getPredicateInfoFor(V: ReplacedInst);
4087 if (!PI || DominatingLeader != PI->OriginalOp)
4088 patchReplacementInstruction(I: ReplacedInst, Repl: DominatingLeader);
4089
4090 LLVM_DEBUG(dbgs()
4091 << "Found replacement " << *DominatingLeader << " for "
4092 << *U->get() << " in " << *(U->getUser()) << "\n");
4093 U->set(DominatingLeader);
4094 // This is now a use of the dominating leader, which means if the
4095 // dominating leader was dead, it's now live!
4096 auto &LeaderUseCount = UseCounts[DominatingLeader];
4097 // It's about to be alive again.
4098 if (LeaderUseCount == 0 && isa<Instruction>(Val: DominatingLeader))
4099 ProbablyDead.erase(Ptr: cast<Instruction>(Val: DominatingLeader));
4100 // For copy instructions, we use their operand as a leader,
4101 // which means we remove a user of the copy and it may become dead.
4102 if (SSACopy) {
4103 auto It = UseCounts.find(Val: SSACopy);
4104 if (It != UseCounts.end()) {
4105 unsigned &IIUseCount = It->second;
4106 if (--IIUseCount == 0)
4107 ProbablyDead.insert(Ptr: SSACopy);
4108 }
4109 }
4110 ++LeaderUseCount;
4111 AnythingReplaced = true;
4112 }
4113 }
4114 }
4115
4116 // At this point, anything still in the ProbablyDead set is actually dead if
4117 // would be trivially dead.
4118 for (auto *I : ProbablyDead)
4119 if (wouldInstructionBeTriviallyDead(I))
4120 markInstructionForDeletion(I);
4121
4122 // Cleanup the congruence class.
4123 CongruenceClass::MemberSet MembersLeft;
4124 for (auto *Member : *CC)
4125 if (!isa<Instruction>(Val: Member) ||
4126 !InstructionsToErase.count(Ptr: cast<Instruction>(Val: Member)))
4127 MembersLeft.insert(Ptr: Member);
4128 CC->swap(Other&: MembersLeft);
4129
4130 // If we have possible dead stores to look at, try to eliminate them.
4131 if (CC->getStoreCount() > 0) {
4132 convertClassToLoadsAndStores(Dense: *CC, LoadsAndStores&: PossibleDeadStores);
4133 llvm::sort(C&: PossibleDeadStores);
4134 ValueDFSStack EliminationStack;
4135 for (auto &VD : PossibleDeadStores) {
4136 int MemberDFSIn = VD.DFSIn;
4137 int MemberDFSOut = VD.DFSOut;
4138 Instruction *Member = cast<Instruction>(Val: VD.Def.getPointer());
4139 if (EliminationStack.empty() ||
4140 !EliminationStack.isInScope(DFSIn: MemberDFSIn, DFSOut: MemberDFSOut)) {
4141 // Sync to our current scope.
4142 EliminationStack.popUntilDFSScope(DFSIn: MemberDFSIn, DFSOut: MemberDFSOut);
4143 if (EliminationStack.empty()) {
4144 EliminationStack.push_back(V: Member, DFSIn: MemberDFSIn, DFSOut: MemberDFSOut);
4145 continue;
4146 }
4147 }
4148 // We already did load elimination, so nothing to do here.
4149 if (isa<LoadInst>(Val: Member))
4150 continue;
4151 assert(!EliminationStack.empty());
4152 Instruction *Leader = cast<Instruction>(Val: EliminationStack.back());
4153 (void)Leader;
4154 assert(DT->dominates(Leader->getParent(), Member->getParent()));
4155 // Member is dominater by Leader, and thus dead
4156 LLVM_DEBUG(dbgs() << "Marking dead store " << *Member
4157 << " that is dominated by " << *Leader << "\n");
4158 markInstructionForDeletion(I: Member);
4159 CC->erase(M: Member);
4160 ++NumGVNDeadStores;
4161 }
4162 }
4163 }
4164 return AnythingReplaced;
4165}
4166
4167// This function provides global ranking of operations so that we can place them
4168// in a canonical order. Note that rank alone is not necessarily enough for a
4169// complete ordering, as constants all have the same rank. However, generally,
4170// we will simplify an operation with all constants so that it doesn't matter
4171// what order they appear in.
4172unsigned int NewGVN::getRank(const Value *V) const {
4173 // Prefer constants to undef to anything else
4174 // Undef is a constant, have to check it first.
4175 // Prefer poison to undef as it's less defined.
4176 // Prefer smaller constants to constantexprs
4177 // Note that the order here matters because of class inheritance
4178 if (isa<ConstantExpr>(Val: V))
4179 return 3;
4180 if (isa<PoisonValue>(Val: V))
4181 return 1;
4182 if (isa<UndefValue>(Val: V))
4183 return 2;
4184 if (isa<Constant>(Val: V))
4185 return 0;
4186 if (auto *A = dyn_cast<Argument>(Val: V))
4187 return 4 + A->getArgNo();
4188
4189 // Need to shift the instruction DFS by number of arguments + 5 to account for
4190 // the constant and argument ranking above.
4191 unsigned Result = InstrToDFSNum(V);
4192 if (Result > 0)
4193 return 5 + NumFuncArgs + Result;
4194 // Unreachable or something else, just return a really large number.
4195 return ~0;
4196}
4197
4198// This is a function that says whether two commutative operations should
4199// have their order swapped when canonicalizing.
4200bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
4201 // Because we only care about a total ordering, and don't rewrite expressions
4202 // in this order, we order by rank, which will give a strict weak ordering to
4203 // everything but constants, and then we order by pointer address.
4204 return std::make_pair(x: getRank(V: A), y&: A) > std::make_pair(x: getRank(V: B), y&: B);
4205}
4206
4207bool NewGVN::shouldSwapOperandsForPredicate(const Value *A, const Value *B,
4208 const BitCastInst *I) const {
4209 if (shouldSwapOperands(A, B)) {
4210 PredicateSwapChoice[I] = B;
4211 return true;
4212 }
4213
4214 auto LookupResult = PredicateSwapChoice.find(Val: I);
4215 if (LookupResult != PredicateSwapChoice.end()) {
4216 auto *SeenPredicate = LookupResult->second;
4217 if (SeenPredicate) {
4218 // We previously decided to swap B to the left. Keep that choice.
4219 if (SeenPredicate == B)
4220 return true;
4221 else
4222 LookupResult->second = nullptr;
4223 }
4224 }
4225 return false;
4226}
4227
4228PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
4229 // Apparently the order in which we get these results matter for
4230 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
4231 // the same order here, just in case.
4232 auto &AC = AM.getResult<AssumptionAnalysis>(IR&: F);
4233 auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
4234 auto &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F);
4235 auto &AA = AM.getResult<AAManager>(IR&: F);
4236 auto &MSSA = AM.getResult<MemorySSAAnalysis>(IR&: F).getMSSA();
4237 bool Changed =
4238 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getDataLayout())
4239 .runGVN();
4240 if (!Changed)
4241 return PreservedAnalyses::all();
4242 PreservedAnalyses PA;
4243 PA.preserve<DominatorTreeAnalysis>();
4244 return PA;
4245}
4246