blob: 1717e1848995f1e8be99d11db7aecbac2d9dfe87 [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",
Craig Topper9cd976d2017-08-10 17:48:11 +0000121 "Controls which instructions are value numbered");
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000122DEBUG_COUNTER(PHIOfOpsCounter, "newgvn-phi",
Craig Topper9cd976d2017-08-10 17:48:11 +0000123 "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
Chad Rosiera5508e32017-08-10 14:12:57 +0000130/// Currently, the generation "phi of ops" can result in correctness issues.
Daniel Berlin94090dd2017-09-02 02:18:44 +0000131static cl::opt<bool> EnablePhiOfOps("enable-phi-of-ops", cl::init(true),
Chad Rosiera5508e32017-08-10 14:12:57 +0000132 cl::Hidden);
133
Davide Italiano7e274e02016-12-22 16:03:48 +0000134//===----------------------------------------------------------------------===//
135// GVN Pass
136//===----------------------------------------------------------------------===//
137
138// Anchor methods.
139namespace llvm {
140namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000141Expression::~Expression() = default;
142BasicExpression::~BasicExpression() = default;
143CallExpression::~CallExpression() = default;
144LoadExpression::~LoadExpression() = default;
145StoreExpression::~StoreExpression() = default;
146AggregateValueExpression::~AggregateValueExpression() = default;
147PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000148}
149}
150
Benjamin Kramer49a49fe2017-08-20 13:03:48 +0000151namespace {
Daniel Berlin2f72b192017-04-14 02:53:37 +0000152// Tarjan's SCC finding algorithm with Nuutila's improvements
153// SCCIterator is actually fairly complex for the simple thing we want.
154// It also wants to hand us SCC's that are unrelated to the phi node we ask
155// about, and have us process them there or risk redoing work.
156// Graph traits over a filter iterator also doesn't work that well here.
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000157// This SCC finder is specialized to walk use-def chains, and only follows
158// instructions,
Daniel Berlin2f72b192017-04-14 02:53:37 +0000159// not generic values (arguments, etc).
160struct TarjanSCC {
161
162 TarjanSCC() : Components(1) {}
163
164 void Start(const Instruction *Start) {
165 if (Root.lookup(Start) == 0)
166 FindSCC(Start);
167 }
168
169 const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
170 unsigned ComponentID = ValueToComponent.lookup(V);
171
172 assert(ComponentID > 0 &&
173 "Asking for a component for a value we never processed");
174 return Components[ComponentID];
175 }
176
177private:
178 void FindSCC(const Instruction *I) {
179 Root[I] = ++DFSNum;
180 // Store the DFS Number we had before it possibly gets incremented.
181 unsigned int OurDFS = DFSNum;
182 for (auto &Op : I->operands()) {
183 if (auto *InstOp = dyn_cast<Instruction>(Op)) {
184 if (Root.lookup(Op) == 0)
185 FindSCC(InstOp);
186 if (!InComponent.count(Op))
187 Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
188 }
189 }
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000190 // See if we really were the root of a component, by seeing if we still have
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000191 // our DFSNumber. If we do, we are the root of the component, and we have
192 // completed a component. If we do not, we are not the root of a component,
193 // and belong on the component stack.
Daniel Berlin2f72b192017-04-14 02:53:37 +0000194 if (Root.lookup(I) == OurDFS) {
195 unsigned ComponentID = Components.size();
196 Components.resize(Components.size() + 1);
197 auto &Component = Components.back();
198 Component.insert(I);
199 DEBUG(dbgs() << "Component root is " << *I << "\n");
200 InComponent.insert(I);
201 ValueToComponent[I] = ComponentID;
202 // Pop a component off the stack and label it.
203 while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
204 auto *Member = Stack.back();
205 DEBUG(dbgs() << "Component member is " << *Member << "\n");
206 Component.insert(Member);
207 InComponent.insert(Member);
208 ValueToComponent[Member] = ComponentID;
209 Stack.pop_back();
210 }
211 } else {
212 // Part of a component, push to stack
213 Stack.push_back(I);
214 }
215 }
216 unsigned int DFSNum = 1;
217 SmallPtrSet<const Value *, 8> InComponent;
218 DenseMap<const Value *, unsigned int> Root;
219 SmallVector<const Value *, 8> Stack;
220 // Store the components as vector of ptr sets, because we need the topo order
221 // of SCC's, but not individual member order
222 SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
223 DenseMap<const Value *, unsigned> ValueToComponent;
224};
Davide Italiano7e274e02016-12-22 16:03:48 +0000225// Congruence classes represent the set of expressions/instructions
226// that are all the same *during some scope in the function*.
227// That is, because of the way we perform equality propagation, and
228// because of memory value numbering, it is not correct to assume
229// you can willy-nilly replace any member with any other at any
230// point in the function.
231//
232// For any Value in the Member set, it is valid to replace any dominated member
233// with that Value.
234//
Daniel Berlin1316a942017-04-06 18:52:50 +0000235// Every congruence class has a leader, and the leader is used to symbolize
236// instructions in a canonical way (IE every operand of an instruction that is a
237// member of the same congruence class will always be replaced with leader
238// during symbolization). To simplify symbolization, we keep the leader as a
239// constant if class can be proved to be a constant value. Otherwise, the
240// leader is the member of the value set with the smallest DFS number. Each
241// congruence class also has a defining expression, though the expression may be
242// null. If it exists, it can be used for forward propagation and reassociation
243// of values.
244
245// For memory, we also track a representative MemoryAccess, and a set of memory
246// members for MemoryPhis (which have no real instructions). Note that for
247// memory, it seems tempting to try to split the memory members into a
248// MemoryCongruenceClass or something. Unfortunately, this does not work
249// easily. The value numbering of a given memory expression depends on the
250// leader of the memory congruence class, and the leader of memory congruence
251// class depends on the value numbering of a given memory expression. This
252// leads to wasted propagation, and in some cases, missed optimization. For
253// example: If we had value numbered two stores together before, but now do not,
254// we move them to a new value congruence class. This in turn will move at one
255// of the memorydefs to a new memory congruence class. Which in turn, affects
256// the value numbering of the stores we just value numbered (because the memory
257// congruence class is part of the value number). So while theoretically
258// possible to split them up, it turns out to be *incredibly* complicated to get
259// it to work right, because of the interdependency. While structurally
260// slightly messier, it is algorithmically much simpler and faster to do what we
Daniel Berlina8236562017-04-07 18:38:09 +0000261// do here, and track them both at once in the same class.
262// Note: The default iterators for this class iterate over values
263class CongruenceClass {
264public:
265 using MemberType = Value;
266 using MemberSet = SmallPtrSet<MemberType *, 4>;
267 using MemoryMemberType = MemoryPhi;
268 using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
269
270 explicit CongruenceClass(unsigned ID) : ID(ID) {}
271 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
272 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
273 unsigned getID() const { return ID; }
274 // True if this class has no members left. This is mainly used for assertion
275 // purposes, and for skipping empty classes.
276 bool isDead() const {
277 // If it's both dead from a value perspective, and dead from a memory
278 // perspective, it's really dead.
279 return empty() && memory_empty();
280 }
281 // Leader functions
282 Value *getLeader() const { return RepLeader; }
283 void setLeader(Value *Leader) { RepLeader = Leader; }
284 const std::pair<Value *, unsigned int> &getNextLeader() const {
285 return NextLeader;
286 }
287 void resetNextLeader() { NextLeader = {nullptr, ~0}; }
288
289 void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
290 if (LeaderPair.second < NextLeader.second)
291 NextLeader = LeaderPair;
292 }
293
294 Value *getStoredValue() const { return RepStoredValue; }
295 void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
296 const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
297 void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
298
299 // Forward propagation info
300 const Expression *getDefiningExpr() const { return DefiningExpr; }
Daniel Berlina8236562017-04-07 18:38:09 +0000301
302 // Value member set
303 bool empty() const { return Members.empty(); }
304 unsigned size() const { return Members.size(); }
305 MemberSet::const_iterator begin() const { return Members.begin(); }
306 MemberSet::const_iterator end() const { return Members.end(); }
307 void insert(MemberType *M) { Members.insert(M); }
308 void erase(MemberType *M) { Members.erase(M); }
309 void swap(MemberSet &Other) { Members.swap(Other); }
310
311 // Memory member set
312 bool memory_empty() const { return MemoryMembers.empty(); }
313 unsigned memory_size() const { return MemoryMembers.size(); }
314 MemoryMemberSet::const_iterator memory_begin() const {
315 return MemoryMembers.begin();
316 }
317 MemoryMemberSet::const_iterator memory_end() const {
318 return MemoryMembers.end();
319 }
320 iterator_range<MemoryMemberSet::const_iterator> memory() const {
321 return make_range(memory_begin(), memory_end());
322 }
323 void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
324 void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
325
326 // Store count
327 unsigned getStoreCount() const { return StoreCount; }
328 void incStoreCount() { ++StoreCount; }
329 void decStoreCount() {
330 assert(StoreCount != 0 && "Store count went negative");
331 --StoreCount;
332 }
333
Davide Italianodc435322017-05-10 19:57:43 +0000334 // True if this class has no memory members.
335 bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
336
Daniel Berlina8236562017-04-07 18:38:09 +0000337 // Return true if two congruence classes are equivalent to each other. This
338 // means
339 // that every field but the ID number and the dead field are equivalent.
340 bool isEquivalentTo(const CongruenceClass *Other) const {
341 if (!Other)
342 return false;
343 if (this == Other)
344 return true;
345
346 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
347 std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
348 Other->RepMemoryAccess))
349 return false;
350 if (DefiningExpr != Other->DefiningExpr)
351 if (!DefiningExpr || !Other->DefiningExpr ||
352 *DefiningExpr != *Other->DefiningExpr)
353 return false;
354 // We need some ordered set
355 std::set<Value *> AMembers(Members.begin(), Members.end());
356 std::set<Value *> BMembers(Members.begin(), Members.end());
357 return AMembers == BMembers;
358 }
359
360private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000361 unsigned ID;
362 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000363 Value *RepLeader = nullptr;
Daniel Berlina8236562017-04-07 18:38:09 +0000364 // The most dominating leader after our current leader, because the member set
365 // is not sorted and is expensive to keep sorted all the time.
366 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
Daniel Berlin1316a942017-04-06 18:52:50 +0000367 // If this is represented by a store, the value of the store.
Daniel Berlin26addef2017-01-20 21:04:30 +0000368 Value *RepStoredValue = nullptr;
Daniel Berlin1316a942017-04-06 18:52:50 +0000369 // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
370 // access.
371 const MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000372 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000373 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000374 // Actual members of this class.
375 MemberSet Members;
Daniel Berlin1316a942017-04-06 18:52:50 +0000376 // This is the set of MemoryPhis that exist in the class. MemoryDefs and
377 // MemoryUses have real instructions representing them, so we only need to
378 // track MemoryPhis here.
379 MemoryMemberSet MemoryMembers;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000380 // Number of stores in this congruence class.
381 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000382 int StoreCount = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +0000383};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +0000384} // namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000385
386namespace llvm {
Daniel Berlineafdd862017-06-06 17:15:28 +0000387struct ExactEqualsExpression {
388 const Expression &E;
389 explicit ExactEqualsExpression(const Expression &E) : E(E) {}
390 hash_code getComputedHash() const { return E.getComputedHash(); }
391 bool operator==(const Expression &Other) const {
392 return E.exactlyEquals(Other);
393 }
394};
395
Daniel Berlin85f91b02016-12-26 20:06:58 +0000396template <> struct DenseMapInfo<const Expression *> {
397 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000398 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000399 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
400 return reinterpret_cast<const Expression *>(Val);
401 }
402 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000403 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000404 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
405 return reinterpret_cast<const Expression *>(Val);
406 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000407 static unsigned getHashValue(const Expression *E) {
Daniel Berlineafdd862017-06-06 17:15:28 +0000408 return E->getComputedHash();
Daniel Berlin85f91b02016-12-26 20:06:58 +0000409 }
Daniel Berlineafdd862017-06-06 17:15:28 +0000410 static unsigned getHashValue(const ExactEqualsExpression &E) {
411 return E.getComputedHash();
412 }
413 static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS) {
414 if (RHS == getTombstoneKey() || RHS == getEmptyKey())
415 return false;
416 return LHS == *RHS;
417 }
418
Daniel Berlin85f91b02016-12-26 20:06:58 +0000419 static bool isEqual(const Expression *LHS, const Expression *RHS) {
420 if (LHS == RHS)
421 return true;
422 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
423 LHS == getEmptyKey() || RHS == getEmptyKey())
424 return false;
Daniel Berlin2aa5dc12017-05-30 06:58:18 +0000425 // Compare hashes before equality. This is *not* what the hashtable does,
426 // since it is computing it modulo the number of buckets, whereas we are
427 // using the full hash keyspace. Since the hashes are precomputed, this
428 // check is *much* faster than equality.
429 if (LHS->getComputedHash() != RHS->getComputedHash())
430 return false;
Daniel Berlin85f91b02016-12-26 20:06:58 +0000431 return *LHS == *RHS;
432 }
433};
Davide Italiano7e274e02016-12-22 16:03:48 +0000434} // end namespace llvm
435
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000436namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000437class NewGVN {
438 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000439 DominatorTree *DT;
Daniel Berlin64e68992017-03-12 04:46:45 +0000440 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000441 AliasAnalysis *AA;
442 MemorySSA *MSSA;
443 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000444 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000445 std::unique_ptr<PredicateInfo> PredInfo;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000446
447 // These are the only two things the create* functions should have
448 // side-effects on due to allocating memory.
449 mutable BumpPtrAllocator ExpressionAllocator;
450 mutable ArrayRecycler<Value *> ArgRecycler;
451 mutable TarjanSCC SCCFinder;
Daniel Berlinede130d2017-04-26 20:56:14 +0000452 const SimplifyQuery SQ;
Davide Italiano7e274e02016-12-22 16:03:48 +0000453
Daniel Berlin1c087672017-02-11 15:07:01 +0000454 // Number of function arguments, used by ranking
455 unsigned int NumFuncArgs;
456
Daniel Berlin2f72b192017-04-14 02:53:37 +0000457 // RPOOrdering of basic blocks
458 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
459
Davide Italiano7e274e02016-12-22 16:03:48 +0000460 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000461
462 // This class is called INITIAL in the paper. It is the class everything
463 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000464 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000465 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000466 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000467 std::vector<CongruenceClass *> CongruenceClasses;
468 unsigned NextCongruenceNum;
469
470 // Value Mappings.
471 DenseMap<Value *, CongruenceClass *> ValueToClass;
472 DenseMap<Value *, const Expression *> ValueToExpression;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000473 // Value PHI handling, used to make equivalence between phi(op, op) and
474 // op(phi, phi).
475 // These mappings just store various data that would normally be part of the
476 // IR.
477 DenseSet<const Instruction *> PHINodeUses;
Daniel Berlin94090dd2017-09-02 02:18:44 +0000478 DenseMap<const Value *, bool> OpSafeForPHIOfOps;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000479 // Map a temporary instruction we created to a parent block.
480 DenseMap<const Value *, BasicBlock *> TempToBlock;
Davide Italiano5974c312017-08-03 21:17:49 +0000481 // Map between the already in-program instructions and the temporary phis we
482 // created that they are known equivalent to.
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000483 DenseMap<const Value *, PHINode *> RealToTemp;
484 // In order to know when we should re-process instructions that have
485 // phi-of-ops, we track the set of expressions that they needed as
486 // leaders. When we discover new leaders for those expressions, we process the
487 // associated phi-of-op instructions again in case they have changed. The
488 // other way they may change is if they had leaders, and those leaders
489 // disappear. However, at the point they have leaders, there are uses of the
490 // relevant operands in the created phi node, and so they will get reprocessed
491 // through the normal user marking we perform.
492 mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
493 DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
494 ExpressionToPhiOfOps;
495 // Map from basic block to the temporary operations we created
Davide Italiano5974c312017-08-03 21:17:49 +0000496 DenseMap<const BasicBlock *, SmallPtrSet<PHINode *, 2>> PHIOfOpsPHIs;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000497 // Map from temporary operation to MemoryAccess.
498 DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
499 // Set of all temporary instructions we created.
Davide Italiano5974c312017-08-03 21:17:49 +0000500 // Note: This will include instructions that were just created during value
501 // numbering. The way to test if something is using them is to check
502 // RealToTemp.
503
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000504 DenseSet<Instruction *> AllTempInstructions;
Davide Italiano7e274e02016-12-22 16:03:48 +0000505
Daniel Berlinf7d95802017-02-18 23:06:50 +0000506 // Mapping from predicate info we used to the instructions we used it with.
507 // In order to correctly ensure propagation, we must keep track of what
508 // comparisons we used, so that when the values of the comparisons change, we
509 // propagate the information to the places we used the comparison.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000510 mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
511 PredicateToUsers;
Daniel Berlin1316a942017-04-06 18:52:50 +0000512 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
513 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000514 mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
515 MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000516
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000517 // A table storing which memorydefs/phis represent a memory state provably
518 // equivalent to another memory state.
519 // We could use the congruence class machinery, but the MemoryAccess's are
520 // abstract memory states, so they can only ever be equivalent to each other,
521 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000522 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000523
Daniel Berlin1316a942017-04-06 18:52:50 +0000524 // We could, if we wanted, build MemoryPhiExpressions and
525 // MemoryVariableExpressions, etc, and value number them the same way we value
526 // number phi expressions. For the moment, this seems like overkill. They
527 // can only exist in one of three states: they can be TOP (equal to
528 // everything), Equivalent to something else, or unique. Because we do not
529 // create expressions for them, we need to simulate leader change not just
530 // when they change class, but when they change state. Note: We can do the
531 // same thing for phis, and avoid having phi expressions if we wanted, We
532 // should eventually unify in one direction or the other, so this is a little
533 // bit of an experiment in which turns out easier to maintain.
534 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
535 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
536
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000537 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
538 mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
Davide Italiano7e274e02016-12-22 16:03:48 +0000539 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000540 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000541 ExpressionClassMap ExpressionToClass;
542
Daniel Berline021d2d2017-05-19 20:22:20 +0000543 // We have a single expression that represents currently DeadExpressions.
544 // For dead expressions we can prove will stay dead, we mark them with
545 // DFS number zero. However, it's possible in the case of phi nodes
546 // for us to assume/prove all arguments are dead during fixpointing.
547 // We use DeadExpression for that case.
548 DeadExpression *SingletonDeadExpression = nullptr;
549
Davide Italiano7e274e02016-12-22 16:03:48 +0000550 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000551 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000552
553 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000554 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000555 DenseSet<BlockEdge> ReachableEdges;
556 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
557
558 // This is a bitvector because, on larger functions, we may have
559 // thousands of touched instructions at once (entire blocks,
560 // instructions with hundreds of uses, etc). Even with optimization
561 // for when we mark whole blocks as touched, when this was a
562 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
563 // the time in GVN just managing this list. The bitvector, on the
564 // other hand, efficiently supports test/set/clear of both
565 // individual and ranges, as well as "find next element" This
566 // enables us to use it as a worklist with essentially 0 cost.
567 BitVector TouchedInstructions;
568
569 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000570
571#ifndef NDEBUG
572 // Debugging for how many times each block and instruction got processed.
573 DenseMap<const Value *, unsigned> ProcessedCount;
574#endif
575
576 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000577 // This contains a mapping from Instructions to DFS numbers.
578 // The numbering starts at 1. An instruction with DFS number zero
579 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000580 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000581
582 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000583 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000584
585 // Deletion info.
586 SmallPtrSet<Instruction *, 8> InstructionsToErase;
587
588public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000589 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
590 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
591 const DataLayout &DL)
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000592 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
Daniel Berlinede130d2017-04-26 20:56:14 +0000593 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
594 }
Daniel Berlin64e68992017-03-12 04:46:45 +0000595 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000596
597private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000598 // Expression handling.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000599 const Expression *createExpression(Instruction *) const;
Daniel Berlin54a92fc2017-09-05 02:17:42 +0000600 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
601 Instruction *) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000602 PHIExpression *createPHIExpression(Instruction *, bool &HasBackEdge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000603 bool &OriginalOpsConstant) const;
Daniel Berline021d2d2017-05-19 20:22:20 +0000604 const DeadExpression *createDeadExpression() const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000605 const VariableExpression *createVariableExpression(Value *) const;
606 const ConstantExpression *createConstantExpression(Constant *) const;
607 const Expression *createVariableOrConstant(Value *V) const;
608 const UnknownExpression *createUnknownExpression(Instruction *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000609 const StoreExpression *createStoreExpression(StoreInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000610 const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000611 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000612 const MemoryAccess *) const;
613 const CallExpression *createCallExpression(CallInst *,
614 const MemoryAccess *) const;
615 const AggregateValueExpression *
616 createAggregateValueExpression(Instruction *) const;
617 bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000618
619 // Congruence class handling.
620 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000621 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000622 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000623 return result;
624 }
625
Daniel Berlin1316a942017-04-06 18:52:50 +0000626 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
627 auto *CC = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000628 CC->setMemoryLeader(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000629 return CC;
630 }
631 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
632 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +0000633 if (CC->getMemoryLeader() != MA)
Daniel Berlin1316a942017-04-06 18:52:50 +0000634 CC = createMemoryClass(MA);
635 return CC;
636 }
637
Davide Italiano7e274e02016-12-22 16:03:48 +0000638 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000639 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000640 CClass->insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +0000641 ValueToClass[Member] = CClass;
642 return CClass;
643 }
644 void initializeCongruenceClasses(Function &F);
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +0000645 const Expression *makePossiblePhiOfOps(Instruction *,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000646 SmallPtrSetImpl<Value *> &);
Daniel Berlin94090dd2017-09-02 02:18:44 +0000647 Value *findLeaderForInst(Instruction *ValueOp,
648 SmallPtrSetImpl<Value *> &Visited,
649 MemoryAccess *MemAccess, Instruction *OrigInst,
650 BasicBlock *PredBB);
651
652 bool OpIsSafeForPHIOfOps(Value *Op, Instruction *OrigInst,
653 const BasicBlock *PHIBlock,
654 SmallPtrSetImpl<const Value *> &);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000655 void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
Davide Italiano5974c312017-08-03 21:17:49 +0000656 void removePhiOfOps(Instruction *I, PHINode *PHITemp);
Davide Italiano7e274e02016-12-22 16:03:48 +0000657
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000658 // Value number an Instruction or MemoryPhi.
659 void valueNumberMemoryPhi(MemoryPhi *);
660 void valueNumberInstruction(Instruction *);
661
Davide Italiano7e274e02016-12-22 16:03:48 +0000662 // Symbolic evaluation.
663 const Expression *checkSimplificationResults(Expression *, Instruction *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000664 Value *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000665 const Expression *performSymbolicEvaluation(Value *,
666 SmallPtrSetImpl<Value *> &) const;
Daniel Berlin07daac82017-04-02 13:23:44 +0000667 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000668 Instruction *,
669 MemoryAccess *) const;
670 const Expression *performSymbolicLoadEvaluation(Instruction *) const;
671 const Expression *performSymbolicStoreEvaluation(Instruction *) const;
672 const Expression *performSymbolicCallEvaluation(Instruction *) const;
673 const Expression *performSymbolicPHIEvaluation(Instruction *) const;
674 const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
675 const Expression *performSymbolicCmpEvaluation(Instruction *) const;
676 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000677
678 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000679 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000680 Value *lookupOperandLeader(Value *) const;
Daniel Berlin94090dd2017-09-02 02:18:44 +0000681 CongruenceClass *getClassForExpression(const Expression *E) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000682 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000683 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
684 CongruenceClass *, CongruenceClass *);
685 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
686 CongruenceClass *, CongruenceClass *);
687 Value *getNextValueLeader(CongruenceClass *) const;
688 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
689 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
690 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
691 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000692 bool isMemoryAccessTOP(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000693
Daniel Berlin1c087672017-02-11 15:07:01 +0000694 // Ranking
695 unsigned int getRank(const Value *) const;
696 bool shouldSwapOperands(const Value *, const Value *) const;
697
Davide Italiano7e274e02016-12-22 16:03:48 +0000698 // Reachability handling.
699 void updateReachableEdge(BasicBlock *, BasicBlock *);
700 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000701 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000702
703 // Elimination.
704 struct ValueDFS;
Daniel Berlina8236562017-04-07 18:38:09 +0000705 void convertClassToDFSOrdered(const CongruenceClass &,
Daniel Berline3e69e12017-03-10 00:32:33 +0000706 SmallVectorImpl<ValueDFS> &,
707 DenseMap<const Value *, unsigned int> &,
Daniel Berlina8236562017-04-07 18:38:09 +0000708 SmallPtrSetImpl<Instruction *> &) const;
709 void convertClassToLoadsAndStores(const CongruenceClass &,
710 SmallVectorImpl<ValueDFS> &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000711
712 bool eliminateInstructions(Function &);
713 void replaceInstruction(Instruction *, Value *);
714 void markInstructionForDeletion(Instruction *);
715 void deleteInstructionsInBlock(BasicBlock *);
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +0000716 Value *findPHIOfOpsLeader(const Expression *, const Instruction *,
717 const BasicBlock *) const;
718
Davide Italiano7e274e02016-12-22 16:03:48 +0000719 // New instruction creation.
720 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000721
722 // Various instruction touch utilities
Daniel Berlin0207cca2017-05-21 23:41:56 +0000723 template <typename Map, typename KeyType, typename Func>
724 void for_each_found(Map &, const KeyType &, Func);
725 template <typename Map, typename KeyType>
726 void touchAndErase(Map &, const KeyType &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000727 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000728 void markMemoryUsersTouched(const MemoryAccess *);
729 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000730 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000731 void markValueLeaderChangeTouched(CongruenceClass *CC);
732 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +0000733 void markPhiOfOpsChanged(const Expression *E);
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000734 void addPredicateUsers(const PredicateBase *, Instruction *) const;
735 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000736 void addAdditionalUsers(Value *To, Value *User) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000737
Daniel Berlin06329a92017-03-18 15:41:40 +0000738 // Main loop of value numbering
739 void iterateTouchedInstructions();
740
Davide Italiano7e274e02016-12-22 16:03:48 +0000741 // Utilities.
742 void cleanupTables();
743 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000744 void updateProcessedCount(const Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000745 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000746 void verifyIterationSettled(Function &F);
Daniel Berlin45403572017-05-16 19:58:47 +0000747 void verifyStoreExpressions() const;
Davide Italianoeab0de22017-05-18 23:22:44 +0000748 bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
749 const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000750 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000751 void deleteExpression(const Expression *E) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000752 MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
753 MemoryAccess *getDefiningAccess(const MemoryAccess *) const;
754 MemoryPhi *getMemoryAccess(const BasicBlock *) const;
755 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin21279bd2017-04-06 18:52:58 +0000756 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000757 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
758 return InstrDFS.lookup(V);
759 }
760
Daniel Berlin21279bd2017-04-06 18:52:58 +0000761 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
762 return MemoryToDFSNum(MA);
763 }
764 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
765 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
766 // This deliberately takes a value so it can be used with Use's, which will
767 // auto-convert to Value's but not to MemoryAccess's.
768 unsigned MemoryToDFSNum(const Value *MA) const {
769 assert(isa<MemoryAccess>(MA) &&
770 "This should not be used with instructions");
771 return isa<MemoryUseOrDef>(MA)
772 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
773 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000774 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000775 bool isCycleFree(const Instruction *) const;
776 bool isBackedge(BasicBlock *From, BasicBlock *To) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000777 // Debug counter info. When verifying, we have to reset the value numbering
778 // debug counter to the same state it started in to get the same results.
779 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000780};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000781} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000782
Davide Italianob1114092016-12-28 13:37:17 +0000783template <typename T>
784static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000785 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000786 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000787 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000788}
789
Davide Italianob1114092016-12-28 13:37:17 +0000790bool LoadExpression::equals(const Expression &Other) const {
791 return equalsLoadStoreHelper(*this, Other);
792}
Davide Italiano7e274e02016-12-22 16:03:48 +0000793
Davide Italianob1114092016-12-28 13:37:17 +0000794bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000795 if (!equalsLoadStoreHelper(*this, Other))
796 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000797 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000798 if (const auto *S = dyn_cast<StoreExpression>(&Other))
799 if (getStoredValue() != S->getStoredValue())
800 return false;
801 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000802}
803
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000804// Determine if the edge From->To is a backedge
805bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
Davide Italianoc2f73b72017-08-02 04:05:49 +0000806 return From == To ||
807 RPOOrdering.lookup(DT->getNode(From)) >=
808 RPOOrdering.lookup(DT->getNode(To));
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000809}
810
Davide Italiano7e274e02016-12-22 16:03:48 +0000811#ifndef NDEBUG
812static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000813 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000814}
815#endif
816
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000817// Get a MemoryAccess for an instruction, fake or real.
818MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
819 auto *Result = MSSA->getMemoryAccess(I);
820 return Result ? Result : TempToMemory.lookup(I);
821}
822
823// Get a MemoryPhi for a basic block. These are all real.
824MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
825 return MSSA->getMemoryAccess(BB);
826}
827
Daniel Berlin06329a92017-03-18 15:41:40 +0000828// Get the basic block from an instruction/memory value.
829BasicBlock *NewGVN::getBlockForValue(Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000830 if (auto *I = dyn_cast<Instruction>(V)) {
831 auto *Parent = I->getParent();
832 if (Parent)
833 return Parent;
834 Parent = TempToBlock.lookup(V);
835 assert(Parent && "Every fake instruction should have a block");
836 return Parent;
837 }
838
839 auto *MP = dyn_cast<MemoryPhi>(V);
840 assert(MP && "Should have been an instruction or a MemoryPhi");
841 return MP->getBlock();
Daniel Berlin06329a92017-03-18 15:41:40 +0000842}
843
Daniel Berlin0e900112017-03-24 06:33:48 +0000844// Delete a definitely dead expression, so it can be reused by the expression
845// allocator. Some of these are not in creation functions, so we have to accept
846// const versions.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000847void NewGVN::deleteExpression(const Expression *E) const {
Daniel Berlin0e900112017-03-24 06:33:48 +0000848 assert(isa<BasicExpression>(E));
849 auto *BE = cast<BasicExpression>(E);
850 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
851 ExpressionAllocator.Deallocate(E);
852}
Daniel Berlin1a582582017-09-05 02:17:41 +0000853
Daniel Berlinf9c94552017-09-05 02:17:43 +0000854// If V is a predicateinfo copy, get the thing it is a copy of.
855static Value *getCopyOf(const Value *V) {
Daniel Berlin1a582582017-09-05 02:17:41 +0000856 if (auto *II = dyn_cast<IntrinsicInst>(V))
Daniel Berlinf9c94552017-09-05 02:17:43 +0000857 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
858 return II->getOperand(0);
859 return nullptr;
860}
861
862// Return true if V is really PN, even accounting for predicateinfo copies.
863static bool isCopyOfPHI(const Value *V, const PHINode *PN) {
864 return V == PN || getCopyOf(V) == PN;
865}
866
867static bool isCopyOfAPHI(const Value *V) {
868 auto *CO = getCopyOf(V);
869 return CO && isa<PHINode>(CO);
Daniel Berlin1a582582017-09-05 02:17:41 +0000870}
871
Daniel Berlin2f72b192017-04-14 02:53:37 +0000872PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000873 bool &OriginalOpsConstant) const {
874 BasicBlock *PHIBlock = getBlockForValue(I);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000875 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000876 auto *E =
877 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000878
879 E->allocateOperands(ArgRecycler, ExpressionAllocator);
880 E->setType(I->getType());
881 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000882
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000883 // NewGVN assumes the operands of a PHI node are in a consistent order across
884 // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix
885 // this in LLVM at some point we don't want GVN to find wrong congruences.
886 // Therefore, here we sort uses in predecessor order.
Davide Italiano63998ec2017-05-09 18:29:37 +0000887 // We're sorting the values by pointer. In theory this might be cause of
888 // non-determinism, but here we don't rely on the ordering for anything
889 // significant, e.g. we don't create new instructions based on it so we're
890 // fine.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000891 SmallVector<const Use *, 4> PHIOperands;
892 for (const Use &U : PN->operands())
893 PHIOperands.push_back(&U);
894 std::sort(PHIOperands.begin(), PHIOperands.end(),
895 [&](const Use *U1, const Use *U2) {
896 return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
897 });
898
Davide Italianob3886dd2017-01-25 23:37:49 +0000899 // Filter out unreachable phi operands.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000900 auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) {
Daniel Berlinf9c94552017-09-05 02:17:43 +0000901 auto *BB = PN->getIncomingBlock(*U);
902 if (isCopyOfPHI(*U, PN))
Daniel Berline67c3222017-05-25 15:44:20 +0000903 return false;
Daniel Berlinf9c94552017-09-05 02:17:43 +0000904 if (!ReachableEdges.count({BB, PHIBlock}))
Daniel Berline67c3222017-05-25 15:44:20 +0000905 return false;
906 // Things in TOPClass are equivalent to everything.
907 if (ValueToClass.lookup(*U) == TOPClass)
908 return false;
Daniel Berlinf9c94552017-09-05 02:17:43 +0000909 OriginalOpsConstant = OriginalOpsConstant && isa<Constant>(*U);
910 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
Davide Italianoa7a77542017-07-10 20:45:00 +0000911 return lookupOperandLeader(*U) != PN;
Davide Italianob3886dd2017-01-25 23:37:49 +0000912 });
Daniel Berlinf9c94552017-09-05 02:17:43 +0000913 std::transform(
914 Filtered.begin(), Filtered.end(), op_inserter(E),
915 [&](const Use *U) -> Value * { return lookupOperandLeader(*U); });
Davide Italiano7e274e02016-12-22 16:03:48 +0000916 return E;
917}
918
919// Set basic expression info (Arguments, type, opcode) for Expression
920// E from Instruction I in block B.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000921bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000922 bool AllConstant = true;
923 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
924 E->setType(GEP->getSourceElementType());
925 else
926 E->setType(I->getType());
927 E->setOpcode(I->getOpcode());
928 E->allocateOperands(ArgRecycler, ExpressionAllocator);
929
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000930 // Transform the operand array into an operand leader array, and keep track of
931 // whether all members are constant.
932 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000933 auto Operand = lookupOperandLeader(O);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000934 AllConstant = AllConstant && isa<Constant>(Operand);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000935 return Operand;
936 });
937
Davide Italiano7e274e02016-12-22 16:03:48 +0000938 return AllConstant;
939}
940
941const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin54a92fc2017-09-05 02:17:42 +0000942 Value *Arg1, Value *Arg2,
943 Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000944 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000945
946 E->setType(T);
947 E->setOpcode(Opcode);
948 E->allocateOperands(ArgRecycler, ExpressionAllocator);
949 if (Instruction::isCommutative(Opcode)) {
950 // Ensure that commutative instructions that only differ by a permutation
951 // of their operands get the same value number by sorting the operand value
952 // numbers. Since all commutative instructions have two operands it is more
953 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000954 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000955 std::swap(Arg1, Arg2);
956 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000957 E->op_push_back(lookupOperandLeader(Arg1));
958 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000959
Daniel Berlinede130d2017-04-26 20:56:14 +0000960 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlin54a92fc2017-09-05 02:17:42 +0000961 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
Davide Italiano7e274e02016-12-22 16:03:48 +0000962 return SimplifiedE;
963 return E;
964}
965
966// Take a Value returned by simplification of Expression E/Instruction
967// I, and see if it resulted in a simpler expression. If so, return
968// that expression.
Davide Italiano7e274e02016-12-22 16:03:48 +0000969const Expression *NewGVN::checkSimplificationResults(Expression *E,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000970 Instruction *I,
971 Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000972 if (!V)
973 return nullptr;
974 if (auto *C = dyn_cast<Constant>(V)) {
975 if (I)
976 DEBUG(dbgs() << "Simplified " << *I << " to "
977 << " constant " << *C << "\n");
978 NumGVNOpsSimplified++;
979 assert(isa<BasicExpression>(E) &&
980 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000981 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000982 return createConstantExpression(C);
983 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
984 if (I)
985 DEBUG(dbgs() << "Simplified " << *I << " to "
986 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000987 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000988 return createVariableExpression(V);
989 }
990
991 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlin7ef26da2017-08-30 19:52:39 +0000992 if (CC) {
993 if (CC->getLeader() && CC->getLeader() != I) {
Daniel Berlin94090dd2017-09-02 02:18:44 +0000994 // Don't add temporary instructions to the user lists.
995 if (!AllTempInstructions.count(I))
996 addAdditionalUsers(V, I);
Daniel Berlin7ef26da2017-08-30 19:52:39 +0000997 return createVariableOrConstant(CC->getLeader());
Daniel Berlinc8ed4042017-05-30 06:42:29 +0000998 }
Daniel Berlin7ef26da2017-08-30 19:52:39 +0000999 if (CC->getDefiningExpr()) {
1000 // If we simplified to something else, we need to communicate
1001 // that we're users of the value we simplified to.
1002 if (I != V) {
1003 // Don't add temporary instructions to the user lists.
1004 if (!AllTempInstructions.count(I))
1005 addAdditionalUsers(V, I);
1006 }
1007
1008 if (I)
1009 DEBUG(dbgs() << "Simplified " << *I << " to "
1010 << " expression " << *CC->getDefiningExpr() << "\n");
1011 NumGVNOpsSimplified++;
1012 deleteExpression(E);
1013 return CC->getDefiningExpr();
1014 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001015 }
Daniel Berlin7ef26da2017-08-30 19:52:39 +00001016
Davide Italiano7e274e02016-12-22 16:03:48 +00001017 return nullptr;
1018}
1019
Daniel Berlin94090dd2017-09-02 02:18:44 +00001020// Create a value expression from the instruction I, replacing operands with
1021// their leaders.
1022
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001023const Expression *NewGVN::createExpression(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001024 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +00001025
Daniel Berlin97718e62017-01-31 22:32:03 +00001026 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001027
1028 if (I->isCommutative()) {
1029 // Ensure that commutative instructions that only differ by a permutation
1030 // of their operands get the same value number by sorting the operand value
1031 // numbers. Since all commutative instructions have two operands it is more
1032 // efficient to sort by hand rather than using, say, std::sort.
1033 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +00001034 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +00001035 E->swapOperands(0, 1);
1036 }
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001037 // Perform simplification.
Davide Italiano7e274e02016-12-22 16:03:48 +00001038 if (auto *CI = dyn_cast<CmpInst>(I)) {
1039 // Sort the operand value numbers so x<y and y>x get the same value
1040 // number.
1041 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +00001042 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001043 E->swapOperands(0, 1);
1044 Predicate = CmpInst::getSwappedPredicate(Predicate);
1045 }
1046 E->setOpcode((CI->getOpcode() << 8) | Predicate);
1047 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +00001048 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
1049 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +00001050 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
1051 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +00001052 Value *V =
1053 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +00001054 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1055 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001056 } else if (isa<SelectInst>(I)) {
1057 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlinf9486032017-08-24 02:43:17 +00001058 E->getOperand(1) == E->getOperand(2)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001059 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
1060 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +00001061 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +00001062 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001063 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1064 return SimplifiedE;
1065 }
1066 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001067 Value *V =
1068 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001069 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1070 return SimplifiedE;
1071 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001072 Value *V =
1073 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001074 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1075 return SimplifiedE;
1076 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001077 Value *V = SimplifyGEPInst(
1078 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001079 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1080 return SimplifiedE;
1081 } else if (AllConstant) {
1082 // We don't bother trying to simplify unless all of the operands
1083 // were constant.
1084 // TODO: There are a lot of Simplify*'s we could call here, if we
1085 // wanted to. The original motivating case for this code was a
1086 // zext i1 false to i8, which we don't have an interface to
1087 // simplify (IE there is no SimplifyZExt).
1088
1089 SmallVector<Constant *, 8> C;
1090 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001091 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +00001092
Daniel Berlin64e68992017-03-12 04:46:45 +00001093 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +00001094 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1095 return SimplifiedE;
1096 }
1097 return E;
1098}
1099
1100const AggregateValueExpression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001101NewGVN::createAggregateValueExpression(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001102 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001103 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001104 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001105 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001106 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001107 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001108 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001109 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001110 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001111 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001112 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001113 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001114 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001115 return E;
1116 }
1117 llvm_unreachable("Unhandled type of aggregate value operation");
1118}
1119
Daniel Berline021d2d2017-05-19 20:22:20 +00001120const DeadExpression *NewGVN::createDeadExpression() const {
1121 // DeadExpression has no arguments and all DeadExpression's are the same,
1122 // so we only need one of them.
1123 return SingletonDeadExpression;
1124}
1125
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001126const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001127 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001128 E->setOpcode(V->getValueID());
1129 return E;
1130}
1131
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001132const Expression *NewGVN::createVariableOrConstant(Value *V) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001133 if (auto *C = dyn_cast<Constant>(V))
1134 return createConstantExpression(C);
1135 return createVariableExpression(V);
1136}
1137
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001138const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001139 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +00001140 E->setOpcode(C->getValueID());
1141 return E;
1142}
1143
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001144const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001145 auto *E = new (ExpressionAllocator) UnknownExpression(I);
1146 E->setOpcode(I->getOpcode());
1147 return E;
1148}
1149
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001150const CallExpression *
1151NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001152 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001153 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +00001154 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +00001155 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001156 return E;
1157}
1158
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001159// Return true if some equivalent of instruction Inst dominates instruction U.
1160bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1161 const Instruction *U) const {
1162 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +00001163 // This must be an instruction because we are only called from phi nodes
1164 // in the case that the value it needs to check against is an instruction.
1165
1166 // The most likely candiates for dominance are the leader and the next leader.
1167 // The leader or nextleader will dominate in all cases where there is an
1168 // equivalent that is higher up in the dom tree.
1169 // We can't *only* check them, however, because the
1170 // dominator tree could have an infinite number of non-dominating siblings
1171 // with instructions that are in the right congruence class.
1172 // A
1173 // B C D E F G
1174 // |
1175 // H
1176 // Instruction U could be in H, with equivalents in every other sibling.
1177 // Depending on the rpo order picked, the leader could be the equivalent in
1178 // any of these siblings.
1179 if (!CC)
1180 return false;
Daniel Berlina8236562017-04-07 18:38:09 +00001181 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001182 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001183 if (CC->getNextLeader().first &&
1184 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001185 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001186 return llvm::any_of(*CC, [&](const Value *Member) {
1187 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001188 DT->dominates(cast<Instruction>(Member), U);
1189 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001190}
1191
Davide Italiano7e274e02016-12-22 16:03:48 +00001192// See if we have a congruence class and leader for this operand, and if so,
1193// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001194Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001195 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001196 if (CC) {
Daniel Berline021d2d2017-05-19 20:22:20 +00001197 // Everything in TOP is represented by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001198 // We do have to make sure we get the type right though, so we can't set the
1199 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001200 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001201 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001202 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001203 }
1204
Davide Italiano7e274e02016-12-22 16:03:48 +00001205 return V;
1206}
1207
Daniel Berlin1316a942017-04-06 18:52:50 +00001208const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1209 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001210 assert(CC->getMemoryLeader() &&
Davide Italianob60f6e02017-05-12 15:25:56 +00001211 "Every MemoryAccess should be mapped to a congruence class with a "
1212 "representative memory access");
Daniel Berlina8236562017-04-07 18:38:09 +00001213 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001214}
1215
Daniel Berlinc4796862017-01-27 02:37:11 +00001216// Return true if the MemoryAccess is really equivalent to everything. This is
1217// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001218// state of all MemoryAccesses.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001219bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001220 return getMemoryClass(MA) == TOPClass;
1221}
1222
Davide Italiano7e274e02016-12-22 16:03:48 +00001223LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001224 LoadInst *LI,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001225 const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001226 auto *E =
1227 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001228 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1229 E->setType(LoadType);
1230
1231 // Give store and loads same opcode so they value number together.
1232 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001233 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001234 if (LI)
1235 E->setAlignment(LI->getAlignment());
1236
1237 // TODO: Value number heap versions. We may be able to discover
1238 // things alias analysis can't on it's own (IE that a store and a
1239 // load have the same value, and thus, it isn't clobbering the load).
1240 return E;
1241}
1242
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001243const StoreExpression *
1244NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001245 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001246 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001247 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001248 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1249 E->setType(SI->getValueOperand()->getType());
1250
1251 // Give store and loads same opcode so they value number together.
1252 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001253 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001254
1255 // TODO: Value number heap versions. We may be able to discover
1256 // things alias analysis can't on it's own (IE that a store and a
1257 // load have the same value, and thus, it isn't clobbering the load).
1258 return E;
1259}
1260
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001261const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001262 // Unlike loads, we never try to eliminate stores, so we do not check if they
1263 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001264 auto *SI = cast<StoreInst>(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001265 auto *StoreAccess = getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001266 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001267 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1268 if (EnableStoreRefinement)
1269 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1270 // If we bypassed the use-def chains, make sure we add a use.
Daniel Berlinde269f42017-08-26 07:37:11 +00001271 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlin1316a942017-04-06 18:52:50 +00001272 if (StoreRHS != StoreAccess->getDefiningAccess())
1273 addMemoryUsers(StoreRHS, StoreAccess);
Daniel Berlinc4796862017-01-27 02:37:11 +00001274 // If we are defined by ourselves, use the live on entry def.
1275 if (StoreRHS == StoreAccess)
1276 StoreRHS = MSSA->getLiveOnEntryDef();
1277
Daniel Berlin589cecc2017-01-02 18:00:46 +00001278 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001279 // See if we are defined by a previous store expression, it already has a
1280 // value, and it's the same value as our current store. FIXME: Right now, we
1281 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001282 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1283 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlin36b08b22017-06-19 00:24:00 +00001284 // We really want to check whether the expression we matched was a store. No
1285 // easy way to do that. However, we can check that the class we found has a
1286 // store, which, assuming the value numbering state is not corrupt, is
1287 // sufficient, because we must also be equivalent to that store's expression
1288 // for it to be in the same class as the load.
1289 if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
Daniel Berlin1316a942017-04-06 18:52:50 +00001290 return LastStore;
Daniel Berlinc4796862017-01-27 02:37:11 +00001291 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001292 // location, and the memory state is the same as it was then (otherwise, it
1293 // could have been overwritten later. See test32 in
1294 // transforms/DeadStoreElimination/simple.ll).
Daniel Berlin36b08b22017-06-19 00:24:00 +00001295 if (auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
Daniel Berlin203f47b2017-01-31 22:31:53 +00001296 if ((lookupOperandLeader(LI->getPointerOperand()) ==
Daniel Berlin36b08b22017-06-19 00:24:00 +00001297 LastStore->getOperand(0)) &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001298 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
Daniel Berlin1316a942017-04-06 18:52:50 +00001299 StoreRHS))
Daniel Berlin36b08b22017-06-19 00:24:00 +00001300 return LastStore;
1301 deleteExpression(LastStore);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001302 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001303
1304 // If the store is not equivalent to anything, value number it as a store that
1305 // produces a unique memory state (instead of using it's MemoryUse, we use
1306 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001307 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001308}
1309
Daniel Berlin07daac82017-04-02 13:23:44 +00001310// See if we can extract the value of a loaded pointer from a load, a store, or
1311// a memory instruction.
1312const Expression *
1313NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1314 LoadInst *LI, Instruction *DepInst,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001315 MemoryAccess *DefiningAccess) const {
Daniel Berlin07daac82017-04-02 13:23:44 +00001316 assert((!LI || LI->isSimple()) && "Not a simple load");
1317 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1318 // Can't forward from non-atomic to atomic without violating memory model.
1319 // Also don't need to coerce if they are the same type, we will just
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001320 // propagate.
Daniel Berlin07daac82017-04-02 13:23:44 +00001321 if (LI->isAtomic() > DepSI->isAtomic() ||
1322 LoadType == DepSI->getValueOperand()->getType())
1323 return nullptr;
1324 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1325 if (Offset >= 0) {
1326 if (auto *C = dyn_cast<Constant>(
1327 lookupOperandLeader(DepSI->getValueOperand()))) {
1328 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1329 << *C << "\n");
1330 return createConstantExpression(
1331 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1332 }
1333 }
1334
Davide Italiano9bdccb32017-08-26 22:31:10 +00001335 } else if (auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
Daniel Berlin07daac82017-04-02 13:23:44 +00001336 // Can't forward from non-atomic to atomic without violating memory model.
1337 if (LI->isAtomic() > DepLI->isAtomic())
1338 return nullptr;
1339 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1340 if (Offset >= 0) {
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001341 // We can coerce a constant load into a load.
Daniel Berlin07daac82017-04-02 13:23:44 +00001342 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1343 if (auto *PossibleConstant =
1344 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1345 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1346 << *PossibleConstant << "\n");
1347 return createConstantExpression(PossibleConstant);
1348 }
1349 }
1350
Davide Italiano9bdccb32017-08-26 22:31:10 +00001351 } else if (auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
Daniel Berlin07daac82017-04-02 13:23:44 +00001352 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1353 if (Offset >= 0) {
1354 if (auto *PossibleConstant =
1355 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1356 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1357 << " to constant " << *PossibleConstant << "\n");
1358 return createConstantExpression(PossibleConstant);
1359 }
1360 }
1361 }
1362
1363 // All of the below are only true if the loaded pointer is produced
1364 // by the dependent instruction.
1365 if (LoadPtr != lookupOperandLeader(DepInst) &&
1366 !AA->isMustAlias(LoadPtr, DepInst))
1367 return nullptr;
1368 // If this load really doesn't depend on anything, then we must be loading an
1369 // undef value. This can happen when loading for a fresh allocation with no
1370 // intervening stores, for example. Note that this is only true in the case
1371 // that the result of the allocation is pointer equal to the load ptr.
1372 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1373 return createConstantExpression(UndefValue::get(LoadType));
1374 }
1375 // If this load occurs either right after a lifetime begin,
1376 // then the loaded value is undefined.
1377 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1378 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1379 return createConstantExpression(UndefValue::get(LoadType));
1380 }
1381 // If this load follows a calloc (which zero initializes memory),
1382 // then the loaded value is zero
1383 else if (isCallocLikeFn(DepInst, TLI)) {
1384 return createConstantExpression(Constant::getNullValue(LoadType));
1385 }
1386
1387 return nullptr;
1388}
1389
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001390const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001391 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001392
1393 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001394 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001395 if (!LI->isSimple())
1396 return nullptr;
1397
Daniel Berlin203f47b2017-01-31 22:31:53 +00001398 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001399 // Load of undef is undef.
1400 if (isa<UndefValue>(LoadAddressLeader))
1401 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001402 MemoryAccess *OriginalAccess = getMemoryAccess(I);
1403 MemoryAccess *DefiningAccess =
1404 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001405
1406 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1407 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1408 Instruction *DefiningInst = MD->getMemoryInst();
1409 // If the defining instruction is not reachable, replace with undef.
1410 if (!ReachableBlocks.count(DefiningInst->getParent()))
1411 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001412 // This will handle stores and memory insts. We only do if it the
1413 // defining access has a different type, or it is a pointer produced by
1414 // certain memory operations that cause the memory to have a fixed value
1415 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001416 if (const auto *CoercionResult =
1417 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1418 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001419 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001420 }
1421 }
1422
Daniel Berlin94090dd2017-09-02 02:18:44 +00001423 const auto *LE = createLoadExpression(LI->getType(), LoadAddressLeader, LI,
1424 DefiningAccess);
Daniel Berlinde269f42017-08-26 07:37:11 +00001425 // If our MemoryLeader is not our defining access, add a use to the
1426 // MemoryLeader, so that we get reprocessed when it changes.
1427 if (LE->getMemoryLeader() != DefiningAccess)
1428 addMemoryUsers(LE->getMemoryLeader(), OriginalAccess);
1429 return LE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001430}
1431
Daniel Berlinf7d95802017-02-18 23:06:50 +00001432const Expression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001433NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001434 auto *PI = PredInfo->getPredicateInfoFor(I);
1435 if (!PI)
1436 return nullptr;
1437
1438 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001439
1440 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1441 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001442 return nullptr;
1443
Daniel Berlinfccbda92017-02-22 22:20:58 +00001444 auto *CopyOf = I->getOperand(0);
1445 auto *Cond = PWC->Condition;
1446
Daniel Berlinf7d95802017-02-18 23:06:50 +00001447 // If this a copy of the condition, it must be either true or false depending
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001448 // on the predicate info type and edge.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001449 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001450 // We should not need to add predicate users because the predicate info is
1451 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001452 if (isa<PredicateAssume>(PI))
1453 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1454 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1455 if (PBranch->TrueEdge)
1456 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1457 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1458 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001459 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1460 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001461 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001462
Daniel Berlinf7d95802017-02-18 23:06:50 +00001463 // Not a copy of the condition, so see what the predicates tell us about this
1464 // value. First, though, we check to make sure the value is actually a copy
1465 // of one of the condition operands. It's possible, in certain cases, for it
1466 // to be a copy of a predicateinfo copy. In particular, if two branch
1467 // operations use the same condition, and one branch dominates the other, we
1468 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001469 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001470 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001471
1472 // Everything below relies on the condition being a comparison.
1473 auto *Cmp = dyn_cast<CmpInst>(Cond);
1474 if (!Cmp)
1475 return nullptr;
1476
1477 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Davide Italianoc43a9f82017-05-12 15:28:12 +00001478 DEBUG(dbgs() << "Copy is not of any condition operands!\n");
Daniel Berlinf7d95802017-02-18 23:06:50 +00001479 return nullptr;
1480 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001481 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1482 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001483 bool SwappedOps = false;
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001484 // Sort the ops.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001485 if (shouldSwapOperands(FirstOp, SecondOp)) {
1486 std::swap(FirstOp, SecondOp);
1487 SwappedOps = true;
1488 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001489 CmpInst::Predicate Predicate =
1490 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1491
1492 if (isa<PredicateAssume>(PI)) {
1493 // If the comparison is true when the operands are equal, then we know the
1494 // operands are equal, because assumes must always be true.
1495 if (CmpInst::isTrueWhenEqual(Predicate)) {
1496 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001497 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001498 return createVariableOrConstant(FirstOp);
1499 }
1500 }
1501 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1502 // If we are *not* a copy of the comparison, we may equal to the other
1503 // operand when the predicate implies something about equality of
1504 // operations. In particular, if the comparison is true/false when the
1505 // operands are equal, and we are on the right edge, we know this operation
1506 // is equal to something.
1507 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1508 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1509 addPredicateUsers(PI, I);
Daniel Berlin23fec572017-08-30 19:53:23 +00001510 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1511 I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001512 return createVariableOrConstant(FirstOp);
1513 }
1514 // Handle the special case of floating point.
1515 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1516 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1517 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1518 addPredicateUsers(PI, I);
Daniel Berlin23fec572017-08-30 19:53:23 +00001519 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1520 I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001521 return createConstantExpression(cast<Constant>(FirstOp));
1522 }
1523 }
1524 return nullptr;
1525}
1526
Davide Italiano7e274e02016-12-22 16:03:48 +00001527// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001528const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001529 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001530 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1531 // Instrinsics with the returned attribute are copies of arguments.
1532 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1533 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1534 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1535 return Result;
1536 return createVariableOrConstant(ReturnedValue);
1537 }
1538 }
1539 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001540 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001541 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001542 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001543 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001544 }
1545 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001546}
1547
Daniel Berlin1316a942017-04-06 18:52:50 +00001548// Retrieve the memory class for a given MemoryAccess.
1549CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1550
1551 auto *Result = MemoryAccessToClass.lookup(MA);
1552 assert(Result && "Should have found memory class");
1553 return Result;
1554}
1555
1556// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001557// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001558bool NewGVN::setMemoryClass(const MemoryAccess *From,
1559 CongruenceClass *NewClass) {
1560 assert(NewClass &&
1561 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001562 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001563 DEBUG(dbgs() << " equivalent to congruence class ");
Daniel Berlina8236562017-04-07 18:38:09 +00001564 DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
Davide Italianob7a66982017-05-09 20:02:48 +00001565 DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001566
1567 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001568 bool Changed = false;
1569 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001570 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001571 auto *OldClass = LookupResult->second;
1572 if (OldClass != NewClass) {
1573 // If this is a phi, we have to handle memory member updates.
1574 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001575 OldClass->memory_erase(MP);
1576 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001577 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001578 if (OldClass->getMemoryLeader() == From) {
Davide Italiano41f5c7b2017-05-12 15:22:45 +00001579 if (OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00001580 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001581 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001582 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Daniel Berlin1316a942017-04-06 18:52:50 +00001583 DEBUG(dbgs() << "Memory class leader change for class "
Daniel Berlina8236562017-04-07 18:38:09 +00001584 << OldClass->getID() << " to "
1585 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001586 << " due to removal of a memory member " << *From
1587 << "\n");
1588 markMemoryLeaderChangeTouched(OldClass);
1589 }
1590 }
1591 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001592 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001593 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001594 Changed = true;
1595 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001596 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001597
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001598 return Changed;
1599}
Daniel Berlin0e900112017-03-24 06:33:48 +00001600
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001601// Determine if a instruction is cycle-free. That means the values in the
1602// instruction don't depend on any expressions that can change value as a result
1603// of the instruction. For example, a non-cycle free instruction would be v =
1604// phi(0, v+1).
1605bool NewGVN::isCycleFree(const Instruction *I) const {
1606 // In order to compute cycle-freeness, we do SCC finding on the instruction,
1607 // and see what kind of SCC it ends up in. If it is a singleton, it is
1608 // cycle-free. If it is not in a singleton, it is only cycle free if the
1609 // other members are all phi nodes (as they do not compute anything, they are
1610 // copies).
1611 auto ICS = InstCycleState.lookup(I);
1612 if (ICS == ICS_Unknown) {
1613 SCCFinder.Start(I);
1614 auto &SCC = SCCFinder.getComponentFor(I);
Daniel Berlin2f72b192017-04-14 02:53:37 +00001615 // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1616 if (SCC.size() == 1)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001617 InstCycleState.insert({I, ICS_CycleFree});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001618 else {
Daniel Berlinf9c94552017-09-05 02:17:43 +00001619 bool AllPhis = llvm::all_of(SCC, [](const Value *V) {
1620 return isa<PHINode>(V) || isCopyOfAPHI(V);
1621 });
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001622 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
Daniel Berlin2f72b192017-04-14 02:53:37 +00001623 for (auto *Member : SCC)
1624 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001625 InstCycleState.insert({MemberPhi, ICS});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001626 }
1627 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001628 if (ICS == ICS_Cycle)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001629 return false;
1630 return true;
1631}
1632
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001633// Evaluate PHI nodes symbolically and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001634const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001635 // True if one of the incoming phi edges is a backedge.
1636 bool HasBackedge = false;
1637 // All constant tracks the state of whether all the *original* phi operands
Daniel Berline021d2d2017-05-19 20:22:20 +00001638 // This is really shorthand for "this phi cannot cycle due to forward
1639 // change in value of the phi is guaranteed not to later change the value of
1640 // the phi. IE it can't be v = phi(undef, v+1)
Daniel Berlinf9c94552017-09-05 02:17:43 +00001641 bool OriginalOpsConstant = true;
1642 auto *E = cast<PHIExpression>(
1643 createPHIExpression(I, HasBackedge, OriginalOpsConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001644 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001645 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001646 // We track if any were undef because they need special handling.
1647 bool HasUndef = false;
Daniel Berline021d2d2017-05-19 20:22:20 +00001648 auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
Daniel Berlind92e7f92017-01-07 00:01:42 +00001649 if (isa<UndefValue>(Arg)) {
1650 HasUndef = true;
1651 return false;
1652 }
1653 return true;
1654 });
Daniel Berline021d2d2017-05-19 20:22:20 +00001655 // If we are left with no operands, it's dead.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001656 if (Filtered.begin() == Filtered.end()) {
Daniel Berline67c3222017-05-25 15:44:20 +00001657 // If it has undef at this point, it means there are no-non-undef arguments,
1658 // and thus, the value of the phi node must be undef.
1659 if (HasUndef) {
1660 DEBUG(dbgs() << "PHI Node " << *I
1661 << " has no non-undef arguments, valuing it as undef\n");
1662 return createConstantExpression(UndefValue::get(I->getType()));
1663 }
1664
Daniel Berline021d2d2017-05-19 20:22:20 +00001665 DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001666 deleteExpression(E);
Daniel Berline021d2d2017-05-19 20:22:20 +00001667 return createDeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00001668 }
Daniel Berlind92e7f92017-01-07 00:01:42 +00001669 Value *AllSameValue = *(Filtered.begin());
1670 ++Filtered.begin();
1671 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berlinf9c94552017-09-05 02:17:43 +00001672 if (llvm::all_of(Filtered, [&](Value *Arg) { return Arg == AllSameValue; })) {
Daniel Berlind92e7f92017-01-07 00:01:42 +00001673 // In LLVM's non-standard representation of phi nodes, it's possible to have
1674 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1675 // on the original phi node), especially in weird CFG's where some arguments
1676 // are unreachable, or uninitialized along certain paths. This can cause
1677 // infinite loops during evaluation. We work around this by not trying to
1678 // really evaluate them independently, but instead using a variable
1679 // expression to say if one is equivalent to the other.
1680 // We also special case undef, so that if we have an undef, we can't use the
1681 // common value unless it dominates the phi block.
1682 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001683 // If we have undef and at least one other value, this is really a
1684 // multivalued phi, and we need to know if it's cycle free in order to
1685 // evaluate whether we can ignore the undef. The other parts of this are
1686 // just shortcuts. If there is no backedge, or all operands are
Daniel Berlinf9c94552017-09-05 02:17:43 +00001687 // constants, it also must be cycle free.
1688 if (HasBackedge && !OriginalOpsConstant &&
Daniel Berline67c3222017-05-25 15:44:20 +00001689 !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
Daniel Berlin2f72b192017-04-14 02:53:37 +00001690 return E;
1691
Daniel Berlind92e7f92017-01-07 00:01:42 +00001692 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001693 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001694 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001695 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001696 }
Daniel Berlineafdd862017-06-06 17:15:28 +00001697 // Can't simplify to something that comes later in the iteration.
1698 // Otherwise, when and if it changes congruence class, we will never catch
1699 // up. We will always be a class behind it.
1700 if (isa<Instruction>(AllSameValue) &&
1701 InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
1702 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001703 NumGVNPhisAllSame++;
1704 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1705 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001706 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001707 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001708 }
1709 return E;
1710}
1711
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001712const Expression *
1713NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001714 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1715 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1716 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1717 unsigned Opcode = 0;
1718 // EI might be an extract from one of our recognised intrinsics. If it
1719 // is we'll synthesize a semantically equivalent expression instead on
1720 // an extract value expression.
1721 switch (II->getIntrinsicID()) {
1722 case Intrinsic::sadd_with_overflow:
1723 case Intrinsic::uadd_with_overflow:
1724 Opcode = Instruction::Add;
1725 break;
1726 case Intrinsic::ssub_with_overflow:
1727 case Intrinsic::usub_with_overflow:
1728 Opcode = Instruction::Sub;
1729 break;
1730 case Intrinsic::smul_with_overflow:
1731 case Intrinsic::umul_with_overflow:
1732 Opcode = Instruction::Mul;
1733 break;
1734 default:
1735 break;
1736 }
1737
1738 if (Opcode != 0) {
1739 // Intrinsic recognized. Grab its args to finish building the
1740 // expression.
1741 assert(II->getNumArgOperands() == 2 &&
1742 "Expect two args for recognised intrinsics.");
Daniel Berlin54a92fc2017-09-05 02:17:42 +00001743 return createBinaryExpression(Opcode, EI->getType(),
1744 II->getArgOperand(0),
1745 II->getArgOperand(1), I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001746 }
1747 }
1748 }
1749
Daniel Berlin97718e62017-01-31 22:32:03 +00001750 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001751}
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001752const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
Chad Rosier4d852592017-08-08 18:41:49 +00001753 assert(isa<CmpInst>(I) && "Expected a cmp instruction.");
1754
1755 auto *CI = cast<CmpInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001756 // See if our operands are equal to those of a previous predicate, and if so,
1757 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001758 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1759 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001760 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001761 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001762 std::swap(Op0, Op1);
1763 OurPredicate = CI->getSwappedPredicate();
1764 }
1765
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001766 // Avoid processing the same info twice.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001767 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001768 // See if we know something about the comparison itself, like it is the target
1769 // of an assume.
1770 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1771 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1772 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1773
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001774 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001775 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001776 if (CI->isTrueWhenEqual())
1777 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1778 else if (CI->isFalseWhenEqual())
1779 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1780 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001781
1782 // NOTE: Because we are comparing both operands here and below, and using
1783 // previous comparisons, we rely on fact that predicateinfo knows to mark
1784 // comparisons that use renamed operands as users of the earlier comparisons.
1785 // It is *not* enough to just mark predicateinfo renamed operands as users of
1786 // the earlier comparisons, because the *other* operand may have changed in a
1787 // previous iteration.
1788 // Example:
1789 // icmp slt %a, %b
1790 // %b.0 = ssa.copy(%b)
1791 // false branch:
1792 // icmp slt %c, %b.0
1793
1794 // %c and %a may start out equal, and thus, the code below will say the second
1795 // %icmp is false. c may become equal to something else, and in that case the
1796 // %second icmp *must* be reexamined, but would not if only the renamed
1797 // %operands are considered users of the icmp.
1798
1799 // *Currently* we only check one level of comparisons back, and only mark one
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001800 // level back as touched when changes happen. If you modify this code to look
Daniel Berlinf7d95802017-02-18 23:06:50 +00001801 // back farther through comparisons, you *must* mark the appropriate
1802 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1803 // we know something just from the operands themselves
1804
1805 // See if our operands have predicate info, so that we may be able to derive
1806 // something from a previous comparison.
1807 for (const auto &Op : CI->operands()) {
1808 auto *PI = PredInfo->getPredicateInfoFor(Op);
1809 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1810 if (PI == LastPredInfo)
1811 continue;
1812 LastPredInfo = PI;
Daniel Berlin86932102017-09-01 19:20:18 +00001813 // In phi of ops cases, we may have predicate info that we are evaluating
1814 // in a different context.
1815 if (!DT->dominates(PBranch->To, getBlockForValue(I)))
1816 continue;
1817 // TODO: Along the false edge, we may know more things too, like
1818 // icmp of
Daniel Berlinf7d95802017-02-18 23:06:50 +00001819 // same operands is false.
Daniel Berlin86932102017-09-01 19:20:18 +00001820 // TODO: We only handle actual comparison conditions below, not
1821 // and/or.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001822 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1823 if (!BranchCond)
1824 continue;
1825 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1826 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1827 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001828 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001829 std::swap(BranchOp0, BranchOp1);
1830 BranchPredicate = BranchCond->getSwappedPredicate();
1831 }
1832 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1833 if (PBranch->TrueEdge) {
1834 // If we know the previous predicate is true and we are in the true
1835 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001836 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1837 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001838 addPredicateUsers(PI, I);
1839 return createConstantExpression(
1840 ConstantInt::getTrue(CI->getType()));
1841 }
1842
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001843 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1844 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001845 addPredicateUsers(PI, I);
1846 return createConstantExpression(
1847 ConstantInt::getFalse(CI->getType()));
1848 }
1849
1850 } else {
1851 // Just handle the ne and eq cases, where if we have the same
1852 // operands, we may know something.
1853 if (BranchPredicate == OurPredicate) {
1854 addPredicateUsers(PI, I);
1855 // Same predicate, same ops,we know it was false, so this is false.
1856 return createConstantExpression(
1857 ConstantInt::getFalse(CI->getType()));
1858 } else if (BranchPredicate ==
1859 CmpInst::getInversePredicate(OurPredicate)) {
1860 addPredicateUsers(PI, I);
1861 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001862 return createConstantExpression(
1863 ConstantInt::getTrue(CI->getType()));
1864 }
1865 }
1866 }
1867 }
1868 }
1869 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001870 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001871}
Davide Italiano7e274e02016-12-22 16:03:48 +00001872
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001873// Return true if V is a value that will always be available (IE can
1874// be placed anywhere) in the function. We don't do globals here
1875// because they are often worse to put in place.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001876static bool alwaysAvailable(Value *V) {
1877 return isa<Constant>(V) || isa<Argument>(V);
1878}
1879
Davide Italiano7e274e02016-12-22 16:03:48 +00001880// Substitute and symbolize the value before value numbering.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001881const Expression *
1882NewGVN::performSymbolicEvaluation(Value *V,
1883 SmallPtrSetImpl<Value *> &Visited) const {
Davide Italiano0e714802016-12-28 14:00:11 +00001884 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001885 if (auto *C = dyn_cast<Constant>(V))
1886 E = createConstantExpression(C);
1887 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1888 E = createVariableExpression(V);
1889 } else {
1890 // TODO: memory intrinsics.
1891 // TODO: Some day, we should do the forward propagation and reassociation
1892 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001893 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001894 switch (I->getOpcode()) {
1895 case Instruction::ExtractValue:
1896 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001897 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001898 break;
1899 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001900 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001901 break;
1902 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001903 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001904 break;
1905 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001906 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001907 break;
1908 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001909 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001910 break;
1911 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001912 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001913 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001914 case Instruction::ICmp:
1915 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001916 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001917 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001918 case Instruction::Add:
1919 case Instruction::FAdd:
1920 case Instruction::Sub:
1921 case Instruction::FSub:
1922 case Instruction::Mul:
1923 case Instruction::FMul:
1924 case Instruction::UDiv:
1925 case Instruction::SDiv:
1926 case Instruction::FDiv:
1927 case Instruction::URem:
1928 case Instruction::SRem:
1929 case Instruction::FRem:
1930 case Instruction::Shl:
1931 case Instruction::LShr:
1932 case Instruction::AShr:
1933 case Instruction::And:
1934 case Instruction::Or:
1935 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001936 case Instruction::Trunc:
1937 case Instruction::ZExt:
1938 case Instruction::SExt:
1939 case Instruction::FPToUI:
1940 case Instruction::FPToSI:
1941 case Instruction::UIToFP:
1942 case Instruction::SIToFP:
1943 case Instruction::FPTrunc:
1944 case Instruction::FPExt:
1945 case Instruction::PtrToInt:
1946 case Instruction::IntToPtr:
1947 case Instruction::Select:
1948 case Instruction::ExtractElement:
1949 case Instruction::InsertElement:
1950 case Instruction::ShuffleVector:
1951 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001952 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001953 break;
1954 default:
1955 return nullptr;
1956 }
1957 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001958 return E;
1959}
1960
Daniel Berlin0207cca2017-05-21 23:41:56 +00001961// Look up a container in a map, and then call a function for each thing in the
1962// found container.
1963template <typename Map, typename KeyType, typename Func>
1964void NewGVN::for_each_found(Map &M, const KeyType &Key, Func F) {
1965 const auto Result = M.find_as(Key);
1966 if (Result != M.end())
1967 for (typename Map::mapped_type::value_type Mapped : Result->second)
1968 F(Mapped);
1969}
1970
1971// Look up a container of values/instructions in a map, and touch all the
1972// instructions in the container. Then erase value from the map.
1973template <typename Map, typename KeyType>
1974void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
1975 const auto Result = M.find_as(Key);
1976 if (Result != M.end()) {
1977 for (const typename Map::mapped_type::value_type Mapped : Result->second)
1978 TouchedInstructions.set(InstrToDFSNum(Mapped));
1979 M.erase(Result);
1980 }
1981}
1982
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001983void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
Daniel Berlin54a92fc2017-09-05 02:17:42 +00001984 assert(User && To != User);
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00001985 if (isa<Instruction>(To))
1986 AdditionalUsers[To].insert(User);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001987}
1988
Davide Italiano7e274e02016-12-22 16:03:48 +00001989void NewGVN::markUsersTouched(Value *V) {
1990 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001991 for (auto *User : V->users()) {
1992 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001993 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001994 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00001995 touchAndErase(AdditionalUsers, V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001996}
1997
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001998void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001999 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
2000 MemoryToUsers[To].insert(U);
2001}
2002
2003void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002004 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00002005}
2006
2007void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
2008 if (isa<MemoryUse>(MA))
2009 return;
2010 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00002011 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin0207cca2017-05-21 23:41:56 +00002012 touchAndErase(MemoryToUsers, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00002013}
2014
Daniel Berlinf7d95802017-02-18 23:06:50 +00002015// Add I to the set of users of a given predicate.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00002016void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002017 // Don't add temporary instructions to the user lists.
2018 if (AllTempInstructions.count(I))
2019 return;
2020
Daniel Berlinf7d95802017-02-18 23:06:50 +00002021 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
2022 PredicateToUsers[PBranch->Condition].insert(I);
2023 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
2024 PredicateToUsers[PAssume->Condition].insert(I);
2025}
2026
2027// Touch all the predicates that depend on this instruction.
2028void NewGVN::markPredicateUsersTouched(Instruction *I) {
Daniel Berlin0207cca2017-05-21 23:41:56 +00002029 touchAndErase(PredicateToUsers, I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002030}
2031
Daniel Berlin1316a942017-04-06 18:52:50 +00002032// Mark users affected by a memory leader change.
2033void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00002034 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002035 markMemoryDefTouched(M);
2036}
2037
Daniel Berlin32f8d562017-01-07 16:55:14 +00002038// Touch the instructions that need to be updated after a congruence class has a
2039// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00002040void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00002041 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00002042 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002043 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002044 LeaderChanges.insert(M);
2045 }
2046}
2047
Daniel Berlin1316a942017-04-06 18:52:50 +00002048// Give a range of things that have instruction DFS numbers, this will return
2049// the member of the range with the smallest dfs number.
2050template <class T, class Range>
2051T *NewGVN::getMinDFSOfRange(const Range &R) const {
2052 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
2053 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002054 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00002055 if (DFSNum < MinDFS.second)
2056 MinDFS = {X, DFSNum};
2057 }
2058 return MinDFS.first;
2059}
2060
2061// This function returns the MemoryAccess that should be the next leader of
2062// congruence class CC, under the assumption that the current leader is going to
2063// disappear.
2064const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
2065 // TODO: If this ends up to slow, we can maintain a next memory leader like we
2066 // do for regular leaders.
Daniel Berlinde269f42017-08-26 07:37:11 +00002067 // Make sure there will be a leader to find.
Davide Italianodc435322017-05-10 19:57:43 +00002068 assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00002069 if (CC->getStoreCount() > 0) {
2070 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002071 return getMemoryAccess(NL);
Daniel Berlin1316a942017-04-06 18:52:50 +00002072 // Find the store with the minimum DFS number.
2073 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00002074 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002075 return getMemoryAccess(cast<StoreInst>(V));
Daniel Berlin1316a942017-04-06 18:52:50 +00002076 }
Daniel Berlina8236562017-04-07 18:38:09 +00002077 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00002078
2079 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00002080 // !OldClass->memory_empty()
2081 if (CC->memory_size() == 1)
2082 return *CC->memory_begin();
2083 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00002084}
2085
2086// This function returns the next value leader of a congruence class, under the
2087// assumption that the current leader is going away. This should end up being
2088// the next most dominating member.
2089Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
2090 // We don't need to sort members if there is only 1, and we don't care about
2091 // sorting the TOP class because everything either gets out of it or is
2092 // unreachable.
2093
Daniel Berlina8236562017-04-07 18:38:09 +00002094 if (CC->size() == 1 || CC == TOPClass) {
2095 return *(CC->begin());
2096 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002097 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00002098 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00002099 } else {
2100 ++NumGVNSortedLeaderChanges;
2101 // NOTE: If this ends up to slow, we can maintain a dual structure for
2102 // member testing/insertion, or keep things mostly sorted, and sort only
2103 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00002104 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00002105 }
2106}
2107
2108// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
2109// the memory members, etc for the move.
2110//
2111// The invariants of this function are:
2112//
Davide Italianofb4544c2017-07-11 19:15:36 +00002113// - I must be moving to NewClass from OldClass
2114// - The StoreCount of OldClass and NewClass is expected to have been updated
2115// for I already if it is is a store.
2116// - The OldClass memory leader has not been updated yet if I was the leader.
Daniel Berlin1316a942017-04-06 18:52:50 +00002117void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
2118 MemoryAccess *InstMA,
2119 CongruenceClass *OldClass,
2120 CongruenceClass *NewClass) {
2121 // If the leader is I, and we had a represenative MemoryAccess, it should
2122 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00002123 assert((!InstMA || !OldClass->getMemoryLeader() ||
2124 OldClass->getLeader() != I ||
Davide Italianoee1c8212017-07-11 19:49:12 +00002125 MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
2126 MemoryAccessToClass.lookup(InstMA)) &&
Davide Italianof58a30232017-04-10 23:08:35 +00002127 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00002128 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00002129 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002130 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00002131 assert(NewClass->size() == 1 ||
2132 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
2133 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00002134 // Mark it touched if we didn't just create a singleton
Daniel Berlina8236562017-04-07 18:38:09 +00002135 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002136 << " due to new memory instruction becoming leader\n");
2137 markMemoryLeaderChangeTouched(NewClass);
2138 }
2139 setMemoryClass(InstMA, NewClass);
2140 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00002141 if (OldClass->getMemoryLeader() == InstMA) {
Davide Italianodc435322017-05-10 19:57:43 +00002142 if (!OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00002143 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2144 DEBUG(dbgs() << "Memory class leader change for class "
2145 << OldClass->getID() << " to "
2146 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00002147 << " due to removal of old leader " << *InstMA << "\n");
2148 markMemoryLeaderChangeTouched(OldClass);
2149 } else
Daniel Berlina8236562017-04-07 18:38:09 +00002150 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00002151 }
2152}
2153
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002154// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00002155// Update OldClass and NewClass for the move (including changing leaders, etc).
2156void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002157 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002158 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00002159 if (I == OldClass->getNextLeader().first)
2160 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002161
Daniel Berlinff152002017-05-19 19:01:24 +00002162 OldClass->erase(I);
2163 NewClass->insert(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002164
Daniel Berlina8236562017-04-07 18:38:09 +00002165 if (NewClass->getLeader() != I)
2166 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlin1316a942017-04-06 18:52:50 +00002167 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002168 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002169 OldClass->decStoreCount();
2170 // Okay, so when do we want to make a store a leader of a class?
2171 // If we have a store defined by an earlier load, we want the earlier load
2172 // to lead the class.
2173 // If we have a store defined by something else, we want the store to lead
2174 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00002175 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00002176 // as the leader
2177 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002178 // If it's a store expression we are using, it means we are not equivalent
2179 // to something earlier.
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002180 if (auto *SE = dyn_cast<StoreExpression>(E)) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002181 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1316a942017-04-06 18:52:50 +00002182 markValueLeaderChangeTouched(NewClass);
2183 // Shift the new class leader to be the store
Daniel Berlina8236562017-04-07 18:38:09 +00002184 DEBUG(dbgs() << "Changing leader of congruence class "
2185 << NewClass->getID() << " from " << *NewClass->getLeader()
2186 << " to " << *SI << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002187 // If we changed the leader, we have to mark it changed because we don't
Davide Italiano67b0e532017-07-11 19:19:45 +00002188 // know what it will do to symbolic evaluation.
Daniel Berlina8236562017-04-07 18:38:09 +00002189 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002190 }
2191 // We rely on the code below handling the MemoryAccess change.
2192 }
Daniel Berlina8236562017-04-07 18:38:09 +00002193 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002194 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002195 // True if there is no memory instructions left in a class that had memory
2196 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002197
Daniel Berlin1316a942017-04-06 18:52:50 +00002198 // If it's not a memory use, set the MemoryAccess equivalence
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002199 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
Daniel Berlin1316a942017-04-06 18:52:50 +00002200 if (InstMA)
2201 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002202 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002203 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00002204 if (OldClass->empty() && OldClass != TOPClass) {
2205 if (OldClass->getDefiningExpr()) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002206 DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002207 << " from table\n");
Daniel Berlineafdd862017-06-06 17:15:28 +00002208 // We erase it as an exact expression to make sure we don't just erase an
2209 // equivalent one.
2210 auto Iter = ExpressionToClass.find_as(
2211 ExactEqualsExpression(*OldClass->getDefiningExpr()));
2212 if (Iter != ExpressionToClass.end())
2213 ExpressionToClass.erase(Iter);
2214#ifdef EXPENSIVE_CHECKS
2215 assert(
2216 (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
2217 "We erased the expression we just inserted, which should not happen");
2218#endif
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002219 }
Daniel Berlina8236562017-04-07 18:38:09 +00002220 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002221 // When the leader changes, the value numbering of
2222 // everything may change due to symbolization changes, so we need to
2223 // reprocess.
Daniel Berlina8236562017-04-07 18:38:09 +00002224 DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002225 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002226 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00002227 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002228 // Note that this is basically clean up for the expression removal that
2229 // happens below. If we remove stores from a class, we may leave it as a
2230 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002231 if (OldClass->getStoreCount() == 0) {
2232 if (OldClass->getStoredValue())
2233 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002234 }
Daniel Berlina8236562017-04-07 18:38:09 +00002235 OldClass->setLeader(getNextValueLeader(OldClass));
2236 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002237 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002238 }
2239}
2240
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002241// For a given expression, mark the phi of ops instructions that could have
2242// changed as a result.
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002243void NewGVN::markPhiOfOpsChanged(const Expression *E) {
Daniel Berlin51e878e2017-06-14 21:19:28 +00002244 touchAndErase(ExpressionToPhiOfOps, ExactEqualsExpression(*E));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002245}
Daniel Berlin0207cca2017-05-21 23:41:56 +00002246
Davide Italiano7e274e02016-12-22 16:03:48 +00002247// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002248void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002249 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002250 // TOP.
Daniel Berline021d2d2017-05-19 20:22:20 +00002251
2252 CongruenceClass *IClass = ValueToClass.lookup(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002253 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002254 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002255 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002256
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002257 CongruenceClass *EClass = nullptr;
Daniel Berlin02c6b172017-01-02 18:00:53 +00002258 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002259 EClass = ValueToClass.lookup(VE->getVariableValue());
Daniel Berline021d2d2017-05-19 20:22:20 +00002260 } else if (isa<DeadExpression>(E)) {
2261 EClass = TOPClass;
2262 }
2263 if (!EClass) {
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002264 auto lookupResult = ExpressionToClass.insert({E, nullptr});
Davide Italiano7e274e02016-12-22 16:03:48 +00002265
2266 // If it's not in the value table, create a new congruence class.
2267 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002268 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002269 auto place = lookupResult.first;
2270 place->second = NewClass;
2271
2272 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002273 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002274 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002275 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2276 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002277 NewClass->setLeader(SI);
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002278 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002279 // The RepMemoryAccess field will be filled in properly by the
2280 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002281 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002282 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002283 }
2284 assert(!isa<VariableExpression>(E) &&
2285 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002286
2287 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002288 DEBUG(dbgs() << "Created new congruence class for " << *I
Daniel Berlina8236562017-04-07 18:38:09 +00002289 << " using expression " << *E << " at " << NewClass->getID()
2290 << " and leader " << *(NewClass->getLeader()));
2291 if (NewClass->getStoredValue())
2292 DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
Daniel Berlin26addef2017-01-20 21:04:30 +00002293 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002294 } else {
2295 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002296 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002297 assert((isa<Constant>(EClass->getLeader()) ||
2298 (EClass->getStoredValue() &&
2299 isa<Constant>(EClass->getStoredValue()))) &&
2300 "Any class with a constant expression should have a "
2301 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002302
Davide Italiano7e274e02016-12-22 16:03:48 +00002303 assert(EClass && "Somehow don't have an eclass");
2304
Daniel Berlin1316a942017-04-06 18:52:50 +00002305 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002306 }
2307 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002308 bool ClassChanged = IClass != EClass;
2309 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002310 if (ClassChanged || LeaderChanged) {
Daniel Berlina8236562017-04-07 18:38:09 +00002311 DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00002312 << "\n");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002313 if (ClassChanged) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002314 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002315 markPhiOfOpsChanged(E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002316 }
2317
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002318 markUsersTouched(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002319 if (MemoryAccess *MA = getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002320 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002321 if (auto *CI = dyn_cast<CmpInst>(I))
2322 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002323 }
Daniel Berlin45403572017-05-16 19:58:47 +00002324 // If we changed the class of the store, we want to ensure nothing finds the
2325 // old store expression. In particular, loads do not compare against stored
2326 // value, so they will find old store expressions (and associated class
2327 // mappings) if we leave them in the table.
Davide Italianoee49f492017-05-19 04:06:10 +00002328 if (ClassChanged && isa<StoreInst>(I)) {
Daniel Berlin45403572017-05-16 19:58:47 +00002329 auto *OldE = ValueToExpression.lookup(I);
2330 // It could just be that the old class died. We don't want to erase it if we
2331 // just moved classes.
Daniel Berlineafdd862017-06-06 17:15:28 +00002332 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
2333 // Erase this as an exact expression to ensure we don't erase expressions
2334 // equivalent to it.
2335 auto Iter = ExpressionToClass.find_as(ExactEqualsExpression(*OldE));
2336 if (Iter != ExpressionToClass.end())
2337 ExpressionToClass.erase(Iter);
2338 }
Daniel Berlin45403572017-05-16 19:58:47 +00002339 }
2340 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002341}
2342
2343// Process the fact that Edge (from, to) is reachable, including marking
2344// any newly reachable blocks and instructions for processing.
2345void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2346 // Check if the Edge was reachable before.
2347 if (ReachableEdges.insert({From, To}).second) {
2348 // If this block wasn't reachable before, all instructions are touched.
2349 if (ReachableBlocks.insert(To).second) {
2350 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2351 const auto &InstRange = BlockInstRange.lookup(To);
2352 TouchedInstructions.set(InstRange.first, InstRange.second);
2353 } else {
2354 DEBUG(dbgs() << "Block " << getBlockName(To)
2355 << " was reachable, but new edge {" << getBlockName(From)
2356 << "," << getBlockName(To) << "} to it found\n");
2357
2358 // We've made an edge reachable to an existing block, which may
2359 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2360 // they are the only thing that depend on new edges. Anything using their
2361 // values will get propagated to if necessary.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002362 if (MemoryAccess *MemPhi = getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002363 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002364
Davide Italiano7e274e02016-12-22 16:03:48 +00002365 auto BI = To->begin();
2366 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002367 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00002368 ++BI;
2369 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00002370 for_each_found(PHIOfOpsPHIs, To, [&](const PHINode *I) {
2371 TouchedInstructions.set(InstrToDFSNum(I));
2372 });
Davide Italiano7e274e02016-12-22 16:03:48 +00002373 }
2374 }
2375}
2376
2377// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2378// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002379Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002380 auto Result = lookupOperandLeader(Cond);
Davide Italianodaa9c0e2017-06-19 16:46:15 +00002381 return isa<Constant>(Result) ? Result : nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002382}
2383
2384// Process the outgoing edges of a block for reachability.
2385void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2386 // Evaluate reachability of terminator instruction.
2387 BranchInst *BR;
2388 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2389 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002390 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002391 if (!CondEvaluated) {
2392 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002393 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002394 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2395 CondEvaluated = CE->getConstantValue();
2396 }
2397 } else if (isa<ConstantInt>(Cond)) {
2398 CondEvaluated = Cond;
2399 }
2400 }
2401 ConstantInt *CI;
2402 BasicBlock *TrueSucc = BR->getSuccessor(0);
2403 BasicBlock *FalseSucc = BR->getSuccessor(1);
2404 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2405 if (CI->isOne()) {
2406 DEBUG(dbgs() << "Condition for Terminator " << *TI
2407 << " evaluated to true\n");
2408 updateReachableEdge(B, TrueSucc);
2409 } else if (CI->isZero()) {
2410 DEBUG(dbgs() << "Condition for Terminator " << *TI
2411 << " evaluated to false\n");
2412 updateReachableEdge(B, FalseSucc);
2413 }
2414 } else {
2415 updateReachableEdge(B, TrueSucc);
2416 updateReachableEdge(B, FalseSucc);
2417 }
2418 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2419 // For switches, propagate the case values into the case
2420 // destinations.
2421
2422 // Remember how many outgoing edges there are to every successor.
2423 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2424
Davide Italiano7e274e02016-12-22 16:03:48 +00002425 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002426 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002427 // See if we were able to turn this switch statement into a constant.
2428 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002429 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002430 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002431 auto Case = *SI->findCaseValue(CondVal);
2432 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002433 // We proved the value is outside of the range of the case.
2434 // We can't do anything other than mark the default dest as reachable,
2435 // and go home.
2436 updateReachableEdge(B, SI->getDefaultDest());
2437 return;
2438 }
2439 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002440 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002441 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002442 } else {
2443 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2444 BasicBlock *TargetBlock = SI->getSuccessor(i);
2445 ++SwitchEdges[TargetBlock];
2446 updateReachableEdge(B, TargetBlock);
2447 }
2448 }
2449 } else {
2450 // Otherwise this is either unconditional, or a type we have no
2451 // idea about. Just mark successors as reachable.
2452 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2453 BasicBlock *TargetBlock = TI->getSuccessor(i);
2454 updateReachableEdge(B, TargetBlock);
2455 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002456
2457 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002458 // equivalent only to itself.
2459 //
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002460 auto *MA = getMemoryAccess(TI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002461 if (MA && !isa<MemoryUse>(MA)) {
2462 auto *CC = ensureLeaderOfMemoryClass(MA);
2463 if (setMemoryClass(MA, CC))
2464 markMemoryUsersTouched(MA);
2465 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002466 }
2467}
2468
Davide Italiano5974c312017-08-03 21:17:49 +00002469// Remove the PHI of Ops PHI for I
2470void NewGVN::removePhiOfOps(Instruction *I, PHINode *PHITemp) {
2471 InstrDFS.erase(PHITemp);
2472 // It's still a temp instruction. We keep it in the array so it gets erased.
2473 // However, it's no longer used by I, or in the block/
2474 PHIOfOpsPHIs[getBlockForValue(PHITemp)].erase(PHITemp);
2475 TempToBlock.erase(PHITemp);
2476 RealToTemp.erase(I);
2477}
2478
2479// Add PHI Op in BB as a PHI of operations version of ExistingValue.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002480void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
2481 Instruction *ExistingValue) {
2482 InstrDFS[Op] = InstrToDFSNum(ExistingValue);
2483 AllTempInstructions.insert(Op);
Davide Italiano5974c312017-08-03 21:17:49 +00002484 PHIOfOpsPHIs[BB].insert(Op);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002485 TempToBlock[Op] = BB;
Daniel Berlinb779db72017-06-29 17:01:10 +00002486 RealToTemp[ExistingValue] = Op;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002487}
2488
2489static bool okayForPHIOfOps(const Instruction *I) {
Chad Rosiera5508e32017-08-10 14:12:57 +00002490 if (!EnablePhiOfOps)
2491 return false;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002492 return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
2493 isa<LoadInst>(I);
2494}
2495
Daniel Berlin94090dd2017-09-02 02:18:44 +00002496// Return true if this operand will be safe to use for phi of ops.
2497//
2498// The reason some operands are unsafe is that we are not trying to recursively
2499// translate everything back through phi nodes. We actually expect some lookups
2500// of expressions to fail. In particular, a lookup where the expression cannot
2501// exist in the predecessor. This is true even if the expression, as shown, can
2502// be determined to be constant.
2503bool NewGVN::OpIsSafeForPHIOfOps(Value *V, Instruction *OrigInst,
2504 const BasicBlock *PHIBlock,
2505 SmallPtrSetImpl<const Value *> &Visited) {
2506 if (!isa<Instruction>(V))
2507 return true;
2508 auto OISIt = OpSafeForPHIOfOps.find(V);
2509 if (OISIt != OpSafeForPHIOfOps.end())
2510 return OISIt->second;
2511 // Keep walking until we either dominate the phi block, or hit a phi, or run
2512 // out of things to check.
2513 if (DT->properlyDominates(getBlockForValue(V), PHIBlock)) {
2514 OpSafeForPHIOfOps.insert({V, true});
2515 return true;
2516 }
2517 // PHI in the same block.
2518 if (isa<PHINode>(V) && getBlockForValue(V) == PHIBlock) {
2519 OpSafeForPHIOfOps.insert({V, false});
2520 return false;
2521 }
2522 for (auto Op : cast<Instruction>(V)->operand_values()) {
2523 if (!isa<Instruction>(Op))
2524 continue;
2525 // See if we already know the answer for this node.
2526 auto OISIt = OpSafeForPHIOfOps.find(Op);
2527 if (OISIt != OpSafeForPHIOfOps.end()) {
2528 if (!OISIt->second) {
2529 OpSafeForPHIOfOps.insert({V, false});
2530 return false;
2531 }
2532 }
2533 if (!Visited.insert(Op).second)
2534 continue;
2535 if (!OpIsSafeForPHIOfOps(Op, OrigInst, PHIBlock, Visited)) {
2536 OpSafeForPHIOfOps.insert({V, false});
2537 return false;
2538 }
2539 }
2540 OpSafeForPHIOfOps.insert({V, true});
2541 return true;
2542}
2543
2544// Try to find a leader for instruction TransInst, which is a phi translated
2545// version of something in our original program. Visited is used to ensure we
2546// don't infinite loop during translations of cycles. OrigInst is the
2547// instruction in the original program, and PredBB is the predecessor we
2548// translated it through.
2549Value *NewGVN::findLeaderForInst(Instruction *TransInst,
2550 SmallPtrSetImpl<Value *> &Visited,
2551 MemoryAccess *MemAccess, Instruction *OrigInst,
2552 BasicBlock *PredBB) {
2553 unsigned IDFSNum = InstrToDFSNum(OrigInst);
2554 // Make sure it's marked as a temporary instruction.
2555 AllTempInstructions.insert(TransInst);
2556 // and make sure anything that tries to add it's DFS number is
2557 // redirected to the instruction we are making a phi of ops
2558 // for.
2559 TempToBlock.insert({TransInst, PredBB});
2560 InstrDFS.insert({TransInst, IDFSNum});
2561
2562 const Expression *E = performSymbolicEvaluation(TransInst, Visited);
2563 InstrDFS.erase(TransInst);
2564 AllTempInstructions.erase(TransInst);
2565 TempToBlock.erase(TransInst);
2566 if (MemAccess)
2567 TempToMemory.erase(TransInst);
2568 if (!E)
2569 return nullptr;
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +00002570 auto *FoundVal = findPHIOfOpsLeader(E, OrigInst, PredBB);
2571 if (!FoundVal) {
Daniel Berlin94090dd2017-09-02 02:18:44 +00002572 ExpressionToPhiOfOps[E].insert(OrigInst);
2573 DEBUG(dbgs() << "Cannot find phi of ops operand for " << *TransInst
2574 << " in block " << getBlockName(PredBB) << "\n");
2575 return nullptr;
2576 }
2577 if (auto *SI = dyn_cast<StoreInst>(FoundVal))
2578 FoundVal = SI->getValueOperand();
2579 return FoundVal;
2580}
2581
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002582// When we see an instruction that is an op of phis, generate the equivalent phi
2583// of ops form.
2584const Expression *
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002585NewGVN::makePossiblePhiOfOps(Instruction *I,
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002586 SmallPtrSetImpl<Value *> &Visited) {
2587 if (!okayForPHIOfOps(I))
2588 return nullptr;
2589
2590 if (!Visited.insert(I).second)
2591 return nullptr;
2592 // For now, we require the instruction be cycle free because we don't
2593 // *always* create a phi of ops for instructions that could be done as phi
2594 // of ops, we only do it if we think it is useful. If we did do it all the
2595 // time, we could remove the cycle free check.
2596 if (!isCycleFree(I))
2597 return nullptr;
2598
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002599 SmallPtrSet<const Value *, 8> ProcessedPHIs;
2600 // TODO: We don't do phi translation on memory accesses because it's
2601 // complicated. For a load, we'd need to be able to simulate a new memoryuse,
2602 // which we don't have a good way of doing ATM.
2603 auto *MemAccess = getMemoryAccess(I);
2604 // If the memory operation is defined by a memory operation this block that
2605 // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
2606 // can't help, as it would still be killed by that memory operation.
2607 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2608 MemAccess->getDefiningAccess()->getBlock() == I->getParent())
2609 return nullptr;
2610
Daniel Berlin94090dd2017-09-02 02:18:44 +00002611 SmallPtrSet<const Value *, 10> VisitedOps;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002612 // Convert op of phis to phi of ops
2613 for (auto &Op : I->operands()) {
2614 if (!isa<PHINode>(Op))
2615 continue;
2616 auto *OpPHI = cast<PHINode>(Op);
2617 // No point in doing this for one-operand phis.
2618 if (OpPHI->getNumOperands() == 1)
2619 continue;
2620 if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
2621 return nullptr;
2622 SmallVector<std::pair<Value *, BasicBlock *>, 4> Ops;
2623 auto *PHIBlock = getBlockForValue(OpPHI);
2624 for (auto PredBB : OpPHI->blocks()) {
2625 Value *FoundVal = nullptr;
2626 // We could just skip unreachable edges entirely but it's tricky to do
2627 // with rewriting existing phi nodes.
2628 if (ReachableEdges.count({PredBB, PHIBlock})) {
2629 // Clone the instruction, create an expression from it, and see if we
2630 // have a leader.
2631 Instruction *ValueOp = I->clone();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002632 if (MemAccess)
Daniel Berlinc8ed4042017-05-30 06:42:29 +00002633 TempToMemory.insert({ValueOp, MemAccess});
Daniel Berlin94090dd2017-09-02 02:18:44 +00002634 bool SafeForPHIOfOps = true;
2635 VisitedOps.clear();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002636 for (auto &Op : ValueOp->operands()) {
Daniel Berlin94090dd2017-09-02 02:18:44 +00002637 auto *OrigOp = &*Op;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002638 Op = Op->DoPHITranslation(PHIBlock, PredBB);
2639 // When this operand changes, it could change whether there is a
2640 // leader for us or not.
2641 addAdditionalUsers(Op, I);
Daniel Berlin94090dd2017-09-02 02:18:44 +00002642 // If we phi-translated the op, it must be safe.
2643 SafeForPHIOfOps = SafeForPHIOfOps &&
2644 (Op != OrigOp ||
2645 OpIsSafeForPHIOfOps(Op, I, PHIBlock, VisitedOps));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002646 }
Daniel Berlin94090dd2017-09-02 02:18:44 +00002647 // FIXME: For those things that are not safe We could generate
2648 // expressions all the way down, and see if this comes out to a
2649 // constant. For anything where that is true, and unsafe, we should
2650 // have made a phi-of-ops (or value numbered it equivalent to something)
2651 // for the pieces already.
2652 FoundVal = !SafeForPHIOfOps ? nullptr
2653 : findLeaderForInst(ValueOp, Visited,
2654 MemAccess, I, PredBB);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002655 ValueOp->deleteValue();
Daniel Berlin94090dd2017-09-02 02:18:44 +00002656 if (!FoundVal)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002657 return nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002658 } else {
2659 DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
2660 << getBlockName(PredBB)
2661 << " because the block is unreachable\n");
2662 FoundVal = UndefValue::get(I->getType());
2663 }
2664
2665 Ops.push_back({FoundVal, PredBB});
2666 DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
2667 << getBlockName(PredBB) << "\n");
2668 }
2669 auto *ValuePHI = RealToTemp.lookup(I);
2670 bool NewPHI = false;
2671 if (!ValuePHI) {
Daniel Berlin94090dd2017-09-02 02:18:44 +00002672 ValuePHI =
2673 PHINode::Create(I->getType(), OpPHI->getNumOperands(), "phiofops");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002674 addPhiOfOps(ValuePHI, PHIBlock, I);
2675 NewPHI = true;
2676 NumGVNPHIOfOpsCreated++;
2677 }
2678 if (NewPHI) {
2679 for (auto PHIOp : Ops)
2680 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2681 } else {
2682 unsigned int i = 0;
2683 for (auto PHIOp : Ops) {
2684 ValuePHI->setIncomingValue(i, PHIOp.first);
2685 ValuePHI->setIncomingBlock(i, PHIOp.second);
2686 ++i;
2687 }
2688 }
2689
2690 DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
2691 << "\n");
2692 return performSymbolicEvaluation(ValuePHI, Visited);
2693 }
2694 return nullptr;
2695}
2696
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002697// The algorithm initially places the values of the routine in the TOP
2698// congruence class. The leader of TOP is the undetermined value `undef`.
2699// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002700void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002701 NextCongruenceNum = 0;
2702
2703 // Note that even though we use the live on entry def as a representative
2704 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2705 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2706 // should be checking whether the MemoryAccess is top if we want to know if it
2707 // is equivalent to everything. Otherwise, what this really signifies is that
2708 // the access "it reaches all the way back to the beginning of the function"
2709
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002710 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002711 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002712 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002713 // The live on entry def gets put into it's own class
2714 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2715 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002716
Daniel Berlinec9deb72017-04-18 17:06:11 +00002717 for (auto DTN : nodes(DT)) {
2718 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002719 // All MemoryAccesses are equivalent to live on entry to start. They must
2720 // be initialized to something so that initial changes are noticed. For
2721 // the maximal answer, we initialize them all to be the same as
2722 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002723 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002724 if (MemoryBlockDefs)
2725 for (const auto &Def : *MemoryBlockDefs) {
2726 MemoryAccessToClass[&Def] = TOPClass;
2727 auto *MD = dyn_cast<MemoryDef>(&Def);
2728 // Insert the memory phis into the member list.
2729 if (!MD) {
2730 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002731 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002732 MemoryPhiState.insert({MP, MPS_TOP});
2733 }
2734
2735 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002736 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002737 }
Daniel Berlinec9deb72017-04-18 17:06:11 +00002738 for (auto &I : *BB) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002739 // TODO: Move to helper
2740 if (isa<PHINode>(&I))
2741 for (auto *U : I.users())
2742 if (auto *UInst = dyn_cast<Instruction>(U))
2743 if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
2744 PHINodeUses.insert(UInst);
Daniel Berlin22a4a012017-02-11 15:20:15 +00002745 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002746 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002747 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2748 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002749 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002750 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002751 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002752 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002753
2754 // Initialize arguments to be in their own unique congruence classes
2755 for (auto &FA : F.args())
2756 createSingletonCongruenceClass(&FA);
2757}
2758
2759void NewGVN::cleanupTables() {
2760 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Daniel Berlina8236562017-04-07 18:38:09 +00002761 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2762 << " has " << CongruenceClasses[i]->size() << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002763 // Make sure we delete the congruence class (probably worth switching to
2764 // a unique_ptr at some point.
2765 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002766 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002767 }
2768
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002769 // Destroy the value expressions
2770 SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
2771 AllTempInstructions.end());
2772 AllTempInstructions.clear();
2773
2774 // We have to drop all references for everything first, so there are no uses
2775 // left as we delete them.
2776 for (auto *I : TempInst) {
2777 I->dropAllReferences();
2778 }
2779
2780 while (!TempInst.empty()) {
2781 auto *I = TempInst.back();
2782 TempInst.pop_back();
2783 I->deleteValue();
2784 }
2785
Davide Italiano7e274e02016-12-22 16:03:48 +00002786 ValueToClass.clear();
2787 ArgRecycler.clear(ExpressionAllocator);
2788 ExpressionAllocator.Reset();
2789 CongruenceClasses.clear();
2790 ExpressionToClass.clear();
2791 ValueToExpression.clear();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002792 RealToTemp.clear();
2793 AdditionalUsers.clear();
2794 ExpressionToPhiOfOps.clear();
2795 TempToBlock.clear();
2796 TempToMemory.clear();
2797 PHIOfOpsPHIs.clear();
Daniel Berlin94090dd2017-09-02 02:18:44 +00002798 PHINodeUses.clear();
2799 OpSafeForPHIOfOps.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002800 ReachableBlocks.clear();
2801 ReachableEdges.clear();
2802#ifndef NDEBUG
2803 ProcessedCount.clear();
2804#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002805 InstrDFS.clear();
2806 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002807 DFSToInstr.clear();
2808 BlockInstRange.clear();
2809 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002810 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002811 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002812 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002813}
2814
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002815// Assign local DFS number mapping to instructions, and leave space for Value
2816// PHI's.
Davide Italiano7e274e02016-12-22 16:03:48 +00002817std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2818 unsigned Start) {
2819 unsigned End = Start;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002820 if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002821 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002822 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002823 }
2824
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002825 // Then the real block goes next.
Davide Italiano7e274e02016-12-22 16:03:48 +00002826 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002827 // There's no need to call isInstructionTriviallyDead more than once on
2828 // an instruction. Therefore, once we know that an instruction is dead
2829 // we change its DFS number so that it doesn't get value numbered.
2830 if (isInstructionTriviallyDead(&I, TLI)) {
2831 InstrDFS[&I] = 0;
2832 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2833 markInstructionForDeletion(&I);
2834 continue;
2835 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002836 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002837 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002838 }
2839
2840 // All of the range functions taken half-open ranges (open on the end side).
2841 // So we do not subtract one from count, because at this point it is one
2842 // greater than the last instruction.
2843 return std::make_pair(Start, End);
2844}
2845
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002846void NewGVN::updateProcessedCount(const Value *V) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002847#ifndef NDEBUG
2848 if (ProcessedCount.count(V) == 0) {
2849 ProcessedCount.insert({V, 1});
2850 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002851 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002852 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002853 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002854 }
2855#endif
2856}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002857// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2858void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2859 // If all the arguments are the same, the MemoryPhi has the same value as the
Daniel Berlind130b6c2017-05-21 23:41:58 +00002860 // argument. Filter out unreachable blocks and self phis from our operands.
2861 // TODO: We could do cycle-checking on the memory phis to allow valueizing for
2862 // self-phi checking.
Daniel Berlin41b39162017-03-18 15:41:36 +00002863 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002864 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlind130b6c2017-05-21 23:41:58 +00002865 return cast<MemoryAccess>(U) != MP &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002866 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002867 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002868 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002869 // If all that is left is nothing, our memoryphi is undef. We keep it as
2870 // InitialClass. Note: The only case this should happen is if we have at
2871 // least one self-argument.
2872 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002873 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002874 markMemoryUsersTouched(MP);
2875 return;
2876 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002877
2878 // Transform the remaining operands into operand leaders.
2879 // FIXME: mapped_iterator should have a range version.
2880 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002881 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002882 };
2883 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2884 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2885
2886 // and now check if all the elements are equal.
2887 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002888 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002889 ++MappedBegin;
2890 bool AllEqual = std::all_of(
2891 MappedBegin, MappedEnd,
2892 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2893
2894 if (AllEqual)
2895 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2896 else
2897 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002898 // If it's equal to something, it's in that class. Otherwise, it has to be in
2899 // a class where it is the leader (other things may be equivalent to it, but
2900 // it needs to start off in its own class, which means it must have been the
2901 // leader, and it can't have stopped being the leader because it was never
2902 // removed).
2903 CongruenceClass *CC =
2904 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2905 auto OldState = MemoryPhiState.lookup(MP);
2906 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2907 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2908 MemoryPhiState[MP] = NewState;
2909 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002910 markMemoryUsersTouched(MP);
2911}
2912
2913// Value number a single instruction, symbolically evaluating, performing
2914// congruence finding, and updating mappings.
2915void NewGVN::valueNumberInstruction(Instruction *I) {
2916 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002917 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002918 const Expression *Symbolized = nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002919 SmallPtrSet<Value *, 2> Visited;
Daniel Berlin283a6082017-03-01 19:59:26 +00002920 if (DebugCounter::shouldExecute(VNCounter)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002921 Symbolized = performSymbolicEvaluation(I, Visited);
2922 // Make a phi of ops if necessary
2923 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
2924 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002925 auto *PHIE = makePossiblePhiOfOps(I, Visited);
Davide Italiano5974c312017-08-03 21:17:49 +00002926 // If we created a phi of ops, use it.
2927 // If we couldn't create one, make sure we don't leave one lying around
2928 if (PHIE) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002929 Symbolized = PHIE;
Davide Italiano5974c312017-08-03 21:17:49 +00002930 } else if (auto *Op = RealToTemp.lookup(I)) {
2931 removePhiOfOps(I, Op);
2932 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002933 }
2934
Daniel Berlin283a6082017-03-01 19:59:26 +00002935 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002936 // Mark the instruction as unused so we don't value number it again.
2937 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002938 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002939 // If we couldn't come up with a symbolic expression, use the unknown
2940 // expression
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002941 if (Symbolized == nullptr)
Daniel Berlin02c6b172017-01-02 18:00:53 +00002942 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002943 performCongruenceFinding(I, Symbolized);
2944 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002945 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002946 // don't currently understand. We don't place non-value producing
2947 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002948 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002949 auto *Symbolized = createUnknownExpression(I);
2950 performCongruenceFinding(I, Symbolized);
2951 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002952 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2953 }
2954}
Davide Italiano7e274e02016-12-22 16:03:48 +00002955
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002956// Check if there is a path, using single or equal argument phi nodes, from
2957// First to Second.
Davide Italianoeab0de22017-05-18 23:22:44 +00002958bool NewGVN::singleReachablePHIPath(
2959 SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
2960 const MemoryAccess *Second) const {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002961 if (First == Second)
2962 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002963 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002964 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002965
Davide Italianoeab0de22017-05-18 23:22:44 +00002966 // This is not perfect, but as we're just verifying here, we can live with
2967 // the loss of precision. The real solution would be that of doing strongly
2968 // connected component finding in this routine, and it's probably not worth
2969 // the complexity for the time being. So, we just keep a set of visited
2970 // MemoryAccess and return true when we hit a cycle.
2971 if (Visited.count(First))
2972 return true;
2973 Visited.insert(First);
2974
Daniel Berlin871ecd92017-04-01 09:44:24 +00002975 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002976 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002977 if (ChainDef == Second)
2978 return true;
2979 if (MSSA->isLiveOnEntryDef(ChainDef))
2980 return false;
2981 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002982 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002983 auto *MP = cast<MemoryPhi>(EndDef);
2984 auto ReachableOperandPred = [&](const Use &U) {
2985 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2986 };
2987 auto FilteredPhiArgs =
2988 make_filter_range(MP->operands(), ReachableOperandPred);
2989 SmallVector<const Value *, 32> OperandList;
2990 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2991 std::back_inserter(OperandList));
2992 bool Okay = OperandList.size() == 1;
2993 if (!Okay)
2994 Okay =
2995 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2996 if (Okay)
Davide Italianoeab0de22017-05-18 23:22:44 +00002997 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
2998 Second);
Daniel Berlin871ecd92017-04-01 09:44:24 +00002999 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003000}
3001
Daniel Berlin589cecc2017-01-02 18:00:46 +00003002// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003003// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00003004// subject to very rare false negatives. It is only useful for
3005// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003006void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00003007#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00003008 // Verify that the memory table equivalence and memory member set match
3009 for (const auto *CC : CongruenceClasses) {
3010 if (CC == TOPClass || CC->isDead())
3011 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00003012 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00003013 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00003014 "Any class with a store as a leader should have a "
3015 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00003016 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00003017 "Any congruence class with a store should have a "
3018 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00003019 }
3020
Daniel Berlina8236562017-04-07 18:38:09 +00003021 if (CC->getMemoryLeader())
3022 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00003023 "Representative MemoryAccess does not appear to be reverse "
3024 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00003025 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00003026 assert(MemoryAccessToClass.lookup(M) == CC &&
3027 "Memory member does not appear to be reverse mapped properly");
3028 }
3029
3030 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00003031 // congruence class.
3032
3033 // Filter out the unreachable and trivially dead entries, because they may
3034 // never have been updated if the instructions were not processed.
3035 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00003036 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00003037 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00003038 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
3039 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00003040 return false;
3041 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
3042 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Davide Italiano6e7a2122017-05-15 18:50:53 +00003043
3044 // We could have phi nodes which operands are all trivially dead,
3045 // so we don't process them.
3046 if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
3047 for (auto &U : MemPHI->incoming_values()) {
3048 if (Instruction *I = dyn_cast<Instruction>(U.get())) {
3049 if (!isInstructionTriviallyDead(I))
3050 return true;
3051 }
3052 }
3053 return false;
3054 }
3055
Daniel Berlin589cecc2017-01-02 18:00:46 +00003056 return true;
3057 };
3058
Daniel Berlin1ea5f322017-01-26 22:21:48 +00003059 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00003060 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00003061 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00003062 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italianoeab0de22017-05-18 23:22:44 +00003063 if (FirstMUD && SecondMUD) {
3064 SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
3065 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00003066 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
3067 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
3068 "The instructions for these memory operations should have "
3069 "been in the same congruence class or reachable through"
3070 "a single argument phi");
Davide Italianoeab0de22017-05-18 23:22:44 +00003071 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00003072 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00003073 // We can only sanely verify that MemoryDefs in the operand list all have
3074 // the same class.
3075 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00003076 return ReachableEdges.count(
3077 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00003078 isa<MemoryDef>(U);
3079
3080 };
3081 // All arguments should in the same class, ignoring unreachable arguments
3082 auto FilteredPhiArgs =
3083 make_filter_range(FirstMP->operands(), ReachableOperandPred);
3084 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
3085 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
3086 std::back_inserter(PhiOpClasses), [&](const Use &U) {
3087 const MemoryDef *MD = cast<MemoryDef>(U);
3088 return ValueToClass.lookup(MD->getMemoryInst());
3089 });
3090 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
3091 PhiOpClasses.begin()) &&
3092 "All MemoryPhi arguments should be in the same class");
3093 }
3094 }
Davide Italianoe9781e72017-03-25 02:40:02 +00003095#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00003096}
3097
Daniel Berlin06329a92017-03-18 15:41:40 +00003098// Verify that the sparse propagation we did actually found the maximal fixpoint
3099// We do this by storing the value to class mapping, touching all instructions,
3100// and redoing the iteration to see if anything changed.
3101void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00003102#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00003103 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00003104 if (DebugCounter::isCounterSet(VNCounter))
3105 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
3106
3107 // Note that we have to store the actual classes, as we may change existing
3108 // classes during iteration. This is because our memory iteration propagation
3109 // is not perfect, and so may waste a little work. But it should generate
3110 // exactly the same congruence classes we have now, with different IDs.
3111 std::map<const Value *, CongruenceClass> BeforeIteration;
3112
3113 for (auto &KV : ValueToClass) {
3114 if (auto *I = dyn_cast<Instruction>(KV.first))
3115 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003116 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00003117 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00003118 BeforeIteration.insert({KV.first, *KV.second});
3119 }
3120
3121 TouchedInstructions.set();
3122 TouchedInstructions.reset(0);
3123 iterateTouchedInstructions();
3124 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
3125 EqualClasses;
3126 for (const auto &KV : ValueToClass) {
3127 if (auto *I = dyn_cast<Instruction>(KV.first))
3128 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003129 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00003130 continue;
3131 // We could sink these uses, but i think this adds a bit of clarity here as
3132 // to what we are comparing.
3133 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
3134 auto *AfterCC = KV.second;
3135 // Note that the classes can't change at this point, so we memoize the set
3136 // that are equal.
3137 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00003138 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00003139 "Value number changed after main loop completed!");
3140 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00003141 }
3142 }
3143#endif
3144}
3145
Daniel Berlin45403572017-05-16 19:58:47 +00003146// Verify that for each store expression in the expression to class mapping,
3147// only the latest appears, and multiple ones do not appear.
3148// Because loads do not use the stored value when doing equality with stores,
3149// if we don't erase the old store expressions from the table, a load can find
3150// a no-longer valid StoreExpression.
3151void NewGVN::verifyStoreExpressions() const {
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003152#ifndef NDEBUG
Daniel Berlin36b08b22017-06-19 00:24:00 +00003153 // This is the only use of this, and it's not worth defining a complicated
3154 // densemapinfo hash/equality function for it.
3155 std::set<
3156 std::pair<const Value *,
3157 std::tuple<const Value *, const CongruenceClass *, Value *>>>
3158 StoreExpressionSet;
Daniel Berlin45403572017-05-16 19:58:47 +00003159 for (const auto &KV : ExpressionToClass) {
3160 if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3161 // Make sure a version that will conflict with loads is not already there
Daniel Berlin36b08b22017-06-19 00:24:00 +00003162 auto Res = StoreExpressionSet.insert(
3163 {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
3164 SE->getStoredValue())});
3165 bool Okay = Res.second;
3166 // It's okay to have the same expression already in there if it is
3167 // identical in nature.
3168 // This can happen when the leader of the stored value changes over time.
Davide Italiano0ec715b2017-06-20 22:57:40 +00003169 if (!Okay)
3170 Okay = (std::get<1>(Res.first->second) == KV.second) &&
3171 (lookupOperandLeader(std::get<2>(Res.first->second)) ==
3172 lookupOperandLeader(SE->getStoredValue()));
Daniel Berlin36b08b22017-06-19 00:24:00 +00003173 assert(Okay && "Stored expression conflict exists in expression table");
Daniel Berlin45403572017-05-16 19:58:47 +00003174 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3175 assert(ValueExpr && ValueExpr->equals(*SE) &&
3176 "StoreExpression in ExpressionToClass is not latest "
3177 "StoreExpression for value");
3178 }
3179 }
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003180#endif
Daniel Berlin45403572017-05-16 19:58:47 +00003181}
3182
Daniel Berlin06329a92017-03-18 15:41:40 +00003183// This is the main value numbering loop, it iterates over the initial touched
3184// instruction set, propagating value numbers, marking things touched, etc,
3185// until the set of touched instructions is completely empty.
3186void NewGVN::iterateTouchedInstructions() {
3187 unsigned int Iterations = 0;
3188 // Figure out where touchedinstructions starts
3189 int FirstInstr = TouchedInstructions.find_first();
3190 // Nothing set, nothing to iterate, just return.
3191 if (FirstInstr == -1)
3192 return;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003193 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00003194 while (TouchedInstructions.any()) {
3195 ++Iterations;
3196 // Walk through all the instructions in all the blocks in RPO.
3197 // TODO: As we hit a new block, we should push and pop equalities into a
3198 // table lookupOperandLeader can use, to catch things PredicateInfo
3199 // might miss, like edge-only equivalences.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003200 for (unsigned InstrNum : TouchedInstructions.set_bits()) {
Daniel Berlin06329a92017-03-18 15:41:40 +00003201
3202 // This instruction was found to be dead. We don't bother looking
3203 // at it again.
3204 if (InstrNum == 0) {
3205 TouchedInstructions.reset(InstrNum);
3206 continue;
3207 }
3208
Daniel Berlin21279bd2017-04-06 18:52:58 +00003209 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003210 const BasicBlock *CurrBlock = getBlockForValue(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003211
3212 // If we hit a new block, do reachability processing.
3213 if (CurrBlock != LastBlock) {
3214 LastBlock = CurrBlock;
3215 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3216 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3217
3218 // If it's not reachable, erase any touched instructions and move on.
3219 if (!BlockReachable) {
3220 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3221 DEBUG(dbgs() << "Skipping instructions in block "
3222 << getBlockName(CurrBlock)
3223 << " because it is unreachable\n");
3224 continue;
3225 }
3226 updateProcessedCount(CurrBlock);
3227 }
Daniel Berlineafdd862017-06-06 17:15:28 +00003228 // Reset after processing (because we may mark ourselves as touched when
3229 // we propagate equalities).
3230 TouchedInstructions.reset(InstrNum);
Daniel Berlin06329a92017-03-18 15:41:40 +00003231
3232 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
3233 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
3234 valueNumberMemoryPhi(MP);
3235 } else if (auto *I = dyn_cast<Instruction>(V)) {
3236 valueNumberInstruction(I);
3237 } else {
3238 llvm_unreachable("Should have been a MemoryPhi or Instruction");
3239 }
3240 updateProcessedCount(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003241 }
3242 }
3243 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
3244}
3245
Daniel Berlin85f91b02016-12-26 20:06:58 +00003246// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00003247bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00003248 if (DebugCounter::isCounterSet(VNCounter))
3249 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00003250 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00003251 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00003252 MSSAWalker = MSSA->getWalker();
Daniel Berline021d2d2017-05-19 20:22:20 +00003253 SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00003254
3255 // Count number of instructions for sizing of hash tables, and come
3256 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003257 unsigned ICount = 1;
3258 // Add an empty instruction to account for the fact that we start at 1
3259 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00003260 // Note: We want ideal RPO traversal of the blocks, which is not quite the
3261 // same as dominator tree order, particularly with regard whether backedges
3262 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00003263 // If we visit in the wrong order, we will end up performing N times as many
3264 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00003265 // The dominator tree does guarantee that, for a given dom tree node, it's
3266 // parent must occur before it in the RPO ordering. Thus, we only need to sort
3267 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00003268 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00003269 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00003270 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003271 auto *Node = DT->getNode(B);
3272 assert(Node && "RPO and Dominator tree should have same reachability");
3273 RPOOrdering[Node] = ++Counter;
3274 }
3275 // Sort dominator tree children arrays into RPO.
3276 for (auto &B : RPOT) {
3277 auto *Node = DT->getNode(B);
3278 if (Node->getChildren().size() > 1)
3279 std::sort(Node->begin(), Node->end(),
Daniel Berlin2f72b192017-04-14 02:53:37 +00003280 [&](const DomTreeNode *A, const DomTreeNode *B) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003281 return RPOOrdering[A] < RPOOrdering[B];
3282 });
3283 }
3284
3285 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00003286 for (auto DTN : depth_first(DT->getRootNode())) {
3287 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00003288 const auto &BlockRange = assignDFSNumbers(B, ICount);
3289 BlockInstRange.insert({B, BlockRange});
3290 ICount += BlockRange.second - BlockRange.first;
3291 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003292 initializeCongruenceClasses(F);
Davide Italiano7e274e02016-12-22 16:03:48 +00003293
Daniel Berline0bd37e2016-12-29 22:15:12 +00003294 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003295 // Ensure we don't end up resizing the expressionToClass map, as
3296 // that can be quite expensive. At most, we have one expression per
3297 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003298 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003299
3300 // Initialize the touched instructions to include the entry block.
3301 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
3302 TouchedInstructions.set(InstRange.first, InstRange.second);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003303 DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
3304 << " marked reachable\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003305 ReachableBlocks.insert(&F.getEntryBlock());
3306
Daniel Berlin06329a92017-03-18 15:41:40 +00003307 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00003308 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00003309 verifyIterationSettled(F);
Daniel Berlin45403572017-05-16 19:58:47 +00003310 verifyStoreExpressions();
Daniel Berlinf7d95802017-02-18 23:06:50 +00003311
Davide Italiano7e274e02016-12-22 16:03:48 +00003312 Changed |= eliminateInstructions(F);
3313
3314 // Delete all instructions marked for deletion.
3315 for (Instruction *ToErase : InstructionsToErase) {
3316 if (!ToErase->use_empty())
3317 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
3318
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003319 if (ToErase->getParent())
3320 ToErase->eraseFromParent();
Davide Italiano7e274e02016-12-22 16:03:48 +00003321 }
3322
3323 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003324 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
3325 return !ReachableBlocks.count(&BB);
3326 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003327
3328 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
3329 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00003330 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003331 deleteInstructionsInBlock(&BB);
3332 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003333 }
3334
3335 cleanupTables();
3336 return Changed;
3337}
3338
Davide Italiano7e274e02016-12-22 16:03:48 +00003339struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003340 int DFSIn = 0;
3341 int DFSOut = 0;
3342 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003343 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003344 // The bool in the Def tells us whether the Def is the stored value of a
3345 // store.
3346 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003347 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00003348 bool operator<(const ValueDFS &Other) const {
3349 // It's not enough that any given field be less than - we have sets
3350 // of fields that need to be evaluated together to give a proper ordering.
3351 // For example, if you have;
3352 // DFS (1, 3)
3353 // Val 0
3354 // DFS (1, 2)
3355 // Val 50
3356 // We want the second to be less than the first, but if we just go field
3357 // by field, we will get to Val 0 < Val 50 and say the first is less than
3358 // the second. We only want it to be less than if the DFS orders are equal.
3359 //
3360 // Each LLVM instruction only produces one value, and thus the lowest-level
3361 // differentiator that really matters for the stack (and what we use as as a
3362 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003363 // Everything else in the structure is instruction level, and only affects
3364 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00003365 //
3366 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
3367 // the order of replacement of uses does not matter.
3368 // IE given,
3369 // a = 5
3370 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00003371 // When you hit b, you will have two valuedfs with the same dfsin, out, and
3372 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00003373 // The .val will be the same as well.
3374 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003375 // You will replace both, and it does not matter what order you replace them
3376 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
3377 // operand 2).
3378 // Similarly for the case of same dfsin, dfsout, localnum, but different
3379 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00003380 // a = 5
3381 // b = 6
3382 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00003383 // in c, we will a valuedfs for a, and one for b,with everything the same
3384 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00003385 // It does not matter what order we replace these operands in.
3386 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003387 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3388 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00003389 Other.U);
3390 }
3391};
3392
Daniel Berlinc4796862017-01-27 02:37:11 +00003393// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003394// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00003395// reachable uses for each value is stored in UseCount, and instructions that
3396// seem
3397// dead (have no non-dead uses) are stored in ProbablyDead.
3398void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00003399 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00003400 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00003401 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00003402 for (auto D : Dense) {
3403 // First add the value.
3404 BasicBlock *BB = getBlockForValue(D);
3405 // Constants are handled prior to ever calling this function, so
3406 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00003407 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003408 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003409 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003410 VDDef.DFSIn = DomNode->getDFSNumIn();
3411 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003412 // If it's a store, use the leader of the value operand, if it's always
3413 // available, or the value operand. TODO: We could do dominance checks to
3414 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00003415 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00003416 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003417 if (alwaysAvailable(Leader)) {
3418 VDDef.Def.setPointer(Leader);
3419 } else {
3420 VDDef.Def.setPointer(SI->getValueOperand());
3421 VDDef.Def.setInt(true);
3422 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003423 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003424 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00003425 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003426 assert(isa<Instruction>(D) &&
3427 "The dense set member should always be an instruction");
Daniel Berline3e69e12017-03-10 00:32:33 +00003428 Instruction *Def = cast<Instruction>(D);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003429 VDDef.LocalNum = InstrToDFSNum(D);
3430 DFSOrderedSet.push_back(VDDef);
3431 // If there is a phi node equivalent, add it
3432 if (auto *PN = RealToTemp.lookup(Def)) {
3433 auto *PHIE =
3434 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3435 if (PHIE) {
3436 VDDef.Def.setInt(false);
3437 VDDef.Def.setPointer(PN);
3438 VDDef.LocalNum = 0;
3439 DFSOrderedSet.push_back(VDDef);
3440 }
3441 }
3442
Daniel Berline3e69e12017-03-10 00:32:33 +00003443 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003444 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00003445 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003446 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003447 // Don't try to replace into dead uses
3448 if (InstructionsToErase.count(I))
3449 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003450 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00003451 // Put the phi node uses in the incoming block.
3452 BasicBlock *IBlock;
3453 if (auto *P = dyn_cast<PHINode>(I)) {
3454 IBlock = P->getIncomingBlock(U);
3455 // Make phi node users appear last in the incoming block
3456 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003457 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00003458 } else {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003459 IBlock = getBlockForValue(I);
Daniel Berlin21279bd2017-04-06 18:52:58 +00003460 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003461 }
Davide Italianoccbbc832017-01-26 00:42:42 +00003462
3463 // Skip uses in unreachable blocks, as we're going
3464 // to delete them.
3465 if (ReachableBlocks.count(IBlock) == 0)
3466 continue;
3467
Daniel Berlinb66164c2017-01-14 00:24:23 +00003468 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003469 VDUse.DFSIn = DomNode->getDFSNumIn();
3470 VDUse.DFSOut = DomNode->getDFSNumOut();
3471 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00003472 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003473 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00003474 }
3475 }
Daniel Berline3e69e12017-03-10 00:32:33 +00003476
3477 // If there are no uses, it's probably dead (but it may have side-effects,
3478 // so not definitely dead. Otherwise, store the number of uses so we can
3479 // track if it becomes dead later).
3480 if (UseCount == 0)
3481 ProbablyDead.insert(Def);
3482 else
3483 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003484 }
3485}
3486
Daniel Berlinc4796862017-01-27 02:37:11 +00003487// This function converts the set of members for a congruence class from values,
3488// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00003489void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00003490 const CongruenceClass &Dense,
3491 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00003492 for (auto D : Dense) {
3493 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
3494 continue;
3495
3496 BasicBlock *BB = getBlockForValue(D);
3497 ValueDFS VD;
3498 DomTreeNode *DomNode = DT->getNode(BB);
3499 VD.DFSIn = DomNode->getDFSNumIn();
3500 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003501 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00003502
3503 // If it's an instruction, use the real local dfs number.
3504 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00003505 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00003506 else
3507 llvm_unreachable("Should have been an instruction");
3508
3509 LoadsAndStores.emplace_back(VD);
3510 }
3511}
3512
Davide Italiano7e274e02016-12-22 16:03:48 +00003513static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00003514 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00003515 if (!ReplInst)
3516 return;
3517
Davide Italiano7e274e02016-12-22 16:03:48 +00003518 // Patch the replacement so that it is not more restrictive than the value
3519 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00003520 // Note that if 'I' is a load being replaced by some operation,
3521 // for example, by an arithmetic operation, then andIRFlags()
3522 // would just erase all math flags from the original arithmetic
3523 // operation, which is clearly not wanted and not needed.
3524 if (!isa<LoadInst>(I))
3525 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003526
Daniel Berlin86eab152017-02-12 22:25:20 +00003527 // FIXME: If both the original and replacement value are part of the
3528 // same control-flow region (meaning that the execution of one
3529 // guarantees the execution of the other), then we can combine the
3530 // noalias scopes here and do better than the general conservative
3531 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00003532
Daniel Berlin86eab152017-02-12 22:25:20 +00003533 // In general, GVN unifies expressions over different control-flow
3534 // regions, and so we need a conservative combination of the noalias
3535 // scopes.
3536 static const unsigned KnownIDs[] = {
3537 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
3538 LLVMContext::MD_noalias, LLVMContext::MD_range,
3539 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
3540 LLVMContext::MD_invariant_group};
3541 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00003542}
3543
3544static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3545 patchReplacementInstruction(I, Repl);
3546 I->replaceAllUsesWith(Repl);
3547}
3548
3549void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
3550 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
3551 ++NumGVNBlocksDeleted;
3552
Daniel Berline19f0e02017-01-30 17:06:55 +00003553 // Delete the instructions backwards, as it has a reduced likelihood of having
3554 // to update as many def-use and use-def chains. Start after the terminator.
3555 auto StartPoint = BB->rbegin();
3556 ++StartPoint;
3557 // Note that we explicitly recalculate BB->rend() on each iteration,
3558 // as it may change when we remove the first instruction.
3559 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3560 Instruction &Inst = *I++;
3561 if (!Inst.use_empty())
3562 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3563 if (isa<LandingPadInst>(Inst))
3564 continue;
3565
3566 Inst.eraseFromParent();
3567 ++NumGVNInstrDeleted;
3568 }
Daniel Berlina53a7222017-01-30 18:12:56 +00003569 // Now insert something that simplifycfg will turn into an unreachable.
3570 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3571 new StoreInst(UndefValue::get(Int8Ty),
3572 Constant::getNullValue(Int8Ty->getPointerTo()),
3573 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00003574}
3575
3576void NewGVN::markInstructionForDeletion(Instruction *I) {
3577 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3578 InstructionsToErase.insert(I);
3579}
3580
3581void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3582
3583 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3584 patchAndReplaceAllUsesWith(I, V);
3585 // We save the actual erasing to avoid invalidating memory
3586 // dependencies until we are done with everything.
3587 markInstructionForDeletion(I);
3588}
3589
3590namespace {
3591
3592// This is a stack that contains both the value and dfs info of where
3593// that value is valid.
3594class ValueDFSStack {
3595public:
3596 Value *back() const { return ValueStack.back(); }
3597 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3598
3599 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003600 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003601 DFSStack.emplace_back(DFSIn, DFSOut);
3602 }
3603 bool empty() const { return DFSStack.empty(); }
3604 bool isInScope(int DFSIn, int DFSOut) const {
3605 if (empty())
3606 return false;
3607 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3608 }
3609
3610 void popUntilDFSScope(int DFSIn, int DFSOut) {
3611
3612 // These two should always be in sync at this point.
3613 assert(ValueStack.size() == DFSStack.size() &&
3614 "Mismatch between ValueStack and DFSStack");
3615 while (
3616 !DFSStack.empty() &&
3617 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3618 DFSStack.pop_back();
3619 ValueStack.pop_back();
3620 }
3621 }
3622
3623private:
3624 SmallVector<Value *, 8> ValueStack;
3625 SmallVector<std::pair<int, int>, 8> DFSStack;
3626};
3627}
Daniel Berlin04443432017-01-07 03:23:47 +00003628
Daniel Berlin94090dd2017-09-02 02:18:44 +00003629// Given an expression, get the congruence class for it.
3630CongruenceClass *NewGVN::getClassForExpression(const Expression *E) const {
3631 if (auto *VE = dyn_cast<VariableExpression>(E))
3632 return ValueToClass.lookup(VE->getVariableValue());
3633 else if (isa<DeadExpression>(E))
3634 return TOPClass;
3635 return ExpressionToClass.lookup(E);
3636}
3637
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003638// Given a value and a basic block we are trying to see if it is available in,
3639// see if the value has a leader available in that block.
Daniel Berlin94090dd2017-09-02 02:18:44 +00003640Value *NewGVN::findPHIOfOpsLeader(const Expression *E,
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +00003641 const Instruction *OrigInst,
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003642 const BasicBlock *BB) const {
3643 // It would already be constant if we could make it constant
3644 if (auto *CE = dyn_cast<ConstantExpression>(E))
3645 return CE->getConstantValue();
Daniel Berlin94090dd2017-09-02 02:18:44 +00003646 if (auto *VE = dyn_cast<VariableExpression>(E)) {
3647 auto *V = VE->getVariableValue();
3648 if (alwaysAvailable(V) || DT->dominates(getBlockForValue(V), BB))
3649 return VE->getVariableValue();
3650 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003651
Daniel Berlin94090dd2017-09-02 02:18:44 +00003652 auto *CC = getClassForExpression(E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003653 if (!CC)
3654 return nullptr;
3655 if (alwaysAvailable(CC->getLeader()))
3656 return CC->getLeader();
3657
3658 for (auto Member : *CC) {
3659 auto *MemberInst = dyn_cast<Instruction>(Member);
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +00003660 if (MemberInst == OrigInst)
3661 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003662 // Anything that isn't an instruction is always available.
3663 if (!MemberInst)
3664 return Member;
Daniel Berlin94090dd2017-09-02 02:18:44 +00003665 if (DT->dominates(getBlockForValue(MemberInst), BB))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003666 return Member;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003667 }
3668 return nullptr;
3669}
3670
Davide Italiano7e274e02016-12-22 16:03:48 +00003671bool NewGVN::eliminateInstructions(Function &F) {
3672 // This is a non-standard eliminator. The normal way to eliminate is
3673 // to walk the dominator tree in order, keeping track of available
3674 // values, and eliminating them. However, this is mildly
3675 // pointless. It requires doing lookups on every instruction,
3676 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003677 // instructions part of most singleton congruence classes, we know we
3678 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003679
3680 // Instead, this eliminator looks at the congruence classes directly, sorts
3681 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003682 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003683 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003684 // last member. This is worst case O(E log E) where E = number of
3685 // instructions in a single congruence class. In theory, this is all
3686 // instructions. In practice, it is much faster, as most instructions are
3687 // either in singleton congruence classes or can't possibly be eliminated
3688 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003689 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003690 // for elimination purposes.
3691 // TODO: If we wanted to be faster, We could remove any members with no
3692 // overlapping ranges while sorting, as we will never eliminate anything
3693 // with those members, as they don't dominate anything else in our set.
3694
Davide Italiano7e274e02016-12-22 16:03:48 +00003695 bool AnythingReplaced = false;
3696
3697 // Since we are going to walk the domtree anyway, and we can't guarantee the
3698 // DFS numbers are updated, we compute some ourselves.
3699 DT->updateDFSNumbers();
3700
Daniel Berlin0207cca2017-05-21 23:41:56 +00003701 // Go through all of our phi nodes, and kill the arguments associated with
3702 // unreachable edges.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003703 auto ReplaceUnreachablePHIArgs = [&](PHINode &PHI, BasicBlock *BB) {
3704 for (auto &Operand : PHI.incoming_values())
3705 if (!ReachableEdges.count({PHI.getIncomingBlock(Operand), BB})) {
3706 DEBUG(dbgs() << "Replacing incoming value of " << PHI << " for block "
3707 << getBlockName(PHI.getIncomingBlock(Operand))
3708 << " with undef due to it being unreachable\n");
3709 Operand.set(UndefValue::get(PHI.getType()));
3710 }
3711 };
3712 SmallPtrSet<BasicBlock *, 8> BlocksWithPhis;
3713 for (auto &B : F)
3714 if ((!B.empty() && isa<PHINode>(*B.begin())) ||
3715 (PHIOfOpsPHIs.find(&B) != PHIOfOpsPHIs.end()))
3716 BlocksWithPhis.insert(&B);
3717 DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
3718 for (auto KV : ReachableEdges)
3719 ReachablePredCount[KV.getEnd()]++;
3720 for (auto *BB : BlocksWithPhis)
3721 // TODO: It would be faster to use getNumIncomingBlocks() on a phi node in
3722 // the block and subtract the pred count, but it's more complicated.
3723 if (ReachablePredCount.lookup(BB) !=
George Burgess IVf6137492017-06-13 01:28:49 +00003724 unsigned(std::distance(pred_begin(BB), pred_end(BB)))) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003725 for (auto II = BB->begin(); isa<PHINode>(II); ++II) {
3726 auto &PHI = cast<PHINode>(*II);
3727 ReplaceUnreachablePHIArgs(PHI, BB);
3728 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00003729 for_each_found(PHIOfOpsPHIs, BB, [&](PHINode *PHI) {
3730 ReplaceUnreachablePHIArgs(*PHI, BB);
3731 });
Davide Italiano7e274e02016-12-22 16:03:48 +00003732 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003733
Daniel Berline3e69e12017-03-10 00:32:33 +00003734 // Map to store the use counts
3735 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003736 for (auto *CC : reverse(CongruenceClasses)) {
Daniel Berline67c3222017-05-25 15:44:20 +00003737 DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID() << "\n");
Daniel Berlinc4796862017-01-27 02:37:11 +00003738 // Track the equivalent store info so we can decide whether to try
3739 // dead store elimination.
3740 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003741 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003742 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003743 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003744 // Everything still in the TOP class is unreachable or dead.
3745 if (CC == TOPClass) {
Daniel Berline021d2d2017-05-19 20:22:20 +00003746 for (auto M : *CC) {
3747 auto *VTE = ValueToExpression.lookup(M);
3748 if (VTE && isa<DeadExpression>(VTE))
3749 markInstructionForDeletion(cast<Instruction>(M));
Daniel Berlinb79f5362017-02-11 12:48:50 +00003750 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3751 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003752 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003753 "point");
Daniel Berline021d2d2017-05-19 20:22:20 +00003754 }
Daniel Berlinb79f5362017-02-11 12:48:50 +00003755 continue;
3756 }
3757
Daniel Berlina8236562017-04-07 18:38:09 +00003758 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003759 // If this is a leader that is always available, and it's a
3760 // constant or has no equivalences, just replace everything with
3761 // it. We then update the congruence class with whatever members
3762 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003763 Value *Leader =
3764 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003765 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003766 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003767 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003768 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003769 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003770 if (Member == Leader || !isa<Instruction>(Member) ||
3771 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003772 MembersLeft.insert(Member);
3773 continue;
3774 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003775 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3776 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003777 auto *I = cast<Instruction>(Member);
3778 assert(Leader != I && "About to accidentally remove our leader");
3779 replaceInstruction(I, Leader);
3780 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003781 }
Daniel Berlina8236562017-04-07 18:38:09 +00003782 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003783 } else {
Davide Italiano7e274e02016-12-22 16:03:48 +00003784 // If this is a singleton, we can skip it.
Davide Italiano5974c312017-08-03 21:17:49 +00003785 if (CC->size() != 1 || RealToTemp.count(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003786 // This is a stack because equality replacement/etc may place
3787 // constants in the middle of the member list, and we want to use
3788 // those constant values in preference to the current leader, over
3789 // the scope of those constants.
3790 ValueDFSStack EliminationStack;
3791
3792 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003793 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003794 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003795
3796 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003797 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003798 for (auto &VD : DFSOrderedSet) {
3799 int MemberDFSIn = VD.DFSIn;
3800 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003801 Value *Def = VD.Def.getPointer();
3802 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003803 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003804 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003805 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003806 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003807 auto *DefInst = dyn_cast_or_null<Instruction>(Def);
3808 if (DefInst && AllTempInstructions.count(DefInst)) {
3809 auto *PN = cast<PHINode>(DefInst);
3810
3811 // If this is a value phi and that's the expression we used, insert
3812 // it into the program
3813 // remove from temp instruction list.
3814 AllTempInstructions.erase(PN);
3815 auto *DefBlock = getBlockForValue(Def);
3816 DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
3817 << " into block "
3818 << getBlockName(getBlockForValue(Def)) << "\n");
3819 PN->insertBefore(&DefBlock->front());
3820 Def = PN;
3821 NumGVNPHIOfOpsEliminations++;
3822 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003823
3824 if (EliminationStack.empty()) {
3825 DEBUG(dbgs() << "Elimination Stack is empty\n");
3826 } else {
3827 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3828 << EliminationStack.dfs_back().first << ","
3829 << EliminationStack.dfs_back().second << ")\n");
3830 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003831
3832 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3833 << MemberDFSOut << ")\n");
3834 // First, we see if we are out of scope or empty. If so,
3835 // and there equivalences, we try to replace the top of
3836 // stack with equivalences (if it's on the stack, it must
3837 // not have been eliminated yet).
3838 // Then we synchronize to our current scope, by
3839 // popping until we are back within a DFS scope that
3840 // dominates the current member.
3841 // Then, what happens depends on a few factors
3842 // If the stack is now empty, we need to push
3843 // If we have a constant or a local equivalence we want to
3844 // start using, we also push.
3845 // Otherwise, we walk along, processing members who are
3846 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003847 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003848 bool OutOfScope =
3849 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3850
3851 if (OutOfScope || ShouldPush) {
3852 // Sync to our current scope.
3853 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003854 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003855 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003856 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003857 }
3858 }
3859
Daniel Berline3e69e12017-03-10 00:32:33 +00003860 // Skip the Def's, we only want to eliminate on their uses. But mark
3861 // dominated defs as dead.
3862 if (Def) {
3863 // For anything in this case, what and how we value number
3864 // guarantees that any side-effets that would have occurred (ie
3865 // throwing, etc) can be proven to either still occur (because it's
3866 // dominated by something that has the same side-effects), or never
3867 // occur. Otherwise, we would not have been able to prove it value
3868 // equivalent to something else. For these things, we can just mark
3869 // it all dead. Note that this is different from the "ProbablyDead"
3870 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003871 // easy to prove dead if they are also side-effect free. Note that
3872 // because stores are put in terms of the stored value, we skip
3873 // stored values here. If the stored value is really dead, it will
3874 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003875 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003876 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003877 markInstructionForDeletion(cast<Instruction>(Def));
3878 continue;
3879 }
3880 // At this point, we know it is a Use we are trying to possibly
3881 // replace.
3882
3883 assert(isa<Instruction>(U->get()) &&
3884 "Current def should have been an instruction");
3885 assert(isa<Instruction>(U->getUser()) &&
3886 "Current user should have been an instruction");
3887
3888 // If the thing we are replacing into is already marked to be dead,
3889 // this use is dead. Note that this is true regardless of whether
3890 // we have anything dominating the use or not. We do this here
3891 // because we are already walking all the uses anyway.
3892 Instruction *InstUse = cast<Instruction>(U->getUser());
3893 if (InstructionsToErase.count(InstUse)) {
3894 auto &UseCount = UseCounts[U->get()];
3895 if (--UseCount == 0) {
3896 ProbablyDead.insert(cast<Instruction>(U->get()));
3897 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003898 }
3899
Davide Italiano7e274e02016-12-22 16:03:48 +00003900 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003901 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003902 if (EliminationStack.empty())
3903 continue;
3904
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003905 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003906
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003907 auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
3908 if (II && II->getIntrinsicID() == Intrinsic::ssa_copy)
3909 DominatingLeader = II->getOperand(0);
3910
Daniel Berlind92e7f92017-01-07 00:01:42 +00003911 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003912 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003913 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003914 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003915 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003916
3917 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003918 // metadata. Skip this if we are replacing predicateinfo with its
3919 // original operand, as we already know we can just drop it.
3920 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003921 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3922 if (!PI || DominatingLeader != PI->OriginalOp)
3923 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003924 U->set(DominatingLeader);
3925 // This is now a use of the dominating leader, which means if the
3926 // dominating leader was dead, it's now live!
3927 auto &LeaderUseCount = UseCounts[DominatingLeader];
3928 // It's about to be alive again.
3929 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3930 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003931 if (LeaderUseCount == 0 && II)
3932 ProbablyDead.insert(II);
Daniel Berline3e69e12017-03-10 00:32:33 +00003933 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003934 AnythingReplaced = true;
3935 }
3936 }
3937 }
3938
Daniel Berline3e69e12017-03-10 00:32:33 +00003939 // At this point, anything still in the ProbablyDead set is actually dead if
3940 // would be trivially dead.
3941 for (auto *I : ProbablyDead)
3942 if (wouldInstructionBeTriviallyDead(I))
3943 markInstructionForDeletion(I);
3944
Davide Italiano7e274e02016-12-22 16:03:48 +00003945 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003946 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003947 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003948 if (!isa<Instruction>(Member) ||
3949 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003950 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003951 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003952
3953 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00003954 if (CC->getStoreCount() > 0) {
3955 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003956 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3957 ValueDFSStack EliminationStack;
3958 for (auto &VD : PossibleDeadStores) {
3959 int MemberDFSIn = VD.DFSIn;
3960 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003961 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003962 if (EliminationStack.empty() ||
3963 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3964 // Sync to our current scope.
3965 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3966 if (EliminationStack.empty()) {
3967 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3968 continue;
3969 }
3970 }
3971 // We already did load elimination, so nothing to do here.
3972 if (isa<LoadInst>(Member))
3973 continue;
3974 assert(!EliminationStack.empty());
3975 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003976 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003977 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3978 // Member is dominater by Leader, and thus dead
3979 DEBUG(dbgs() << "Marking dead store " << *Member
3980 << " that is dominated by " << *Leader << "\n");
3981 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003982 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00003983 ++NumGVNDeadStores;
3984 }
3985 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003986 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003987 return AnythingReplaced;
3988}
Daniel Berlin1c087672017-02-11 15:07:01 +00003989
3990// This function provides global ranking of operations so that we can place them
3991// in a canonical order. Note that rank alone is not necessarily enough for a
3992// complete ordering, as constants all have the same rank. However, generally,
3993// we will simplify an operation with all constants so that it doesn't matter
3994// what order they appear in.
3995unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003996 // Prefer constants to undef to anything else
3997 // Undef is a constant, have to check it first.
3998 // Prefer smaller constants to constantexprs
3999 if (isa<ConstantExpr>(V))
4000 return 2;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004001 if (isa<UndefValue>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004002 return 1;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00004003 if (isa<Constant>(V))
4004 return 0;
Daniel Berlin1c087672017-02-11 15:07:01 +00004005 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00004006 return 3 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00004007
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004008 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00004009 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00004010 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00004011 if (Result > 0)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00004012 return 4 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00004013 // Unreachable or something else, just return a really large number.
4014 return ~0;
4015}
4016
4017// This is a function that says whether two commutative operations should
4018// have their order swapped when canonicalizing.
4019bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
4020 // Because we only care about a total ordering, and don't rewrite expressions
4021 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004022 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00004023 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00004024}
Daniel Berlin64e68992017-03-12 04:46:45 +00004025
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00004026namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +00004027class NewGVNLegacyPass : public FunctionPass {
4028public:
4029 static char ID; // Pass identification, replacement for typeid.
4030 NewGVNLegacyPass() : FunctionPass(ID) {
4031 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
4032 }
4033 bool runOnFunction(Function &F) override;
4034
4035private:
4036 void getAnalysisUsage(AnalysisUsage &AU) const override {
4037 AU.addRequired<AssumptionCacheTracker>();
4038 AU.addRequired<DominatorTreeWrapperPass>();
4039 AU.addRequired<TargetLibraryInfoWrapperPass>();
4040 AU.addRequired<MemorySSAWrapperPass>();
4041 AU.addRequired<AAResultsWrapperPass>();
4042 AU.addPreserved<DominatorTreeWrapperPass>();
4043 AU.addPreserved<GlobalsAAWrapperPass>();
4044 }
4045};
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00004046} // namespace
Daniel Berlin64e68992017-03-12 04:46:45 +00004047
4048bool NewGVNLegacyPass::runOnFunction(Function &F) {
4049 if (skipFunction(F))
4050 return false;
4051 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4052 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
4053 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
4054 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
4055 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
4056 F.getParent()->getDataLayout())
4057 .runGVN();
4058}
4059
4060INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
4061 false, false)
4062INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4063INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
4064INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4065INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
4066INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
4067INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
4068INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
4069 false)
4070
4071char NewGVNLegacyPass::ID = 0;
4072
4073// createGVNPass - The public interface to this file.
4074FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
4075
4076PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
4077 // Apparently the order in which we get these results matter for
4078 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
4079 // the same order here, just in case.
4080 auto &AC = AM.getResult<AssumptionAnalysis>(F);
4081 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
4082 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
4083 auto &AA = AM.getResult<AAManager>(F);
4084 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
4085 bool Changed =
4086 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
4087 .runGVN();
4088 if (!Changed)
4089 return PreservedAnalyses::all();
4090 PreservedAnalyses PA;
4091 PA.preserve<DominatorTreeAnalysis>();
4092 PA.preserve<GlobalsAA>();
4093 return PA;
4094}