blob: 6926aae37963f5627d3d06617d39b6c3ab94c261 [file] [log] [blame]
Davide Italiano7e274e02016-12-22 16:03:48 +00001//===---- NewGVN.cpp - Global Value Numbering Pass --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
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///
Daniel Berlindb3c7be2017-01-26 21:39:49 +000020/// 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
Daniel Berlinb527b2c2017-05-19 19:01:27 +000033/// 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.
Daniel Berlindb3c7be2017-01-26 21:39:49 +000046///
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.
Davide Italiano7e274e02016-12-22 16:03:48 +000051//===----------------------------------------------------------------------===//
52
53#include "llvm/Transforms/Scalar/NewGVN.h"
54#include "llvm/ADT/BitVector.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/DenseSet.h"
57#include "llvm/ADT/DepthFirstIterator.h"
58#include "llvm/ADT/Hashing.h"
59#include "llvm/ADT/MapVector.h"
60#include "llvm/ADT/PostOrderIterator.h"
Daniel Berlind7c12ee2016-12-25 22:23:49 +000061#include "llvm/ADT/STLExtras.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000062#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallSet.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000064#include "llvm/ADT/Statistic.h"
65#include "llvm/ADT/TinyPtrVector.h"
66#include "llvm/Analysis/AliasAnalysis.h"
67#include "llvm/Analysis/AssumptionCache.h"
68#include "llvm/Analysis/CFG.h"
69#include "llvm/Analysis/CFGPrinter.h"
70#include "llvm/Analysis/ConstantFolding.h"
71#include "llvm/Analysis/GlobalsModRef.h"
72#include "llvm/Analysis/InstructionSimplify.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000073#include "llvm/Analysis/MemoryBuiltins.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000074#include "llvm/Analysis/MemoryLocation.h"
Daniel Berlin2f72b192017-04-14 02:53:37 +000075#include "llvm/Analysis/MemorySSA.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000076#include "llvm/Analysis/TargetLibraryInfo.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000077#include "llvm/IR/DataLayout.h"
78#include "llvm/IR/Dominators.h"
79#include "llvm/IR/GlobalVariable.h"
80#include "llvm/IR/IRBuilder.h"
81#include "llvm/IR/IntrinsicInst.h"
82#include "llvm/IR/LLVMContext.h"
83#include "llvm/IR/Metadata.h"
84#include "llvm/IR/PatternMatch.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000085#include "llvm/IR/Type.h"
86#include "llvm/Support/Allocator.h"
87#include "llvm/Support/CommandLine.h"
88#include "llvm/Support/Debug.h"
Daniel Berlin283a6082017-03-01 19:59:26 +000089#include "llvm/Support/DebugCounter.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000090#include "llvm/Transforms/Scalar.h"
91#include "llvm/Transforms/Scalar/GVNExpression.h"
92#include "llvm/Transforms/Utils/BasicBlockUtils.h"
93#include "llvm/Transforms/Utils/Local.h"
Daniel Berlinf7d95802017-02-18 23:06:50 +000094#include "llvm/Transforms/Utils/PredicateInfo.h"
Daniel Berlin07daac82017-04-02 13:23:44 +000095#include "llvm/Transforms/Utils/VNCoercion.h"
Daniel Berlin1316a942017-04-06 18:52:50 +000096#include <numeric>
Davide Italiano7e274e02016-12-22 16:03:48 +000097#include <unordered_map>
98#include <utility>
99#include <vector>
100using namespace llvm;
101using namespace PatternMatch;
102using namespace llvm::GVNExpression;
Daniel Berlin07daac82017-04-02 13:23:44 +0000103using namespace llvm::VNCoercion;
Davide Italiano7e274e02016-12-22 16:03:48 +0000104#define DEBUG_TYPE "newgvn"
105
106STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
107STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
108STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
109STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +0000110STATISTIC(NumGVNMaxIterations,
111 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000112STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
113STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
114STATISTIC(NumGVNAvoidedSortedLeaderChanges,
115 "Number of avoided sorted leader changes");
Daniel Berlinc4796862017-01-27 02:37:11 +0000116STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000117STATISTIC(NumGVNPHIOfOpsCreated, "Number of PHI of ops created");
118STATISTIC(NumGVNPHIOfOpsEliminations,
119 "Number of things eliminated using PHI of ops");
Daniel Berlin283a6082017-03-01 19:59:26 +0000120DEBUG_COUNTER(VNCounter, "newgvn-vn",
121 "Controls which instructions are value numbered")
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000122DEBUG_COUNTER(PHIOfOpsCounter, "newgvn-phi",
123 "Controls which instructions we create phi of ops for")
Daniel Berlin1316a942017-04-06 18:52:50 +0000124// Currently store defining access refinement is too slow due to basicaa being
125// egregiously slow. This flag lets us keep it working while we work on this
126// issue.
127static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
128 cl::init(false), cl::Hidden);
129
Davide Italiano7e274e02016-12-22 16:03:48 +0000130//===----------------------------------------------------------------------===//
131// GVN Pass
132//===----------------------------------------------------------------------===//
133
134// Anchor methods.
135namespace llvm {
136namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000137Expression::~Expression() = default;
138BasicExpression::~BasicExpression() = default;
139CallExpression::~CallExpression() = default;
140LoadExpression::~LoadExpression() = default;
141StoreExpression::~StoreExpression() = default;
142AggregateValueExpression::~AggregateValueExpression() = default;
143PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000144}
145}
146
Daniel Berlin2f72b192017-04-14 02:53:37 +0000147// Tarjan's SCC finding algorithm with Nuutila's improvements
148// SCCIterator is actually fairly complex for the simple thing we want.
149// It also wants to hand us SCC's that are unrelated to the phi node we ask
150// about, and have us process them there or risk redoing work.
151// Graph traits over a filter iterator also doesn't work that well here.
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000152// This SCC finder is specialized to walk use-def chains, and only follows
153// instructions,
Daniel Berlin2f72b192017-04-14 02:53:37 +0000154// not generic values (arguments, etc).
155struct TarjanSCC {
156
157 TarjanSCC() : Components(1) {}
158
159 void Start(const Instruction *Start) {
160 if (Root.lookup(Start) == 0)
161 FindSCC(Start);
162 }
163
164 const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
165 unsigned ComponentID = ValueToComponent.lookup(V);
166
167 assert(ComponentID > 0 &&
168 "Asking for a component for a value we never processed");
169 return Components[ComponentID];
170 }
171
172private:
173 void FindSCC(const Instruction *I) {
174 Root[I] = ++DFSNum;
175 // Store the DFS Number we had before it possibly gets incremented.
176 unsigned int OurDFS = DFSNum;
177 for (auto &Op : I->operands()) {
178 if (auto *InstOp = dyn_cast<Instruction>(Op)) {
179 if (Root.lookup(Op) == 0)
180 FindSCC(InstOp);
181 if (!InComponent.count(Op))
182 Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
183 }
184 }
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000185 // See if we really were the root of a component, by seeing if we still have
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000186 // our DFSNumber. If we do, we are the root of the component, and we have
187 // completed a component. If we do not, we are not the root of a component,
188 // and belong on the component stack.
Daniel Berlin2f72b192017-04-14 02:53:37 +0000189 if (Root.lookup(I) == OurDFS) {
190 unsigned ComponentID = Components.size();
191 Components.resize(Components.size() + 1);
192 auto &Component = Components.back();
193 Component.insert(I);
194 DEBUG(dbgs() << "Component root is " << *I << "\n");
195 InComponent.insert(I);
196 ValueToComponent[I] = ComponentID;
197 // Pop a component off the stack and label it.
198 while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
199 auto *Member = Stack.back();
200 DEBUG(dbgs() << "Component member is " << *Member << "\n");
201 Component.insert(Member);
202 InComponent.insert(Member);
203 ValueToComponent[Member] = ComponentID;
204 Stack.pop_back();
205 }
206 } else {
207 // Part of a component, push to stack
208 Stack.push_back(I);
209 }
210 }
211 unsigned int DFSNum = 1;
212 SmallPtrSet<const Value *, 8> InComponent;
213 DenseMap<const Value *, unsigned int> Root;
214 SmallVector<const Value *, 8> Stack;
215 // Store the components as vector of ptr sets, because we need the topo order
216 // of SCC's, but not individual member order
217 SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
218 DenseMap<const Value *, unsigned> ValueToComponent;
219};
Davide Italiano7e274e02016-12-22 16:03:48 +0000220// Congruence classes represent the set of expressions/instructions
221// that are all the same *during some scope in the function*.
222// That is, because of the way we perform equality propagation, and
223// because of memory value numbering, it is not correct to assume
224// you can willy-nilly replace any member with any other at any
225// point in the function.
226//
227// For any Value in the Member set, it is valid to replace any dominated member
228// with that Value.
229//
Daniel Berlin1316a942017-04-06 18:52:50 +0000230// Every congruence class has a leader, and the leader is used to symbolize
231// instructions in a canonical way (IE every operand of an instruction that is a
232// member of the same congruence class will always be replaced with leader
233// during symbolization). To simplify symbolization, we keep the leader as a
234// constant if class can be proved to be a constant value. Otherwise, the
235// leader is the member of the value set with the smallest DFS number. Each
236// congruence class also has a defining expression, though the expression may be
237// null. If it exists, it can be used for forward propagation and reassociation
238// of values.
239
240// For memory, we also track a representative MemoryAccess, and a set of memory
241// members for MemoryPhis (which have no real instructions). Note that for
242// memory, it seems tempting to try to split the memory members into a
243// MemoryCongruenceClass or something. Unfortunately, this does not work
244// easily. The value numbering of a given memory expression depends on the
245// leader of the memory congruence class, and the leader of memory congruence
246// class depends on the value numbering of a given memory expression. This
247// leads to wasted propagation, and in some cases, missed optimization. For
248// example: If we had value numbered two stores together before, but now do not,
249// we move them to a new value congruence class. This in turn will move at one
250// of the memorydefs to a new memory congruence class. Which in turn, affects
251// the value numbering of the stores we just value numbered (because the memory
252// congruence class is part of the value number). So while theoretically
253// possible to split them up, it turns out to be *incredibly* complicated to get
254// it to work right, because of the interdependency. While structurally
255// slightly messier, it is algorithmically much simpler and faster to do what we
Daniel Berlina8236562017-04-07 18:38:09 +0000256// do here, and track them both at once in the same class.
257// Note: The default iterators for this class iterate over values
258class CongruenceClass {
259public:
260 using MemberType = Value;
261 using MemberSet = SmallPtrSet<MemberType *, 4>;
262 using MemoryMemberType = MemoryPhi;
263 using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
264
265 explicit CongruenceClass(unsigned ID) : ID(ID) {}
266 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
267 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
268 unsigned getID() const { return ID; }
269 // True if this class has no members left. This is mainly used for assertion
270 // purposes, and for skipping empty classes.
271 bool isDead() const {
272 // If it's both dead from a value perspective, and dead from a memory
273 // perspective, it's really dead.
274 return empty() && memory_empty();
275 }
276 // Leader functions
277 Value *getLeader() const { return RepLeader; }
278 void setLeader(Value *Leader) { RepLeader = Leader; }
279 const std::pair<Value *, unsigned int> &getNextLeader() const {
280 return NextLeader;
281 }
282 void resetNextLeader() { NextLeader = {nullptr, ~0}; }
283
284 void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
285 if (LeaderPair.second < NextLeader.second)
286 NextLeader = LeaderPair;
287 }
288
289 Value *getStoredValue() const { return RepStoredValue; }
290 void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
291 const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
292 void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
293
294 // Forward propagation info
295 const Expression *getDefiningExpr() const { return DefiningExpr; }
Daniel Berlina8236562017-04-07 18:38:09 +0000296
297 // Value member set
298 bool empty() const { return Members.empty(); }
299 unsigned size() const { return Members.size(); }
300 MemberSet::const_iterator begin() const { return Members.begin(); }
301 MemberSet::const_iterator end() const { return Members.end(); }
302 void insert(MemberType *M) { Members.insert(M); }
303 void erase(MemberType *M) { Members.erase(M); }
304 void swap(MemberSet &Other) { Members.swap(Other); }
305
306 // Memory member set
307 bool memory_empty() const { return MemoryMembers.empty(); }
308 unsigned memory_size() const { return MemoryMembers.size(); }
309 MemoryMemberSet::const_iterator memory_begin() const {
310 return MemoryMembers.begin();
311 }
312 MemoryMemberSet::const_iterator memory_end() const {
313 return MemoryMembers.end();
314 }
315 iterator_range<MemoryMemberSet::const_iterator> memory() const {
316 return make_range(memory_begin(), memory_end());
317 }
318 void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
319 void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
320
321 // Store count
322 unsigned getStoreCount() const { return StoreCount; }
323 void incStoreCount() { ++StoreCount; }
324 void decStoreCount() {
325 assert(StoreCount != 0 && "Store count went negative");
326 --StoreCount;
327 }
328
Davide Italianodc435322017-05-10 19:57:43 +0000329 // True if this class has no memory members.
330 bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
331
Daniel Berlina8236562017-04-07 18:38:09 +0000332 // Return true if two congruence classes are equivalent to each other. This
333 // means
334 // that every field but the ID number and the dead field are equivalent.
335 bool isEquivalentTo(const CongruenceClass *Other) const {
336 if (!Other)
337 return false;
338 if (this == Other)
339 return true;
340
341 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
342 std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
343 Other->RepMemoryAccess))
344 return false;
345 if (DefiningExpr != Other->DefiningExpr)
346 if (!DefiningExpr || !Other->DefiningExpr ||
347 *DefiningExpr != *Other->DefiningExpr)
348 return false;
349 // We need some ordered set
350 std::set<Value *> AMembers(Members.begin(), Members.end());
351 std::set<Value *> BMembers(Members.begin(), Members.end());
352 return AMembers == BMembers;
353 }
354
355private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000356 unsigned ID;
357 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000358 Value *RepLeader = nullptr;
Daniel Berlina8236562017-04-07 18:38:09 +0000359 // The most dominating leader after our current leader, because the member set
360 // is not sorted and is expensive to keep sorted all the time.
361 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
Daniel Berlin1316a942017-04-06 18:52:50 +0000362 // If this is represented by a store, the value of the store.
Daniel Berlin26addef2017-01-20 21:04:30 +0000363 Value *RepStoredValue = nullptr;
Daniel Berlin1316a942017-04-06 18:52:50 +0000364 // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
365 // access.
366 const MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000367 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000368 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000369 // Actual members of this class.
370 MemberSet Members;
Daniel Berlin1316a942017-04-06 18:52:50 +0000371 // This is the set of MemoryPhis that exist in the class. MemoryDefs and
372 // MemoryUses have real instructions representing them, so we only need to
373 // track MemoryPhis here.
374 MemoryMemberSet MemoryMembers;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000375 // Number of stores in this congruence class.
376 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000377 int StoreCount = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +0000378};
379
380namespace llvm {
Daniel Berlineafdd862017-06-06 17:15:28 +0000381struct ExactEqualsExpression {
382 const Expression &E;
383 explicit ExactEqualsExpression(const Expression &E) : E(E) {}
384 hash_code getComputedHash() const { return E.getComputedHash(); }
385 bool operator==(const Expression &Other) const {
386 return E.exactlyEquals(Other);
387 }
388};
389
Daniel Berlin85f91b02016-12-26 20:06:58 +0000390template <> struct DenseMapInfo<const Expression *> {
391 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000392 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000393 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
394 return reinterpret_cast<const Expression *>(Val);
395 }
396 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000397 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000398 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
399 return reinterpret_cast<const Expression *>(Val);
400 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000401 static unsigned getHashValue(const Expression *E) {
Daniel Berlineafdd862017-06-06 17:15:28 +0000402 return E->getComputedHash();
Daniel Berlin85f91b02016-12-26 20:06:58 +0000403 }
Daniel Berlineafdd862017-06-06 17:15:28 +0000404 static unsigned getHashValue(const ExactEqualsExpression &E) {
405 return E.getComputedHash();
406 }
407 static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS) {
408 if (RHS == getTombstoneKey() || RHS == getEmptyKey())
409 return false;
410 return LHS == *RHS;
411 }
412
Daniel Berlin85f91b02016-12-26 20:06:58 +0000413 static bool isEqual(const Expression *LHS, const Expression *RHS) {
414 if (LHS == RHS)
415 return true;
416 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
417 LHS == getEmptyKey() || RHS == getEmptyKey())
418 return false;
Daniel Berlin2aa5dc12017-05-30 06:58:18 +0000419 // Compare hashes before equality. This is *not* what the hashtable does,
420 // since it is computing it modulo the number of buckets, whereas we are
421 // using the full hash keyspace. Since the hashes are precomputed, this
422 // check is *much* faster than equality.
423 if (LHS->getComputedHash() != RHS->getComputedHash())
424 return false;
Daniel Berlin85f91b02016-12-26 20:06:58 +0000425 return *LHS == *RHS;
426 }
427};
Davide Italiano7e274e02016-12-22 16:03:48 +0000428} // end namespace llvm
429
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000430namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000431class NewGVN {
432 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000433 DominatorTree *DT;
Daniel Berlin64e68992017-03-12 04:46:45 +0000434 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000435 AliasAnalysis *AA;
436 MemorySSA *MSSA;
437 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000438 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000439 std::unique_ptr<PredicateInfo> PredInfo;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000440
441 // These are the only two things the create* functions should have
442 // side-effects on due to allocating memory.
443 mutable BumpPtrAllocator ExpressionAllocator;
444 mutable ArrayRecycler<Value *> ArgRecycler;
445 mutable TarjanSCC SCCFinder;
Daniel Berlinede130d2017-04-26 20:56:14 +0000446 const SimplifyQuery SQ;
Davide Italiano7e274e02016-12-22 16:03:48 +0000447
Daniel Berlin1c087672017-02-11 15:07:01 +0000448 // Number of function arguments, used by ranking
449 unsigned int NumFuncArgs;
450
Daniel Berlin2f72b192017-04-14 02:53:37 +0000451 // RPOOrdering of basic blocks
452 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
453
Davide Italiano7e274e02016-12-22 16:03:48 +0000454 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000455
456 // This class is called INITIAL in the paper. It is the class everything
457 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000458 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000459 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000460 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000461 std::vector<CongruenceClass *> CongruenceClasses;
462 unsigned NextCongruenceNum;
463
464 // Value Mappings.
465 DenseMap<Value *, CongruenceClass *> ValueToClass;
466 DenseMap<Value *, const Expression *> ValueToExpression;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000467 // Value PHI handling, used to make equivalence between phi(op, op) and
468 // op(phi, phi).
469 // These mappings just store various data that would normally be part of the
470 // IR.
471 DenseSet<const Instruction *> PHINodeUses;
472 // Map a temporary instruction we created to a parent block.
473 DenseMap<const Value *, BasicBlock *> TempToBlock;
474 // Map between the temporary phis we created and the real instructions they
475 // are known equivalent to.
476 DenseMap<const Value *, PHINode *> RealToTemp;
477 // In order to know when we should re-process instructions that have
478 // phi-of-ops, we track the set of expressions that they needed as
479 // leaders. When we discover new leaders for those expressions, we process the
480 // associated phi-of-op instructions again in case they have changed. The
481 // other way they may change is if they had leaders, and those leaders
482 // disappear. However, at the point they have leaders, there are uses of the
483 // relevant operands in the created phi node, and so they will get reprocessed
484 // through the normal user marking we perform.
485 mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
486 DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
487 ExpressionToPhiOfOps;
488 // Map from basic block to the temporary operations we created
Daniel Berlin0207cca2017-05-21 23:41:56 +0000489 DenseMap<const BasicBlock *, SmallVector<PHINode *, 8>> PHIOfOpsPHIs;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000490 // Map from temporary operation to MemoryAccess.
491 DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
492 // Set of all temporary instructions we created.
493 DenseSet<Instruction *> AllTempInstructions;
Davide Italiano7e274e02016-12-22 16:03:48 +0000494
Daniel Berlinf7d95802017-02-18 23:06:50 +0000495 // Mapping from predicate info we used to the instructions we used it with.
496 // In order to correctly ensure propagation, we must keep track of what
497 // comparisons we used, so that when the values of the comparisons change, we
498 // propagate the information to the places we used the comparison.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000499 mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
500 PredicateToUsers;
Daniel Berlin1316a942017-04-06 18:52:50 +0000501 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
502 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000503 mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
504 MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000505
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000506 // A table storing which memorydefs/phis represent a memory state provably
507 // equivalent to another memory state.
508 // We could use the congruence class machinery, but the MemoryAccess's are
509 // abstract memory states, so they can only ever be equivalent to each other,
510 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000511 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000512
Daniel Berlin1316a942017-04-06 18:52:50 +0000513 // We could, if we wanted, build MemoryPhiExpressions and
514 // MemoryVariableExpressions, etc, and value number them the same way we value
515 // number phi expressions. For the moment, this seems like overkill. They
516 // can only exist in one of three states: they can be TOP (equal to
517 // everything), Equivalent to something else, or unique. Because we do not
518 // create expressions for them, we need to simulate leader change not just
519 // when they change class, but when they change state. Note: We can do the
520 // same thing for phis, and avoid having phi expressions if we wanted, We
521 // should eventually unify in one direction or the other, so this is a little
522 // bit of an experiment in which turns out easier to maintain.
523 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
524 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
525
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000526 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
527 mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
Davide Italiano7e274e02016-12-22 16:03:48 +0000528 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000529 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000530 ExpressionClassMap ExpressionToClass;
531
Daniel Berline021d2d2017-05-19 20:22:20 +0000532 // We have a single expression that represents currently DeadExpressions.
533 // For dead expressions we can prove will stay dead, we mark them with
534 // DFS number zero. However, it's possible in the case of phi nodes
535 // for us to assume/prove all arguments are dead during fixpointing.
536 // We use DeadExpression for that case.
537 DeadExpression *SingletonDeadExpression = nullptr;
538
Davide Italiano7e274e02016-12-22 16:03:48 +0000539 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000540 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000541
542 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000543 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000544 DenseSet<BlockEdge> ReachableEdges;
545 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
546
547 // This is a bitvector because, on larger functions, we may have
548 // thousands of touched instructions at once (entire blocks,
549 // instructions with hundreds of uses, etc). Even with optimization
550 // for when we mark whole blocks as touched, when this was a
551 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
552 // the time in GVN just managing this list. The bitvector, on the
553 // other hand, efficiently supports test/set/clear of both
554 // individual and ranges, as well as "find next element" This
555 // enables us to use it as a worklist with essentially 0 cost.
556 BitVector TouchedInstructions;
557
558 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000559
560#ifndef NDEBUG
561 // Debugging for how many times each block and instruction got processed.
562 DenseMap<const Value *, unsigned> ProcessedCount;
563#endif
564
565 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000566 // This contains a mapping from Instructions to DFS numbers.
567 // The numbering starts at 1. An instruction with DFS number zero
568 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000569 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000570
571 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000572 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000573
574 // Deletion info.
575 SmallPtrSet<Instruction *, 8> InstructionsToErase;
576
577public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000578 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
579 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
580 const DataLayout &DL)
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000581 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
Daniel Berlinede130d2017-04-26 20:56:14 +0000582 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
583 }
Daniel Berlin64e68992017-03-12 04:46:45 +0000584 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000585
586private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000587 // Expression handling.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000588 const Expression *createExpression(Instruction *) const;
589 const Expression *createBinaryExpression(unsigned, Type *, Value *,
590 Value *) const;
591 PHIExpression *createPHIExpression(Instruction *, bool &HasBackEdge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000592 bool &OriginalOpsConstant) const;
Daniel Berline021d2d2017-05-19 20:22:20 +0000593 const DeadExpression *createDeadExpression() const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000594 const VariableExpression *createVariableExpression(Value *) const;
595 const ConstantExpression *createConstantExpression(Constant *) const;
596 const Expression *createVariableOrConstant(Value *V) const;
597 const UnknownExpression *createUnknownExpression(Instruction *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000598 const StoreExpression *createStoreExpression(StoreInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000599 const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000600 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000601 const MemoryAccess *) const;
602 const CallExpression *createCallExpression(CallInst *,
603 const MemoryAccess *) const;
604 const AggregateValueExpression *
605 createAggregateValueExpression(Instruction *) const;
606 bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000607
608 // Congruence class handling.
609 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000610 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000611 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000612 return result;
613 }
614
Daniel Berlin1316a942017-04-06 18:52:50 +0000615 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
616 auto *CC = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000617 CC->setMemoryLeader(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000618 return CC;
619 }
620 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
621 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +0000622 if (CC->getMemoryLeader() != MA)
Daniel Berlin1316a942017-04-06 18:52:50 +0000623 CC = createMemoryClass(MA);
624 return CC;
625 }
626
Davide Italiano7e274e02016-12-22 16:03:48 +0000627 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000628 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000629 CClass->insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +0000630 ValueToClass[Member] = CClass;
631 return CClass;
632 }
633 void initializeCongruenceClasses(Function &F);
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +0000634 const Expression *makePossiblePhiOfOps(Instruction *,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000635 SmallPtrSetImpl<Value *> &);
636 void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
Davide Italiano7e274e02016-12-22 16:03:48 +0000637
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000638 // Value number an Instruction or MemoryPhi.
639 void valueNumberMemoryPhi(MemoryPhi *);
640 void valueNumberInstruction(Instruction *);
641
Davide Italiano7e274e02016-12-22 16:03:48 +0000642 // Symbolic evaluation.
643 const Expression *checkSimplificationResults(Expression *, Instruction *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000644 Value *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000645 const Expression *performSymbolicEvaluation(Value *,
646 SmallPtrSetImpl<Value *> &) const;
Daniel Berlin07daac82017-04-02 13:23:44 +0000647 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000648 Instruction *,
649 MemoryAccess *) const;
650 const Expression *performSymbolicLoadEvaluation(Instruction *) const;
651 const Expression *performSymbolicStoreEvaluation(Instruction *) const;
652 const Expression *performSymbolicCallEvaluation(Instruction *) const;
653 const Expression *performSymbolicPHIEvaluation(Instruction *) const;
654 const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
655 const Expression *performSymbolicCmpEvaluation(Instruction *) const;
656 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000657
658 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000659 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000660 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000661 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000662 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
663 CongruenceClass *, CongruenceClass *);
664 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
665 CongruenceClass *, CongruenceClass *);
666 Value *getNextValueLeader(CongruenceClass *) const;
667 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
668 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
669 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
670 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000671 bool isMemoryAccessTOP(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000672
Daniel Berlin1c087672017-02-11 15:07:01 +0000673 // Ranking
674 unsigned int getRank(const Value *) const;
675 bool shouldSwapOperands(const Value *, const Value *) const;
676
Davide Italiano7e274e02016-12-22 16:03:48 +0000677 // Reachability handling.
678 void updateReachableEdge(BasicBlock *, BasicBlock *);
679 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000680 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000681
682 // Elimination.
683 struct ValueDFS;
Daniel Berlina8236562017-04-07 18:38:09 +0000684 void convertClassToDFSOrdered(const CongruenceClass &,
Daniel Berline3e69e12017-03-10 00:32:33 +0000685 SmallVectorImpl<ValueDFS> &,
686 DenseMap<const Value *, unsigned int> &,
Daniel Berlina8236562017-04-07 18:38:09 +0000687 SmallPtrSetImpl<Instruction *> &) const;
688 void convertClassToLoadsAndStores(const CongruenceClass &,
689 SmallVectorImpl<ValueDFS> &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000690
691 bool eliminateInstructions(Function &);
692 void replaceInstruction(Instruction *, Value *);
693 void markInstructionForDeletion(Instruction *);
694 void deleteInstructionsInBlock(BasicBlock *);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000695 Value *findPhiOfOpsLeader(const Expression *E, const BasicBlock *BB) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000696
697 // New instruction creation.
698 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000699
700 // Various instruction touch utilities
Daniel Berlin0207cca2017-05-21 23:41:56 +0000701 template <typename Map, typename KeyType, typename Func>
702 void for_each_found(Map &, const KeyType &, Func);
703 template <typename Map, typename KeyType>
704 void touchAndErase(Map &, const KeyType &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000705 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000706 void markMemoryUsersTouched(const MemoryAccess *);
707 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000708 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000709 void markValueLeaderChangeTouched(CongruenceClass *CC);
710 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +0000711 void markPhiOfOpsChanged(const Expression *E);
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000712 void addPredicateUsers(const PredicateBase *, Instruction *) const;
713 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000714 void addAdditionalUsers(Value *To, Value *User) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000715
Daniel Berlin06329a92017-03-18 15:41:40 +0000716 // Main loop of value numbering
717 void iterateTouchedInstructions();
718
Davide Italiano7e274e02016-12-22 16:03:48 +0000719 // Utilities.
720 void cleanupTables();
721 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000722 void updateProcessedCount(const Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000723 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000724 void verifyIterationSettled(Function &F);
Daniel Berlin45403572017-05-16 19:58:47 +0000725 void verifyStoreExpressions() const;
Davide Italianoeab0de22017-05-18 23:22:44 +0000726 bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
727 const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000728 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000729 void deleteExpression(const Expression *E) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000730 MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
731 MemoryAccess *getDefiningAccess(const MemoryAccess *) const;
732 MemoryPhi *getMemoryAccess(const BasicBlock *) const;
733 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin21279bd2017-04-06 18:52:58 +0000734 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000735 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
736 return InstrDFS.lookup(V);
737 }
738
Daniel Berlin21279bd2017-04-06 18:52:58 +0000739 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
740 return MemoryToDFSNum(MA);
741 }
742 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
743 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
744 // This deliberately takes a value so it can be used with Use's, which will
745 // auto-convert to Value's but not to MemoryAccess's.
746 unsigned MemoryToDFSNum(const Value *MA) const {
747 assert(isa<MemoryAccess>(MA) &&
748 "This should not be used with instructions");
749 return isa<MemoryUseOrDef>(MA)
750 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
751 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000752 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000753 bool isCycleFree(const Instruction *) const;
754 bool isBackedge(BasicBlock *From, BasicBlock *To) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000755 // Debug counter info. When verifying, we have to reset the value numbering
756 // debug counter to the same state it started in to get the same results.
757 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000758};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000759} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000760
Davide Italianob1114092016-12-28 13:37:17 +0000761template <typename T>
762static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000763 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000764 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000765 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000766}
767
Davide Italianob1114092016-12-28 13:37:17 +0000768bool LoadExpression::equals(const Expression &Other) const {
769 return equalsLoadStoreHelper(*this, Other);
770}
Davide Italiano7e274e02016-12-22 16:03:48 +0000771
Davide Italianob1114092016-12-28 13:37:17 +0000772bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000773 if (!equalsLoadStoreHelper(*this, Other))
774 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000775 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000776 if (const auto *S = dyn_cast<StoreExpression>(&Other))
777 if (getStoredValue() != S->getStoredValue())
778 return false;
779 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000780}
781
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000782// Determine if the edge From->To is a backedge
783bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
784 if (From == To)
785 return true;
786 auto *FromDTN = DT->getNode(From);
787 auto *ToDTN = DT->getNode(To);
788 return RPOOrdering.lookup(FromDTN) >= RPOOrdering.lookup(ToDTN);
789}
790
Davide Italiano7e274e02016-12-22 16:03:48 +0000791#ifndef NDEBUG
792static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000793 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000794}
795#endif
796
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000797// Get a MemoryAccess for an instruction, fake or real.
798MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
799 auto *Result = MSSA->getMemoryAccess(I);
800 return Result ? Result : TempToMemory.lookup(I);
801}
802
803// Get a MemoryPhi for a basic block. These are all real.
804MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
805 return MSSA->getMemoryAccess(BB);
806}
807
Daniel Berlin06329a92017-03-18 15:41:40 +0000808// Get the basic block from an instruction/memory value.
809BasicBlock *NewGVN::getBlockForValue(Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000810 if (auto *I = dyn_cast<Instruction>(V)) {
811 auto *Parent = I->getParent();
812 if (Parent)
813 return Parent;
814 Parent = TempToBlock.lookup(V);
815 assert(Parent && "Every fake instruction should have a block");
816 return Parent;
817 }
818
819 auto *MP = dyn_cast<MemoryPhi>(V);
820 assert(MP && "Should have been an instruction or a MemoryPhi");
821 return MP->getBlock();
Daniel Berlin06329a92017-03-18 15:41:40 +0000822}
823
Daniel Berlin0e900112017-03-24 06:33:48 +0000824// Delete a definitely dead expression, so it can be reused by the expression
825// allocator. Some of these are not in creation functions, so we have to accept
826// const versions.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000827void NewGVN::deleteExpression(const Expression *E) const {
Daniel Berlin0e900112017-03-24 06:33:48 +0000828 assert(isa<BasicExpression>(E));
829 auto *BE = cast<BasicExpression>(E);
830 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
831 ExpressionAllocator.Deallocate(E);
832}
Daniel Berlin2f72b192017-04-14 02:53:37 +0000833PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000834 bool &OriginalOpsConstant) const {
835 BasicBlock *PHIBlock = getBlockForValue(I);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000836 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000837 auto *E =
838 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000839
840 E->allocateOperands(ArgRecycler, ExpressionAllocator);
841 E->setType(I->getType());
842 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000843
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000844 // NewGVN assumes the operands of a PHI node are in a consistent order across
845 // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix
846 // this in LLVM at some point we don't want GVN to find wrong congruences.
847 // Therefore, here we sort uses in predecessor order.
Davide Italiano63998ec2017-05-09 18:29:37 +0000848 // We're sorting the values by pointer. In theory this might be cause of
849 // non-determinism, but here we don't rely on the ordering for anything
850 // significant, e.g. we don't create new instructions based on it so we're
851 // fine.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000852 SmallVector<const Use *, 4> PHIOperands;
853 for (const Use &U : PN->operands())
854 PHIOperands.push_back(&U);
855 std::sort(PHIOperands.begin(), PHIOperands.end(),
856 [&](const Use *U1, const Use *U2) {
857 return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
858 });
859
Davide Italianob3886dd2017-01-25 23:37:49 +0000860 // Filter out unreachable phi operands.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000861 auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) {
Daniel Berline67c3222017-05-25 15:44:20 +0000862 if (*U == PN)
863 return false;
864 if (!ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock}))
865 return false;
866 // Things in TOPClass are equivalent to everything.
867 if (ValueToClass.lookup(*U) == TOPClass)
868 return false;
Daniel Berlineafdd862017-06-06 17:15:28 +0000869 if (lookupOperandLeader(*U) == PN)
870 return false;
Daniel Berline67c3222017-05-25 15:44:20 +0000871 return true;
Davide Italianob3886dd2017-01-25 23:37:49 +0000872 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000873 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000874 [&](const Use *U) -> Value * {
875 auto *BB = PN->getIncomingBlock(*U);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000876 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
877 OriginalOpsConstant =
878 OriginalOpsConstant && isa<Constant>(*U);
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000879 return lookupOperandLeader(*U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000880 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000881 return E;
882}
883
884// Set basic expression info (Arguments, type, opcode) for Expression
885// E from Instruction I in block B.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000886bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000887 bool AllConstant = true;
888 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
889 E->setType(GEP->getSourceElementType());
890 else
891 E->setType(I->getType());
892 E->setOpcode(I->getOpcode());
893 E->allocateOperands(ArgRecycler, ExpressionAllocator);
894
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000895 // Transform the operand array into an operand leader array, and keep track of
896 // whether all members are constant.
897 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000898 auto Operand = lookupOperandLeader(O);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000899 AllConstant = AllConstant && isa<Constant>(Operand);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000900 return Operand;
901 });
902
Davide Italiano7e274e02016-12-22 16:03:48 +0000903 return AllConstant;
904}
905
906const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000907 Value *Arg1,
908 Value *Arg2) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000909 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000910
911 E->setType(T);
912 E->setOpcode(Opcode);
913 E->allocateOperands(ArgRecycler, ExpressionAllocator);
914 if (Instruction::isCommutative(Opcode)) {
915 // Ensure that commutative instructions that only differ by a permutation
916 // of their operands get the same value number by sorting the operand value
917 // numbers. Since all commutative instructions have two operands it is more
918 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000919 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000920 std::swap(Arg1, Arg2);
921 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000922 E->op_push_back(lookupOperandLeader(Arg1));
923 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000924
Daniel Berlinede130d2017-04-26 20:56:14 +0000925 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000926 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
927 return SimplifiedE;
928 return E;
929}
930
931// Take a Value returned by simplification of Expression E/Instruction
932// I, and see if it resulted in a simpler expression. If so, return
933// that expression.
934// TODO: Once finished, this should not take an Instruction, we only
935// use it for printing.
936const Expression *NewGVN::checkSimplificationResults(Expression *E,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000937 Instruction *I,
938 Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000939 if (!V)
940 return nullptr;
941 if (auto *C = dyn_cast<Constant>(V)) {
942 if (I)
943 DEBUG(dbgs() << "Simplified " << *I << " to "
944 << " constant " << *C << "\n");
945 NumGVNOpsSimplified++;
946 assert(isa<BasicExpression>(E) &&
947 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000948 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000949 return createConstantExpression(C);
950 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
951 if (I)
952 DEBUG(dbgs() << "Simplified " << *I << " to "
953 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000954 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000955 return createVariableExpression(V);
956 }
957
958 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlina8236562017-04-07 18:38:09 +0000959 if (CC && CC->getDefiningExpr()) {
Davide Italianofd9100e2017-05-24 02:30:24 +0000960 // If we simplified to something else, we need to communicate
961 // that we're users of the value we simplified to.
Daniel Berlinc8ed4042017-05-30 06:42:29 +0000962 if (I != V) {
963 // Don't add temporary instructions to the user lists.
964 if (!AllTempInstructions.count(I))
965 addAdditionalUsers(V, I);
966 }
967
Davide Italiano7e274e02016-12-22 16:03:48 +0000968 if (I)
969 DEBUG(dbgs() << "Simplified " << *I << " to "
Daniel Berlin01939972017-05-21 23:41:53 +0000970 << " expression " << *CC->getDefiningExpr() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +0000971 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000972 deleteExpression(E);
Daniel Berlina8236562017-04-07 18:38:09 +0000973 return CC->getDefiningExpr();
Davide Italiano7e274e02016-12-22 16:03:48 +0000974 }
975 return nullptr;
976}
977
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000978const Expression *NewGVN::createExpression(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000979 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000980
Daniel Berlin97718e62017-01-31 22:32:03 +0000981 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000982
983 if (I->isCommutative()) {
984 // Ensure that commutative instructions that only differ by a permutation
985 // of their operands get the same value number by sorting the operand value
986 // numbers. Since all commutative instructions have two operands it is more
987 // efficient to sort by hand rather than using, say, std::sort.
988 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000989 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000990 E->swapOperands(0, 1);
991 }
992
993 // Perform simplificaiton
994 // TODO: Right now we only check to see if we get a constant result.
995 // We may get a less than constant, but still better, result for
996 // some operations.
997 // IE
998 // add 0, x -> x
999 // and x, x -> x
1000 // We should handle this by simply rewriting the expression.
1001 if (auto *CI = dyn_cast<CmpInst>(I)) {
1002 // Sort the operand value numbers so x<y and y>x get the same value
1003 // number.
1004 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +00001005 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001006 E->swapOperands(0, 1);
1007 Predicate = CmpInst::getSwappedPredicate(Predicate);
1008 }
1009 E->setOpcode((CI->getOpcode() << 8) | Predicate);
1010 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +00001011 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
1012 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +00001013 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
1014 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +00001015 Value *V =
1016 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +00001017 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1018 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001019 } else if (isa<SelectInst>(I)) {
1020 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +00001021 E->getOperand(0) == E->getOperand(1)) {
1022 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
1023 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +00001024 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +00001025 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001026 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1027 return SimplifiedE;
1028 }
1029 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001030 Value *V =
1031 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001032 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1033 return SimplifiedE;
1034 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001035 Value *V =
1036 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001037 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1038 return SimplifiedE;
1039 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001040 Value *V = SimplifyGEPInst(
1041 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001042 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1043 return SimplifiedE;
1044 } else if (AllConstant) {
1045 // We don't bother trying to simplify unless all of the operands
1046 // were constant.
1047 // TODO: There are a lot of Simplify*'s we could call here, if we
1048 // wanted to. The original motivating case for this code was a
1049 // zext i1 false to i8, which we don't have an interface to
1050 // simplify (IE there is no SimplifyZExt).
1051
1052 SmallVector<Constant *, 8> C;
1053 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001054 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +00001055
Daniel Berlin64e68992017-03-12 04:46:45 +00001056 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +00001057 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1058 return SimplifiedE;
1059 }
1060 return E;
1061}
1062
1063const AggregateValueExpression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001064NewGVN::createAggregateValueExpression(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001065 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001066 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001067 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001068 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001069 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001070 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001071 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001072 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001073 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001074 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001075 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001076 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001077 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001078 return E;
1079 }
1080 llvm_unreachable("Unhandled type of aggregate value operation");
1081}
1082
Daniel Berline021d2d2017-05-19 20:22:20 +00001083const DeadExpression *NewGVN::createDeadExpression() const {
1084 // DeadExpression has no arguments and all DeadExpression's are the same,
1085 // so we only need one of them.
1086 return SingletonDeadExpression;
1087}
1088
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001089const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001090 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001091 E->setOpcode(V->getValueID());
1092 return E;
1093}
1094
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001095const Expression *NewGVN::createVariableOrConstant(Value *V) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001096 if (auto *C = dyn_cast<Constant>(V))
1097 return createConstantExpression(C);
1098 return createVariableExpression(V);
1099}
1100
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001101const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001102 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +00001103 E->setOpcode(C->getValueID());
1104 return E;
1105}
1106
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001107const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001108 auto *E = new (ExpressionAllocator) UnknownExpression(I);
1109 E->setOpcode(I->getOpcode());
1110 return E;
1111}
1112
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001113const CallExpression *
1114NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001115 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001116 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +00001117 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +00001118 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001119 return E;
1120}
1121
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001122// Return true if some equivalent of instruction Inst dominates instruction U.
1123bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1124 const Instruction *U) const {
1125 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +00001126 // This must be an instruction because we are only called from phi nodes
1127 // in the case that the value it needs to check against is an instruction.
1128
1129 // The most likely candiates for dominance are the leader and the next leader.
1130 // The leader or nextleader will dominate in all cases where there is an
1131 // equivalent that is higher up in the dom tree.
1132 // We can't *only* check them, however, because the
1133 // dominator tree could have an infinite number of non-dominating siblings
1134 // with instructions that are in the right congruence class.
1135 // A
1136 // B C D E F G
1137 // |
1138 // H
1139 // Instruction U could be in H, with equivalents in every other sibling.
1140 // Depending on the rpo order picked, the leader could be the equivalent in
1141 // any of these siblings.
1142 if (!CC)
1143 return false;
Daniel Berlina8236562017-04-07 18:38:09 +00001144 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001145 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001146 if (CC->getNextLeader().first &&
1147 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001148 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001149 return llvm::any_of(*CC, [&](const Value *Member) {
1150 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001151 DT->dominates(cast<Instruction>(Member), U);
1152 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001153}
1154
Davide Italiano7e274e02016-12-22 16:03:48 +00001155// See if we have a congruence class and leader for this operand, and if so,
1156// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001157Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001158 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001159 if (CC) {
Daniel Berline021d2d2017-05-19 20:22:20 +00001160 // Everything in TOP is represented by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001161 // We do have to make sure we get the type right though, so we can't set the
1162 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001163 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001164 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001165 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001166 }
1167
Davide Italiano7e274e02016-12-22 16:03:48 +00001168 return V;
1169}
1170
Daniel Berlin1316a942017-04-06 18:52:50 +00001171const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1172 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001173 assert(CC->getMemoryLeader() &&
Davide Italianob60f6e02017-05-12 15:25:56 +00001174 "Every MemoryAccess should be mapped to a congruence class with a "
1175 "representative memory access");
Daniel Berlina8236562017-04-07 18:38:09 +00001176 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001177}
1178
Daniel Berlinc4796862017-01-27 02:37:11 +00001179// Return true if the MemoryAccess is really equivalent to everything. This is
1180// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001181// state of all MemoryAccesses.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001182bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001183 return getMemoryClass(MA) == TOPClass;
1184}
1185
Davide Italiano7e274e02016-12-22 16:03:48 +00001186LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001187 LoadInst *LI,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001188 const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001189 auto *E =
1190 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001191 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1192 E->setType(LoadType);
1193
1194 // Give store and loads same opcode so they value number together.
1195 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001196 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001197 if (LI)
1198 E->setAlignment(LI->getAlignment());
1199
1200 // TODO: Value number heap versions. We may be able to discover
1201 // things alias analysis can't on it's own (IE that a store and a
1202 // load have the same value, and thus, it isn't clobbering the load).
1203 return E;
1204}
1205
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001206const StoreExpression *
1207NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001208 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001209 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001210 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001211 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1212 E->setType(SI->getValueOperand()->getType());
1213
1214 // Give store and loads same opcode so they value number together.
1215 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001216 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001217
1218 // TODO: Value number heap versions. We may be able to discover
1219 // things alias analysis can't on it's own (IE that a store and a
1220 // load have the same value, and thus, it isn't clobbering the load).
1221 return E;
1222}
1223
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001224const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001225 // Unlike loads, we never try to eliminate stores, so we do not check if they
1226 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001227 auto *SI = cast<StoreInst>(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001228 auto *StoreAccess = getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001229 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001230 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1231 if (EnableStoreRefinement)
1232 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1233 // If we bypassed the use-def chains, make sure we add a use.
1234 if (StoreRHS != StoreAccess->getDefiningAccess())
1235 addMemoryUsers(StoreRHS, StoreAccess);
Daniel Berlin1316a942017-04-06 18:52:50 +00001236 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001237 // If we are defined by ourselves, use the live on entry def.
1238 if (StoreRHS == StoreAccess)
1239 StoreRHS = MSSA->getLiveOnEntryDef();
1240
Daniel Berlin589cecc2017-01-02 18:00:46 +00001241 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001242 // See if we are defined by a previous store expression, it already has a
1243 // value, and it's the same value as our current store. FIXME: Right now, we
1244 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001245 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1246 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +00001247 // Basically, check if the congruence class the store is in is defined by a
1248 // store that isn't us, and has the same value. MemorySSA takes care of
1249 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +00001250 // The RepStoredValue gets nulled if all the stores disappear in a class, so
1251 // we don't need to check if the class contains a store besides us.
Daniel Berlin1316a942017-04-06 18:52:50 +00001252 if (LastCC &&
Daniel Berlina8236562017-04-07 18:38:09 +00001253 LastCC->getStoredValue() == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin1316a942017-04-06 18:52:50 +00001254 return LastStore;
1255 deleteExpression(LastStore);
Daniel Berlinc4796862017-01-27 02:37:11 +00001256 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001257 // location, and the memory state is the same as it was then (otherwise, it
1258 // could have been overwritten later. See test32 in
1259 // transforms/DeadStoreElimination/simple.ll).
1260 if (auto *LI =
1261 dyn_cast<LoadInst>(lookupOperandLeader(SI->getValueOperand()))) {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001262 if ((lookupOperandLeader(LI->getPointerOperand()) ==
1263 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001264 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
Daniel Berlin1316a942017-04-06 18:52:50 +00001265 StoreRHS))
Davide Italiano9a0f5422017-05-20 00:46:54 +00001266 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001267 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001268 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001269
1270 // If the store is not equivalent to anything, value number it as a store that
1271 // produces a unique memory state (instead of using it's MemoryUse, we use
1272 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001273 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001274}
1275
Daniel Berlin07daac82017-04-02 13:23:44 +00001276// See if we can extract the value of a loaded pointer from a load, a store, or
1277// a memory instruction.
1278const Expression *
1279NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1280 LoadInst *LI, Instruction *DepInst,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001281 MemoryAccess *DefiningAccess) const {
Daniel Berlin07daac82017-04-02 13:23:44 +00001282 assert((!LI || LI->isSimple()) && "Not a simple load");
1283 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1284 // Can't forward from non-atomic to atomic without violating memory model.
1285 // Also don't need to coerce if they are the same type, we will just
1286 // propogate..
1287 if (LI->isAtomic() > DepSI->isAtomic() ||
1288 LoadType == DepSI->getValueOperand()->getType())
1289 return nullptr;
1290 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1291 if (Offset >= 0) {
1292 if (auto *C = dyn_cast<Constant>(
1293 lookupOperandLeader(DepSI->getValueOperand()))) {
1294 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1295 << *C << "\n");
1296 return createConstantExpression(
1297 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1298 }
1299 }
1300
1301 } else if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1302 // Can't forward from non-atomic to atomic without violating memory model.
1303 if (LI->isAtomic() > DepLI->isAtomic())
1304 return nullptr;
1305 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1306 if (Offset >= 0) {
1307 // We can coerce a constant load into a load
1308 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1309 if (auto *PossibleConstant =
1310 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1311 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1312 << *PossibleConstant << "\n");
1313 return createConstantExpression(PossibleConstant);
1314 }
1315 }
1316
1317 } else if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1318 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1319 if (Offset >= 0) {
1320 if (auto *PossibleConstant =
1321 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1322 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1323 << " to constant " << *PossibleConstant << "\n");
1324 return createConstantExpression(PossibleConstant);
1325 }
1326 }
1327 }
1328
1329 // All of the below are only true if the loaded pointer is produced
1330 // by the dependent instruction.
1331 if (LoadPtr != lookupOperandLeader(DepInst) &&
1332 !AA->isMustAlias(LoadPtr, DepInst))
1333 return nullptr;
1334 // If this load really doesn't depend on anything, then we must be loading an
1335 // undef value. This can happen when loading for a fresh allocation with no
1336 // intervening stores, for example. Note that this is only true in the case
1337 // that the result of the allocation is pointer equal to the load ptr.
1338 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1339 return createConstantExpression(UndefValue::get(LoadType));
1340 }
1341 // If this load occurs either right after a lifetime begin,
1342 // then the loaded value is undefined.
1343 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1344 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1345 return createConstantExpression(UndefValue::get(LoadType));
1346 }
1347 // If this load follows a calloc (which zero initializes memory),
1348 // then the loaded value is zero
1349 else if (isCallocLikeFn(DepInst, TLI)) {
1350 return createConstantExpression(Constant::getNullValue(LoadType));
1351 }
1352
1353 return nullptr;
1354}
1355
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001356const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001357 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001358
1359 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001360 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001361 if (!LI->isSimple())
1362 return nullptr;
1363
Daniel Berlin203f47b2017-01-31 22:31:53 +00001364 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001365 // Load of undef is undef.
1366 if (isa<UndefValue>(LoadAddressLeader))
1367 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001368 MemoryAccess *OriginalAccess = getMemoryAccess(I);
1369 MemoryAccess *DefiningAccess =
1370 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001371
1372 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1373 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1374 Instruction *DefiningInst = MD->getMemoryInst();
1375 // If the defining instruction is not reachable, replace with undef.
1376 if (!ReachableBlocks.count(DefiningInst->getParent()))
1377 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001378 // This will handle stores and memory insts. We only do if it the
1379 // defining access has a different type, or it is a pointer produced by
1380 // certain memory operations that cause the memory to have a fixed value
1381 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001382 if (const auto *CoercionResult =
1383 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1384 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001385 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001386 }
1387 }
1388
Daniel Berlin1316a942017-04-06 18:52:50 +00001389 const Expression *E = createLoadExpression(LI->getType(), LoadAddressLeader,
1390 LI, DefiningAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001391 return E;
1392}
1393
Daniel Berlinf7d95802017-02-18 23:06:50 +00001394const Expression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001395NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001396 auto *PI = PredInfo->getPredicateInfoFor(I);
1397 if (!PI)
1398 return nullptr;
1399
1400 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001401
1402 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1403 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001404 return nullptr;
1405
Daniel Berlinfccbda92017-02-22 22:20:58 +00001406 auto *CopyOf = I->getOperand(0);
1407 auto *Cond = PWC->Condition;
1408
Daniel Berlinf7d95802017-02-18 23:06:50 +00001409 // If this a copy of the condition, it must be either true or false depending
1410 // on the predicate info type and edge
1411 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001412 // We should not need to add predicate users because the predicate info is
1413 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001414 if (isa<PredicateAssume>(PI))
1415 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1416 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1417 if (PBranch->TrueEdge)
1418 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1419 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1420 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001421 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1422 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001423 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001424
Daniel Berlinf7d95802017-02-18 23:06:50 +00001425 // Not a copy of the condition, so see what the predicates tell us about this
1426 // value. First, though, we check to make sure the value is actually a copy
1427 // of one of the condition operands. It's possible, in certain cases, for it
1428 // to be a copy of a predicateinfo copy. In particular, if two branch
1429 // operations use the same condition, and one branch dominates the other, we
1430 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001431 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001432 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001433
1434 // Everything below relies on the condition being a comparison.
1435 auto *Cmp = dyn_cast<CmpInst>(Cond);
1436 if (!Cmp)
1437 return nullptr;
1438
1439 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Davide Italianoc43a9f82017-05-12 15:28:12 +00001440 DEBUG(dbgs() << "Copy is not of any condition operands!\n");
Daniel Berlinf7d95802017-02-18 23:06:50 +00001441 return nullptr;
1442 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001443 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1444 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001445 bool SwappedOps = false;
1446 // Sort the ops
1447 if (shouldSwapOperands(FirstOp, SecondOp)) {
1448 std::swap(FirstOp, SecondOp);
1449 SwappedOps = true;
1450 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001451 CmpInst::Predicate Predicate =
1452 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1453
1454 if (isa<PredicateAssume>(PI)) {
1455 // If the comparison is true when the operands are equal, then we know the
1456 // operands are equal, because assumes must always be true.
1457 if (CmpInst::isTrueWhenEqual(Predicate)) {
1458 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001459 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001460 return createVariableOrConstant(FirstOp);
1461 }
1462 }
1463 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1464 // If we are *not* a copy of the comparison, we may equal to the other
1465 // operand when the predicate implies something about equality of
1466 // operations. In particular, if the comparison is true/false when the
1467 // operands are equal, and we are on the right edge, we know this operation
1468 // is equal to something.
1469 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1470 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1471 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001472 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001473 return createVariableOrConstant(FirstOp);
1474 }
1475 // Handle the special case of floating point.
1476 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1477 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1478 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1479 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001480 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001481 return createConstantExpression(cast<Constant>(FirstOp));
1482 }
1483 }
1484 return nullptr;
1485}
1486
Davide Italiano7e274e02016-12-22 16:03:48 +00001487// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001488const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001489 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001490 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1491 // Instrinsics with the returned attribute are copies of arguments.
1492 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1493 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1494 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1495 return Result;
1496 return createVariableOrConstant(ReturnedValue);
1497 }
1498 }
1499 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001500 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001501 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001502 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001503 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001504 }
1505 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001506}
1507
Daniel Berlin1316a942017-04-06 18:52:50 +00001508// Retrieve the memory class for a given MemoryAccess.
1509CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1510
1511 auto *Result = MemoryAccessToClass.lookup(MA);
1512 assert(Result && "Should have found memory class");
1513 return Result;
1514}
1515
1516// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001517// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001518bool NewGVN::setMemoryClass(const MemoryAccess *From,
1519 CongruenceClass *NewClass) {
1520 assert(NewClass &&
1521 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001522 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001523 DEBUG(dbgs() << " equivalent to congruence class ");
Daniel Berlina8236562017-04-07 18:38:09 +00001524 DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
Davide Italianob7a66982017-05-09 20:02:48 +00001525 DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001526
1527 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001528 bool Changed = false;
1529 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001530 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001531 auto *OldClass = LookupResult->second;
1532 if (OldClass != NewClass) {
1533 // If this is a phi, we have to handle memory member updates.
1534 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001535 OldClass->memory_erase(MP);
1536 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001537 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001538 if (OldClass->getMemoryLeader() == From) {
Davide Italiano41f5c7b2017-05-12 15:22:45 +00001539 if (OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00001540 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001541 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001542 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Daniel Berlin1316a942017-04-06 18:52:50 +00001543 DEBUG(dbgs() << "Memory class leader change for class "
Daniel Berlina8236562017-04-07 18:38:09 +00001544 << OldClass->getID() << " to "
1545 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001546 << " due to removal of a memory member " << *From
1547 << "\n");
1548 markMemoryLeaderChangeTouched(OldClass);
1549 }
1550 }
1551 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001552 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001553 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001554 Changed = true;
1555 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001556 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001557
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001558 return Changed;
1559}
Daniel Berlin0e900112017-03-24 06:33:48 +00001560
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001561// Determine if a instruction is cycle-free. That means the values in the
1562// instruction don't depend on any expressions that can change value as a result
1563// of the instruction. For example, a non-cycle free instruction would be v =
1564// phi(0, v+1).
1565bool NewGVN::isCycleFree(const Instruction *I) const {
1566 // In order to compute cycle-freeness, we do SCC finding on the instruction,
1567 // and see what kind of SCC it ends up in. If it is a singleton, it is
1568 // cycle-free. If it is not in a singleton, it is only cycle free if the
1569 // other members are all phi nodes (as they do not compute anything, they are
1570 // copies).
1571 auto ICS = InstCycleState.lookup(I);
1572 if (ICS == ICS_Unknown) {
1573 SCCFinder.Start(I);
1574 auto &SCC = SCCFinder.getComponentFor(I);
Daniel Berlin2f72b192017-04-14 02:53:37 +00001575 // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1576 if (SCC.size() == 1)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001577 InstCycleState.insert({I, ICS_CycleFree});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001578 else {
1579 bool AllPhis =
1580 llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001581 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
Daniel Berlin2f72b192017-04-14 02:53:37 +00001582 for (auto *Member : SCC)
1583 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001584 InstCycleState.insert({MemberPhi, ICS});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001585 }
1586 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001587 if (ICS == ICS_Cycle)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001588 return false;
1589 return true;
1590}
1591
Davide Italiano7e274e02016-12-22 16:03:48 +00001592// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001593const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001594 // True if one of the incoming phi edges is a backedge.
1595 bool HasBackedge = false;
1596 // All constant tracks the state of whether all the *original* phi operands
Daniel Berline021d2d2017-05-19 20:22:20 +00001597 // This is really shorthand for "this phi cannot cycle due to forward
1598 // change in value of the phi is guaranteed not to later change the value of
1599 // the phi. IE it can't be v = phi(undef, v+1)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001600 bool AllConstant = true;
Daniel Berlinabd632d2017-05-16 06:06:12 +00001601 auto *E =
1602 cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001603 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001604 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001605 // We track if any were undef because they need special handling.
1606 bool HasUndef = false;
Daniel Berline021d2d2017-05-19 20:22:20 +00001607 auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
Daniel Berlind92e7f92017-01-07 00:01:42 +00001608 if (isa<UndefValue>(Arg)) {
1609 HasUndef = true;
1610 return false;
1611 }
1612 return true;
1613 });
Daniel Berline021d2d2017-05-19 20:22:20 +00001614 // If we are left with no operands, it's dead.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001615 if (Filtered.begin() == Filtered.end()) {
Daniel Berline67c3222017-05-25 15:44:20 +00001616 // If it has undef at this point, it means there are no-non-undef arguments,
1617 // and thus, the value of the phi node must be undef.
1618 if (HasUndef) {
1619 DEBUG(dbgs() << "PHI Node " << *I
1620 << " has no non-undef arguments, valuing it as undef\n");
1621 return createConstantExpression(UndefValue::get(I->getType()));
1622 }
1623
Daniel Berline021d2d2017-05-19 20:22:20 +00001624 DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001625 deleteExpression(E);
Daniel Berline021d2d2017-05-19 20:22:20 +00001626 return createDeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00001627 }
Daniel Berlin2f72b192017-04-14 02:53:37 +00001628 unsigned NumOps = 0;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001629 Value *AllSameValue = *(Filtered.begin());
1630 ++Filtered.begin();
1631 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berline021d2d2017-05-19 20:22:20 +00001632 if (llvm::all_of(Filtered, [&](Value *Arg) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001633 ++NumOps;
Daniel Berline021d2d2017-05-19 20:22:20 +00001634 return Arg == AllSameValue;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001635 })) {
1636 // In LLVM's non-standard representation of phi nodes, it's possible to have
1637 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1638 // on the original phi node), especially in weird CFG's where some arguments
1639 // are unreachable, or uninitialized along certain paths. This can cause
1640 // infinite loops during evaluation. We work around this by not trying to
1641 // really evaluate them independently, but instead using a variable
1642 // expression to say if one is equivalent to the other.
1643 // We also special case undef, so that if we have an undef, we can't use the
1644 // common value unless it dominates the phi block.
1645 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001646 // If we have undef and at least one other value, this is really a
1647 // multivalued phi, and we need to know if it's cycle free in order to
1648 // evaluate whether we can ignore the undef. The other parts of this are
1649 // just shortcuts. If there is no backedge, or all operands are
1650 // constants, or all operands are ignored but the undef, it also must be
1651 // cycle free.
1652 if (!AllConstant && HasBackedge && NumOps > 0 &&
Daniel Berline67c3222017-05-25 15:44:20 +00001653 !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
Daniel Berlin2f72b192017-04-14 02:53:37 +00001654 return E;
1655
Daniel Berlind92e7f92017-01-07 00:01:42 +00001656 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001657 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001658 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001659 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001660 }
Daniel Berlineafdd862017-06-06 17:15:28 +00001661 // Can't simplify to something that comes later in the iteration.
1662 // Otherwise, when and if it changes congruence class, we will never catch
1663 // up. We will always be a class behind it.
1664 if (isa<Instruction>(AllSameValue) &&
1665 InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
1666 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001667 NumGVNPhisAllSame++;
1668 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1669 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001670 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001671 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001672 }
1673 return E;
1674}
1675
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001676const Expression *
1677NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001678 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1679 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1680 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1681 unsigned Opcode = 0;
1682 // EI might be an extract from one of our recognised intrinsics. If it
1683 // is we'll synthesize a semantically equivalent expression instead on
1684 // an extract value expression.
1685 switch (II->getIntrinsicID()) {
1686 case Intrinsic::sadd_with_overflow:
1687 case Intrinsic::uadd_with_overflow:
1688 Opcode = Instruction::Add;
1689 break;
1690 case Intrinsic::ssub_with_overflow:
1691 case Intrinsic::usub_with_overflow:
1692 Opcode = Instruction::Sub;
1693 break;
1694 case Intrinsic::smul_with_overflow:
1695 case Intrinsic::umul_with_overflow:
1696 Opcode = Instruction::Mul;
1697 break;
1698 default:
1699 break;
1700 }
1701
1702 if (Opcode != 0) {
1703 // Intrinsic recognized. Grab its args to finish building the
1704 // expression.
1705 assert(II->getNumArgOperands() == 2 &&
1706 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001707 return createBinaryExpression(
1708 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001709 }
1710 }
1711 }
1712
Daniel Berlin97718e62017-01-31 22:32:03 +00001713 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001714}
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001715const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001716 auto *CI = dyn_cast<CmpInst>(I);
1717 // See if our operands are equal to those of a previous predicate, and if so,
1718 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001719 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1720 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001721 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001722 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001723 std::swap(Op0, Op1);
1724 OurPredicate = CI->getSwappedPredicate();
1725 }
1726
1727 // Avoid processing the same info twice
1728 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001729 // See if we know something about the comparison itself, like it is the target
1730 // of an assume.
1731 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1732 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1733 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1734
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001735 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001736 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001737 if (CI->isTrueWhenEqual())
1738 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1739 else if (CI->isFalseWhenEqual())
1740 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1741 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001742
1743 // NOTE: Because we are comparing both operands here and below, and using
1744 // previous comparisons, we rely on fact that predicateinfo knows to mark
1745 // comparisons that use renamed operands as users of the earlier comparisons.
1746 // It is *not* enough to just mark predicateinfo renamed operands as users of
1747 // the earlier comparisons, because the *other* operand may have changed in a
1748 // previous iteration.
1749 // Example:
1750 // icmp slt %a, %b
1751 // %b.0 = ssa.copy(%b)
1752 // false branch:
1753 // icmp slt %c, %b.0
1754
1755 // %c and %a may start out equal, and thus, the code below will say the second
1756 // %icmp is false. c may become equal to something else, and in that case the
1757 // %second icmp *must* be reexamined, but would not if only the renamed
1758 // %operands are considered users of the icmp.
1759
1760 // *Currently* we only check one level of comparisons back, and only mark one
1761 // level back as touched when changes appen . If you modify this code to look
1762 // back farther through comparisons, you *must* mark the appropriate
1763 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1764 // we know something just from the operands themselves
1765
1766 // See if our operands have predicate info, so that we may be able to derive
1767 // something from a previous comparison.
1768 for (const auto &Op : CI->operands()) {
1769 auto *PI = PredInfo->getPredicateInfoFor(Op);
1770 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1771 if (PI == LastPredInfo)
1772 continue;
1773 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001774
Daniel Berlinf7d95802017-02-18 23:06:50 +00001775 // TODO: Along the false edge, we may know more things too, like icmp of
1776 // same operands is false.
1777 // TODO: We only handle actual comparison conditions below, not and/or.
1778 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1779 if (!BranchCond)
1780 continue;
1781 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1782 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1783 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001784 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001785 std::swap(BranchOp0, BranchOp1);
1786 BranchPredicate = BranchCond->getSwappedPredicate();
1787 }
1788 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1789 if (PBranch->TrueEdge) {
1790 // If we know the previous predicate is true and we are in the true
1791 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001792 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1793 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001794 addPredicateUsers(PI, I);
1795 return createConstantExpression(
1796 ConstantInt::getTrue(CI->getType()));
1797 }
1798
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001799 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1800 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001801 addPredicateUsers(PI, I);
1802 return createConstantExpression(
1803 ConstantInt::getFalse(CI->getType()));
1804 }
1805
1806 } else {
1807 // Just handle the ne and eq cases, where if we have the same
1808 // operands, we may know something.
1809 if (BranchPredicate == OurPredicate) {
1810 addPredicateUsers(PI, I);
1811 // Same predicate, same ops,we know it was false, so this is false.
1812 return createConstantExpression(
1813 ConstantInt::getFalse(CI->getType()));
1814 } else if (BranchPredicate ==
1815 CmpInst::getInversePredicate(OurPredicate)) {
1816 addPredicateUsers(PI, I);
1817 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001818 return createConstantExpression(
1819 ConstantInt::getTrue(CI->getType()));
1820 }
1821 }
1822 }
1823 }
1824 }
1825 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001826 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001827}
Davide Italiano7e274e02016-12-22 16:03:48 +00001828
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001829// Return true if V is a value that will always be available (IE can
1830// be placed anywhere) in the function. We don't do globals here
1831// because they are often worse to put in place.
1832// TODO: Separate cost from availability
1833static bool alwaysAvailable(Value *V) {
1834 return isa<Constant>(V) || isa<Argument>(V);
1835}
1836
Davide Italiano7e274e02016-12-22 16:03:48 +00001837// Substitute and symbolize the value before value numbering.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001838const Expression *
1839NewGVN::performSymbolicEvaluation(Value *V,
1840 SmallPtrSetImpl<Value *> &Visited) const {
Davide Italiano0e714802016-12-28 14:00:11 +00001841 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001842 if (auto *C = dyn_cast<Constant>(V))
1843 E = createConstantExpression(C);
1844 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1845 E = createVariableExpression(V);
1846 } else {
1847 // TODO: memory intrinsics.
1848 // TODO: Some day, we should do the forward propagation and reassociation
1849 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001850 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001851 switch (I->getOpcode()) {
1852 case Instruction::ExtractValue:
1853 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001854 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001855 break;
1856 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001857 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001858 break;
1859 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001860 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001861 break;
1862 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001863 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001864 break;
1865 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001866 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001867 break;
1868 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001869 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001870 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001871 case Instruction::ICmp:
1872 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001873 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001874 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001875 case Instruction::Add:
1876 case Instruction::FAdd:
1877 case Instruction::Sub:
1878 case Instruction::FSub:
1879 case Instruction::Mul:
1880 case Instruction::FMul:
1881 case Instruction::UDiv:
1882 case Instruction::SDiv:
1883 case Instruction::FDiv:
1884 case Instruction::URem:
1885 case Instruction::SRem:
1886 case Instruction::FRem:
1887 case Instruction::Shl:
1888 case Instruction::LShr:
1889 case Instruction::AShr:
1890 case Instruction::And:
1891 case Instruction::Or:
1892 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001893 case Instruction::Trunc:
1894 case Instruction::ZExt:
1895 case Instruction::SExt:
1896 case Instruction::FPToUI:
1897 case Instruction::FPToSI:
1898 case Instruction::UIToFP:
1899 case Instruction::SIToFP:
1900 case Instruction::FPTrunc:
1901 case Instruction::FPExt:
1902 case Instruction::PtrToInt:
1903 case Instruction::IntToPtr:
1904 case Instruction::Select:
1905 case Instruction::ExtractElement:
1906 case Instruction::InsertElement:
1907 case Instruction::ShuffleVector:
1908 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001909 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001910 break;
1911 default:
1912 return nullptr;
1913 }
1914 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001915 return E;
1916}
1917
Daniel Berlin0207cca2017-05-21 23:41:56 +00001918// Look up a container in a map, and then call a function for each thing in the
1919// found container.
1920template <typename Map, typename KeyType, typename Func>
1921void NewGVN::for_each_found(Map &M, const KeyType &Key, Func F) {
1922 const auto Result = M.find_as(Key);
1923 if (Result != M.end())
1924 for (typename Map::mapped_type::value_type Mapped : Result->second)
1925 F(Mapped);
1926}
1927
1928// Look up a container of values/instructions in a map, and touch all the
1929// instructions in the container. Then erase value from the map.
1930template <typename Map, typename KeyType>
1931void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
1932 const auto Result = M.find_as(Key);
1933 if (Result != M.end()) {
1934 for (const typename Map::mapped_type::value_type Mapped : Result->second)
1935 TouchedInstructions.set(InstrToDFSNum(Mapped));
1936 M.erase(Result);
1937 }
1938}
1939
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001940void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00001941 if (isa<Instruction>(To))
1942 AdditionalUsers[To].insert(User);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001943}
1944
Davide Italiano7e274e02016-12-22 16:03:48 +00001945void NewGVN::markUsersTouched(Value *V) {
1946 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001947 for (auto *User : V->users()) {
1948 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001949 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001950 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00001951 touchAndErase(AdditionalUsers, V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001952}
1953
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001954void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001955 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1956 MemoryToUsers[To].insert(U);
1957}
1958
1959void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001960 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00001961}
1962
1963void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1964 if (isa<MemoryUse>(MA))
1965 return;
1966 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00001967 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin0207cca2017-05-21 23:41:56 +00001968 touchAndErase(MemoryToUsers, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001969}
1970
Daniel Berlinf7d95802017-02-18 23:06:50 +00001971// Add I to the set of users of a given predicate.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001972void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001973 // Don't add temporary instructions to the user lists.
1974 if (AllTempInstructions.count(I))
1975 return;
1976
Daniel Berlinf7d95802017-02-18 23:06:50 +00001977 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1978 PredicateToUsers[PBranch->Condition].insert(I);
1979 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1980 PredicateToUsers[PAssume->Condition].insert(I);
1981}
1982
1983// Touch all the predicates that depend on this instruction.
1984void NewGVN::markPredicateUsersTouched(Instruction *I) {
Daniel Berlin0207cca2017-05-21 23:41:56 +00001985 touchAndErase(PredicateToUsers, I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001986}
1987
Daniel Berlin1316a942017-04-06 18:52:50 +00001988// Mark users affected by a memory leader change.
1989void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001990 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00001991 markMemoryDefTouched(M);
1992}
1993
Daniel Berlin32f8d562017-01-07 16:55:14 +00001994// Touch the instructions that need to be updated after a congruence class has a
1995// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00001996void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001997 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00001998 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00001999 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002000 LeaderChanges.insert(M);
2001 }
2002}
2003
Daniel Berlin1316a942017-04-06 18:52:50 +00002004// Give a range of things that have instruction DFS numbers, this will return
2005// the member of the range with the smallest dfs number.
2006template <class T, class Range>
2007T *NewGVN::getMinDFSOfRange(const Range &R) const {
2008 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
2009 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002010 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00002011 if (DFSNum < MinDFS.second)
2012 MinDFS = {X, DFSNum};
2013 }
2014 return MinDFS.first;
2015}
2016
2017// This function returns the MemoryAccess that should be the next leader of
2018// congruence class CC, under the assumption that the current leader is going to
2019// disappear.
2020const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
2021 // TODO: If this ends up to slow, we can maintain a next memory leader like we
2022 // do for regular leaders.
2023 // Make sure there will be a leader to find
Davide Italianodc435322017-05-10 19:57:43 +00002024 assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00002025 if (CC->getStoreCount() > 0) {
2026 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002027 return getMemoryAccess(NL);
Daniel Berlin1316a942017-04-06 18:52:50 +00002028 // Find the store with the minimum DFS number.
2029 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00002030 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002031 return getMemoryAccess(cast<StoreInst>(V));
Daniel Berlin1316a942017-04-06 18:52:50 +00002032 }
Daniel Berlina8236562017-04-07 18:38:09 +00002033 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00002034
2035 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00002036 // !OldClass->memory_empty()
2037 if (CC->memory_size() == 1)
2038 return *CC->memory_begin();
2039 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00002040}
2041
2042// This function returns the next value leader of a congruence class, under the
2043// assumption that the current leader is going away. This should end up being
2044// the next most dominating member.
2045Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
2046 // We don't need to sort members if there is only 1, and we don't care about
2047 // sorting the TOP class because everything either gets out of it or is
2048 // unreachable.
2049
Daniel Berlina8236562017-04-07 18:38:09 +00002050 if (CC->size() == 1 || CC == TOPClass) {
2051 return *(CC->begin());
2052 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002053 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00002054 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00002055 } else {
2056 ++NumGVNSortedLeaderChanges;
2057 // NOTE: If this ends up to slow, we can maintain a dual structure for
2058 // member testing/insertion, or keep things mostly sorted, and sort only
2059 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00002060 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00002061 }
2062}
2063
2064// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
2065// the memory members, etc for the move.
2066//
2067// The invariants of this function are:
2068//
2069// I must be moving to NewClass from OldClass The StoreCount of OldClass and
2070// NewClass is expected to have been updated for I already if it is is a store.
2071// The OldClass memory leader has not been updated yet if I was the leader.
2072void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
2073 MemoryAccess *InstMA,
2074 CongruenceClass *OldClass,
2075 CongruenceClass *NewClass) {
2076 // If the leader is I, and we had a represenative MemoryAccess, it should
2077 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00002078 assert((!InstMA || !OldClass->getMemoryLeader() ||
2079 OldClass->getLeader() != I ||
2080 OldClass->getMemoryLeader() == InstMA) &&
2081 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00002082 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00002083 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002084 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00002085 assert(NewClass->size() == 1 ||
2086 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
2087 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00002088 // Mark it touched if we didn't just create a singleton
Daniel Berlina8236562017-04-07 18:38:09 +00002089 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002090 << " due to new memory instruction becoming leader\n");
2091 markMemoryLeaderChangeTouched(NewClass);
2092 }
2093 setMemoryClass(InstMA, NewClass);
2094 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00002095 if (OldClass->getMemoryLeader() == InstMA) {
Davide Italianodc435322017-05-10 19:57:43 +00002096 if (!OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00002097 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2098 DEBUG(dbgs() << "Memory class leader change for class "
2099 << OldClass->getID() << " to "
2100 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00002101 << " due to removal of old leader " << *InstMA << "\n");
2102 markMemoryLeaderChangeTouched(OldClass);
2103 } else
Daniel Berlina8236562017-04-07 18:38:09 +00002104 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00002105 }
2106}
2107
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002108// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00002109// Update OldClass and NewClass for the move (including changing leaders, etc).
2110void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002111 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002112 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00002113 if (I == OldClass->getNextLeader().first)
2114 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002115
Daniel Berlinff152002017-05-19 19:01:24 +00002116 OldClass->erase(I);
2117 NewClass->insert(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002118
Daniel Berlina8236562017-04-07 18:38:09 +00002119 if (NewClass->getLeader() != I)
2120 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlin1316a942017-04-06 18:52:50 +00002121 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002122 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002123 OldClass->decStoreCount();
2124 // Okay, so when do we want to make a store a leader of a class?
2125 // If we have a store defined by an earlier load, we want the earlier load
2126 // to lead the class.
2127 // If we have a store defined by something else, we want the store to lead
2128 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00002129 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00002130 // as the leader
2131 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002132 // If it's a store expression we are using, it means we are not equivalent
2133 // to something earlier.
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002134 if (auto *SE = dyn_cast<StoreExpression>(E)) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002135 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1316a942017-04-06 18:52:50 +00002136 markValueLeaderChangeTouched(NewClass);
2137 // Shift the new class leader to be the store
Daniel Berlina8236562017-04-07 18:38:09 +00002138 DEBUG(dbgs() << "Changing leader of congruence class "
2139 << NewClass->getID() << " from " << *NewClass->getLeader()
2140 << " to " << *SI << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002141 // If we changed the leader, we have to mark it changed because we don't
2142 // know what it will do to symbolic evlauation.
Daniel Berlina8236562017-04-07 18:38:09 +00002143 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002144 }
2145 // We rely on the code below handling the MemoryAccess change.
2146 }
Daniel Berlina8236562017-04-07 18:38:09 +00002147 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002148 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002149 // True if there is no memory instructions left in a class that had memory
2150 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002151
Daniel Berlin1316a942017-04-06 18:52:50 +00002152 // If it's not a memory use, set the MemoryAccess equivalence
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002153 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
Daniel Berlin1316a942017-04-06 18:52:50 +00002154 if (InstMA)
2155 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002156 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002157 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00002158 if (OldClass->empty() && OldClass != TOPClass) {
2159 if (OldClass->getDefiningExpr()) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002160 DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002161 << " from table\n");
Daniel Berlineafdd862017-06-06 17:15:28 +00002162 // We erase it as an exact expression to make sure we don't just erase an
2163 // equivalent one.
2164 auto Iter = ExpressionToClass.find_as(
2165 ExactEqualsExpression(*OldClass->getDefiningExpr()));
2166 if (Iter != ExpressionToClass.end())
2167 ExpressionToClass.erase(Iter);
2168#ifdef EXPENSIVE_CHECKS
2169 assert(
2170 (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
2171 "We erased the expression we just inserted, which should not happen");
2172#endif
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002173 }
Daniel Berlina8236562017-04-07 18:38:09 +00002174 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002175 // When the leader changes, the value numbering of
2176 // everything may change due to symbolization changes, so we need to
2177 // reprocess.
Daniel Berlina8236562017-04-07 18:38:09 +00002178 DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002179 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002180 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00002181 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002182 // Note that this is basically clean up for the expression removal that
2183 // happens below. If we remove stores from a class, we may leave it as a
2184 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002185 if (OldClass->getStoreCount() == 0) {
2186 if (OldClass->getStoredValue())
2187 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002188 }
Daniel Berlina8236562017-04-07 18:38:09 +00002189 OldClass->setLeader(getNextValueLeader(OldClass));
2190 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002191 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002192 }
2193}
2194
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002195// For a given expression, mark the phi of ops instructions that could have
2196// changed as a result.
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002197void NewGVN::markPhiOfOpsChanged(const Expression *E) {
2198 touchAndErase(ExpressionToPhiOfOps, E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002199}
Daniel Berlin0207cca2017-05-21 23:41:56 +00002200
Davide Italiano7e274e02016-12-22 16:03:48 +00002201// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002202void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002203 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002204 // TOP.
Daniel Berline021d2d2017-05-19 20:22:20 +00002205
2206 CongruenceClass *IClass = ValueToClass.lookup(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002207 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002208 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002209 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002210
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002211 CongruenceClass *EClass = nullptr;
Daniel Berlin02c6b172017-01-02 18:00:53 +00002212 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002213 EClass = ValueToClass.lookup(VE->getVariableValue());
Daniel Berline021d2d2017-05-19 20:22:20 +00002214 } else if (isa<DeadExpression>(E)) {
2215 EClass = TOPClass;
2216 }
2217 if (!EClass) {
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002218 auto lookupResult = ExpressionToClass.insert({E, nullptr});
Davide Italiano7e274e02016-12-22 16:03:48 +00002219
2220 // If it's not in the value table, create a new congruence class.
2221 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002222 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002223 auto place = lookupResult.first;
2224 place->second = NewClass;
2225
2226 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002227 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002228 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002229 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2230 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002231 NewClass->setLeader(SI);
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002232 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002233 // The RepMemoryAccess field will be filled in properly by the
2234 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002235 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002236 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002237 }
2238 assert(!isa<VariableExpression>(E) &&
2239 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002240
2241 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002242 DEBUG(dbgs() << "Created new congruence class for " << *I
Daniel Berlina8236562017-04-07 18:38:09 +00002243 << " using expression " << *E << " at " << NewClass->getID()
2244 << " and leader " << *(NewClass->getLeader()));
2245 if (NewClass->getStoredValue())
2246 DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
Daniel Berlin26addef2017-01-20 21:04:30 +00002247 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002248 } else {
2249 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002250 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002251 assert((isa<Constant>(EClass->getLeader()) ||
2252 (EClass->getStoredValue() &&
2253 isa<Constant>(EClass->getStoredValue()))) &&
2254 "Any class with a constant expression should have a "
2255 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002256
Davide Italiano7e274e02016-12-22 16:03:48 +00002257 assert(EClass && "Somehow don't have an eclass");
2258
Daniel Berlin1316a942017-04-06 18:52:50 +00002259 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002260 }
2261 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002262 bool ClassChanged = IClass != EClass;
2263 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002264 if (ClassChanged || LeaderChanged) {
Daniel Berlina8236562017-04-07 18:38:09 +00002265 DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00002266 << "\n");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002267 if (ClassChanged) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002268 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002269 markPhiOfOpsChanged(E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002270 }
2271
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002272 markUsersTouched(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002273 if (MemoryAccess *MA = getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002274 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002275 if (auto *CI = dyn_cast<CmpInst>(I))
2276 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002277 }
Daniel Berlin45403572017-05-16 19:58:47 +00002278 // If we changed the class of the store, we want to ensure nothing finds the
2279 // old store expression. In particular, loads do not compare against stored
2280 // value, so they will find old store expressions (and associated class
2281 // mappings) if we leave them in the table.
Davide Italianoee49f492017-05-19 04:06:10 +00002282 if (ClassChanged && isa<StoreInst>(I)) {
Daniel Berlin45403572017-05-16 19:58:47 +00002283 auto *OldE = ValueToExpression.lookup(I);
2284 // It could just be that the old class died. We don't want to erase it if we
2285 // just moved classes.
Daniel Berlineafdd862017-06-06 17:15:28 +00002286 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
2287 // Erase this as an exact expression to ensure we don't erase expressions
2288 // equivalent to it.
2289 auto Iter = ExpressionToClass.find_as(ExactEqualsExpression(*OldE));
2290 if (Iter != ExpressionToClass.end())
2291 ExpressionToClass.erase(Iter);
2292 }
Daniel Berlin45403572017-05-16 19:58:47 +00002293 }
2294 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002295}
2296
2297// Process the fact that Edge (from, to) is reachable, including marking
2298// any newly reachable blocks and instructions for processing.
2299void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2300 // Check if the Edge was reachable before.
2301 if (ReachableEdges.insert({From, To}).second) {
2302 // If this block wasn't reachable before, all instructions are touched.
2303 if (ReachableBlocks.insert(To).second) {
2304 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2305 const auto &InstRange = BlockInstRange.lookup(To);
2306 TouchedInstructions.set(InstRange.first, InstRange.second);
2307 } else {
2308 DEBUG(dbgs() << "Block " << getBlockName(To)
2309 << " was reachable, but new edge {" << getBlockName(From)
2310 << "," << getBlockName(To) << "} to it found\n");
2311
2312 // We've made an edge reachable to an existing block, which may
2313 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2314 // they are the only thing that depend on new edges. Anything using their
2315 // values will get propagated to if necessary.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002316 if (MemoryAccess *MemPhi = getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002317 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002318
Davide Italiano7e274e02016-12-22 16:03:48 +00002319 auto BI = To->begin();
2320 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002321 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00002322 ++BI;
2323 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00002324 for_each_found(PHIOfOpsPHIs, To, [&](const PHINode *I) {
2325 TouchedInstructions.set(InstrToDFSNum(I));
2326 });
Davide Italiano7e274e02016-12-22 16:03:48 +00002327 }
2328 }
2329}
2330
2331// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2332// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002333Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002334 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002335 if (isa<Constant>(Result))
2336 return Result;
2337 return nullptr;
2338}
2339
2340// Process the outgoing edges of a block for reachability.
2341void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2342 // Evaluate reachability of terminator instruction.
2343 BranchInst *BR;
2344 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2345 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002346 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002347 if (!CondEvaluated) {
2348 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002349 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002350 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2351 CondEvaluated = CE->getConstantValue();
2352 }
2353 } else if (isa<ConstantInt>(Cond)) {
2354 CondEvaluated = Cond;
2355 }
2356 }
2357 ConstantInt *CI;
2358 BasicBlock *TrueSucc = BR->getSuccessor(0);
2359 BasicBlock *FalseSucc = BR->getSuccessor(1);
2360 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2361 if (CI->isOne()) {
2362 DEBUG(dbgs() << "Condition for Terminator " << *TI
2363 << " evaluated to true\n");
2364 updateReachableEdge(B, TrueSucc);
2365 } else if (CI->isZero()) {
2366 DEBUG(dbgs() << "Condition for Terminator " << *TI
2367 << " evaluated to false\n");
2368 updateReachableEdge(B, FalseSucc);
2369 }
2370 } else {
2371 updateReachableEdge(B, TrueSucc);
2372 updateReachableEdge(B, FalseSucc);
2373 }
2374 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2375 // For switches, propagate the case values into the case
2376 // destinations.
2377
2378 // Remember how many outgoing edges there are to every successor.
2379 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2380
Davide Italiano7e274e02016-12-22 16:03:48 +00002381 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002382 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002383 // See if we were able to turn this switch statement into a constant.
2384 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002385 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002386 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002387 auto Case = *SI->findCaseValue(CondVal);
2388 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002389 // We proved the value is outside of the range of the case.
2390 // We can't do anything other than mark the default dest as reachable,
2391 // and go home.
2392 updateReachableEdge(B, SI->getDefaultDest());
2393 return;
2394 }
2395 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002396 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002397 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002398 } else {
2399 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2400 BasicBlock *TargetBlock = SI->getSuccessor(i);
2401 ++SwitchEdges[TargetBlock];
2402 updateReachableEdge(B, TargetBlock);
2403 }
2404 }
2405 } else {
2406 // Otherwise this is either unconditional, or a type we have no
2407 // idea about. Just mark successors as reachable.
2408 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2409 BasicBlock *TargetBlock = TI->getSuccessor(i);
2410 updateReachableEdge(B, TargetBlock);
2411 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002412
2413 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002414 // equivalent only to itself.
2415 //
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002416 auto *MA = getMemoryAccess(TI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002417 if (MA && !isa<MemoryUse>(MA)) {
2418 auto *CC = ensureLeaderOfMemoryClass(MA);
2419 if (setMemoryClass(MA, CC))
2420 markMemoryUsersTouched(MA);
2421 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002422 }
2423}
2424
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002425void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
2426 Instruction *ExistingValue) {
2427 InstrDFS[Op] = InstrToDFSNum(ExistingValue);
2428 AllTempInstructions.insert(Op);
2429 PHIOfOpsPHIs[BB].push_back(Op);
2430 TempToBlock[Op] = BB;
2431 if (ExistingValue)
2432 RealToTemp[ExistingValue] = Op;
2433}
2434
2435static bool okayForPHIOfOps(const Instruction *I) {
2436 return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
2437 isa<LoadInst>(I);
2438}
2439
2440// When we see an instruction that is an op of phis, generate the equivalent phi
2441// of ops form.
2442const Expression *
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002443NewGVN::makePossiblePhiOfOps(Instruction *I,
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002444 SmallPtrSetImpl<Value *> &Visited) {
2445 if (!okayForPHIOfOps(I))
2446 return nullptr;
2447
2448 if (!Visited.insert(I).second)
2449 return nullptr;
2450 // For now, we require the instruction be cycle free because we don't
2451 // *always* create a phi of ops for instructions that could be done as phi
2452 // of ops, we only do it if we think it is useful. If we did do it all the
2453 // time, we could remove the cycle free check.
2454 if (!isCycleFree(I))
2455 return nullptr;
2456
2457 unsigned IDFSNum = InstrToDFSNum(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002458 SmallPtrSet<const Value *, 8> ProcessedPHIs;
2459 // TODO: We don't do phi translation on memory accesses because it's
2460 // complicated. For a load, we'd need to be able to simulate a new memoryuse,
2461 // which we don't have a good way of doing ATM.
2462 auto *MemAccess = getMemoryAccess(I);
2463 // If the memory operation is defined by a memory operation this block that
2464 // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
2465 // can't help, as it would still be killed by that memory operation.
2466 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2467 MemAccess->getDefiningAccess()->getBlock() == I->getParent())
2468 return nullptr;
2469
2470 // Convert op of phis to phi of ops
2471 for (auto &Op : I->operands()) {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002472 // TODO: We can't handle expressions that must be recursively translated
2473 // IE
2474 // a = phi (b, c)
2475 // f = use a
2476 // g = f + phi of something
2477 // To properly make a phi of ops for g, we'd have to properly translate and
2478 // use the instruction for f. We should add this by splitting out the
2479 // instruction creation we do below.
2480 if (isa<Instruction>(Op) && PHINodeUses.count(cast<Instruction>(Op)))
2481 return nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002482 if (!isa<PHINode>(Op))
2483 continue;
2484 auto *OpPHI = cast<PHINode>(Op);
2485 // No point in doing this for one-operand phis.
2486 if (OpPHI->getNumOperands() == 1)
2487 continue;
2488 if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
2489 return nullptr;
2490 SmallVector<std::pair<Value *, BasicBlock *>, 4> Ops;
2491 auto *PHIBlock = getBlockForValue(OpPHI);
2492 for (auto PredBB : OpPHI->blocks()) {
2493 Value *FoundVal = nullptr;
2494 // We could just skip unreachable edges entirely but it's tricky to do
2495 // with rewriting existing phi nodes.
2496 if (ReachableEdges.count({PredBB, PHIBlock})) {
2497 // Clone the instruction, create an expression from it, and see if we
2498 // have a leader.
2499 Instruction *ValueOp = I->clone();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002500 if (MemAccess)
Daniel Berlinc8ed4042017-05-30 06:42:29 +00002501 TempToMemory.insert({ValueOp, MemAccess});
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002502
2503 for (auto &Op : ValueOp->operands()) {
2504 Op = Op->DoPHITranslation(PHIBlock, PredBB);
2505 // When this operand changes, it could change whether there is a
2506 // leader for us or not.
2507 addAdditionalUsers(Op, I);
2508 }
2509 // Make sure it's marked as a temporary instruction.
2510 AllTempInstructions.insert(ValueOp);
2511 // and make sure anything that tries to add it's DFS number is
2512 // redirected to the instruction we are making a phi of ops
2513 // for.
2514 InstrDFS.insert({ValueOp, IDFSNum});
2515 const Expression *E = performSymbolicEvaluation(ValueOp, Visited);
2516 InstrDFS.erase(ValueOp);
2517 AllTempInstructions.erase(ValueOp);
2518 ValueOp->deleteValue();
2519 if (MemAccess)
Daniel Berlinc8ed4042017-05-30 06:42:29 +00002520 TempToMemory.erase(ValueOp);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002521 if (!E)
2522 return nullptr;
2523 FoundVal = findPhiOfOpsLeader(E, PredBB);
2524 if (!FoundVal) {
2525 ExpressionToPhiOfOps[E].insert(I);
2526 return nullptr;
2527 }
2528 if (auto *SI = dyn_cast<StoreInst>(FoundVal))
2529 FoundVal = SI->getValueOperand();
2530 } else {
2531 DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
2532 << getBlockName(PredBB)
2533 << " because the block is unreachable\n");
2534 FoundVal = UndefValue::get(I->getType());
2535 }
2536
2537 Ops.push_back({FoundVal, PredBB});
2538 DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
2539 << getBlockName(PredBB) << "\n");
2540 }
2541 auto *ValuePHI = RealToTemp.lookup(I);
2542 bool NewPHI = false;
2543 if (!ValuePHI) {
2544 ValuePHI = PHINode::Create(I->getType(), OpPHI->getNumOperands());
2545 addPhiOfOps(ValuePHI, PHIBlock, I);
2546 NewPHI = true;
2547 NumGVNPHIOfOpsCreated++;
2548 }
2549 if (NewPHI) {
2550 for (auto PHIOp : Ops)
2551 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2552 } else {
2553 unsigned int i = 0;
2554 for (auto PHIOp : Ops) {
2555 ValuePHI->setIncomingValue(i, PHIOp.first);
2556 ValuePHI->setIncomingBlock(i, PHIOp.second);
2557 ++i;
2558 }
2559 }
2560
2561 DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
2562 << "\n");
2563 return performSymbolicEvaluation(ValuePHI, Visited);
2564 }
2565 return nullptr;
2566}
2567
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002568// The algorithm initially places the values of the routine in the TOP
2569// congruence class. The leader of TOP is the undetermined value `undef`.
2570// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002571void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002572 NextCongruenceNum = 0;
2573
2574 // Note that even though we use the live on entry def as a representative
2575 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2576 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2577 // should be checking whether the MemoryAccess is top if we want to know if it
2578 // is equivalent to everything. Otherwise, what this really signifies is that
2579 // the access "it reaches all the way back to the beginning of the function"
2580
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002581 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002582 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002583 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002584 // The live on entry def gets put into it's own class
2585 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2586 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002587
Daniel Berlinec9deb72017-04-18 17:06:11 +00002588 for (auto DTN : nodes(DT)) {
2589 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002590 // All MemoryAccesses are equivalent to live on entry to start. They must
2591 // be initialized to something so that initial changes are noticed. For
2592 // the maximal answer, we initialize them all to be the same as
2593 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002594 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002595 if (MemoryBlockDefs)
2596 for (const auto &Def : *MemoryBlockDefs) {
2597 MemoryAccessToClass[&Def] = TOPClass;
2598 auto *MD = dyn_cast<MemoryDef>(&Def);
2599 // Insert the memory phis into the member list.
2600 if (!MD) {
2601 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002602 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002603 MemoryPhiState.insert({MP, MPS_TOP});
2604 }
2605
2606 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002607 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002608 }
Daniel Berlinec9deb72017-04-18 17:06:11 +00002609 for (auto &I : *BB) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002610 // TODO: Move to helper
2611 if (isa<PHINode>(&I))
2612 for (auto *U : I.users())
2613 if (auto *UInst = dyn_cast<Instruction>(U))
2614 if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
2615 PHINodeUses.insert(UInst);
Daniel Berlin22a4a012017-02-11 15:20:15 +00002616 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002617 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002618 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2619 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002620 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002621 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002622 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002623 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002624
2625 // Initialize arguments to be in their own unique congruence classes
2626 for (auto &FA : F.args())
2627 createSingletonCongruenceClass(&FA);
2628}
2629
2630void NewGVN::cleanupTables() {
2631 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Daniel Berlina8236562017-04-07 18:38:09 +00002632 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2633 << " has " << CongruenceClasses[i]->size() << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002634 // Make sure we delete the congruence class (probably worth switching to
2635 // a unique_ptr at some point.
2636 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002637 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002638 }
2639
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002640 // Destroy the value expressions
2641 SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
2642 AllTempInstructions.end());
2643 AllTempInstructions.clear();
2644
2645 // We have to drop all references for everything first, so there are no uses
2646 // left as we delete them.
2647 for (auto *I : TempInst) {
2648 I->dropAllReferences();
2649 }
2650
2651 while (!TempInst.empty()) {
2652 auto *I = TempInst.back();
2653 TempInst.pop_back();
2654 I->deleteValue();
2655 }
2656
Davide Italiano7e274e02016-12-22 16:03:48 +00002657 ValueToClass.clear();
2658 ArgRecycler.clear(ExpressionAllocator);
2659 ExpressionAllocator.Reset();
2660 CongruenceClasses.clear();
2661 ExpressionToClass.clear();
2662 ValueToExpression.clear();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002663 RealToTemp.clear();
2664 AdditionalUsers.clear();
2665 ExpressionToPhiOfOps.clear();
2666 TempToBlock.clear();
2667 TempToMemory.clear();
2668 PHIOfOpsPHIs.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002669 ReachableBlocks.clear();
2670 ReachableEdges.clear();
2671#ifndef NDEBUG
2672 ProcessedCount.clear();
2673#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002674 InstrDFS.clear();
2675 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002676 DFSToInstr.clear();
2677 BlockInstRange.clear();
2678 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002679 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002680 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002681 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002682}
2683
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002684// Assign local DFS number mapping to instructions, and leave space for Value
2685// PHI's.
Davide Italiano7e274e02016-12-22 16:03:48 +00002686std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2687 unsigned Start) {
2688 unsigned End = Start;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002689 if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002690 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002691 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002692 }
2693
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002694 // Then the real block goes next.
Davide Italiano7e274e02016-12-22 16:03:48 +00002695 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002696 // There's no need to call isInstructionTriviallyDead more than once on
2697 // an instruction. Therefore, once we know that an instruction is dead
2698 // we change its DFS number so that it doesn't get value numbered.
2699 if (isInstructionTriviallyDead(&I, TLI)) {
2700 InstrDFS[&I] = 0;
2701 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2702 markInstructionForDeletion(&I);
2703 continue;
2704 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002705 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002706 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002707 }
2708
2709 // All of the range functions taken half-open ranges (open on the end side).
2710 // So we do not subtract one from count, because at this point it is one
2711 // greater than the last instruction.
2712 return std::make_pair(Start, End);
2713}
2714
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002715void NewGVN::updateProcessedCount(const Value *V) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002716#ifndef NDEBUG
2717 if (ProcessedCount.count(V) == 0) {
2718 ProcessedCount.insert({V, 1});
2719 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002720 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002721 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002722 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002723 }
2724#endif
2725}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002726// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2727void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2728 // If all the arguments are the same, the MemoryPhi has the same value as the
Daniel Berlind130b6c2017-05-21 23:41:58 +00002729 // argument. Filter out unreachable blocks and self phis from our operands.
2730 // TODO: We could do cycle-checking on the memory phis to allow valueizing for
2731 // self-phi checking.
Daniel Berlin41b39162017-03-18 15:41:36 +00002732 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002733 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlind130b6c2017-05-21 23:41:58 +00002734 return cast<MemoryAccess>(U) != MP &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002735 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002736 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002737 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002738 // If all that is left is nothing, our memoryphi is undef. We keep it as
2739 // InitialClass. Note: The only case this should happen is if we have at
2740 // least one self-argument.
2741 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002742 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002743 markMemoryUsersTouched(MP);
2744 return;
2745 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002746
2747 // Transform the remaining operands into operand leaders.
2748 // FIXME: mapped_iterator should have a range version.
2749 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002750 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002751 };
2752 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2753 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2754
2755 // and now check if all the elements are equal.
2756 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002757 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002758 ++MappedBegin;
2759 bool AllEqual = std::all_of(
2760 MappedBegin, MappedEnd,
2761 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2762
2763 if (AllEqual)
2764 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2765 else
2766 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002767 // If it's equal to something, it's in that class. Otherwise, it has to be in
2768 // a class where it is the leader (other things may be equivalent to it, but
2769 // it needs to start off in its own class, which means it must have been the
2770 // leader, and it can't have stopped being the leader because it was never
2771 // removed).
2772 CongruenceClass *CC =
2773 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2774 auto OldState = MemoryPhiState.lookup(MP);
2775 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2776 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2777 MemoryPhiState[MP] = NewState;
2778 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002779 markMemoryUsersTouched(MP);
2780}
2781
2782// Value number a single instruction, symbolically evaluating, performing
2783// congruence finding, and updating mappings.
2784void NewGVN::valueNumberInstruction(Instruction *I) {
2785 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002786 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002787 const Expression *Symbolized = nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002788 SmallPtrSet<Value *, 2> Visited;
Daniel Berlin283a6082017-03-01 19:59:26 +00002789 if (DebugCounter::shouldExecute(VNCounter)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002790 Symbolized = performSymbolicEvaluation(I, Visited);
2791 // Make a phi of ops if necessary
2792 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
2793 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002794 auto *PHIE = makePossiblePhiOfOps(I, Visited);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002795 if (PHIE)
2796 Symbolized = PHIE;
2797 }
2798
Daniel Berlin283a6082017-03-01 19:59:26 +00002799 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002800 // Mark the instruction as unused so we don't value number it again.
2801 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002802 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002803 // If we couldn't come up with a symbolic expression, use the unknown
2804 // expression
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002805 if (Symbolized == nullptr)
Daniel Berlin02c6b172017-01-02 18:00:53 +00002806 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002807 performCongruenceFinding(I, Symbolized);
2808 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002809 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002810 // don't currently understand. We don't place non-value producing
2811 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002812 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002813 auto *Symbolized = createUnknownExpression(I);
2814 performCongruenceFinding(I, Symbolized);
2815 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002816 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2817 }
2818}
Davide Italiano7e274e02016-12-22 16:03:48 +00002819
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002820// Check if there is a path, using single or equal argument phi nodes, from
2821// First to Second.
Davide Italianoeab0de22017-05-18 23:22:44 +00002822bool NewGVN::singleReachablePHIPath(
2823 SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
2824 const MemoryAccess *Second) const {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002825 if (First == Second)
2826 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002827 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002828 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002829
Davide Italianoeab0de22017-05-18 23:22:44 +00002830 // This is not perfect, but as we're just verifying here, we can live with
2831 // the loss of precision. The real solution would be that of doing strongly
2832 // connected component finding in this routine, and it's probably not worth
2833 // the complexity for the time being. So, we just keep a set of visited
2834 // MemoryAccess and return true when we hit a cycle.
2835 if (Visited.count(First))
2836 return true;
2837 Visited.insert(First);
2838
Daniel Berlin871ecd92017-04-01 09:44:24 +00002839 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002840 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002841 if (ChainDef == Second)
2842 return true;
2843 if (MSSA->isLiveOnEntryDef(ChainDef))
2844 return false;
2845 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002846 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002847 auto *MP = cast<MemoryPhi>(EndDef);
2848 auto ReachableOperandPred = [&](const Use &U) {
2849 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2850 };
2851 auto FilteredPhiArgs =
2852 make_filter_range(MP->operands(), ReachableOperandPred);
2853 SmallVector<const Value *, 32> OperandList;
2854 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2855 std::back_inserter(OperandList));
2856 bool Okay = OperandList.size() == 1;
2857 if (!Okay)
2858 Okay =
2859 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2860 if (Okay)
Davide Italianoeab0de22017-05-18 23:22:44 +00002861 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
2862 Second);
Daniel Berlin871ecd92017-04-01 09:44:24 +00002863 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002864}
2865
Daniel Berlin589cecc2017-01-02 18:00:46 +00002866// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002867// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00002868// subject to very rare false negatives. It is only useful for
2869// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002870void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00002871#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002872 // Verify that the memory table equivalence and memory member set match
2873 for (const auto *CC : CongruenceClasses) {
2874 if (CC == TOPClass || CC->isDead())
2875 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002876 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00002877 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002878 "Any class with a store as a leader should have a "
2879 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00002880 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002881 "Any congruence class with a store should have a "
2882 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00002883 }
2884
Daniel Berlina8236562017-04-07 18:38:09 +00002885 if (CC->getMemoryLeader())
2886 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00002887 "Representative MemoryAccess does not appear to be reverse "
2888 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00002889 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002890 assert(MemoryAccessToClass.lookup(M) == CC &&
2891 "Memory member does not appear to be reverse mapped properly");
2892 }
2893
2894 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00002895 // congruence class.
2896
2897 // Filter out the unreachable and trivially dead entries, because they may
2898 // never have been updated if the instructions were not processed.
2899 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002900 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002901 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00002902 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2903 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00002904 return false;
2905 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2906 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Davide Italiano6e7a2122017-05-15 18:50:53 +00002907
2908 // We could have phi nodes which operands are all trivially dead,
2909 // so we don't process them.
2910 if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
2911 for (auto &U : MemPHI->incoming_values()) {
2912 if (Instruction *I = dyn_cast<Instruction>(U.get())) {
2913 if (!isInstructionTriviallyDead(I))
2914 return true;
2915 }
2916 }
2917 return false;
2918 }
2919
Daniel Berlin589cecc2017-01-02 18:00:46 +00002920 return true;
2921 };
2922
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002923 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002924 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002925 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002926 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italianoeab0de22017-05-18 23:22:44 +00002927 if (FirstMUD && SecondMUD) {
2928 SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
2929 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00002930 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2931 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2932 "The instructions for these memory operations should have "
2933 "been in the same congruence class or reachable through"
2934 "a single argument phi");
Davide Italianoeab0de22017-05-18 23:22:44 +00002935 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002936 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002937 // We can only sanely verify that MemoryDefs in the operand list all have
2938 // the same class.
2939 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00002940 return ReachableEdges.count(
2941 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00002942 isa<MemoryDef>(U);
2943
2944 };
2945 // All arguments should in the same class, ignoring unreachable arguments
2946 auto FilteredPhiArgs =
2947 make_filter_range(FirstMP->operands(), ReachableOperandPred);
2948 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2949 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2950 std::back_inserter(PhiOpClasses), [&](const Use &U) {
2951 const MemoryDef *MD = cast<MemoryDef>(U);
2952 return ValueToClass.lookup(MD->getMemoryInst());
2953 });
2954 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2955 PhiOpClasses.begin()) &&
2956 "All MemoryPhi arguments should be in the same class");
2957 }
2958 }
Davide Italianoe9781e72017-03-25 02:40:02 +00002959#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00002960}
2961
Daniel Berlin06329a92017-03-18 15:41:40 +00002962// Verify that the sparse propagation we did actually found the maximal fixpoint
2963// We do this by storing the value to class mapping, touching all instructions,
2964// and redoing the iteration to see if anything changed.
2965void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00002966#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002967 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00002968 if (DebugCounter::isCounterSet(VNCounter))
2969 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2970
2971 // Note that we have to store the actual classes, as we may change existing
2972 // classes during iteration. This is because our memory iteration propagation
2973 // is not perfect, and so may waste a little work. But it should generate
2974 // exactly the same congruence classes we have now, with different IDs.
2975 std::map<const Value *, CongruenceClass> BeforeIteration;
2976
2977 for (auto &KV : ValueToClass) {
2978 if (auto *I = dyn_cast<Instruction>(KV.first))
2979 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002980 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002981 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002982 BeforeIteration.insert({KV.first, *KV.second});
2983 }
2984
2985 TouchedInstructions.set();
2986 TouchedInstructions.reset(0);
2987 iterateTouchedInstructions();
2988 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2989 EqualClasses;
2990 for (const auto &KV : ValueToClass) {
2991 if (auto *I = dyn_cast<Instruction>(KV.first))
2992 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002993 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00002994 continue;
2995 // We could sink these uses, but i think this adds a bit of clarity here as
2996 // to what we are comparing.
2997 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2998 auto *AfterCC = KV.second;
2999 // Note that the classes can't change at this point, so we memoize the set
3000 // that are equal.
3001 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00003002 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00003003 "Value number changed after main loop completed!");
3004 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00003005 }
3006 }
3007#endif
3008}
3009
Daniel Berlin45403572017-05-16 19:58:47 +00003010// Verify that for each store expression in the expression to class mapping,
3011// only the latest appears, and multiple ones do not appear.
3012// Because loads do not use the stored value when doing equality with stores,
3013// if we don't erase the old store expressions from the table, a load can find
3014// a no-longer valid StoreExpression.
3015void NewGVN::verifyStoreExpressions() const {
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003016#ifndef NDEBUG
Daniel Berlin45403572017-05-16 19:58:47 +00003017 DenseSet<std::pair<const Value *, const Value *>> StoreExpressionSet;
3018 for (const auto &KV : ExpressionToClass) {
3019 if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3020 // Make sure a version that will conflict with loads is not already there
3021 auto Res =
3022 StoreExpressionSet.insert({SE->getOperand(0), SE->getMemoryLeader()});
3023 assert(Res.second &&
3024 "Stored expression conflict exists in expression table");
3025 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3026 assert(ValueExpr && ValueExpr->equals(*SE) &&
3027 "StoreExpression in ExpressionToClass is not latest "
3028 "StoreExpression for value");
3029 }
3030 }
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003031#endif
Daniel Berlin45403572017-05-16 19:58:47 +00003032}
3033
Daniel Berlin06329a92017-03-18 15:41:40 +00003034// This is the main value numbering loop, it iterates over the initial touched
3035// instruction set, propagating value numbers, marking things touched, etc,
3036// until the set of touched instructions is completely empty.
3037void NewGVN::iterateTouchedInstructions() {
3038 unsigned int Iterations = 0;
3039 // Figure out where touchedinstructions starts
3040 int FirstInstr = TouchedInstructions.find_first();
3041 // Nothing set, nothing to iterate, just return.
3042 if (FirstInstr == -1)
3043 return;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003044 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00003045 while (TouchedInstructions.any()) {
3046 ++Iterations;
3047 // Walk through all the instructions in all the blocks in RPO.
3048 // TODO: As we hit a new block, we should push and pop equalities into a
3049 // table lookupOperandLeader can use, to catch things PredicateInfo
3050 // might miss, like edge-only equivalences.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003051 for (unsigned InstrNum : TouchedInstructions.set_bits()) {
Daniel Berlin06329a92017-03-18 15:41:40 +00003052
3053 // This instruction was found to be dead. We don't bother looking
3054 // at it again.
3055 if (InstrNum == 0) {
3056 TouchedInstructions.reset(InstrNum);
3057 continue;
3058 }
3059
Daniel Berlin21279bd2017-04-06 18:52:58 +00003060 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003061 const BasicBlock *CurrBlock = getBlockForValue(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003062
3063 // If we hit a new block, do reachability processing.
3064 if (CurrBlock != LastBlock) {
3065 LastBlock = CurrBlock;
3066 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3067 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3068
3069 // If it's not reachable, erase any touched instructions and move on.
3070 if (!BlockReachable) {
3071 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3072 DEBUG(dbgs() << "Skipping instructions in block "
3073 << getBlockName(CurrBlock)
3074 << " because it is unreachable\n");
3075 continue;
3076 }
3077 updateProcessedCount(CurrBlock);
3078 }
Daniel Berlineafdd862017-06-06 17:15:28 +00003079 // Reset after processing (because we may mark ourselves as touched when
3080 // we propagate equalities).
3081 TouchedInstructions.reset(InstrNum);
Daniel Berlin06329a92017-03-18 15:41:40 +00003082
3083 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
3084 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
3085 valueNumberMemoryPhi(MP);
3086 } else if (auto *I = dyn_cast<Instruction>(V)) {
3087 valueNumberInstruction(I);
3088 } else {
3089 llvm_unreachable("Should have been a MemoryPhi or Instruction");
3090 }
3091 updateProcessedCount(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003092 }
3093 }
3094 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
3095}
3096
Daniel Berlin85f91b02016-12-26 20:06:58 +00003097// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00003098bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00003099 if (DebugCounter::isCounterSet(VNCounter))
3100 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00003101 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00003102 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00003103 MSSAWalker = MSSA->getWalker();
Daniel Berline021d2d2017-05-19 20:22:20 +00003104 SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00003105
3106 // Count number of instructions for sizing of hash tables, and come
3107 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003108 unsigned ICount = 1;
3109 // Add an empty instruction to account for the fact that we start at 1
3110 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00003111 // Note: We want ideal RPO traversal of the blocks, which is not quite the
3112 // same as dominator tree order, particularly with regard whether backedges
3113 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00003114 // If we visit in the wrong order, we will end up performing N times as many
3115 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00003116 // The dominator tree does guarantee that, for a given dom tree node, it's
3117 // parent must occur before it in the RPO ordering. Thus, we only need to sort
3118 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00003119 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00003120 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00003121 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003122 auto *Node = DT->getNode(B);
3123 assert(Node && "RPO and Dominator tree should have same reachability");
3124 RPOOrdering[Node] = ++Counter;
3125 }
3126 // Sort dominator tree children arrays into RPO.
3127 for (auto &B : RPOT) {
3128 auto *Node = DT->getNode(B);
3129 if (Node->getChildren().size() > 1)
3130 std::sort(Node->begin(), Node->end(),
Daniel Berlin2f72b192017-04-14 02:53:37 +00003131 [&](const DomTreeNode *A, const DomTreeNode *B) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003132 return RPOOrdering[A] < RPOOrdering[B];
3133 });
3134 }
3135
3136 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00003137 for (auto DTN : depth_first(DT->getRootNode())) {
3138 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00003139 const auto &BlockRange = assignDFSNumbers(B, ICount);
3140 BlockInstRange.insert({B, BlockRange});
3141 ICount += BlockRange.second - BlockRange.first;
3142 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003143 initializeCongruenceClasses(F);
Davide Italiano7e274e02016-12-22 16:03:48 +00003144
Daniel Berline0bd37e2016-12-29 22:15:12 +00003145 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003146 // Ensure we don't end up resizing the expressionToClass map, as
3147 // that can be quite expensive. At most, we have one expression per
3148 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003149 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003150
3151 // Initialize the touched instructions to include the entry block.
3152 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
3153 TouchedInstructions.set(InstRange.first, InstRange.second);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003154 DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
3155 << " marked reachable\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003156 ReachableBlocks.insert(&F.getEntryBlock());
3157
Daniel Berlin06329a92017-03-18 15:41:40 +00003158 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00003159 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00003160 verifyIterationSettled(F);
Daniel Berlin45403572017-05-16 19:58:47 +00003161 verifyStoreExpressions();
Daniel Berlinf7d95802017-02-18 23:06:50 +00003162
Davide Italiano7e274e02016-12-22 16:03:48 +00003163 Changed |= eliminateInstructions(F);
3164
3165 // Delete all instructions marked for deletion.
3166 for (Instruction *ToErase : InstructionsToErase) {
3167 if (!ToErase->use_empty())
3168 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
3169
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003170 if (ToErase->getParent())
3171 ToErase->eraseFromParent();
Davide Italiano7e274e02016-12-22 16:03:48 +00003172 }
3173
3174 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003175 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
3176 return !ReachableBlocks.count(&BB);
3177 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003178
3179 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
3180 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00003181 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003182 deleteInstructionsInBlock(&BB);
3183 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003184 }
3185
3186 cleanupTables();
3187 return Changed;
3188}
3189
Davide Italiano7e274e02016-12-22 16:03:48 +00003190struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003191 int DFSIn = 0;
3192 int DFSOut = 0;
3193 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003194 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003195 // The bool in the Def tells us whether the Def is the stored value of a
3196 // store.
3197 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003198 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00003199 bool operator<(const ValueDFS &Other) const {
3200 // It's not enough that any given field be less than - we have sets
3201 // of fields that need to be evaluated together to give a proper ordering.
3202 // For example, if you have;
3203 // DFS (1, 3)
3204 // Val 0
3205 // DFS (1, 2)
3206 // Val 50
3207 // We want the second to be less than the first, but if we just go field
3208 // by field, we will get to Val 0 < Val 50 and say the first is less than
3209 // the second. We only want it to be less than if the DFS orders are equal.
3210 //
3211 // Each LLVM instruction only produces one value, and thus the lowest-level
3212 // differentiator that really matters for the stack (and what we use as as a
3213 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003214 // Everything else in the structure is instruction level, and only affects
3215 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00003216 //
3217 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
3218 // the order of replacement of uses does not matter.
3219 // IE given,
3220 // a = 5
3221 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00003222 // When you hit b, you will have two valuedfs with the same dfsin, out, and
3223 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00003224 // The .val will be the same as well.
3225 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003226 // You will replace both, and it does not matter what order you replace them
3227 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
3228 // operand 2).
3229 // Similarly for the case of same dfsin, dfsout, localnum, but different
3230 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00003231 // a = 5
3232 // b = 6
3233 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00003234 // in c, we will a valuedfs for a, and one for b,with everything the same
3235 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00003236 // It does not matter what order we replace these operands in.
3237 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003238 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3239 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00003240 Other.U);
3241 }
3242};
3243
Daniel Berlinc4796862017-01-27 02:37:11 +00003244// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003245// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00003246// reachable uses for each value is stored in UseCount, and instructions that
3247// seem
3248// dead (have no non-dead uses) are stored in ProbablyDead.
3249void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00003250 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00003251 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00003252 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00003253 for (auto D : Dense) {
3254 // First add the value.
3255 BasicBlock *BB = getBlockForValue(D);
3256 // Constants are handled prior to ever calling this function, so
3257 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00003258 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003259 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003260 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003261 VDDef.DFSIn = DomNode->getDFSNumIn();
3262 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003263 // If it's a store, use the leader of the value operand, if it's always
3264 // available, or the value operand. TODO: We could do dominance checks to
3265 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00003266 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00003267 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003268 if (alwaysAvailable(Leader)) {
3269 VDDef.Def.setPointer(Leader);
3270 } else {
3271 VDDef.Def.setPointer(SI->getValueOperand());
3272 VDDef.Def.setInt(true);
3273 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003274 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003275 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00003276 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003277 assert(isa<Instruction>(D) &&
3278 "The dense set member should always be an instruction");
Daniel Berline3e69e12017-03-10 00:32:33 +00003279 Instruction *Def = cast<Instruction>(D);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003280 VDDef.LocalNum = InstrToDFSNum(D);
3281 DFSOrderedSet.push_back(VDDef);
3282 // If there is a phi node equivalent, add it
3283 if (auto *PN = RealToTemp.lookup(Def)) {
3284 auto *PHIE =
3285 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3286 if (PHIE) {
3287 VDDef.Def.setInt(false);
3288 VDDef.Def.setPointer(PN);
3289 VDDef.LocalNum = 0;
3290 DFSOrderedSet.push_back(VDDef);
3291 }
3292 }
3293
Daniel Berline3e69e12017-03-10 00:32:33 +00003294 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003295 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00003296 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003297 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003298 // Don't try to replace into dead uses
3299 if (InstructionsToErase.count(I))
3300 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003301 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00003302 // Put the phi node uses in the incoming block.
3303 BasicBlock *IBlock;
3304 if (auto *P = dyn_cast<PHINode>(I)) {
3305 IBlock = P->getIncomingBlock(U);
3306 // Make phi node users appear last in the incoming block
3307 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003308 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00003309 } else {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003310 IBlock = getBlockForValue(I);
Daniel Berlin21279bd2017-04-06 18:52:58 +00003311 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003312 }
Davide Italianoccbbc832017-01-26 00:42:42 +00003313
3314 // Skip uses in unreachable blocks, as we're going
3315 // to delete them.
3316 if (ReachableBlocks.count(IBlock) == 0)
3317 continue;
3318
Daniel Berlinb66164c2017-01-14 00:24:23 +00003319 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003320 VDUse.DFSIn = DomNode->getDFSNumIn();
3321 VDUse.DFSOut = DomNode->getDFSNumOut();
3322 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00003323 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003324 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00003325 }
3326 }
Daniel Berline3e69e12017-03-10 00:32:33 +00003327
3328 // If there are no uses, it's probably dead (but it may have side-effects,
3329 // so not definitely dead. Otherwise, store the number of uses so we can
3330 // track if it becomes dead later).
3331 if (UseCount == 0)
3332 ProbablyDead.insert(Def);
3333 else
3334 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003335 }
3336}
3337
Daniel Berlinc4796862017-01-27 02:37:11 +00003338// This function converts the set of members for a congruence class from values,
3339// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00003340void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00003341 const CongruenceClass &Dense,
3342 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00003343 for (auto D : Dense) {
3344 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
3345 continue;
3346
3347 BasicBlock *BB = getBlockForValue(D);
3348 ValueDFS VD;
3349 DomTreeNode *DomNode = DT->getNode(BB);
3350 VD.DFSIn = DomNode->getDFSNumIn();
3351 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003352 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00003353
3354 // If it's an instruction, use the real local dfs number.
3355 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00003356 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00003357 else
3358 llvm_unreachable("Should have been an instruction");
3359
3360 LoadsAndStores.emplace_back(VD);
3361 }
3362}
3363
Davide Italiano7e274e02016-12-22 16:03:48 +00003364static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00003365 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00003366 if (!ReplInst)
3367 return;
3368
Davide Italiano7e274e02016-12-22 16:03:48 +00003369 // Patch the replacement so that it is not more restrictive than the value
3370 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00003371 // Note that if 'I' is a load being replaced by some operation,
3372 // for example, by an arithmetic operation, then andIRFlags()
3373 // would just erase all math flags from the original arithmetic
3374 // operation, which is clearly not wanted and not needed.
3375 if (!isa<LoadInst>(I))
3376 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003377
Daniel Berlin86eab152017-02-12 22:25:20 +00003378 // FIXME: If both the original and replacement value are part of the
3379 // same control-flow region (meaning that the execution of one
3380 // guarantees the execution of the other), then we can combine the
3381 // noalias scopes here and do better than the general conservative
3382 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00003383
Daniel Berlin86eab152017-02-12 22:25:20 +00003384 // In general, GVN unifies expressions over different control-flow
3385 // regions, and so we need a conservative combination of the noalias
3386 // scopes.
3387 static const unsigned KnownIDs[] = {
3388 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
3389 LLVMContext::MD_noalias, LLVMContext::MD_range,
3390 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
3391 LLVMContext::MD_invariant_group};
3392 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00003393}
3394
3395static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3396 patchReplacementInstruction(I, Repl);
3397 I->replaceAllUsesWith(Repl);
3398}
3399
3400void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
3401 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
3402 ++NumGVNBlocksDeleted;
3403
Daniel Berline19f0e02017-01-30 17:06:55 +00003404 // Delete the instructions backwards, as it has a reduced likelihood of having
3405 // to update as many def-use and use-def chains. Start after the terminator.
3406 auto StartPoint = BB->rbegin();
3407 ++StartPoint;
3408 // Note that we explicitly recalculate BB->rend() on each iteration,
3409 // as it may change when we remove the first instruction.
3410 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3411 Instruction &Inst = *I++;
3412 if (!Inst.use_empty())
3413 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3414 if (isa<LandingPadInst>(Inst))
3415 continue;
3416
3417 Inst.eraseFromParent();
3418 ++NumGVNInstrDeleted;
3419 }
Daniel Berlina53a7222017-01-30 18:12:56 +00003420 // Now insert something that simplifycfg will turn into an unreachable.
3421 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3422 new StoreInst(UndefValue::get(Int8Ty),
3423 Constant::getNullValue(Int8Ty->getPointerTo()),
3424 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00003425}
3426
3427void NewGVN::markInstructionForDeletion(Instruction *I) {
3428 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3429 InstructionsToErase.insert(I);
3430}
3431
3432void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3433
3434 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3435 patchAndReplaceAllUsesWith(I, V);
3436 // We save the actual erasing to avoid invalidating memory
3437 // dependencies until we are done with everything.
3438 markInstructionForDeletion(I);
3439}
3440
3441namespace {
3442
3443// This is a stack that contains both the value and dfs info of where
3444// that value is valid.
3445class ValueDFSStack {
3446public:
3447 Value *back() const { return ValueStack.back(); }
3448 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3449
3450 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003451 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003452 DFSStack.emplace_back(DFSIn, DFSOut);
3453 }
3454 bool empty() const { return DFSStack.empty(); }
3455 bool isInScope(int DFSIn, int DFSOut) const {
3456 if (empty())
3457 return false;
3458 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3459 }
3460
3461 void popUntilDFSScope(int DFSIn, int DFSOut) {
3462
3463 // These two should always be in sync at this point.
3464 assert(ValueStack.size() == DFSStack.size() &&
3465 "Mismatch between ValueStack and DFSStack");
3466 while (
3467 !DFSStack.empty() &&
3468 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3469 DFSStack.pop_back();
3470 ValueStack.pop_back();
3471 }
3472 }
3473
3474private:
3475 SmallVector<Value *, 8> ValueStack;
3476 SmallVector<std::pair<int, int>, 8> DFSStack;
3477};
3478}
Daniel Berlin04443432017-01-07 03:23:47 +00003479
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003480// Given a value and a basic block we are trying to see if it is available in,
3481// see if the value has a leader available in that block.
3482Value *NewGVN::findPhiOfOpsLeader(const Expression *E,
3483 const BasicBlock *BB) const {
3484 // It would already be constant if we could make it constant
3485 if (auto *CE = dyn_cast<ConstantExpression>(E))
3486 return CE->getConstantValue();
3487 if (auto *VE = dyn_cast<VariableExpression>(E))
3488 return VE->getVariableValue();
3489
3490 auto *CC = ExpressionToClass.lookup(E);
3491 if (!CC)
3492 return nullptr;
3493 if (alwaysAvailable(CC->getLeader()))
3494 return CC->getLeader();
3495
3496 for (auto Member : *CC) {
3497 auto *MemberInst = dyn_cast<Instruction>(Member);
3498 // Anything that isn't an instruction is always available.
3499 if (!MemberInst)
3500 return Member;
3501 // If we are looking for something in the same block as the member, it must
3502 // be a leader because this function is looking for operands for a phi node.
3503 if (MemberInst->getParent() == BB ||
3504 DT->dominates(MemberInst->getParent(), BB)) {
3505 return Member;
3506 }
3507 }
3508 return nullptr;
3509}
3510
Davide Italiano7e274e02016-12-22 16:03:48 +00003511bool NewGVN::eliminateInstructions(Function &F) {
3512 // This is a non-standard eliminator. The normal way to eliminate is
3513 // to walk the dominator tree in order, keeping track of available
3514 // values, and eliminating them. However, this is mildly
3515 // pointless. It requires doing lookups on every instruction,
3516 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003517 // instructions part of most singleton congruence classes, we know we
3518 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003519
3520 // Instead, this eliminator looks at the congruence classes directly, sorts
3521 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003522 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003523 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003524 // last member. This is worst case O(E log E) where E = number of
3525 // instructions in a single congruence class. In theory, this is all
3526 // instructions. In practice, it is much faster, as most instructions are
3527 // either in singleton congruence classes or can't possibly be eliminated
3528 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003529 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003530 // for elimination purposes.
3531 // TODO: If we wanted to be faster, We could remove any members with no
3532 // overlapping ranges while sorting, as we will never eliminate anything
3533 // with those members, as they don't dominate anything else in our set.
3534
Davide Italiano7e274e02016-12-22 16:03:48 +00003535 bool AnythingReplaced = false;
3536
3537 // Since we are going to walk the domtree anyway, and we can't guarantee the
3538 // DFS numbers are updated, we compute some ourselves.
3539 DT->updateDFSNumbers();
3540
Daniel Berlin0207cca2017-05-21 23:41:56 +00003541 // Go through all of our phi nodes, and kill the arguments associated with
3542 // unreachable edges.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003543 auto ReplaceUnreachablePHIArgs = [&](PHINode &PHI, BasicBlock *BB) {
3544 for (auto &Operand : PHI.incoming_values())
3545 if (!ReachableEdges.count({PHI.getIncomingBlock(Operand), BB})) {
3546 DEBUG(dbgs() << "Replacing incoming value of " << PHI << " for block "
3547 << getBlockName(PHI.getIncomingBlock(Operand))
3548 << " with undef due to it being unreachable\n");
3549 Operand.set(UndefValue::get(PHI.getType()));
3550 }
3551 };
3552 SmallPtrSet<BasicBlock *, 8> BlocksWithPhis;
3553 for (auto &B : F)
3554 if ((!B.empty() && isa<PHINode>(*B.begin())) ||
3555 (PHIOfOpsPHIs.find(&B) != PHIOfOpsPHIs.end()))
3556 BlocksWithPhis.insert(&B);
3557 DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
3558 for (auto KV : ReachableEdges)
3559 ReachablePredCount[KV.getEnd()]++;
3560 for (auto *BB : BlocksWithPhis)
3561 // TODO: It would be faster to use getNumIncomingBlocks() on a phi node in
3562 // the block and subtract the pred count, but it's more complicated.
3563 if (ReachablePredCount.lookup(BB) !=
3564 std::distance(pred_begin(BB), pred_end(BB))) {
3565 for (auto II = BB->begin(); isa<PHINode>(II); ++II) {
3566 auto &PHI = cast<PHINode>(*II);
3567 ReplaceUnreachablePHIArgs(PHI, BB);
3568 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00003569 for_each_found(PHIOfOpsPHIs, BB, [&](PHINode *PHI) {
3570 ReplaceUnreachablePHIArgs(*PHI, BB);
3571 });
Davide Italiano7e274e02016-12-22 16:03:48 +00003572 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003573
Daniel Berline3e69e12017-03-10 00:32:33 +00003574 // Map to store the use counts
3575 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003576 for (auto *CC : reverse(CongruenceClasses)) {
Daniel Berline67c3222017-05-25 15:44:20 +00003577 DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID() << "\n");
Daniel Berlinc4796862017-01-27 02:37:11 +00003578 // Track the equivalent store info so we can decide whether to try
3579 // dead store elimination.
3580 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003581 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003582 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003583 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003584 // Everything still in the TOP class is unreachable or dead.
3585 if (CC == TOPClass) {
Daniel Berline021d2d2017-05-19 20:22:20 +00003586 for (auto M : *CC) {
3587 auto *VTE = ValueToExpression.lookup(M);
3588 if (VTE && isa<DeadExpression>(VTE))
3589 markInstructionForDeletion(cast<Instruction>(M));
Daniel Berlinb79f5362017-02-11 12:48:50 +00003590 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3591 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003592 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003593 "point");
Daniel Berline021d2d2017-05-19 20:22:20 +00003594 }
Daniel Berlinb79f5362017-02-11 12:48:50 +00003595 continue;
3596 }
3597
Daniel Berlina8236562017-04-07 18:38:09 +00003598 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003599 // If this is a leader that is always available, and it's a
3600 // constant or has no equivalences, just replace everything with
3601 // it. We then update the congruence class with whatever members
3602 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003603 Value *Leader =
3604 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003605 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003606 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003607 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003608 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003609 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003610 if (Member == Leader || !isa<Instruction>(Member) ||
3611 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003612 MembersLeft.insert(Member);
3613 continue;
3614 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003615 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3616 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003617 auto *I = cast<Instruction>(Member);
3618 assert(Leader != I && "About to accidentally remove our leader");
3619 replaceInstruction(I, Leader);
3620 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003621 }
Daniel Berlina8236562017-04-07 18:38:09 +00003622 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003623 } else {
Davide Italiano7e274e02016-12-22 16:03:48 +00003624 // If this is a singleton, we can skip it.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003625 if (CC->size() != 1 || RealToTemp.lookup(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003626 // This is a stack because equality replacement/etc may place
3627 // constants in the middle of the member list, and we want to use
3628 // those constant values in preference to the current leader, over
3629 // the scope of those constants.
3630 ValueDFSStack EliminationStack;
3631
3632 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003633 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003634 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003635
3636 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003637 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003638 for (auto &VD : DFSOrderedSet) {
3639 int MemberDFSIn = VD.DFSIn;
3640 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003641 Value *Def = VD.Def.getPointer();
3642 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003643 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003644 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003645 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003646 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003647 auto *DefInst = dyn_cast_or_null<Instruction>(Def);
3648 if (DefInst && AllTempInstructions.count(DefInst)) {
3649 auto *PN = cast<PHINode>(DefInst);
3650
3651 // If this is a value phi and that's the expression we used, insert
3652 // it into the program
3653 // remove from temp instruction list.
3654 AllTempInstructions.erase(PN);
3655 auto *DefBlock = getBlockForValue(Def);
3656 DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
3657 << " into block "
3658 << getBlockName(getBlockForValue(Def)) << "\n");
3659 PN->insertBefore(&DefBlock->front());
3660 Def = PN;
3661 NumGVNPHIOfOpsEliminations++;
3662 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003663
3664 if (EliminationStack.empty()) {
3665 DEBUG(dbgs() << "Elimination Stack is empty\n");
3666 } else {
3667 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3668 << EliminationStack.dfs_back().first << ","
3669 << EliminationStack.dfs_back().second << ")\n");
3670 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003671
3672 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3673 << MemberDFSOut << ")\n");
3674 // First, we see if we are out of scope or empty. If so,
3675 // and there equivalences, we try to replace the top of
3676 // stack with equivalences (if it's on the stack, it must
3677 // not have been eliminated yet).
3678 // Then we synchronize to our current scope, by
3679 // popping until we are back within a DFS scope that
3680 // dominates the current member.
3681 // Then, what happens depends on a few factors
3682 // If the stack is now empty, we need to push
3683 // If we have a constant or a local equivalence we want to
3684 // start using, we also push.
3685 // Otherwise, we walk along, processing members who are
3686 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003687 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003688 bool OutOfScope =
3689 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3690
3691 if (OutOfScope || ShouldPush) {
3692 // Sync to our current scope.
3693 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003694 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003695 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003696 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003697 }
3698 }
3699
Daniel Berline3e69e12017-03-10 00:32:33 +00003700 // Skip the Def's, we only want to eliminate on their uses. But mark
3701 // dominated defs as dead.
3702 if (Def) {
3703 // For anything in this case, what and how we value number
3704 // guarantees that any side-effets that would have occurred (ie
3705 // throwing, etc) can be proven to either still occur (because it's
3706 // dominated by something that has the same side-effects), or never
3707 // occur. Otherwise, we would not have been able to prove it value
3708 // equivalent to something else. For these things, we can just mark
3709 // it all dead. Note that this is different from the "ProbablyDead"
3710 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003711 // easy to prove dead if they are also side-effect free. Note that
3712 // because stores are put in terms of the stored value, we skip
3713 // stored values here. If the stored value is really dead, it will
3714 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003715 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003716 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003717 markInstructionForDeletion(cast<Instruction>(Def));
3718 continue;
3719 }
3720 // At this point, we know it is a Use we are trying to possibly
3721 // replace.
3722
3723 assert(isa<Instruction>(U->get()) &&
3724 "Current def should have been an instruction");
3725 assert(isa<Instruction>(U->getUser()) &&
3726 "Current user should have been an instruction");
3727
3728 // If the thing we are replacing into is already marked to be dead,
3729 // this use is dead. Note that this is true regardless of whether
3730 // we have anything dominating the use or not. We do this here
3731 // because we are already walking all the uses anyway.
3732 Instruction *InstUse = cast<Instruction>(U->getUser());
3733 if (InstructionsToErase.count(InstUse)) {
3734 auto &UseCount = UseCounts[U->get()];
3735 if (--UseCount == 0) {
3736 ProbablyDead.insert(cast<Instruction>(U->get()));
3737 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003738 }
3739
Davide Italiano7e274e02016-12-22 16:03:48 +00003740 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003741 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003742 if (EliminationStack.empty())
3743 continue;
3744
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003745 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003746
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003747 auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
3748 if (II && II->getIntrinsicID() == Intrinsic::ssa_copy)
3749 DominatingLeader = II->getOperand(0);
3750
Daniel Berlind92e7f92017-01-07 00:01:42 +00003751 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003752 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003753 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003754 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003755 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003756
3757 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003758 // metadata. Skip this if we are replacing predicateinfo with its
3759 // original operand, as we already know we can just drop it.
3760 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003761 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3762 if (!PI || DominatingLeader != PI->OriginalOp)
3763 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003764 U->set(DominatingLeader);
3765 // This is now a use of the dominating leader, which means if the
3766 // dominating leader was dead, it's now live!
3767 auto &LeaderUseCount = UseCounts[DominatingLeader];
3768 // It's about to be alive again.
3769 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3770 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003771 if (LeaderUseCount == 0 && II)
3772 ProbablyDead.insert(II);
Daniel Berline3e69e12017-03-10 00:32:33 +00003773 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003774 AnythingReplaced = true;
3775 }
3776 }
3777 }
3778
Daniel Berline3e69e12017-03-10 00:32:33 +00003779 // At this point, anything still in the ProbablyDead set is actually dead if
3780 // would be trivially dead.
3781 for (auto *I : ProbablyDead)
3782 if (wouldInstructionBeTriviallyDead(I))
3783 markInstructionForDeletion(I);
3784
Davide Italiano7e274e02016-12-22 16:03:48 +00003785 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003786 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003787 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003788 if (!isa<Instruction>(Member) ||
3789 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003790 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003791 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003792
3793 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00003794 if (CC->getStoreCount() > 0) {
3795 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003796 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3797 ValueDFSStack EliminationStack;
3798 for (auto &VD : PossibleDeadStores) {
3799 int MemberDFSIn = VD.DFSIn;
3800 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003801 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003802 if (EliminationStack.empty() ||
3803 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3804 // Sync to our current scope.
3805 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3806 if (EliminationStack.empty()) {
3807 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3808 continue;
3809 }
3810 }
3811 // We already did load elimination, so nothing to do here.
3812 if (isa<LoadInst>(Member))
3813 continue;
3814 assert(!EliminationStack.empty());
3815 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003816 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003817 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3818 // Member is dominater by Leader, and thus dead
3819 DEBUG(dbgs() << "Marking dead store " << *Member
3820 << " that is dominated by " << *Leader << "\n");
3821 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003822 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00003823 ++NumGVNDeadStores;
3824 }
3825 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003826 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003827 return AnythingReplaced;
3828}
Daniel Berlin1c087672017-02-11 15:07:01 +00003829
3830// This function provides global ranking of operations so that we can place them
3831// in a canonical order. Note that rank alone is not necessarily enough for a
3832// complete ordering, as constants all have the same rank. However, generally,
3833// we will simplify an operation with all constants so that it doesn't matter
3834// what order they appear in.
3835unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003836 // Prefer constants to undef to anything else
3837 // Undef is a constant, have to check it first.
3838 // Prefer smaller constants to constantexprs
3839 if (isa<ConstantExpr>(V))
3840 return 2;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003841 if (isa<UndefValue>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003842 return 1;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003843 if (isa<Constant>(V))
3844 return 0;
Daniel Berlin1c087672017-02-11 15:07:01 +00003845 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003846 return 3 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00003847
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003848 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00003849 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003850 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00003851 if (Result > 0)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003852 return 4 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00003853 // Unreachable or something else, just return a really large number.
3854 return ~0;
3855}
3856
3857// This is a function that says whether two commutative operations should
3858// have their order swapped when canonicalizing.
3859bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3860 // Because we only care about a total ordering, and don't rewrite expressions
3861 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003862 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00003863 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00003864}
Daniel Berlin64e68992017-03-12 04:46:45 +00003865
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00003866namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +00003867class NewGVNLegacyPass : public FunctionPass {
3868public:
3869 static char ID; // Pass identification, replacement for typeid.
3870 NewGVNLegacyPass() : FunctionPass(ID) {
3871 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3872 }
3873 bool runOnFunction(Function &F) override;
3874
3875private:
3876 void getAnalysisUsage(AnalysisUsage &AU) const override {
3877 AU.addRequired<AssumptionCacheTracker>();
3878 AU.addRequired<DominatorTreeWrapperPass>();
3879 AU.addRequired<TargetLibraryInfoWrapperPass>();
3880 AU.addRequired<MemorySSAWrapperPass>();
3881 AU.addRequired<AAResultsWrapperPass>();
3882 AU.addPreserved<DominatorTreeWrapperPass>();
3883 AU.addPreserved<GlobalsAAWrapperPass>();
3884 }
3885};
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00003886} // namespace
Daniel Berlin64e68992017-03-12 04:46:45 +00003887
3888bool NewGVNLegacyPass::runOnFunction(Function &F) {
3889 if (skipFunction(F))
3890 return false;
3891 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3892 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3893 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3894 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3895 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3896 F.getParent()->getDataLayout())
3897 .runGVN();
3898}
3899
3900INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3901 false, false)
3902INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3903INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3904INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3905INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3906INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3907INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3908INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3909 false)
3910
3911char NewGVNLegacyPass::ID = 0;
3912
3913// createGVNPass - The public interface to this file.
3914FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3915
3916PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3917 // Apparently the order in which we get these results matter for
3918 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3919 // the same order here, just in case.
3920 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3921 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3922 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3923 auto &AA = AM.getResult<AAManager>(F);
3924 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3925 bool Changed =
3926 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3927 .runGVN();
3928 if (!Changed)
3929 return PreservedAnalyses::all();
3930 PreservedAnalyses PA;
3931 PA.preserve<DominatorTreeAnalysis>();
3932 PA.preserve<GlobalsAA>();
3933 return PA;
3934}