blob: 423b4af018a4be1501b462a53b0fe6195c09c30a [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
854// Return true if V is really PN, even accounting for predicateinfo copies.
855static bool isCopyOfSelf(const Value *V, const PHINode *PN) {
856 if (V == PN)
857 return V;
858 if (auto *II = dyn_cast<IntrinsicInst>(V))
859 if (II->getIntrinsicID() == Intrinsic::ssa_copy && II->getOperand(0) == PN)
860 return true;
861 return false;
862}
863
Daniel Berlin2f72b192017-04-14 02:53:37 +0000864PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000865 bool &OriginalOpsConstant) const {
866 BasicBlock *PHIBlock = getBlockForValue(I);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000867 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000868 auto *E =
869 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000870
871 E->allocateOperands(ArgRecycler, ExpressionAllocator);
872 E->setType(I->getType());
873 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000874
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000875 // NewGVN assumes the operands of a PHI node are in a consistent order across
876 // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix
877 // this in LLVM at some point we don't want GVN to find wrong congruences.
878 // Therefore, here we sort uses in predecessor order.
Davide Italiano63998ec2017-05-09 18:29:37 +0000879 // We're sorting the values by pointer. In theory this might be cause of
880 // non-determinism, but here we don't rely on the ordering for anything
881 // significant, e.g. we don't create new instructions based on it so we're
882 // fine.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000883 SmallVector<const Use *, 4> PHIOperands;
884 for (const Use &U : PN->operands())
885 PHIOperands.push_back(&U);
886 std::sort(PHIOperands.begin(), PHIOperands.end(),
887 [&](const Use *U1, const Use *U2) {
888 return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
889 });
890
Davide Italianob3886dd2017-01-25 23:37:49 +0000891 // Filter out unreachable phi operands.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000892 auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) {
Daniel Berlin1a582582017-09-05 02:17:41 +0000893 if (isCopyOfSelf(*U, PN))
Daniel Berline67c3222017-05-25 15:44:20 +0000894 return false;
895 if (!ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock}))
896 return false;
897 // Things in TOPClass are equivalent to everything.
898 if (ValueToClass.lookup(*U) == TOPClass)
899 return false;
Davide Italianoa7a77542017-07-10 20:45:00 +0000900 return lookupOperandLeader(*U) != PN;
Davide Italianob3886dd2017-01-25 23:37:49 +0000901 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000902 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000903 [&](const Use *U) -> Value * {
904 auto *BB = PN->getIncomingBlock(*U);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000905 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
906 OriginalOpsConstant =
907 OriginalOpsConstant && isa<Constant>(*U);
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000908 return lookupOperandLeader(*U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000909 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000910 return E;
911}
912
913// Set basic expression info (Arguments, type, opcode) for Expression
914// E from Instruction I in block B.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000915bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000916 bool AllConstant = true;
917 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
918 E->setType(GEP->getSourceElementType());
919 else
920 E->setType(I->getType());
921 E->setOpcode(I->getOpcode());
922 E->allocateOperands(ArgRecycler, ExpressionAllocator);
923
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000924 // Transform the operand array into an operand leader array, and keep track of
925 // whether all members are constant.
926 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000927 auto Operand = lookupOperandLeader(O);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000928 AllConstant = AllConstant && isa<Constant>(Operand);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000929 return Operand;
930 });
931
Davide Italiano7e274e02016-12-22 16:03:48 +0000932 return AllConstant;
933}
934
935const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin54a92fc2017-09-05 02:17:42 +0000936 Value *Arg1, Value *Arg2,
937 Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000938 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000939
940 E->setType(T);
941 E->setOpcode(Opcode);
942 E->allocateOperands(ArgRecycler, ExpressionAllocator);
943 if (Instruction::isCommutative(Opcode)) {
944 // Ensure that commutative instructions that only differ by a permutation
945 // of their operands get the same value number by sorting the operand value
946 // numbers. Since all commutative instructions have two operands it is more
947 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000948 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000949 std::swap(Arg1, Arg2);
950 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000951 E->op_push_back(lookupOperandLeader(Arg1));
952 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000953
Daniel Berlinede130d2017-04-26 20:56:14 +0000954 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlin54a92fc2017-09-05 02:17:42 +0000955 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
Davide Italiano7e274e02016-12-22 16:03:48 +0000956 return SimplifiedE;
957 return E;
958}
959
960// Take a Value returned by simplification of Expression E/Instruction
961// I, and see if it resulted in a simpler expression. If so, return
962// that expression.
Davide Italiano7e274e02016-12-22 16:03:48 +0000963const Expression *NewGVN::checkSimplificationResults(Expression *E,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000964 Instruction *I,
965 Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000966 if (!V)
967 return nullptr;
968 if (auto *C = dyn_cast<Constant>(V)) {
969 if (I)
970 DEBUG(dbgs() << "Simplified " << *I << " to "
971 << " constant " << *C << "\n");
972 NumGVNOpsSimplified++;
973 assert(isa<BasicExpression>(E) &&
974 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000975 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000976 return createConstantExpression(C);
977 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
978 if (I)
979 DEBUG(dbgs() << "Simplified " << *I << " to "
980 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000981 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000982 return createVariableExpression(V);
983 }
984
985 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlin7ef26da2017-08-30 19:52:39 +0000986 if (CC) {
987 if (CC->getLeader() && CC->getLeader() != I) {
Daniel Berlin94090dd2017-09-02 02:18:44 +0000988 // Don't add temporary instructions to the user lists.
989 if (!AllTempInstructions.count(I))
990 addAdditionalUsers(V, I);
Daniel Berlin7ef26da2017-08-30 19:52:39 +0000991 return createVariableOrConstant(CC->getLeader());
Daniel Berlinc8ed4042017-05-30 06:42:29 +0000992 }
993
Daniel Berlin7ef26da2017-08-30 19:52:39 +0000994 if (CC->getDefiningExpr()) {
995 // If we simplified to something else, we need to communicate
996 // that we're users of the value we simplified to.
997 if (I != V) {
998 // Don't add temporary instructions to the user lists.
999 if (!AllTempInstructions.count(I))
1000 addAdditionalUsers(V, I);
1001 }
1002
1003 if (I)
1004 DEBUG(dbgs() << "Simplified " << *I << " to "
1005 << " expression " << *CC->getDefiningExpr() << "\n");
1006 NumGVNOpsSimplified++;
1007 deleteExpression(E);
1008 return CC->getDefiningExpr();
1009 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001010 }
Daniel Berlin7ef26da2017-08-30 19:52:39 +00001011
Davide Italiano7e274e02016-12-22 16:03:48 +00001012 return nullptr;
1013}
1014
Daniel Berlin94090dd2017-09-02 02:18:44 +00001015// Create a value expression from the instruction I, replacing operands with
1016// their leaders.
1017
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001018const Expression *NewGVN::createExpression(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001019 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +00001020
Daniel Berlin97718e62017-01-31 22:32:03 +00001021 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001022
1023 if (I->isCommutative()) {
1024 // Ensure that commutative instructions that only differ by a permutation
1025 // of their operands get the same value number by sorting the operand value
1026 // numbers. Since all commutative instructions have two operands it is more
1027 // efficient to sort by hand rather than using, say, std::sort.
1028 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +00001029 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +00001030 E->swapOperands(0, 1);
1031 }
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001032 // Perform simplification.
Davide Italiano7e274e02016-12-22 16:03:48 +00001033 if (auto *CI = dyn_cast<CmpInst>(I)) {
1034 // Sort the operand value numbers so x<y and y>x get the same value
1035 // number.
1036 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +00001037 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001038 E->swapOperands(0, 1);
1039 Predicate = CmpInst::getSwappedPredicate(Predicate);
1040 }
1041 E->setOpcode((CI->getOpcode() << 8) | Predicate);
1042 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +00001043 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
1044 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +00001045 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
1046 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +00001047 Value *V =
1048 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +00001049 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1050 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001051 } else if (isa<SelectInst>(I)) {
1052 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlinf9486032017-08-24 02:43:17 +00001053 E->getOperand(1) == E->getOperand(2)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001054 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
1055 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +00001056 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +00001057 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001058 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1059 return SimplifiedE;
1060 }
1061 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001062 Value *V =
1063 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001064 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1065 return SimplifiedE;
1066 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001067 Value *V =
1068 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001069 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1070 return SimplifiedE;
1071 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001072 Value *V = SimplifyGEPInst(
1073 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001074 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1075 return SimplifiedE;
1076 } else if (AllConstant) {
1077 // We don't bother trying to simplify unless all of the operands
1078 // were constant.
1079 // TODO: There are a lot of Simplify*'s we could call here, if we
1080 // wanted to. The original motivating case for this code was a
1081 // zext i1 false to i8, which we don't have an interface to
1082 // simplify (IE there is no SimplifyZExt).
1083
1084 SmallVector<Constant *, 8> C;
1085 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001086 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +00001087
Daniel Berlin64e68992017-03-12 04:46:45 +00001088 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +00001089 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1090 return SimplifiedE;
1091 }
1092 return E;
1093}
1094
1095const AggregateValueExpression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001096NewGVN::createAggregateValueExpression(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001097 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001098 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001099 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001100 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001101 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001102 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001103 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001104 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001105 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001106 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001107 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001108 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001109 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001110 return E;
1111 }
1112 llvm_unreachable("Unhandled type of aggregate value operation");
1113}
1114
Daniel Berline021d2d2017-05-19 20:22:20 +00001115const DeadExpression *NewGVN::createDeadExpression() const {
1116 // DeadExpression has no arguments and all DeadExpression's are the same,
1117 // so we only need one of them.
1118 return SingletonDeadExpression;
1119}
1120
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001121const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001122 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001123 E->setOpcode(V->getValueID());
1124 return E;
1125}
1126
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001127const Expression *NewGVN::createVariableOrConstant(Value *V) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001128 if (auto *C = dyn_cast<Constant>(V))
1129 return createConstantExpression(C);
1130 return createVariableExpression(V);
1131}
1132
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001133const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001134 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +00001135 E->setOpcode(C->getValueID());
1136 return E;
1137}
1138
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001139const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001140 auto *E = new (ExpressionAllocator) UnknownExpression(I);
1141 E->setOpcode(I->getOpcode());
1142 return E;
1143}
1144
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001145const CallExpression *
1146NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001147 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001148 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +00001149 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +00001150 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001151 return E;
1152}
1153
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001154// Return true if some equivalent of instruction Inst dominates instruction U.
1155bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1156 const Instruction *U) const {
1157 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +00001158 // This must be an instruction because we are only called from phi nodes
1159 // in the case that the value it needs to check against is an instruction.
1160
1161 // The most likely candiates for dominance are the leader and the next leader.
1162 // The leader or nextleader will dominate in all cases where there is an
1163 // equivalent that is higher up in the dom tree.
1164 // We can't *only* check them, however, because the
1165 // dominator tree could have an infinite number of non-dominating siblings
1166 // with instructions that are in the right congruence class.
1167 // A
1168 // B C D E F G
1169 // |
1170 // H
1171 // Instruction U could be in H, with equivalents in every other sibling.
1172 // Depending on the rpo order picked, the leader could be the equivalent in
1173 // any of these siblings.
1174 if (!CC)
1175 return false;
Daniel Berlina8236562017-04-07 18:38:09 +00001176 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001177 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001178 if (CC->getNextLeader().first &&
1179 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001180 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001181 return llvm::any_of(*CC, [&](const Value *Member) {
1182 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001183 DT->dominates(cast<Instruction>(Member), U);
1184 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001185}
1186
Davide Italiano7e274e02016-12-22 16:03:48 +00001187// See if we have a congruence class and leader for this operand, and if so,
1188// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001189Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001190 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001191 if (CC) {
Daniel Berline021d2d2017-05-19 20:22:20 +00001192 // Everything in TOP is represented by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001193 // We do have to make sure we get the type right though, so we can't set the
1194 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001195 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001196 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001197 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001198 }
1199
Davide Italiano7e274e02016-12-22 16:03:48 +00001200 return V;
1201}
1202
Daniel Berlin1316a942017-04-06 18:52:50 +00001203const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1204 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001205 assert(CC->getMemoryLeader() &&
Davide Italianob60f6e02017-05-12 15:25:56 +00001206 "Every MemoryAccess should be mapped to a congruence class with a "
1207 "representative memory access");
Daniel Berlina8236562017-04-07 18:38:09 +00001208 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001209}
1210
Daniel Berlinc4796862017-01-27 02:37:11 +00001211// Return true if the MemoryAccess is really equivalent to everything. This is
1212// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001213// state of all MemoryAccesses.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001214bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001215 return getMemoryClass(MA) == TOPClass;
1216}
1217
Davide Italiano7e274e02016-12-22 16:03:48 +00001218LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001219 LoadInst *LI,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001220 const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001221 auto *E =
1222 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001223 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1224 E->setType(LoadType);
1225
1226 // Give store and loads same opcode so they value number together.
1227 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001228 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001229 if (LI)
1230 E->setAlignment(LI->getAlignment());
1231
1232 // TODO: Value number heap versions. We may be able to discover
1233 // things alias analysis can't on it's own (IE that a store and a
1234 // load have the same value, and thus, it isn't clobbering the load).
1235 return E;
1236}
1237
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001238const StoreExpression *
1239NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001240 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001241 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001242 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001243 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1244 E->setType(SI->getValueOperand()->getType());
1245
1246 // Give store and loads same opcode so they value number together.
1247 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001248 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001249
1250 // TODO: Value number heap versions. We may be able to discover
1251 // things alias analysis can't on it's own (IE that a store and a
1252 // load have the same value, and thus, it isn't clobbering the load).
1253 return E;
1254}
1255
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001256const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001257 // Unlike loads, we never try to eliminate stores, so we do not check if they
1258 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001259 auto *SI = cast<StoreInst>(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001260 auto *StoreAccess = getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001261 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001262 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1263 if (EnableStoreRefinement)
1264 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1265 // If we bypassed the use-def chains, make sure we add a use.
Daniel Berlinde269f42017-08-26 07:37:11 +00001266 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlin1316a942017-04-06 18:52:50 +00001267 if (StoreRHS != StoreAccess->getDefiningAccess())
1268 addMemoryUsers(StoreRHS, StoreAccess);
Daniel Berlinc4796862017-01-27 02:37:11 +00001269 // If we are defined by ourselves, use the live on entry def.
1270 if (StoreRHS == StoreAccess)
1271 StoreRHS = MSSA->getLiveOnEntryDef();
1272
Daniel Berlin589cecc2017-01-02 18:00:46 +00001273 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001274 // See if we are defined by a previous store expression, it already has a
1275 // value, and it's the same value as our current store. FIXME: Right now, we
1276 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001277 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1278 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlin36b08b22017-06-19 00:24:00 +00001279 // We really want to check whether the expression we matched was a store. No
1280 // easy way to do that. However, we can check that the class we found has a
1281 // store, which, assuming the value numbering state is not corrupt, is
1282 // sufficient, because we must also be equivalent to that store's expression
1283 // for it to be in the same class as the load.
1284 if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
Daniel Berlin1316a942017-04-06 18:52:50 +00001285 return LastStore;
Daniel Berlinc4796862017-01-27 02:37:11 +00001286 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001287 // location, and the memory state is the same as it was then (otherwise, it
1288 // could have been overwritten later. See test32 in
1289 // transforms/DeadStoreElimination/simple.ll).
Daniel Berlin36b08b22017-06-19 00:24:00 +00001290 if (auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
Daniel Berlin203f47b2017-01-31 22:31:53 +00001291 if ((lookupOperandLeader(LI->getPointerOperand()) ==
Daniel Berlin36b08b22017-06-19 00:24:00 +00001292 LastStore->getOperand(0)) &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001293 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
Daniel Berlin1316a942017-04-06 18:52:50 +00001294 StoreRHS))
Daniel Berlin36b08b22017-06-19 00:24:00 +00001295 return LastStore;
1296 deleteExpression(LastStore);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001297 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001298
1299 // If the store is not equivalent to anything, value number it as a store that
1300 // produces a unique memory state (instead of using it's MemoryUse, we use
1301 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001302 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001303}
1304
Daniel Berlin07daac82017-04-02 13:23:44 +00001305// See if we can extract the value of a loaded pointer from a load, a store, or
1306// a memory instruction.
1307const Expression *
1308NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1309 LoadInst *LI, Instruction *DepInst,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001310 MemoryAccess *DefiningAccess) const {
Daniel Berlin07daac82017-04-02 13:23:44 +00001311 assert((!LI || LI->isSimple()) && "Not a simple load");
1312 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1313 // Can't forward from non-atomic to atomic without violating memory model.
1314 // Also don't need to coerce if they are the same type, we will just
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001315 // propagate.
Daniel Berlin07daac82017-04-02 13:23:44 +00001316 if (LI->isAtomic() > DepSI->isAtomic() ||
1317 LoadType == DepSI->getValueOperand()->getType())
1318 return nullptr;
1319 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1320 if (Offset >= 0) {
1321 if (auto *C = dyn_cast<Constant>(
1322 lookupOperandLeader(DepSI->getValueOperand()))) {
1323 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1324 << *C << "\n");
1325 return createConstantExpression(
1326 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1327 }
1328 }
1329
Davide Italiano9bdccb32017-08-26 22:31:10 +00001330 } else if (auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
Daniel Berlin07daac82017-04-02 13:23:44 +00001331 // Can't forward from non-atomic to atomic without violating memory model.
1332 if (LI->isAtomic() > DepLI->isAtomic())
1333 return nullptr;
1334 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1335 if (Offset >= 0) {
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001336 // We can coerce a constant load into a load.
Daniel Berlin07daac82017-04-02 13:23:44 +00001337 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1338 if (auto *PossibleConstant =
1339 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1340 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1341 << *PossibleConstant << "\n");
1342 return createConstantExpression(PossibleConstant);
1343 }
1344 }
1345
Davide Italiano9bdccb32017-08-26 22:31:10 +00001346 } else if (auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
Daniel Berlin07daac82017-04-02 13:23:44 +00001347 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1348 if (Offset >= 0) {
1349 if (auto *PossibleConstant =
1350 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1351 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1352 << " to constant " << *PossibleConstant << "\n");
1353 return createConstantExpression(PossibleConstant);
1354 }
1355 }
1356 }
1357
1358 // All of the below are only true if the loaded pointer is produced
1359 // by the dependent instruction.
1360 if (LoadPtr != lookupOperandLeader(DepInst) &&
1361 !AA->isMustAlias(LoadPtr, DepInst))
1362 return nullptr;
1363 // If this load really doesn't depend on anything, then we must be loading an
1364 // undef value. This can happen when loading for a fresh allocation with no
1365 // intervening stores, for example. Note that this is only true in the case
1366 // that the result of the allocation is pointer equal to the load ptr.
1367 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1368 return createConstantExpression(UndefValue::get(LoadType));
1369 }
1370 // If this load occurs either right after a lifetime begin,
1371 // then the loaded value is undefined.
1372 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1373 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1374 return createConstantExpression(UndefValue::get(LoadType));
1375 }
1376 // If this load follows a calloc (which zero initializes memory),
1377 // then the loaded value is zero
1378 else if (isCallocLikeFn(DepInst, TLI)) {
1379 return createConstantExpression(Constant::getNullValue(LoadType));
1380 }
1381
1382 return nullptr;
1383}
1384
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001385const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001386 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001387
1388 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001389 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001390 if (!LI->isSimple())
1391 return nullptr;
1392
Daniel Berlin203f47b2017-01-31 22:31:53 +00001393 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001394 // Load of undef is undef.
1395 if (isa<UndefValue>(LoadAddressLeader))
1396 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001397 MemoryAccess *OriginalAccess = getMemoryAccess(I);
1398 MemoryAccess *DefiningAccess =
1399 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001400
1401 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1402 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1403 Instruction *DefiningInst = MD->getMemoryInst();
1404 // If the defining instruction is not reachable, replace with undef.
1405 if (!ReachableBlocks.count(DefiningInst->getParent()))
1406 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001407 // This will handle stores and memory insts. We only do if it the
1408 // defining access has a different type, or it is a pointer produced by
1409 // certain memory operations that cause the memory to have a fixed value
1410 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001411 if (const auto *CoercionResult =
1412 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1413 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001414 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001415 }
1416 }
1417
Daniel Berlin94090dd2017-09-02 02:18:44 +00001418 const auto *LE = createLoadExpression(LI->getType(), LoadAddressLeader, LI,
1419 DefiningAccess);
Daniel Berlinde269f42017-08-26 07:37:11 +00001420 // If our MemoryLeader is not our defining access, add a use to the
1421 // MemoryLeader, so that we get reprocessed when it changes.
1422 if (LE->getMemoryLeader() != DefiningAccess)
1423 addMemoryUsers(LE->getMemoryLeader(), OriginalAccess);
1424 return LE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001425}
1426
Daniel Berlinf7d95802017-02-18 23:06:50 +00001427const Expression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001428NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001429 auto *PI = PredInfo->getPredicateInfoFor(I);
1430 if (!PI)
1431 return nullptr;
1432
1433 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001434
1435 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1436 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001437 return nullptr;
1438
Daniel Berlinfccbda92017-02-22 22:20:58 +00001439 auto *CopyOf = I->getOperand(0);
1440 auto *Cond = PWC->Condition;
1441
Daniel Berlinf7d95802017-02-18 23:06:50 +00001442 // If this a copy of the condition, it must be either true or false depending
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001443 // on the predicate info type and edge.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001444 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001445 // We should not need to add predicate users because the predicate info is
1446 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001447 if (isa<PredicateAssume>(PI))
1448 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1449 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1450 if (PBranch->TrueEdge)
1451 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1452 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1453 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001454 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1455 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001456 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001457
Daniel Berlinf7d95802017-02-18 23:06:50 +00001458 // Not a copy of the condition, so see what the predicates tell us about this
1459 // value. First, though, we check to make sure the value is actually a copy
1460 // of one of the condition operands. It's possible, in certain cases, for it
1461 // to be a copy of a predicateinfo copy. In particular, if two branch
1462 // operations use the same condition, and one branch dominates the other, we
1463 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001464 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001465 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001466
1467 // Everything below relies on the condition being a comparison.
1468 auto *Cmp = dyn_cast<CmpInst>(Cond);
1469 if (!Cmp)
1470 return nullptr;
1471
1472 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Davide Italianoc43a9f82017-05-12 15:28:12 +00001473 DEBUG(dbgs() << "Copy is not of any condition operands!\n");
Daniel Berlinf7d95802017-02-18 23:06:50 +00001474 return nullptr;
1475 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001476 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1477 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001478 bool SwappedOps = false;
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001479 // Sort the ops.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001480 if (shouldSwapOperands(FirstOp, SecondOp)) {
1481 std::swap(FirstOp, SecondOp);
1482 SwappedOps = true;
1483 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001484 CmpInst::Predicate Predicate =
1485 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1486
1487 if (isa<PredicateAssume>(PI)) {
1488 // If the comparison is true when the operands are equal, then we know the
1489 // operands are equal, because assumes must always be true.
1490 if (CmpInst::isTrueWhenEqual(Predicate)) {
1491 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001492 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001493 return createVariableOrConstant(FirstOp);
1494 }
1495 }
1496 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1497 // If we are *not* a copy of the comparison, we may equal to the other
1498 // operand when the predicate implies something about equality of
1499 // operations. In particular, if the comparison is true/false when the
1500 // operands are equal, and we are on the right edge, we know this operation
1501 // is equal to something.
1502 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1503 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1504 addPredicateUsers(PI, I);
Daniel Berlin23fec572017-08-30 19:53:23 +00001505 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1506 I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001507 return createVariableOrConstant(FirstOp);
1508 }
1509 // Handle the special case of floating point.
1510 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1511 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1512 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1513 addPredicateUsers(PI, I);
Daniel Berlin23fec572017-08-30 19:53:23 +00001514 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1515 I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001516 return createConstantExpression(cast<Constant>(FirstOp));
1517 }
1518 }
1519 return nullptr;
1520}
1521
Davide Italiano7e274e02016-12-22 16:03:48 +00001522// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001523const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001524 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001525 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1526 // Instrinsics with the returned attribute are copies of arguments.
1527 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1528 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1529 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1530 return Result;
1531 return createVariableOrConstant(ReturnedValue);
1532 }
1533 }
1534 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001535 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001536 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001537 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001538 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001539 }
1540 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001541}
1542
Daniel Berlin1316a942017-04-06 18:52:50 +00001543// Retrieve the memory class for a given MemoryAccess.
1544CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1545
1546 auto *Result = MemoryAccessToClass.lookup(MA);
1547 assert(Result && "Should have found memory class");
1548 return Result;
1549}
1550
1551// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001552// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001553bool NewGVN::setMemoryClass(const MemoryAccess *From,
1554 CongruenceClass *NewClass) {
1555 assert(NewClass &&
1556 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001557 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001558 DEBUG(dbgs() << " equivalent to congruence class ");
Daniel Berlina8236562017-04-07 18:38:09 +00001559 DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
Davide Italianob7a66982017-05-09 20:02:48 +00001560 DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001561
1562 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001563 bool Changed = false;
1564 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001565 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001566 auto *OldClass = LookupResult->second;
1567 if (OldClass != NewClass) {
1568 // If this is a phi, we have to handle memory member updates.
1569 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001570 OldClass->memory_erase(MP);
1571 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001572 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001573 if (OldClass->getMemoryLeader() == From) {
Davide Italiano41f5c7b2017-05-12 15:22:45 +00001574 if (OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00001575 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001576 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001577 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Daniel Berlin1316a942017-04-06 18:52:50 +00001578 DEBUG(dbgs() << "Memory class leader change for class "
Daniel Berlina8236562017-04-07 18:38:09 +00001579 << OldClass->getID() << " to "
1580 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001581 << " due to removal of a memory member " << *From
1582 << "\n");
1583 markMemoryLeaderChangeTouched(OldClass);
1584 }
1585 }
1586 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001587 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001588 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001589 Changed = true;
1590 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001591 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001592
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001593 return Changed;
1594}
Daniel Berlin0e900112017-03-24 06:33:48 +00001595
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001596// Determine if a instruction is cycle-free. That means the values in the
1597// instruction don't depend on any expressions that can change value as a result
1598// of the instruction. For example, a non-cycle free instruction would be v =
1599// phi(0, v+1).
1600bool NewGVN::isCycleFree(const Instruction *I) const {
1601 // In order to compute cycle-freeness, we do SCC finding on the instruction,
1602 // and see what kind of SCC it ends up in. If it is a singleton, it is
1603 // cycle-free. If it is not in a singleton, it is only cycle free if the
1604 // other members are all phi nodes (as they do not compute anything, they are
1605 // copies).
1606 auto ICS = InstCycleState.lookup(I);
1607 if (ICS == ICS_Unknown) {
1608 SCCFinder.Start(I);
1609 auto &SCC = SCCFinder.getComponentFor(I);
Daniel Berlin2f72b192017-04-14 02:53:37 +00001610 // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1611 if (SCC.size() == 1)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001612 InstCycleState.insert({I, ICS_CycleFree});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001613 else {
1614 bool AllPhis =
1615 llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001616 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
Daniel Berlin2f72b192017-04-14 02:53:37 +00001617 for (auto *Member : SCC)
1618 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001619 InstCycleState.insert({MemberPhi, ICS});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001620 }
1621 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001622 if (ICS == ICS_Cycle)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001623 return false;
1624 return true;
1625}
1626
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001627// Evaluate PHI nodes symbolically and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001628const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001629 // True if one of the incoming phi edges is a backedge.
1630 bool HasBackedge = false;
1631 // All constant tracks the state of whether all the *original* phi operands
Daniel Berline021d2d2017-05-19 20:22:20 +00001632 // This is really shorthand for "this phi cannot cycle due to forward
1633 // change in value of the phi is guaranteed not to later change the value of
1634 // the phi. IE it can't be v = phi(undef, v+1)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001635 bool AllConstant = true;
Daniel Berlinabd632d2017-05-16 06:06:12 +00001636 auto *E =
1637 cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001638 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001639 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001640 // We track if any were undef because they need special handling.
1641 bool HasUndef = false;
Daniel Berline021d2d2017-05-19 20:22:20 +00001642 auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
Daniel Berlind92e7f92017-01-07 00:01:42 +00001643 if (isa<UndefValue>(Arg)) {
1644 HasUndef = true;
1645 return false;
1646 }
1647 return true;
1648 });
Daniel Berline021d2d2017-05-19 20:22:20 +00001649 // If we are left with no operands, it's dead.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001650 if (Filtered.begin() == Filtered.end()) {
Daniel Berline67c3222017-05-25 15:44:20 +00001651 // If it has undef at this point, it means there are no-non-undef arguments,
1652 // and thus, the value of the phi node must be undef.
1653 if (HasUndef) {
1654 DEBUG(dbgs() << "PHI Node " << *I
1655 << " has no non-undef arguments, valuing it as undef\n");
1656 return createConstantExpression(UndefValue::get(I->getType()));
1657 }
1658
Daniel Berline021d2d2017-05-19 20:22:20 +00001659 DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001660 deleteExpression(E);
Daniel Berline021d2d2017-05-19 20:22:20 +00001661 return createDeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00001662 }
Daniel Berlin2f72b192017-04-14 02:53:37 +00001663 unsigned NumOps = 0;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001664 Value *AllSameValue = *(Filtered.begin());
1665 ++Filtered.begin();
1666 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berline021d2d2017-05-19 20:22:20 +00001667 if (llvm::all_of(Filtered, [&](Value *Arg) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001668 ++NumOps;
Daniel Berline021d2d2017-05-19 20:22:20 +00001669 return Arg == AllSameValue;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001670 })) {
1671 // In LLVM's non-standard representation of phi nodes, it's possible to have
1672 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1673 // on the original phi node), especially in weird CFG's where some arguments
1674 // are unreachable, or uninitialized along certain paths. This can cause
1675 // infinite loops during evaluation. We work around this by not trying to
1676 // really evaluate them independently, but instead using a variable
1677 // expression to say if one is equivalent to the other.
1678 // We also special case undef, so that if we have an undef, we can't use the
1679 // common value unless it dominates the phi block.
1680 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001681 // If we have undef and at least one other value, this is really a
1682 // multivalued phi, and we need to know if it's cycle free in order to
1683 // evaluate whether we can ignore the undef. The other parts of this are
1684 // just shortcuts. If there is no backedge, or all operands are
1685 // constants, or all operands are ignored but the undef, it also must be
1686 // cycle free.
1687 if (!AllConstant && HasBackedge && NumOps > 0 &&
Daniel Berline67c3222017-05-25 15:44:20 +00001688 !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
Daniel Berlin2f72b192017-04-14 02:53:37 +00001689 return E;
1690
Daniel Berlind92e7f92017-01-07 00:01:42 +00001691 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001692 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001693 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001694 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001695 }
Daniel Berlineafdd862017-06-06 17:15:28 +00001696 // Can't simplify to something that comes later in the iteration.
1697 // Otherwise, when and if it changes congruence class, we will never catch
1698 // up. We will always be a class behind it.
1699 if (isa<Instruction>(AllSameValue) &&
1700 InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
1701 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001702 NumGVNPhisAllSame++;
1703 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1704 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001705 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001706 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001707 }
1708 return E;
1709}
1710
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001711const Expression *
1712NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001713 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1714 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1715 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1716 unsigned Opcode = 0;
1717 // EI might be an extract from one of our recognised intrinsics. If it
1718 // is we'll synthesize a semantically equivalent expression instead on
1719 // an extract value expression.
1720 switch (II->getIntrinsicID()) {
1721 case Intrinsic::sadd_with_overflow:
1722 case Intrinsic::uadd_with_overflow:
1723 Opcode = Instruction::Add;
1724 break;
1725 case Intrinsic::ssub_with_overflow:
1726 case Intrinsic::usub_with_overflow:
1727 Opcode = Instruction::Sub;
1728 break;
1729 case Intrinsic::smul_with_overflow:
1730 case Intrinsic::umul_with_overflow:
1731 Opcode = Instruction::Mul;
1732 break;
1733 default:
1734 break;
1735 }
1736
1737 if (Opcode != 0) {
1738 // Intrinsic recognized. Grab its args to finish building the
1739 // expression.
1740 assert(II->getNumArgOperands() == 2 &&
1741 "Expect two args for recognised intrinsics.");
Daniel Berlin54a92fc2017-09-05 02:17:42 +00001742 return createBinaryExpression(Opcode, EI->getType(),
1743 II->getArgOperand(0),
1744 II->getArgOperand(1), I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001745 }
1746 }
1747 }
1748
Daniel Berlin97718e62017-01-31 22:32:03 +00001749 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001750}
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001751const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
Chad Rosier4d852592017-08-08 18:41:49 +00001752 assert(isa<CmpInst>(I) && "Expected a cmp instruction.");
1753
1754 auto *CI = cast<CmpInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001755 // See if our operands are equal to those of a previous predicate, and if so,
1756 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001757 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1758 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001759 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001760 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001761 std::swap(Op0, Op1);
1762 OurPredicate = CI->getSwappedPredicate();
1763 }
1764
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001765 // Avoid processing the same info twice.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001766 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001767 // See if we know something about the comparison itself, like it is the target
1768 // of an assume.
1769 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1770 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1771 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1772
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001773 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001774 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001775 if (CI->isTrueWhenEqual())
1776 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1777 else if (CI->isFalseWhenEqual())
1778 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1779 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001780
1781 // NOTE: Because we are comparing both operands here and below, and using
1782 // previous comparisons, we rely on fact that predicateinfo knows to mark
1783 // comparisons that use renamed operands as users of the earlier comparisons.
1784 // It is *not* enough to just mark predicateinfo renamed operands as users of
1785 // the earlier comparisons, because the *other* operand may have changed in a
1786 // previous iteration.
1787 // Example:
1788 // icmp slt %a, %b
1789 // %b.0 = ssa.copy(%b)
1790 // false branch:
1791 // icmp slt %c, %b.0
1792
1793 // %c and %a may start out equal, and thus, the code below will say the second
1794 // %icmp is false. c may become equal to something else, and in that case the
1795 // %second icmp *must* be reexamined, but would not if only the renamed
1796 // %operands are considered users of the icmp.
1797
1798 // *Currently* we only check one level of comparisons back, and only mark one
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001799 // level back as touched when changes happen. If you modify this code to look
Daniel Berlinf7d95802017-02-18 23:06:50 +00001800 // back farther through comparisons, you *must* mark the appropriate
1801 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1802 // we know something just from the operands themselves
1803
1804 // See if our operands have predicate info, so that we may be able to derive
1805 // something from a previous comparison.
1806 for (const auto &Op : CI->operands()) {
1807 auto *PI = PredInfo->getPredicateInfoFor(Op);
1808 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1809 if (PI == LastPredInfo)
1810 continue;
1811 LastPredInfo = PI;
Daniel Berlin86932102017-09-01 19:20:18 +00001812 // In phi of ops cases, we may have predicate info that we are evaluating
1813 // in a different context.
1814 if (!DT->dominates(PBranch->To, getBlockForValue(I)))
1815 continue;
1816 // TODO: Along the false edge, we may know more things too, like
1817 // icmp of
Daniel Berlinf7d95802017-02-18 23:06:50 +00001818 // same operands is false.
Daniel Berlin86932102017-09-01 19:20:18 +00001819 // TODO: We only handle actual comparison conditions below, not
1820 // and/or.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001821 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1822 if (!BranchCond)
1823 continue;
1824 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1825 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1826 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001827 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001828 std::swap(BranchOp0, BranchOp1);
1829 BranchPredicate = BranchCond->getSwappedPredicate();
1830 }
1831 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1832 if (PBranch->TrueEdge) {
1833 // If we know the previous predicate is true and we are in the true
1834 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001835 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1836 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001837 addPredicateUsers(PI, I);
1838 return createConstantExpression(
1839 ConstantInt::getTrue(CI->getType()));
1840 }
1841
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001842 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1843 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001844 addPredicateUsers(PI, I);
1845 return createConstantExpression(
1846 ConstantInt::getFalse(CI->getType()));
1847 }
1848
1849 } else {
1850 // Just handle the ne and eq cases, where if we have the same
1851 // operands, we may know something.
1852 if (BranchPredicate == OurPredicate) {
1853 addPredicateUsers(PI, I);
1854 // Same predicate, same ops,we know it was false, so this is false.
1855 return createConstantExpression(
1856 ConstantInt::getFalse(CI->getType()));
1857 } else if (BranchPredicate ==
1858 CmpInst::getInversePredicate(OurPredicate)) {
1859 addPredicateUsers(PI, I);
1860 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001861 return createConstantExpression(
1862 ConstantInt::getTrue(CI->getType()));
1863 }
1864 }
1865 }
1866 }
1867 }
1868 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001869 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001870}
Davide Italiano7e274e02016-12-22 16:03:48 +00001871
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001872// Return true if V is a value that will always be available (IE can
1873// be placed anywhere) in the function. We don't do globals here
1874// because they are often worse to put in place.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001875static bool alwaysAvailable(Value *V) {
1876 return isa<Constant>(V) || isa<Argument>(V);
1877}
1878
Davide Italiano7e274e02016-12-22 16:03:48 +00001879// Substitute and symbolize the value before value numbering.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001880const Expression *
1881NewGVN::performSymbolicEvaluation(Value *V,
1882 SmallPtrSetImpl<Value *> &Visited) const {
Davide Italiano0e714802016-12-28 14:00:11 +00001883 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001884 if (auto *C = dyn_cast<Constant>(V))
1885 E = createConstantExpression(C);
1886 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1887 E = createVariableExpression(V);
1888 } else {
1889 // TODO: memory intrinsics.
1890 // TODO: Some day, we should do the forward propagation and reassociation
1891 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001892 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001893 switch (I->getOpcode()) {
1894 case Instruction::ExtractValue:
1895 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001896 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001897 break;
1898 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001899 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001900 break;
1901 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001902 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001903 break;
1904 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001905 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001906 break;
1907 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001908 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001909 break;
1910 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001911 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001912 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001913 case Instruction::ICmp:
1914 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001915 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001916 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001917 case Instruction::Add:
1918 case Instruction::FAdd:
1919 case Instruction::Sub:
1920 case Instruction::FSub:
1921 case Instruction::Mul:
1922 case Instruction::FMul:
1923 case Instruction::UDiv:
1924 case Instruction::SDiv:
1925 case Instruction::FDiv:
1926 case Instruction::URem:
1927 case Instruction::SRem:
1928 case Instruction::FRem:
1929 case Instruction::Shl:
1930 case Instruction::LShr:
1931 case Instruction::AShr:
1932 case Instruction::And:
1933 case Instruction::Or:
1934 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001935 case Instruction::Trunc:
1936 case Instruction::ZExt:
1937 case Instruction::SExt:
1938 case Instruction::FPToUI:
1939 case Instruction::FPToSI:
1940 case Instruction::UIToFP:
1941 case Instruction::SIToFP:
1942 case Instruction::FPTrunc:
1943 case Instruction::FPExt:
1944 case Instruction::PtrToInt:
1945 case Instruction::IntToPtr:
1946 case Instruction::Select:
1947 case Instruction::ExtractElement:
1948 case Instruction::InsertElement:
1949 case Instruction::ShuffleVector:
1950 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001951 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001952 break;
1953 default:
1954 return nullptr;
1955 }
1956 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001957 return E;
1958}
1959
Daniel Berlin0207cca2017-05-21 23:41:56 +00001960// Look up a container in a map, and then call a function for each thing in the
1961// found container.
1962template <typename Map, typename KeyType, typename Func>
1963void NewGVN::for_each_found(Map &M, const KeyType &Key, Func F) {
1964 const auto Result = M.find_as(Key);
1965 if (Result != M.end())
1966 for (typename Map::mapped_type::value_type Mapped : Result->second)
1967 F(Mapped);
1968}
1969
1970// Look up a container of values/instructions in a map, and touch all the
1971// instructions in the container. Then erase value from the map.
1972template <typename Map, typename KeyType>
1973void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
1974 const auto Result = M.find_as(Key);
1975 if (Result != M.end()) {
1976 for (const typename Map::mapped_type::value_type Mapped : Result->second)
1977 TouchedInstructions.set(InstrToDFSNum(Mapped));
1978 M.erase(Result);
1979 }
1980}
1981
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001982void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
Daniel Berlin54a92fc2017-09-05 02:17:42 +00001983 assert(User && To != User);
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00001984 if (isa<Instruction>(To))
1985 AdditionalUsers[To].insert(User);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001986}
1987
Davide Italiano7e274e02016-12-22 16:03:48 +00001988void NewGVN::markUsersTouched(Value *V) {
1989 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001990 for (auto *User : V->users()) {
1991 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001992 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001993 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00001994 touchAndErase(AdditionalUsers, V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001995}
1996
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001997void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001998 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1999 MemoryToUsers[To].insert(U);
2000}
2001
2002void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002003 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00002004}
2005
2006void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
2007 if (isa<MemoryUse>(MA))
2008 return;
2009 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00002010 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin0207cca2017-05-21 23:41:56 +00002011 touchAndErase(MemoryToUsers, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00002012}
2013
Daniel Berlinf7d95802017-02-18 23:06:50 +00002014// Add I to the set of users of a given predicate.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00002015void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002016 // Don't add temporary instructions to the user lists.
2017 if (AllTempInstructions.count(I))
2018 return;
2019
Daniel Berlinf7d95802017-02-18 23:06:50 +00002020 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
2021 PredicateToUsers[PBranch->Condition].insert(I);
2022 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
2023 PredicateToUsers[PAssume->Condition].insert(I);
2024}
2025
2026// Touch all the predicates that depend on this instruction.
2027void NewGVN::markPredicateUsersTouched(Instruction *I) {
Daniel Berlin0207cca2017-05-21 23:41:56 +00002028 touchAndErase(PredicateToUsers, I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002029}
2030
Daniel Berlin1316a942017-04-06 18:52:50 +00002031// Mark users affected by a memory leader change.
2032void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00002033 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002034 markMemoryDefTouched(M);
2035}
2036
Daniel Berlin32f8d562017-01-07 16:55:14 +00002037// Touch the instructions that need to be updated after a congruence class has a
2038// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00002039void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00002040 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00002041 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002042 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002043 LeaderChanges.insert(M);
2044 }
2045}
2046
Daniel Berlin1316a942017-04-06 18:52:50 +00002047// Give a range of things that have instruction DFS numbers, this will return
2048// the member of the range with the smallest dfs number.
2049template <class T, class Range>
2050T *NewGVN::getMinDFSOfRange(const Range &R) const {
2051 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
2052 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002053 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00002054 if (DFSNum < MinDFS.second)
2055 MinDFS = {X, DFSNum};
2056 }
2057 return MinDFS.first;
2058}
2059
2060// This function returns the MemoryAccess that should be the next leader of
2061// congruence class CC, under the assumption that the current leader is going to
2062// disappear.
2063const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
2064 // TODO: If this ends up to slow, we can maintain a next memory leader like we
2065 // do for regular leaders.
Daniel Berlinde269f42017-08-26 07:37:11 +00002066 // Make sure there will be a leader to find.
Davide Italianodc435322017-05-10 19:57:43 +00002067 assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00002068 if (CC->getStoreCount() > 0) {
2069 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002070 return getMemoryAccess(NL);
Daniel Berlin1316a942017-04-06 18:52:50 +00002071 // Find the store with the minimum DFS number.
2072 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00002073 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002074 return getMemoryAccess(cast<StoreInst>(V));
Daniel Berlin1316a942017-04-06 18:52:50 +00002075 }
Daniel Berlina8236562017-04-07 18:38:09 +00002076 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00002077
2078 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00002079 // !OldClass->memory_empty()
2080 if (CC->memory_size() == 1)
2081 return *CC->memory_begin();
2082 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00002083}
2084
2085// This function returns the next value leader of a congruence class, under the
2086// assumption that the current leader is going away. This should end up being
2087// the next most dominating member.
2088Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
2089 // We don't need to sort members if there is only 1, and we don't care about
2090 // sorting the TOP class because everything either gets out of it or is
2091 // unreachable.
2092
Daniel Berlina8236562017-04-07 18:38:09 +00002093 if (CC->size() == 1 || CC == TOPClass) {
2094 return *(CC->begin());
2095 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002096 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00002097 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00002098 } else {
2099 ++NumGVNSortedLeaderChanges;
2100 // NOTE: If this ends up to slow, we can maintain a dual structure for
2101 // member testing/insertion, or keep things mostly sorted, and sort only
2102 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00002103 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00002104 }
2105}
2106
2107// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
2108// the memory members, etc for the move.
2109//
2110// The invariants of this function are:
2111//
Davide Italianofb4544c2017-07-11 19:15:36 +00002112// - I must be moving to NewClass from OldClass
2113// - The StoreCount of OldClass and NewClass is expected to have been updated
2114// for I already if it is is a store.
2115// - The OldClass memory leader has not been updated yet if I was the leader.
Daniel Berlin1316a942017-04-06 18:52:50 +00002116void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
2117 MemoryAccess *InstMA,
2118 CongruenceClass *OldClass,
2119 CongruenceClass *NewClass) {
2120 // If the leader is I, and we had a represenative MemoryAccess, it should
2121 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00002122 assert((!InstMA || !OldClass->getMemoryLeader() ||
2123 OldClass->getLeader() != I ||
Davide Italianoee1c8212017-07-11 19:49:12 +00002124 MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
2125 MemoryAccessToClass.lookup(InstMA)) &&
Davide Italianof58a30232017-04-10 23:08:35 +00002126 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00002127 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00002128 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002129 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00002130 assert(NewClass->size() == 1 ||
2131 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
2132 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00002133 // Mark it touched if we didn't just create a singleton
Daniel Berlina8236562017-04-07 18:38:09 +00002134 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002135 << " due to new memory instruction becoming leader\n");
2136 markMemoryLeaderChangeTouched(NewClass);
2137 }
2138 setMemoryClass(InstMA, NewClass);
2139 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00002140 if (OldClass->getMemoryLeader() == InstMA) {
Davide Italianodc435322017-05-10 19:57:43 +00002141 if (!OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00002142 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2143 DEBUG(dbgs() << "Memory class leader change for class "
2144 << OldClass->getID() << " to "
2145 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00002146 << " due to removal of old leader " << *InstMA << "\n");
2147 markMemoryLeaderChangeTouched(OldClass);
2148 } else
Daniel Berlina8236562017-04-07 18:38:09 +00002149 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00002150 }
2151}
2152
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002153// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00002154// Update OldClass and NewClass for the move (including changing leaders, etc).
2155void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002156 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002157 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00002158 if (I == OldClass->getNextLeader().first)
2159 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002160
Daniel Berlinff152002017-05-19 19:01:24 +00002161 OldClass->erase(I);
2162 NewClass->insert(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002163
Daniel Berlina8236562017-04-07 18:38:09 +00002164 if (NewClass->getLeader() != I)
2165 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlin1316a942017-04-06 18:52:50 +00002166 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002167 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002168 OldClass->decStoreCount();
2169 // Okay, so when do we want to make a store a leader of a class?
2170 // If we have a store defined by an earlier load, we want the earlier load
2171 // to lead the class.
2172 // If we have a store defined by something else, we want the store to lead
2173 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00002174 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00002175 // as the leader
2176 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002177 // If it's a store expression we are using, it means we are not equivalent
2178 // to something earlier.
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002179 if (auto *SE = dyn_cast<StoreExpression>(E)) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002180 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1316a942017-04-06 18:52:50 +00002181 markValueLeaderChangeTouched(NewClass);
2182 // Shift the new class leader to be the store
Daniel Berlina8236562017-04-07 18:38:09 +00002183 DEBUG(dbgs() << "Changing leader of congruence class "
2184 << NewClass->getID() << " from " << *NewClass->getLeader()
2185 << " to " << *SI << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002186 // If we changed the leader, we have to mark it changed because we don't
Davide Italiano67b0e532017-07-11 19:19:45 +00002187 // know what it will do to symbolic evaluation.
Daniel Berlina8236562017-04-07 18:38:09 +00002188 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002189 }
2190 // We rely on the code below handling the MemoryAccess change.
2191 }
Daniel Berlina8236562017-04-07 18:38:09 +00002192 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002193 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002194 // True if there is no memory instructions left in a class that had memory
2195 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002196
Daniel Berlin1316a942017-04-06 18:52:50 +00002197 // If it's not a memory use, set the MemoryAccess equivalence
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002198 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
Daniel Berlin1316a942017-04-06 18:52:50 +00002199 if (InstMA)
2200 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002201 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002202 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00002203 if (OldClass->empty() && OldClass != TOPClass) {
2204 if (OldClass->getDefiningExpr()) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002205 DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002206 << " from table\n");
Daniel Berlineafdd862017-06-06 17:15:28 +00002207 // We erase it as an exact expression to make sure we don't just erase an
2208 // equivalent one.
2209 auto Iter = ExpressionToClass.find_as(
2210 ExactEqualsExpression(*OldClass->getDefiningExpr()));
2211 if (Iter != ExpressionToClass.end())
2212 ExpressionToClass.erase(Iter);
2213#ifdef EXPENSIVE_CHECKS
2214 assert(
2215 (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
2216 "We erased the expression we just inserted, which should not happen");
2217#endif
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002218 }
Daniel Berlina8236562017-04-07 18:38:09 +00002219 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002220 // When the leader changes, the value numbering of
2221 // everything may change due to symbolization changes, so we need to
2222 // reprocess.
Daniel Berlina8236562017-04-07 18:38:09 +00002223 DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002224 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002225 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00002226 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002227 // Note that this is basically clean up for the expression removal that
2228 // happens below. If we remove stores from a class, we may leave it as a
2229 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002230 if (OldClass->getStoreCount() == 0) {
2231 if (OldClass->getStoredValue())
2232 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002233 }
Daniel Berlina8236562017-04-07 18:38:09 +00002234 OldClass->setLeader(getNextValueLeader(OldClass));
2235 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002236 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002237 }
2238}
2239
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002240// For a given expression, mark the phi of ops instructions that could have
2241// changed as a result.
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002242void NewGVN::markPhiOfOpsChanged(const Expression *E) {
Daniel Berlin51e878e2017-06-14 21:19:28 +00002243 touchAndErase(ExpressionToPhiOfOps, ExactEqualsExpression(*E));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002244}
Daniel Berlin0207cca2017-05-21 23:41:56 +00002245
Davide Italiano7e274e02016-12-22 16:03:48 +00002246// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002247void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002248 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002249 // TOP.
Daniel Berline021d2d2017-05-19 20:22:20 +00002250
2251 CongruenceClass *IClass = ValueToClass.lookup(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002252 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002253 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002254 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002255
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002256 CongruenceClass *EClass = nullptr;
Daniel Berlin02c6b172017-01-02 18:00:53 +00002257 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002258 EClass = ValueToClass.lookup(VE->getVariableValue());
Daniel Berline021d2d2017-05-19 20:22:20 +00002259 } else if (isa<DeadExpression>(E)) {
2260 EClass = TOPClass;
2261 }
2262 if (!EClass) {
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002263 auto lookupResult = ExpressionToClass.insert({E, nullptr});
Davide Italiano7e274e02016-12-22 16:03:48 +00002264
2265 // If it's not in the value table, create a new congruence class.
2266 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002267 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002268 auto place = lookupResult.first;
2269 place->second = NewClass;
2270
2271 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002272 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002273 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002274 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2275 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002276 NewClass->setLeader(SI);
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002277 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002278 // The RepMemoryAccess field will be filled in properly by the
2279 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002280 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002281 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002282 }
2283 assert(!isa<VariableExpression>(E) &&
2284 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002285
2286 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002287 DEBUG(dbgs() << "Created new congruence class for " << *I
Daniel Berlina8236562017-04-07 18:38:09 +00002288 << " using expression " << *E << " at " << NewClass->getID()
2289 << " and leader " << *(NewClass->getLeader()));
2290 if (NewClass->getStoredValue())
2291 DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
Daniel Berlin26addef2017-01-20 21:04:30 +00002292 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002293 } else {
2294 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002295 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002296 assert((isa<Constant>(EClass->getLeader()) ||
2297 (EClass->getStoredValue() &&
2298 isa<Constant>(EClass->getStoredValue()))) &&
2299 "Any class with a constant expression should have a "
2300 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002301
Davide Italiano7e274e02016-12-22 16:03:48 +00002302 assert(EClass && "Somehow don't have an eclass");
2303
Daniel Berlin1316a942017-04-06 18:52:50 +00002304 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002305 }
2306 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002307 bool ClassChanged = IClass != EClass;
2308 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002309 if (ClassChanged || LeaderChanged) {
Daniel Berlina8236562017-04-07 18:38:09 +00002310 DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00002311 << "\n");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002312 if (ClassChanged) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002313 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002314 markPhiOfOpsChanged(E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002315 }
2316
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002317 markUsersTouched(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002318 if (MemoryAccess *MA = getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002319 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002320 if (auto *CI = dyn_cast<CmpInst>(I))
2321 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002322 }
Daniel Berlin45403572017-05-16 19:58:47 +00002323 // If we changed the class of the store, we want to ensure nothing finds the
2324 // old store expression. In particular, loads do not compare against stored
2325 // value, so they will find old store expressions (and associated class
2326 // mappings) if we leave them in the table.
Davide Italianoee49f492017-05-19 04:06:10 +00002327 if (ClassChanged && isa<StoreInst>(I)) {
Daniel Berlin45403572017-05-16 19:58:47 +00002328 auto *OldE = ValueToExpression.lookup(I);
2329 // It could just be that the old class died. We don't want to erase it if we
2330 // just moved classes.
Daniel Berlineafdd862017-06-06 17:15:28 +00002331 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
2332 // Erase this as an exact expression to ensure we don't erase expressions
2333 // equivalent to it.
2334 auto Iter = ExpressionToClass.find_as(ExactEqualsExpression(*OldE));
2335 if (Iter != ExpressionToClass.end())
2336 ExpressionToClass.erase(Iter);
2337 }
Daniel Berlin45403572017-05-16 19:58:47 +00002338 }
2339 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002340}
2341
2342// Process the fact that Edge (from, to) is reachable, including marking
2343// any newly reachable blocks and instructions for processing.
2344void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2345 // Check if the Edge was reachable before.
2346 if (ReachableEdges.insert({From, To}).second) {
2347 // If this block wasn't reachable before, all instructions are touched.
2348 if (ReachableBlocks.insert(To).second) {
2349 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2350 const auto &InstRange = BlockInstRange.lookup(To);
2351 TouchedInstructions.set(InstRange.first, InstRange.second);
2352 } else {
2353 DEBUG(dbgs() << "Block " << getBlockName(To)
2354 << " was reachable, but new edge {" << getBlockName(From)
2355 << "," << getBlockName(To) << "} to it found\n");
2356
2357 // We've made an edge reachable to an existing block, which may
2358 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2359 // they are the only thing that depend on new edges. Anything using their
2360 // values will get propagated to if necessary.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002361 if (MemoryAccess *MemPhi = getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002362 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002363
Davide Italiano7e274e02016-12-22 16:03:48 +00002364 auto BI = To->begin();
2365 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002366 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00002367 ++BI;
2368 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00002369 for_each_found(PHIOfOpsPHIs, To, [&](const PHINode *I) {
2370 TouchedInstructions.set(InstrToDFSNum(I));
2371 });
Davide Italiano7e274e02016-12-22 16:03:48 +00002372 }
2373 }
2374}
2375
2376// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2377// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002378Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002379 auto Result = lookupOperandLeader(Cond);
Davide Italianodaa9c0e2017-06-19 16:46:15 +00002380 return isa<Constant>(Result) ? Result : nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002381}
2382
2383// Process the outgoing edges of a block for reachability.
2384void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2385 // Evaluate reachability of terminator instruction.
2386 BranchInst *BR;
2387 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2388 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002389 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002390 if (!CondEvaluated) {
2391 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002392 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002393 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2394 CondEvaluated = CE->getConstantValue();
2395 }
2396 } else if (isa<ConstantInt>(Cond)) {
2397 CondEvaluated = Cond;
2398 }
2399 }
2400 ConstantInt *CI;
2401 BasicBlock *TrueSucc = BR->getSuccessor(0);
2402 BasicBlock *FalseSucc = BR->getSuccessor(1);
2403 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2404 if (CI->isOne()) {
2405 DEBUG(dbgs() << "Condition for Terminator " << *TI
2406 << " evaluated to true\n");
2407 updateReachableEdge(B, TrueSucc);
2408 } else if (CI->isZero()) {
2409 DEBUG(dbgs() << "Condition for Terminator " << *TI
2410 << " evaluated to false\n");
2411 updateReachableEdge(B, FalseSucc);
2412 }
2413 } else {
2414 updateReachableEdge(B, TrueSucc);
2415 updateReachableEdge(B, FalseSucc);
2416 }
2417 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2418 // For switches, propagate the case values into the case
2419 // destinations.
2420
2421 // Remember how many outgoing edges there are to every successor.
2422 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2423
Davide Italiano7e274e02016-12-22 16:03:48 +00002424 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002425 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002426 // See if we were able to turn this switch statement into a constant.
2427 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002428 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002429 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002430 auto Case = *SI->findCaseValue(CondVal);
2431 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002432 // We proved the value is outside of the range of the case.
2433 // We can't do anything other than mark the default dest as reachable,
2434 // and go home.
2435 updateReachableEdge(B, SI->getDefaultDest());
2436 return;
2437 }
2438 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002439 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002440 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002441 } else {
2442 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2443 BasicBlock *TargetBlock = SI->getSuccessor(i);
2444 ++SwitchEdges[TargetBlock];
2445 updateReachableEdge(B, TargetBlock);
2446 }
2447 }
2448 } else {
2449 // Otherwise this is either unconditional, or a type we have no
2450 // idea about. Just mark successors as reachable.
2451 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2452 BasicBlock *TargetBlock = TI->getSuccessor(i);
2453 updateReachableEdge(B, TargetBlock);
2454 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002455
2456 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002457 // equivalent only to itself.
2458 //
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002459 auto *MA = getMemoryAccess(TI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002460 if (MA && !isa<MemoryUse>(MA)) {
2461 auto *CC = ensureLeaderOfMemoryClass(MA);
2462 if (setMemoryClass(MA, CC))
2463 markMemoryUsersTouched(MA);
2464 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002465 }
2466}
2467
Davide Italiano5974c312017-08-03 21:17:49 +00002468// Remove the PHI of Ops PHI for I
2469void NewGVN::removePhiOfOps(Instruction *I, PHINode *PHITemp) {
2470 InstrDFS.erase(PHITemp);
2471 // It's still a temp instruction. We keep it in the array so it gets erased.
2472 // However, it's no longer used by I, or in the block/
2473 PHIOfOpsPHIs[getBlockForValue(PHITemp)].erase(PHITemp);
2474 TempToBlock.erase(PHITemp);
2475 RealToTemp.erase(I);
2476}
2477
2478// Add PHI Op in BB as a PHI of operations version of ExistingValue.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002479void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
2480 Instruction *ExistingValue) {
2481 InstrDFS[Op] = InstrToDFSNum(ExistingValue);
2482 AllTempInstructions.insert(Op);
Davide Italiano5974c312017-08-03 21:17:49 +00002483 PHIOfOpsPHIs[BB].insert(Op);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002484 TempToBlock[Op] = BB;
Daniel Berlinb779db72017-06-29 17:01:10 +00002485 RealToTemp[ExistingValue] = Op;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002486}
2487
2488static bool okayForPHIOfOps(const Instruction *I) {
Chad Rosiera5508e32017-08-10 14:12:57 +00002489 if (!EnablePhiOfOps)
2490 return false;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002491 return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
2492 isa<LoadInst>(I);
2493}
2494
Daniel Berlin94090dd2017-09-02 02:18:44 +00002495// Return true if this operand will be safe to use for phi of ops.
2496//
2497// The reason some operands are unsafe is that we are not trying to recursively
2498// translate everything back through phi nodes. We actually expect some lookups
2499// of expressions to fail. In particular, a lookup where the expression cannot
2500// exist in the predecessor. This is true even if the expression, as shown, can
2501// be determined to be constant.
2502bool NewGVN::OpIsSafeForPHIOfOps(Value *V, Instruction *OrigInst,
2503 const BasicBlock *PHIBlock,
2504 SmallPtrSetImpl<const Value *> &Visited) {
2505 if (!isa<Instruction>(V))
2506 return true;
2507 auto OISIt = OpSafeForPHIOfOps.find(V);
2508 if (OISIt != OpSafeForPHIOfOps.end())
2509 return OISIt->second;
2510 // Keep walking until we either dominate the phi block, or hit a phi, or run
2511 // out of things to check.
2512 if (DT->properlyDominates(getBlockForValue(V), PHIBlock)) {
2513 OpSafeForPHIOfOps.insert({V, true});
2514 return true;
2515 }
2516 // PHI in the same block.
2517 if (isa<PHINode>(V) && getBlockForValue(V) == PHIBlock) {
2518 OpSafeForPHIOfOps.insert({V, false});
2519 return false;
2520 }
2521 for (auto Op : cast<Instruction>(V)->operand_values()) {
2522 if (!isa<Instruction>(Op))
2523 continue;
2524 // See if we already know the answer for this node.
2525 auto OISIt = OpSafeForPHIOfOps.find(Op);
2526 if (OISIt != OpSafeForPHIOfOps.end()) {
2527 if (!OISIt->second) {
2528 OpSafeForPHIOfOps.insert({V, false});
2529 return false;
2530 }
2531 }
2532 if (!Visited.insert(Op).second)
2533 continue;
2534 if (!OpIsSafeForPHIOfOps(Op, OrigInst, PHIBlock, Visited)) {
2535 OpSafeForPHIOfOps.insert({V, false});
2536 return false;
2537 }
2538 }
2539 OpSafeForPHIOfOps.insert({V, true});
2540 return true;
2541}
2542
2543// Try to find a leader for instruction TransInst, which is a phi translated
2544// version of something in our original program. Visited is used to ensure we
2545// don't infinite loop during translations of cycles. OrigInst is the
2546// instruction in the original program, and PredBB is the predecessor we
2547// translated it through.
2548Value *NewGVN::findLeaderForInst(Instruction *TransInst,
2549 SmallPtrSetImpl<Value *> &Visited,
2550 MemoryAccess *MemAccess, Instruction *OrigInst,
2551 BasicBlock *PredBB) {
2552 unsigned IDFSNum = InstrToDFSNum(OrigInst);
2553 // Make sure it's marked as a temporary instruction.
2554 AllTempInstructions.insert(TransInst);
2555 // and make sure anything that tries to add it's DFS number is
2556 // redirected to the instruction we are making a phi of ops
2557 // for.
2558 TempToBlock.insert({TransInst, PredBB});
2559 InstrDFS.insert({TransInst, IDFSNum});
2560
2561 const Expression *E = performSymbolicEvaluation(TransInst, Visited);
2562 InstrDFS.erase(TransInst);
2563 AllTempInstructions.erase(TransInst);
2564 TempToBlock.erase(TransInst);
2565 if (MemAccess)
2566 TempToMemory.erase(TransInst);
2567 if (!E)
2568 return nullptr;
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +00002569 auto *FoundVal = findPHIOfOpsLeader(E, OrigInst, PredBB);
2570 if (!FoundVal) {
Daniel Berlin94090dd2017-09-02 02:18:44 +00002571 ExpressionToPhiOfOps[E].insert(OrigInst);
2572 DEBUG(dbgs() << "Cannot find phi of ops operand for " << *TransInst
2573 << " in block " << getBlockName(PredBB) << "\n");
2574 return nullptr;
2575 }
2576 if (auto *SI = dyn_cast<StoreInst>(FoundVal))
2577 FoundVal = SI->getValueOperand();
2578 return FoundVal;
2579}
2580
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002581// When we see an instruction that is an op of phis, generate the equivalent phi
2582// of ops form.
2583const Expression *
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002584NewGVN::makePossiblePhiOfOps(Instruction *I,
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002585 SmallPtrSetImpl<Value *> &Visited) {
2586 if (!okayForPHIOfOps(I))
2587 return nullptr;
2588
2589 if (!Visited.insert(I).second)
2590 return nullptr;
2591 // For now, we require the instruction be cycle free because we don't
2592 // *always* create a phi of ops for instructions that could be done as phi
2593 // of ops, we only do it if we think it is useful. If we did do it all the
2594 // time, we could remove the cycle free check.
2595 if (!isCycleFree(I))
2596 return nullptr;
2597
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002598 SmallPtrSet<const Value *, 8> ProcessedPHIs;
2599 // TODO: We don't do phi translation on memory accesses because it's
2600 // complicated. For a load, we'd need to be able to simulate a new memoryuse,
2601 // which we don't have a good way of doing ATM.
2602 auto *MemAccess = getMemoryAccess(I);
2603 // If the memory operation is defined by a memory operation this block that
2604 // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
2605 // can't help, as it would still be killed by that memory operation.
2606 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2607 MemAccess->getDefiningAccess()->getBlock() == I->getParent())
2608 return nullptr;
2609
Daniel Berlin94090dd2017-09-02 02:18:44 +00002610 SmallPtrSet<const Value *, 10> VisitedOps;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002611 // Convert op of phis to phi of ops
2612 for (auto &Op : I->operands()) {
2613 if (!isa<PHINode>(Op))
2614 continue;
2615 auto *OpPHI = cast<PHINode>(Op);
2616 // No point in doing this for one-operand phis.
2617 if (OpPHI->getNumOperands() == 1)
2618 continue;
2619 if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
2620 return nullptr;
2621 SmallVector<std::pair<Value *, BasicBlock *>, 4> Ops;
2622 auto *PHIBlock = getBlockForValue(OpPHI);
2623 for (auto PredBB : OpPHI->blocks()) {
2624 Value *FoundVal = nullptr;
2625 // We could just skip unreachable edges entirely but it's tricky to do
2626 // with rewriting existing phi nodes.
2627 if (ReachableEdges.count({PredBB, PHIBlock})) {
2628 // Clone the instruction, create an expression from it, and see if we
2629 // have a leader.
2630 Instruction *ValueOp = I->clone();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002631 if (MemAccess)
Daniel Berlinc8ed4042017-05-30 06:42:29 +00002632 TempToMemory.insert({ValueOp, MemAccess});
Daniel Berlin94090dd2017-09-02 02:18:44 +00002633 bool SafeForPHIOfOps = true;
2634 VisitedOps.clear();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002635 for (auto &Op : ValueOp->operands()) {
Daniel Berlin94090dd2017-09-02 02:18:44 +00002636 auto *OrigOp = &*Op;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002637 Op = Op->DoPHITranslation(PHIBlock, PredBB);
2638 // When this operand changes, it could change whether there is a
2639 // leader for us or not.
2640 addAdditionalUsers(Op, I);
Daniel Berlin94090dd2017-09-02 02:18:44 +00002641 // If we phi-translated the op, it must be safe.
2642 SafeForPHIOfOps = SafeForPHIOfOps &&
2643 (Op != OrigOp ||
2644 OpIsSafeForPHIOfOps(Op, I, PHIBlock, VisitedOps));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002645 }
Daniel Berlin94090dd2017-09-02 02:18:44 +00002646 // FIXME: For those things that are not safe We could generate
2647 // expressions all the way down, and see if this comes out to a
2648 // constant. For anything where that is true, and unsafe, we should
2649 // have made a phi-of-ops (or value numbered it equivalent to something)
2650 // for the pieces already.
2651 FoundVal = !SafeForPHIOfOps ? nullptr
2652 : findLeaderForInst(ValueOp, Visited,
2653 MemAccess, I, PredBB);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002654 ValueOp->deleteValue();
Daniel Berlin94090dd2017-09-02 02:18:44 +00002655 if (!FoundVal)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002656 return nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002657 } else {
2658 DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
2659 << getBlockName(PredBB)
2660 << " because the block is unreachable\n");
2661 FoundVal = UndefValue::get(I->getType());
2662 }
2663
2664 Ops.push_back({FoundVal, PredBB});
2665 DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
2666 << getBlockName(PredBB) << "\n");
2667 }
2668 auto *ValuePHI = RealToTemp.lookup(I);
2669 bool NewPHI = false;
2670 if (!ValuePHI) {
Daniel Berlin94090dd2017-09-02 02:18:44 +00002671 ValuePHI =
2672 PHINode::Create(I->getType(), OpPHI->getNumOperands(), "phiofops");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002673 addPhiOfOps(ValuePHI, PHIBlock, I);
2674 NewPHI = true;
2675 NumGVNPHIOfOpsCreated++;
2676 }
2677 if (NewPHI) {
2678 for (auto PHIOp : Ops)
2679 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2680 } else {
2681 unsigned int i = 0;
2682 for (auto PHIOp : Ops) {
2683 ValuePHI->setIncomingValue(i, PHIOp.first);
2684 ValuePHI->setIncomingBlock(i, PHIOp.second);
2685 ++i;
2686 }
2687 }
2688
2689 DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
2690 << "\n");
2691 return performSymbolicEvaluation(ValuePHI, Visited);
2692 }
2693 return nullptr;
2694}
2695
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002696// The algorithm initially places the values of the routine in the TOP
2697// congruence class. The leader of TOP is the undetermined value `undef`.
2698// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002699void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002700 NextCongruenceNum = 0;
2701
2702 // Note that even though we use the live on entry def as a representative
2703 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2704 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2705 // should be checking whether the MemoryAccess is top if we want to know if it
2706 // is equivalent to everything. Otherwise, what this really signifies is that
2707 // the access "it reaches all the way back to the beginning of the function"
2708
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002709 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002710 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002711 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002712 // The live on entry def gets put into it's own class
2713 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2714 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002715
Daniel Berlinec9deb72017-04-18 17:06:11 +00002716 for (auto DTN : nodes(DT)) {
2717 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002718 // All MemoryAccesses are equivalent to live on entry to start. They must
2719 // be initialized to something so that initial changes are noticed. For
2720 // the maximal answer, we initialize them all to be the same as
2721 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002722 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002723 if (MemoryBlockDefs)
2724 for (const auto &Def : *MemoryBlockDefs) {
2725 MemoryAccessToClass[&Def] = TOPClass;
2726 auto *MD = dyn_cast<MemoryDef>(&Def);
2727 // Insert the memory phis into the member list.
2728 if (!MD) {
2729 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002730 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002731 MemoryPhiState.insert({MP, MPS_TOP});
2732 }
2733
2734 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002735 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002736 }
Daniel Berlinec9deb72017-04-18 17:06:11 +00002737 for (auto &I : *BB) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002738 // TODO: Move to helper
2739 if (isa<PHINode>(&I))
2740 for (auto *U : I.users())
2741 if (auto *UInst = dyn_cast<Instruction>(U))
2742 if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
2743 PHINodeUses.insert(UInst);
Daniel Berlin22a4a012017-02-11 15:20:15 +00002744 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002745 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002746 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2747 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002748 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002749 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002750 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002751 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002752
2753 // Initialize arguments to be in their own unique congruence classes
2754 for (auto &FA : F.args())
2755 createSingletonCongruenceClass(&FA);
2756}
2757
2758void NewGVN::cleanupTables() {
2759 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Daniel Berlina8236562017-04-07 18:38:09 +00002760 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2761 << " has " << CongruenceClasses[i]->size() << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002762 // Make sure we delete the congruence class (probably worth switching to
2763 // a unique_ptr at some point.
2764 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002765 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002766 }
2767
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002768 // Destroy the value expressions
2769 SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
2770 AllTempInstructions.end());
2771 AllTempInstructions.clear();
2772
2773 // We have to drop all references for everything first, so there are no uses
2774 // left as we delete them.
2775 for (auto *I : TempInst) {
2776 I->dropAllReferences();
2777 }
2778
2779 while (!TempInst.empty()) {
2780 auto *I = TempInst.back();
2781 TempInst.pop_back();
2782 I->deleteValue();
2783 }
2784
Davide Italiano7e274e02016-12-22 16:03:48 +00002785 ValueToClass.clear();
2786 ArgRecycler.clear(ExpressionAllocator);
2787 ExpressionAllocator.Reset();
2788 CongruenceClasses.clear();
2789 ExpressionToClass.clear();
2790 ValueToExpression.clear();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002791 RealToTemp.clear();
2792 AdditionalUsers.clear();
2793 ExpressionToPhiOfOps.clear();
2794 TempToBlock.clear();
2795 TempToMemory.clear();
2796 PHIOfOpsPHIs.clear();
Daniel Berlin94090dd2017-09-02 02:18:44 +00002797 PHINodeUses.clear();
2798 OpSafeForPHIOfOps.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002799 ReachableBlocks.clear();
2800 ReachableEdges.clear();
2801#ifndef NDEBUG
2802 ProcessedCount.clear();
2803#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002804 InstrDFS.clear();
2805 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002806 DFSToInstr.clear();
2807 BlockInstRange.clear();
2808 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002809 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002810 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002811 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002812}
2813
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002814// Assign local DFS number mapping to instructions, and leave space for Value
2815// PHI's.
Davide Italiano7e274e02016-12-22 16:03:48 +00002816std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2817 unsigned Start) {
2818 unsigned End = Start;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002819 if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002820 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002821 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002822 }
2823
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002824 // Then the real block goes next.
Davide Italiano7e274e02016-12-22 16:03:48 +00002825 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002826 // There's no need to call isInstructionTriviallyDead more than once on
2827 // an instruction. Therefore, once we know that an instruction is dead
2828 // we change its DFS number so that it doesn't get value numbered.
2829 if (isInstructionTriviallyDead(&I, TLI)) {
2830 InstrDFS[&I] = 0;
2831 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2832 markInstructionForDeletion(&I);
2833 continue;
2834 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002835 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002836 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002837 }
2838
2839 // All of the range functions taken half-open ranges (open on the end side).
2840 // So we do not subtract one from count, because at this point it is one
2841 // greater than the last instruction.
2842 return std::make_pair(Start, End);
2843}
2844
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002845void NewGVN::updateProcessedCount(const Value *V) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002846#ifndef NDEBUG
2847 if (ProcessedCount.count(V) == 0) {
2848 ProcessedCount.insert({V, 1});
2849 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002850 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002851 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002852 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002853 }
2854#endif
2855}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002856// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2857void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2858 // If all the arguments are the same, the MemoryPhi has the same value as the
Daniel Berlind130b6c2017-05-21 23:41:58 +00002859 // argument. Filter out unreachable blocks and self phis from our operands.
2860 // TODO: We could do cycle-checking on the memory phis to allow valueizing for
2861 // self-phi checking.
Daniel Berlin41b39162017-03-18 15:41:36 +00002862 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002863 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlind130b6c2017-05-21 23:41:58 +00002864 return cast<MemoryAccess>(U) != MP &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002865 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002866 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002867 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002868 // If all that is left is nothing, our memoryphi is undef. We keep it as
2869 // InitialClass. Note: The only case this should happen is if we have at
2870 // least one self-argument.
2871 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002872 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002873 markMemoryUsersTouched(MP);
2874 return;
2875 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002876
2877 // Transform the remaining operands into operand leaders.
2878 // FIXME: mapped_iterator should have a range version.
2879 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002880 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002881 };
2882 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2883 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2884
2885 // and now check if all the elements are equal.
2886 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002887 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002888 ++MappedBegin;
2889 bool AllEqual = std::all_of(
2890 MappedBegin, MappedEnd,
2891 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2892
2893 if (AllEqual)
2894 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2895 else
2896 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002897 // If it's equal to something, it's in that class. Otherwise, it has to be in
2898 // a class where it is the leader (other things may be equivalent to it, but
2899 // it needs to start off in its own class, which means it must have been the
2900 // leader, and it can't have stopped being the leader because it was never
2901 // removed).
2902 CongruenceClass *CC =
2903 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2904 auto OldState = MemoryPhiState.lookup(MP);
2905 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2906 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2907 MemoryPhiState[MP] = NewState;
2908 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002909 markMemoryUsersTouched(MP);
2910}
2911
2912// Value number a single instruction, symbolically evaluating, performing
2913// congruence finding, and updating mappings.
2914void NewGVN::valueNumberInstruction(Instruction *I) {
2915 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002916 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002917 const Expression *Symbolized = nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002918 SmallPtrSet<Value *, 2> Visited;
Daniel Berlin283a6082017-03-01 19:59:26 +00002919 if (DebugCounter::shouldExecute(VNCounter)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002920 Symbolized = performSymbolicEvaluation(I, Visited);
2921 // Make a phi of ops if necessary
2922 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
2923 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002924 auto *PHIE = makePossiblePhiOfOps(I, Visited);
Davide Italiano5974c312017-08-03 21:17:49 +00002925 // If we created a phi of ops, use it.
2926 // If we couldn't create one, make sure we don't leave one lying around
2927 if (PHIE) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002928 Symbolized = PHIE;
Davide Italiano5974c312017-08-03 21:17:49 +00002929 } else if (auto *Op = RealToTemp.lookup(I)) {
2930 removePhiOfOps(I, Op);
2931 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002932 }
2933
Daniel Berlin283a6082017-03-01 19:59:26 +00002934 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002935 // Mark the instruction as unused so we don't value number it again.
2936 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002937 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002938 // If we couldn't come up with a symbolic expression, use the unknown
2939 // expression
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002940 if (Symbolized == nullptr)
Daniel Berlin02c6b172017-01-02 18:00:53 +00002941 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002942 performCongruenceFinding(I, Symbolized);
2943 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002944 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002945 // don't currently understand. We don't place non-value producing
2946 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002947 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002948 auto *Symbolized = createUnknownExpression(I);
2949 performCongruenceFinding(I, Symbolized);
2950 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002951 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2952 }
2953}
Davide Italiano7e274e02016-12-22 16:03:48 +00002954
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002955// Check if there is a path, using single or equal argument phi nodes, from
2956// First to Second.
Davide Italianoeab0de22017-05-18 23:22:44 +00002957bool NewGVN::singleReachablePHIPath(
2958 SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
2959 const MemoryAccess *Second) const {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002960 if (First == Second)
2961 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002962 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002963 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002964
Davide Italianoeab0de22017-05-18 23:22:44 +00002965 // This is not perfect, but as we're just verifying here, we can live with
2966 // the loss of precision. The real solution would be that of doing strongly
2967 // connected component finding in this routine, and it's probably not worth
2968 // the complexity for the time being. So, we just keep a set of visited
2969 // MemoryAccess and return true when we hit a cycle.
2970 if (Visited.count(First))
2971 return true;
2972 Visited.insert(First);
2973
Daniel Berlin871ecd92017-04-01 09:44:24 +00002974 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002975 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002976 if (ChainDef == Second)
2977 return true;
2978 if (MSSA->isLiveOnEntryDef(ChainDef))
2979 return false;
2980 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002981 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002982 auto *MP = cast<MemoryPhi>(EndDef);
2983 auto ReachableOperandPred = [&](const Use &U) {
2984 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2985 };
2986 auto FilteredPhiArgs =
2987 make_filter_range(MP->operands(), ReachableOperandPred);
2988 SmallVector<const Value *, 32> OperandList;
2989 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2990 std::back_inserter(OperandList));
2991 bool Okay = OperandList.size() == 1;
2992 if (!Okay)
2993 Okay =
2994 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2995 if (Okay)
Davide Italianoeab0de22017-05-18 23:22:44 +00002996 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
2997 Second);
Daniel Berlin871ecd92017-04-01 09:44:24 +00002998 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002999}
3000
Daniel Berlin589cecc2017-01-02 18:00:46 +00003001// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003002// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00003003// subject to very rare false negatives. It is only useful for
3004// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00003005void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00003006#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00003007 // Verify that the memory table equivalence and memory member set match
3008 for (const auto *CC : CongruenceClasses) {
3009 if (CC == TOPClass || CC->isDead())
3010 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00003011 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00003012 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00003013 "Any class with a store as a leader should have a "
3014 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00003015 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00003016 "Any congruence class with a store should have a "
3017 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00003018 }
3019
Daniel Berlina8236562017-04-07 18:38:09 +00003020 if (CC->getMemoryLeader())
3021 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00003022 "Representative MemoryAccess does not appear to be reverse "
3023 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00003024 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00003025 assert(MemoryAccessToClass.lookup(M) == CC &&
3026 "Memory member does not appear to be reverse mapped properly");
3027 }
3028
3029 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00003030 // congruence class.
3031
3032 // Filter out the unreachable and trivially dead entries, because they may
3033 // never have been updated if the instructions were not processed.
3034 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00003035 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00003036 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00003037 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
3038 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00003039 return false;
3040 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
3041 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Davide Italiano6e7a2122017-05-15 18:50:53 +00003042
3043 // We could have phi nodes which operands are all trivially dead,
3044 // so we don't process them.
3045 if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
3046 for (auto &U : MemPHI->incoming_values()) {
3047 if (Instruction *I = dyn_cast<Instruction>(U.get())) {
3048 if (!isInstructionTriviallyDead(I))
3049 return true;
3050 }
3051 }
3052 return false;
3053 }
3054
Daniel Berlin589cecc2017-01-02 18:00:46 +00003055 return true;
3056 };
3057
Daniel Berlin1ea5f322017-01-26 22:21:48 +00003058 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00003059 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00003060 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00003061 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italianoeab0de22017-05-18 23:22:44 +00003062 if (FirstMUD && SecondMUD) {
3063 SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
3064 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00003065 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
3066 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
3067 "The instructions for these memory operations should have "
3068 "been in the same congruence class or reachable through"
3069 "a single argument phi");
Davide Italianoeab0de22017-05-18 23:22:44 +00003070 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00003071 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00003072 // We can only sanely verify that MemoryDefs in the operand list all have
3073 // the same class.
3074 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00003075 return ReachableEdges.count(
3076 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00003077 isa<MemoryDef>(U);
3078
3079 };
3080 // All arguments should in the same class, ignoring unreachable arguments
3081 auto FilteredPhiArgs =
3082 make_filter_range(FirstMP->operands(), ReachableOperandPred);
3083 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
3084 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
3085 std::back_inserter(PhiOpClasses), [&](const Use &U) {
3086 const MemoryDef *MD = cast<MemoryDef>(U);
3087 return ValueToClass.lookup(MD->getMemoryInst());
3088 });
3089 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
3090 PhiOpClasses.begin()) &&
3091 "All MemoryPhi arguments should be in the same class");
3092 }
3093 }
Davide Italianoe9781e72017-03-25 02:40:02 +00003094#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00003095}
3096
Daniel Berlin06329a92017-03-18 15:41:40 +00003097// Verify that the sparse propagation we did actually found the maximal fixpoint
3098// We do this by storing the value to class mapping, touching all instructions,
3099// and redoing the iteration to see if anything changed.
3100void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00003101#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00003102 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00003103 if (DebugCounter::isCounterSet(VNCounter))
3104 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
3105
3106 // Note that we have to store the actual classes, as we may change existing
3107 // classes during iteration. This is because our memory iteration propagation
3108 // is not perfect, and so may waste a little work. But it should generate
3109 // exactly the same congruence classes we have now, with different IDs.
3110 std::map<const Value *, CongruenceClass> BeforeIteration;
3111
3112 for (auto &KV : ValueToClass) {
3113 if (auto *I = dyn_cast<Instruction>(KV.first))
3114 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003115 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00003116 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00003117 BeforeIteration.insert({KV.first, *KV.second});
3118 }
3119
3120 TouchedInstructions.set();
3121 TouchedInstructions.reset(0);
3122 iterateTouchedInstructions();
3123 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
3124 EqualClasses;
3125 for (const auto &KV : ValueToClass) {
3126 if (auto *I = dyn_cast<Instruction>(KV.first))
3127 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003128 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00003129 continue;
3130 // We could sink these uses, but i think this adds a bit of clarity here as
3131 // to what we are comparing.
3132 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
3133 auto *AfterCC = KV.second;
3134 // Note that the classes can't change at this point, so we memoize the set
3135 // that are equal.
3136 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00003137 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00003138 "Value number changed after main loop completed!");
3139 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00003140 }
3141 }
3142#endif
3143}
3144
Daniel Berlin45403572017-05-16 19:58:47 +00003145// Verify that for each store expression in the expression to class mapping,
3146// only the latest appears, and multiple ones do not appear.
3147// Because loads do not use the stored value when doing equality with stores,
3148// if we don't erase the old store expressions from the table, a load can find
3149// a no-longer valid StoreExpression.
3150void NewGVN::verifyStoreExpressions() const {
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003151#ifndef NDEBUG
Daniel Berlin36b08b22017-06-19 00:24:00 +00003152 // This is the only use of this, and it's not worth defining a complicated
3153 // densemapinfo hash/equality function for it.
3154 std::set<
3155 std::pair<const Value *,
3156 std::tuple<const Value *, const CongruenceClass *, Value *>>>
3157 StoreExpressionSet;
Daniel Berlin45403572017-05-16 19:58:47 +00003158 for (const auto &KV : ExpressionToClass) {
3159 if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3160 // Make sure a version that will conflict with loads is not already there
Daniel Berlin36b08b22017-06-19 00:24:00 +00003161 auto Res = StoreExpressionSet.insert(
3162 {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
3163 SE->getStoredValue())});
3164 bool Okay = Res.second;
3165 // It's okay to have the same expression already in there if it is
3166 // identical in nature.
3167 // This can happen when the leader of the stored value changes over time.
Davide Italiano0ec715b2017-06-20 22:57:40 +00003168 if (!Okay)
3169 Okay = (std::get<1>(Res.first->second) == KV.second) &&
3170 (lookupOperandLeader(std::get<2>(Res.first->second)) ==
3171 lookupOperandLeader(SE->getStoredValue()));
Daniel Berlin36b08b22017-06-19 00:24:00 +00003172 assert(Okay && "Stored expression conflict exists in expression table");
Daniel Berlin45403572017-05-16 19:58:47 +00003173 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3174 assert(ValueExpr && ValueExpr->equals(*SE) &&
3175 "StoreExpression in ExpressionToClass is not latest "
3176 "StoreExpression for value");
3177 }
3178 }
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003179#endif
Daniel Berlin45403572017-05-16 19:58:47 +00003180}
3181
Daniel Berlin06329a92017-03-18 15:41:40 +00003182// This is the main value numbering loop, it iterates over the initial touched
3183// instruction set, propagating value numbers, marking things touched, etc,
3184// until the set of touched instructions is completely empty.
3185void NewGVN::iterateTouchedInstructions() {
3186 unsigned int Iterations = 0;
3187 // Figure out where touchedinstructions starts
3188 int FirstInstr = TouchedInstructions.find_first();
3189 // Nothing set, nothing to iterate, just return.
3190 if (FirstInstr == -1)
3191 return;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003192 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00003193 while (TouchedInstructions.any()) {
3194 ++Iterations;
3195 // Walk through all the instructions in all the blocks in RPO.
3196 // TODO: As we hit a new block, we should push and pop equalities into a
3197 // table lookupOperandLeader can use, to catch things PredicateInfo
3198 // might miss, like edge-only equivalences.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003199 for (unsigned InstrNum : TouchedInstructions.set_bits()) {
Daniel Berlin06329a92017-03-18 15:41:40 +00003200
3201 // This instruction was found to be dead. We don't bother looking
3202 // at it again.
3203 if (InstrNum == 0) {
3204 TouchedInstructions.reset(InstrNum);
3205 continue;
3206 }
3207
Daniel Berlin21279bd2017-04-06 18:52:58 +00003208 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003209 const BasicBlock *CurrBlock = getBlockForValue(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003210
3211 // If we hit a new block, do reachability processing.
3212 if (CurrBlock != LastBlock) {
3213 LastBlock = CurrBlock;
3214 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3215 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3216
3217 // If it's not reachable, erase any touched instructions and move on.
3218 if (!BlockReachable) {
3219 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3220 DEBUG(dbgs() << "Skipping instructions in block "
3221 << getBlockName(CurrBlock)
3222 << " because it is unreachable\n");
3223 continue;
3224 }
3225 updateProcessedCount(CurrBlock);
3226 }
Daniel Berlineafdd862017-06-06 17:15:28 +00003227 // Reset after processing (because we may mark ourselves as touched when
3228 // we propagate equalities).
3229 TouchedInstructions.reset(InstrNum);
Daniel Berlin06329a92017-03-18 15:41:40 +00003230
3231 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
3232 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
3233 valueNumberMemoryPhi(MP);
3234 } else if (auto *I = dyn_cast<Instruction>(V)) {
3235 valueNumberInstruction(I);
3236 } else {
3237 llvm_unreachable("Should have been a MemoryPhi or Instruction");
3238 }
3239 updateProcessedCount(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003240 }
3241 }
3242 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
3243}
3244
Daniel Berlin85f91b02016-12-26 20:06:58 +00003245// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00003246bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00003247 if (DebugCounter::isCounterSet(VNCounter))
3248 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00003249 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00003250 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00003251 MSSAWalker = MSSA->getWalker();
Daniel Berline021d2d2017-05-19 20:22:20 +00003252 SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00003253
3254 // Count number of instructions for sizing of hash tables, and come
3255 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003256 unsigned ICount = 1;
3257 // Add an empty instruction to account for the fact that we start at 1
3258 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00003259 // Note: We want ideal RPO traversal of the blocks, which is not quite the
3260 // same as dominator tree order, particularly with regard whether backedges
3261 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00003262 // If we visit in the wrong order, we will end up performing N times as many
3263 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00003264 // The dominator tree does guarantee that, for a given dom tree node, it's
3265 // parent must occur before it in the RPO ordering. Thus, we only need to sort
3266 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00003267 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00003268 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00003269 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003270 auto *Node = DT->getNode(B);
3271 assert(Node && "RPO and Dominator tree should have same reachability");
3272 RPOOrdering[Node] = ++Counter;
3273 }
3274 // Sort dominator tree children arrays into RPO.
3275 for (auto &B : RPOT) {
3276 auto *Node = DT->getNode(B);
3277 if (Node->getChildren().size() > 1)
3278 std::sort(Node->begin(), Node->end(),
Daniel Berlin2f72b192017-04-14 02:53:37 +00003279 [&](const DomTreeNode *A, const DomTreeNode *B) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003280 return RPOOrdering[A] < RPOOrdering[B];
3281 });
3282 }
3283
3284 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00003285 for (auto DTN : depth_first(DT->getRootNode())) {
3286 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00003287 const auto &BlockRange = assignDFSNumbers(B, ICount);
3288 BlockInstRange.insert({B, BlockRange});
3289 ICount += BlockRange.second - BlockRange.first;
3290 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003291 initializeCongruenceClasses(F);
Davide Italiano7e274e02016-12-22 16:03:48 +00003292
Daniel Berline0bd37e2016-12-29 22:15:12 +00003293 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003294 // Ensure we don't end up resizing the expressionToClass map, as
3295 // that can be quite expensive. At most, we have one expression per
3296 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003297 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003298
3299 // Initialize the touched instructions to include the entry block.
3300 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
3301 TouchedInstructions.set(InstRange.first, InstRange.second);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003302 DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
3303 << " marked reachable\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003304 ReachableBlocks.insert(&F.getEntryBlock());
3305
Daniel Berlin06329a92017-03-18 15:41:40 +00003306 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00003307 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00003308 verifyIterationSettled(F);
Daniel Berlin45403572017-05-16 19:58:47 +00003309 verifyStoreExpressions();
Daniel Berlinf7d95802017-02-18 23:06:50 +00003310
Davide Italiano7e274e02016-12-22 16:03:48 +00003311 Changed |= eliminateInstructions(F);
3312
3313 // Delete all instructions marked for deletion.
3314 for (Instruction *ToErase : InstructionsToErase) {
3315 if (!ToErase->use_empty())
3316 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
3317
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003318 if (ToErase->getParent())
3319 ToErase->eraseFromParent();
Davide Italiano7e274e02016-12-22 16:03:48 +00003320 }
3321
3322 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003323 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
3324 return !ReachableBlocks.count(&BB);
3325 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003326
3327 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
3328 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00003329 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003330 deleteInstructionsInBlock(&BB);
3331 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003332 }
3333
3334 cleanupTables();
3335 return Changed;
3336}
3337
Davide Italiano7e274e02016-12-22 16:03:48 +00003338struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003339 int DFSIn = 0;
3340 int DFSOut = 0;
3341 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003342 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003343 // The bool in the Def tells us whether the Def is the stored value of a
3344 // store.
3345 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003346 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00003347 bool operator<(const ValueDFS &Other) const {
3348 // It's not enough that any given field be less than - we have sets
3349 // of fields that need to be evaluated together to give a proper ordering.
3350 // For example, if you have;
3351 // DFS (1, 3)
3352 // Val 0
3353 // DFS (1, 2)
3354 // Val 50
3355 // We want the second to be less than the first, but if we just go field
3356 // by field, we will get to Val 0 < Val 50 and say the first is less than
3357 // the second. We only want it to be less than if the DFS orders are equal.
3358 //
3359 // Each LLVM instruction only produces one value, and thus the lowest-level
3360 // differentiator that really matters for the stack (and what we use as as a
3361 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003362 // Everything else in the structure is instruction level, and only affects
3363 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00003364 //
3365 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
3366 // the order of replacement of uses does not matter.
3367 // IE given,
3368 // a = 5
3369 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00003370 // When you hit b, you will have two valuedfs with the same dfsin, out, and
3371 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00003372 // The .val will be the same as well.
3373 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003374 // You will replace both, and it does not matter what order you replace them
3375 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
3376 // operand 2).
3377 // Similarly for the case of same dfsin, dfsout, localnum, but different
3378 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00003379 // a = 5
3380 // b = 6
3381 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00003382 // in c, we will a valuedfs for a, and one for b,with everything the same
3383 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00003384 // It does not matter what order we replace these operands in.
3385 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003386 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3387 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00003388 Other.U);
3389 }
3390};
3391
Daniel Berlinc4796862017-01-27 02:37:11 +00003392// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003393// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00003394// reachable uses for each value is stored in UseCount, and instructions that
3395// seem
3396// dead (have no non-dead uses) are stored in ProbablyDead.
3397void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00003398 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00003399 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00003400 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00003401 for (auto D : Dense) {
3402 // First add the value.
3403 BasicBlock *BB = getBlockForValue(D);
3404 // Constants are handled prior to ever calling this function, so
3405 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00003406 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003407 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003408 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003409 VDDef.DFSIn = DomNode->getDFSNumIn();
3410 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003411 // If it's a store, use the leader of the value operand, if it's always
3412 // available, or the value operand. TODO: We could do dominance checks to
3413 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00003414 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00003415 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003416 if (alwaysAvailable(Leader)) {
3417 VDDef.Def.setPointer(Leader);
3418 } else {
3419 VDDef.Def.setPointer(SI->getValueOperand());
3420 VDDef.Def.setInt(true);
3421 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003422 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003423 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00003424 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003425 assert(isa<Instruction>(D) &&
3426 "The dense set member should always be an instruction");
Daniel Berline3e69e12017-03-10 00:32:33 +00003427 Instruction *Def = cast<Instruction>(D);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003428 VDDef.LocalNum = InstrToDFSNum(D);
3429 DFSOrderedSet.push_back(VDDef);
3430 // If there is a phi node equivalent, add it
3431 if (auto *PN = RealToTemp.lookup(Def)) {
3432 auto *PHIE =
3433 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3434 if (PHIE) {
3435 VDDef.Def.setInt(false);
3436 VDDef.Def.setPointer(PN);
3437 VDDef.LocalNum = 0;
3438 DFSOrderedSet.push_back(VDDef);
3439 }
3440 }
3441
Daniel Berline3e69e12017-03-10 00:32:33 +00003442 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003443 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00003444 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003445 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003446 // Don't try to replace into dead uses
3447 if (InstructionsToErase.count(I))
3448 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003449 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00003450 // Put the phi node uses in the incoming block.
3451 BasicBlock *IBlock;
3452 if (auto *P = dyn_cast<PHINode>(I)) {
3453 IBlock = P->getIncomingBlock(U);
3454 // Make phi node users appear last in the incoming block
3455 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003456 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00003457 } else {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003458 IBlock = getBlockForValue(I);
Daniel Berlin21279bd2017-04-06 18:52:58 +00003459 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003460 }
Davide Italianoccbbc832017-01-26 00:42:42 +00003461
3462 // Skip uses in unreachable blocks, as we're going
3463 // to delete them.
3464 if (ReachableBlocks.count(IBlock) == 0)
3465 continue;
3466
Daniel Berlinb66164c2017-01-14 00:24:23 +00003467 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003468 VDUse.DFSIn = DomNode->getDFSNumIn();
3469 VDUse.DFSOut = DomNode->getDFSNumOut();
3470 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00003471 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003472 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00003473 }
3474 }
Daniel Berline3e69e12017-03-10 00:32:33 +00003475
3476 // If there are no uses, it's probably dead (but it may have side-effects,
3477 // so not definitely dead. Otherwise, store the number of uses so we can
3478 // track if it becomes dead later).
3479 if (UseCount == 0)
3480 ProbablyDead.insert(Def);
3481 else
3482 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003483 }
3484}
3485
Daniel Berlinc4796862017-01-27 02:37:11 +00003486// This function converts the set of members for a congruence class from values,
3487// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00003488void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00003489 const CongruenceClass &Dense,
3490 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00003491 for (auto D : Dense) {
3492 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
3493 continue;
3494
3495 BasicBlock *BB = getBlockForValue(D);
3496 ValueDFS VD;
3497 DomTreeNode *DomNode = DT->getNode(BB);
3498 VD.DFSIn = DomNode->getDFSNumIn();
3499 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003500 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00003501
3502 // If it's an instruction, use the real local dfs number.
3503 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00003504 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00003505 else
3506 llvm_unreachable("Should have been an instruction");
3507
3508 LoadsAndStores.emplace_back(VD);
3509 }
3510}
3511
Davide Italiano7e274e02016-12-22 16:03:48 +00003512static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00003513 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00003514 if (!ReplInst)
3515 return;
3516
Davide Italiano7e274e02016-12-22 16:03:48 +00003517 // Patch the replacement so that it is not more restrictive than the value
3518 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00003519 // Note that if 'I' is a load being replaced by some operation,
3520 // for example, by an arithmetic operation, then andIRFlags()
3521 // would just erase all math flags from the original arithmetic
3522 // operation, which is clearly not wanted and not needed.
3523 if (!isa<LoadInst>(I))
3524 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003525
Daniel Berlin86eab152017-02-12 22:25:20 +00003526 // FIXME: If both the original and replacement value are part of the
3527 // same control-flow region (meaning that the execution of one
3528 // guarantees the execution of the other), then we can combine the
3529 // noalias scopes here and do better than the general conservative
3530 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00003531
Daniel Berlin86eab152017-02-12 22:25:20 +00003532 // In general, GVN unifies expressions over different control-flow
3533 // regions, and so we need a conservative combination of the noalias
3534 // scopes.
3535 static const unsigned KnownIDs[] = {
3536 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
3537 LLVMContext::MD_noalias, LLVMContext::MD_range,
3538 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
3539 LLVMContext::MD_invariant_group};
3540 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00003541}
3542
3543static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3544 patchReplacementInstruction(I, Repl);
3545 I->replaceAllUsesWith(Repl);
3546}
3547
3548void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
3549 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
3550 ++NumGVNBlocksDeleted;
3551
Daniel Berline19f0e02017-01-30 17:06:55 +00003552 // Delete the instructions backwards, as it has a reduced likelihood of having
3553 // to update as many def-use and use-def chains. Start after the terminator.
3554 auto StartPoint = BB->rbegin();
3555 ++StartPoint;
3556 // Note that we explicitly recalculate BB->rend() on each iteration,
3557 // as it may change when we remove the first instruction.
3558 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3559 Instruction &Inst = *I++;
3560 if (!Inst.use_empty())
3561 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3562 if (isa<LandingPadInst>(Inst))
3563 continue;
3564
3565 Inst.eraseFromParent();
3566 ++NumGVNInstrDeleted;
3567 }
Daniel Berlina53a7222017-01-30 18:12:56 +00003568 // Now insert something that simplifycfg will turn into an unreachable.
3569 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3570 new StoreInst(UndefValue::get(Int8Ty),
3571 Constant::getNullValue(Int8Ty->getPointerTo()),
3572 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00003573}
3574
3575void NewGVN::markInstructionForDeletion(Instruction *I) {
3576 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3577 InstructionsToErase.insert(I);
3578}
3579
3580void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3581
3582 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3583 patchAndReplaceAllUsesWith(I, V);
3584 // We save the actual erasing to avoid invalidating memory
3585 // dependencies until we are done with everything.
3586 markInstructionForDeletion(I);
3587}
3588
3589namespace {
3590
3591// This is a stack that contains both the value and dfs info of where
3592// that value is valid.
3593class ValueDFSStack {
3594public:
3595 Value *back() const { return ValueStack.back(); }
3596 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3597
3598 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003599 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003600 DFSStack.emplace_back(DFSIn, DFSOut);
3601 }
3602 bool empty() const { return DFSStack.empty(); }
3603 bool isInScope(int DFSIn, int DFSOut) const {
3604 if (empty())
3605 return false;
3606 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3607 }
3608
3609 void popUntilDFSScope(int DFSIn, int DFSOut) {
3610
3611 // These two should always be in sync at this point.
3612 assert(ValueStack.size() == DFSStack.size() &&
3613 "Mismatch between ValueStack and DFSStack");
3614 while (
3615 !DFSStack.empty() &&
3616 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3617 DFSStack.pop_back();
3618 ValueStack.pop_back();
3619 }
3620 }
3621
3622private:
3623 SmallVector<Value *, 8> ValueStack;
3624 SmallVector<std::pair<int, int>, 8> DFSStack;
3625};
3626}
Daniel Berlin04443432017-01-07 03:23:47 +00003627
Daniel Berlin94090dd2017-09-02 02:18:44 +00003628// Given an expression, get the congruence class for it.
3629CongruenceClass *NewGVN::getClassForExpression(const Expression *E) const {
3630 if (auto *VE = dyn_cast<VariableExpression>(E))
3631 return ValueToClass.lookup(VE->getVariableValue());
3632 else if (isa<DeadExpression>(E))
3633 return TOPClass;
3634 return ExpressionToClass.lookup(E);
3635}
3636
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003637// Given a value and a basic block we are trying to see if it is available in,
3638// see if the value has a leader available in that block.
Daniel Berlin94090dd2017-09-02 02:18:44 +00003639Value *NewGVN::findPHIOfOpsLeader(const Expression *E,
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +00003640 const Instruction *OrigInst,
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003641 const BasicBlock *BB) const {
3642 // It would already be constant if we could make it constant
3643 if (auto *CE = dyn_cast<ConstantExpression>(E))
3644 return CE->getConstantValue();
Daniel Berlin94090dd2017-09-02 02:18:44 +00003645 if (auto *VE = dyn_cast<VariableExpression>(E)) {
3646 auto *V = VE->getVariableValue();
3647 if (alwaysAvailable(V) || DT->dominates(getBlockForValue(V), BB))
3648 return VE->getVariableValue();
3649 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003650
Daniel Berlin94090dd2017-09-02 02:18:44 +00003651 auto *CC = getClassForExpression(E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003652 if (!CC)
3653 return nullptr;
3654 if (alwaysAvailable(CC->getLeader()))
3655 return CC->getLeader();
3656
3657 for (auto Member : *CC) {
3658 auto *MemberInst = dyn_cast<Instruction>(Member);
Daniel Berlin4ad7e8d2017-09-05 02:17:40 +00003659 if (MemberInst == OrigInst)
3660 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003661 // Anything that isn't an instruction is always available.
3662 if (!MemberInst)
3663 return Member;
Daniel Berlin94090dd2017-09-02 02:18:44 +00003664 if (DT->dominates(getBlockForValue(MemberInst), BB))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003665 return Member;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003666 }
3667 return nullptr;
3668}
3669
Davide Italiano7e274e02016-12-22 16:03:48 +00003670bool NewGVN::eliminateInstructions(Function &F) {
3671 // This is a non-standard eliminator. The normal way to eliminate is
3672 // to walk the dominator tree in order, keeping track of available
3673 // values, and eliminating them. However, this is mildly
3674 // pointless. It requires doing lookups on every instruction,
3675 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003676 // instructions part of most singleton congruence classes, we know we
3677 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003678
3679 // Instead, this eliminator looks at the congruence classes directly, sorts
3680 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003681 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003682 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003683 // last member. This is worst case O(E log E) where E = number of
3684 // instructions in a single congruence class. In theory, this is all
3685 // instructions. In practice, it is much faster, as most instructions are
3686 // either in singleton congruence classes or can't possibly be eliminated
3687 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003688 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003689 // for elimination purposes.
3690 // TODO: If we wanted to be faster, We could remove any members with no
3691 // overlapping ranges while sorting, as we will never eliminate anything
3692 // with those members, as they don't dominate anything else in our set.
3693
Davide Italiano7e274e02016-12-22 16:03:48 +00003694 bool AnythingReplaced = false;
3695
3696 // Since we are going to walk the domtree anyway, and we can't guarantee the
3697 // DFS numbers are updated, we compute some ourselves.
3698 DT->updateDFSNumbers();
3699
Daniel Berlin0207cca2017-05-21 23:41:56 +00003700 // Go through all of our phi nodes, and kill the arguments associated with
3701 // unreachable edges.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003702 auto ReplaceUnreachablePHIArgs = [&](PHINode &PHI, BasicBlock *BB) {
3703 for (auto &Operand : PHI.incoming_values())
3704 if (!ReachableEdges.count({PHI.getIncomingBlock(Operand), BB})) {
3705 DEBUG(dbgs() << "Replacing incoming value of " << PHI << " for block "
3706 << getBlockName(PHI.getIncomingBlock(Operand))
3707 << " with undef due to it being unreachable\n");
3708 Operand.set(UndefValue::get(PHI.getType()));
3709 }
3710 };
3711 SmallPtrSet<BasicBlock *, 8> BlocksWithPhis;
3712 for (auto &B : F)
3713 if ((!B.empty() && isa<PHINode>(*B.begin())) ||
3714 (PHIOfOpsPHIs.find(&B) != PHIOfOpsPHIs.end()))
3715 BlocksWithPhis.insert(&B);
3716 DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
3717 for (auto KV : ReachableEdges)
3718 ReachablePredCount[KV.getEnd()]++;
3719 for (auto *BB : BlocksWithPhis)
3720 // TODO: It would be faster to use getNumIncomingBlocks() on a phi node in
3721 // the block and subtract the pred count, but it's more complicated.
3722 if (ReachablePredCount.lookup(BB) !=
George Burgess IVf6137492017-06-13 01:28:49 +00003723 unsigned(std::distance(pred_begin(BB), pred_end(BB)))) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003724 for (auto II = BB->begin(); isa<PHINode>(II); ++II) {
3725 auto &PHI = cast<PHINode>(*II);
3726 ReplaceUnreachablePHIArgs(PHI, BB);
3727 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00003728 for_each_found(PHIOfOpsPHIs, BB, [&](PHINode *PHI) {
3729 ReplaceUnreachablePHIArgs(*PHI, BB);
3730 });
Davide Italiano7e274e02016-12-22 16:03:48 +00003731 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003732
Daniel Berline3e69e12017-03-10 00:32:33 +00003733 // Map to store the use counts
3734 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003735 for (auto *CC : reverse(CongruenceClasses)) {
Daniel Berline67c3222017-05-25 15:44:20 +00003736 DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID() << "\n");
Daniel Berlinc4796862017-01-27 02:37:11 +00003737 // Track the equivalent store info so we can decide whether to try
3738 // dead store elimination.
3739 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003740 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003741 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003742 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003743 // Everything still in the TOP class is unreachable or dead.
3744 if (CC == TOPClass) {
Daniel Berline021d2d2017-05-19 20:22:20 +00003745 for (auto M : *CC) {
3746 auto *VTE = ValueToExpression.lookup(M);
3747 if (VTE && isa<DeadExpression>(VTE))
3748 markInstructionForDeletion(cast<Instruction>(M));
Daniel Berlinb79f5362017-02-11 12:48:50 +00003749 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3750 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003751 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003752 "point");
Daniel Berline021d2d2017-05-19 20:22:20 +00003753 }
Daniel Berlinb79f5362017-02-11 12:48:50 +00003754 continue;
3755 }
3756
Daniel Berlina8236562017-04-07 18:38:09 +00003757 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003758 // If this is a leader that is always available, and it's a
3759 // constant or has no equivalences, just replace everything with
3760 // it. We then update the congruence class with whatever members
3761 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003762 Value *Leader =
3763 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003764 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003765 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003766 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003767 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003768 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003769 if (Member == Leader || !isa<Instruction>(Member) ||
3770 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003771 MembersLeft.insert(Member);
3772 continue;
3773 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003774 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3775 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003776 auto *I = cast<Instruction>(Member);
3777 assert(Leader != I && "About to accidentally remove our leader");
3778 replaceInstruction(I, Leader);
3779 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003780 }
Daniel Berlina8236562017-04-07 18:38:09 +00003781 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003782 } else {
Davide Italiano7e274e02016-12-22 16:03:48 +00003783 // If this is a singleton, we can skip it.
Davide Italiano5974c312017-08-03 21:17:49 +00003784 if (CC->size() != 1 || RealToTemp.count(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003785 // This is a stack because equality replacement/etc may place
3786 // constants in the middle of the member list, and we want to use
3787 // those constant values in preference to the current leader, over
3788 // the scope of those constants.
3789 ValueDFSStack EliminationStack;
3790
3791 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003792 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003793 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003794
3795 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003796 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003797 for (auto &VD : DFSOrderedSet) {
3798 int MemberDFSIn = VD.DFSIn;
3799 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003800 Value *Def = VD.Def.getPointer();
3801 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003802 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003803 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003804 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003805 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003806 auto *DefInst = dyn_cast_or_null<Instruction>(Def);
3807 if (DefInst && AllTempInstructions.count(DefInst)) {
3808 auto *PN = cast<PHINode>(DefInst);
3809
3810 // If this is a value phi and that's the expression we used, insert
3811 // it into the program
3812 // remove from temp instruction list.
3813 AllTempInstructions.erase(PN);
3814 auto *DefBlock = getBlockForValue(Def);
3815 DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
3816 << " into block "
3817 << getBlockName(getBlockForValue(Def)) << "\n");
3818 PN->insertBefore(&DefBlock->front());
3819 Def = PN;
3820 NumGVNPHIOfOpsEliminations++;
3821 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003822
3823 if (EliminationStack.empty()) {
3824 DEBUG(dbgs() << "Elimination Stack is empty\n");
3825 } else {
3826 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3827 << EliminationStack.dfs_back().first << ","
3828 << EliminationStack.dfs_back().second << ")\n");
3829 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003830
3831 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3832 << MemberDFSOut << ")\n");
3833 // First, we see if we are out of scope or empty. If so,
3834 // and there equivalences, we try to replace the top of
3835 // stack with equivalences (if it's on the stack, it must
3836 // not have been eliminated yet).
3837 // Then we synchronize to our current scope, by
3838 // popping until we are back within a DFS scope that
3839 // dominates the current member.
3840 // Then, what happens depends on a few factors
3841 // If the stack is now empty, we need to push
3842 // If we have a constant or a local equivalence we want to
3843 // start using, we also push.
3844 // Otherwise, we walk along, processing members who are
3845 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003846 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003847 bool OutOfScope =
3848 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3849
3850 if (OutOfScope || ShouldPush) {
3851 // Sync to our current scope.
3852 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003853 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003854 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003855 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003856 }
3857 }
3858
Daniel Berline3e69e12017-03-10 00:32:33 +00003859 // Skip the Def's, we only want to eliminate on their uses. But mark
3860 // dominated defs as dead.
3861 if (Def) {
3862 // For anything in this case, what and how we value number
3863 // guarantees that any side-effets that would have occurred (ie
3864 // throwing, etc) can be proven to either still occur (because it's
3865 // dominated by something that has the same side-effects), or never
3866 // occur. Otherwise, we would not have been able to prove it value
3867 // equivalent to something else. For these things, we can just mark
3868 // it all dead. Note that this is different from the "ProbablyDead"
3869 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003870 // easy to prove dead if they are also side-effect free. Note that
3871 // because stores are put in terms of the stored value, we skip
3872 // stored values here. If the stored value is really dead, it will
3873 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003874 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003875 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003876 markInstructionForDeletion(cast<Instruction>(Def));
3877 continue;
3878 }
3879 // At this point, we know it is a Use we are trying to possibly
3880 // replace.
3881
3882 assert(isa<Instruction>(U->get()) &&
3883 "Current def should have been an instruction");
3884 assert(isa<Instruction>(U->getUser()) &&
3885 "Current user should have been an instruction");
3886
3887 // If the thing we are replacing into is already marked to be dead,
3888 // this use is dead. Note that this is true regardless of whether
3889 // we have anything dominating the use or not. We do this here
3890 // because we are already walking all the uses anyway.
3891 Instruction *InstUse = cast<Instruction>(U->getUser());
3892 if (InstructionsToErase.count(InstUse)) {
3893 auto &UseCount = UseCounts[U->get()];
3894 if (--UseCount == 0) {
3895 ProbablyDead.insert(cast<Instruction>(U->get()));
3896 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003897 }
3898
Davide Italiano7e274e02016-12-22 16:03:48 +00003899 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003900 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003901 if (EliminationStack.empty())
3902 continue;
3903
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003904 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003905
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003906 auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
3907 if (II && II->getIntrinsicID() == Intrinsic::ssa_copy)
3908 DominatingLeader = II->getOperand(0);
3909
Daniel Berlind92e7f92017-01-07 00:01:42 +00003910 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003911 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003912 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003913 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003914 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003915
3916 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003917 // metadata. Skip this if we are replacing predicateinfo with its
3918 // original operand, as we already know we can just drop it.
3919 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003920 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3921 if (!PI || DominatingLeader != PI->OriginalOp)
3922 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003923 U->set(DominatingLeader);
3924 // This is now a use of the dominating leader, which means if the
3925 // dominating leader was dead, it's now live!
3926 auto &LeaderUseCount = UseCounts[DominatingLeader];
3927 // It's about to be alive again.
3928 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3929 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003930 if (LeaderUseCount == 0 && II)
3931 ProbablyDead.insert(II);
Daniel Berline3e69e12017-03-10 00:32:33 +00003932 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003933 AnythingReplaced = true;
3934 }
3935 }
3936 }
3937
Daniel Berline3e69e12017-03-10 00:32:33 +00003938 // At this point, anything still in the ProbablyDead set is actually dead if
3939 // would be trivially dead.
3940 for (auto *I : ProbablyDead)
3941 if (wouldInstructionBeTriviallyDead(I))
3942 markInstructionForDeletion(I);
3943
Davide Italiano7e274e02016-12-22 16:03:48 +00003944 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003945 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003946 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003947 if (!isa<Instruction>(Member) ||
3948 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003949 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003950 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003951
3952 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00003953 if (CC->getStoreCount() > 0) {
3954 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003955 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3956 ValueDFSStack EliminationStack;
3957 for (auto &VD : PossibleDeadStores) {
3958 int MemberDFSIn = VD.DFSIn;
3959 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003960 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003961 if (EliminationStack.empty() ||
3962 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3963 // Sync to our current scope.
3964 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3965 if (EliminationStack.empty()) {
3966 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3967 continue;
3968 }
3969 }
3970 // We already did load elimination, so nothing to do here.
3971 if (isa<LoadInst>(Member))
3972 continue;
3973 assert(!EliminationStack.empty());
3974 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003975 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003976 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3977 // Member is dominater by Leader, and thus dead
3978 DEBUG(dbgs() << "Marking dead store " << *Member
3979 << " that is dominated by " << *Leader << "\n");
3980 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003981 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00003982 ++NumGVNDeadStores;
3983 }
3984 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003985 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003986 return AnythingReplaced;
3987}
Daniel Berlin1c087672017-02-11 15:07:01 +00003988
3989// This function provides global ranking of operations so that we can place them
3990// in a canonical order. Note that rank alone is not necessarily enough for a
3991// complete ordering, as constants all have the same rank. However, generally,
3992// we will simplify an operation with all constants so that it doesn't matter
3993// what order they appear in.
3994unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003995 // Prefer constants to undef to anything else
3996 // Undef is a constant, have to check it first.
3997 // Prefer smaller constants to constantexprs
3998 if (isa<ConstantExpr>(V))
3999 return 2;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004000 if (isa<UndefValue>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004001 return 1;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00004002 if (isa<Constant>(V))
4003 return 0;
Daniel Berlin1c087672017-02-11 15:07:01 +00004004 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00004005 return 3 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00004006
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004007 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00004008 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00004009 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00004010 if (Result > 0)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00004011 return 4 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00004012 // Unreachable or something else, just return a really large number.
4013 return ~0;
4014}
4015
4016// This is a function that says whether two commutative operations should
4017// have their order swapped when canonicalizing.
4018bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
4019 // Because we only care about a total ordering, and don't rewrite expressions
4020 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00004021 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00004022 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00004023}
Daniel Berlin64e68992017-03-12 04:46:45 +00004024
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00004025namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +00004026class NewGVNLegacyPass : public FunctionPass {
4027public:
4028 static char ID; // Pass identification, replacement for typeid.
4029 NewGVNLegacyPass() : FunctionPass(ID) {
4030 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
4031 }
4032 bool runOnFunction(Function &F) override;
4033
4034private:
4035 void getAnalysisUsage(AnalysisUsage &AU) const override {
4036 AU.addRequired<AssumptionCacheTracker>();
4037 AU.addRequired<DominatorTreeWrapperPass>();
4038 AU.addRequired<TargetLibraryInfoWrapperPass>();
4039 AU.addRequired<MemorySSAWrapperPass>();
4040 AU.addRequired<AAResultsWrapperPass>();
4041 AU.addPreserved<DominatorTreeWrapperPass>();
4042 AU.addPreserved<GlobalsAAWrapperPass>();
4043 }
4044};
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00004045} // namespace
Daniel Berlin64e68992017-03-12 04:46:45 +00004046
4047bool NewGVNLegacyPass::runOnFunction(Function &F) {
4048 if (skipFunction(F))
4049 return false;
4050 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4051 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
4052 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
4053 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
4054 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
4055 F.getParent()->getDataLayout())
4056 .runGVN();
4057}
4058
4059INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
4060 false, false)
4061INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4062INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
4063INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4064INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
4065INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
4066INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
4067INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
4068 false)
4069
4070char NewGVNLegacyPass::ID = 0;
4071
4072// createGVNPass - The public interface to this file.
4073FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
4074
4075PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
4076 // Apparently the order in which we get these results matter for
4077 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
4078 // the same order here, just in case.
4079 auto &AC = AM.getResult<AssumptionAnalysis>(F);
4080 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
4081 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
4082 auto &AA = AM.getResult<AAManager>(F);
4083 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
4084 bool Changed =
4085 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
4086 .runGVN();
4087 if (!Changed)
4088 return PreservedAnalyses::all();
4089 PreservedAnalyses PA;
4090 PA.preserve<DominatorTreeAnalysis>();
4091 PA.preserve<GlobalsAA>();
4092 return PA;
4093}