blob: ababf7f76e39e929d78961b0c968e5adeb1379b7 [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.
131static cl::opt<bool> EnablePhiOfOps("enable-phi-of-ops", cl::init(false),
132 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;
478 // Map a temporary instruction we created to a parent block.
479 DenseMap<const Value *, BasicBlock *> TempToBlock;
Davide Italiano5974c312017-08-03 21:17:49 +0000480 // Map between the already in-program instructions and the temporary phis we
481 // created that they are known equivalent to.
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000482 DenseMap<const Value *, PHINode *> RealToTemp;
483 // In order to know when we should re-process instructions that have
484 // phi-of-ops, we track the set of expressions that they needed as
485 // leaders. When we discover new leaders for those expressions, we process the
486 // associated phi-of-op instructions again in case they have changed. The
487 // other way they may change is if they had leaders, and those leaders
488 // disappear. However, at the point they have leaders, there are uses of the
489 // relevant operands in the created phi node, and so they will get reprocessed
490 // through the normal user marking we perform.
491 mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
492 DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
493 ExpressionToPhiOfOps;
494 // Map from basic block to the temporary operations we created
Davide Italiano5974c312017-08-03 21:17:49 +0000495 DenseMap<const BasicBlock *, SmallPtrSet<PHINode *, 2>> PHIOfOpsPHIs;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000496 // Map from temporary operation to MemoryAccess.
497 DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
498 // Set of all temporary instructions we created.
Davide Italiano5974c312017-08-03 21:17:49 +0000499 // Note: This will include instructions that were just created during value
500 // numbering. The way to test if something is using them is to check
501 // RealToTemp.
502
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000503 DenseSet<Instruction *> AllTempInstructions;
Davide Italiano7e274e02016-12-22 16:03:48 +0000504
Daniel Berlinf7d95802017-02-18 23:06:50 +0000505 // Mapping from predicate info we used to the instructions we used it with.
506 // In order to correctly ensure propagation, we must keep track of what
507 // comparisons we used, so that when the values of the comparisons change, we
508 // propagate the information to the places we used the comparison.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000509 mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
510 PredicateToUsers;
Daniel Berlin1316a942017-04-06 18:52:50 +0000511 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
512 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000513 mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
514 MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000515
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000516 // A table storing which memorydefs/phis represent a memory state provably
517 // equivalent to another memory state.
518 // We could use the congruence class machinery, but the MemoryAccess's are
519 // abstract memory states, so they can only ever be equivalent to each other,
520 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000521 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000522
Daniel Berlin1316a942017-04-06 18:52:50 +0000523 // We could, if we wanted, build MemoryPhiExpressions and
524 // MemoryVariableExpressions, etc, and value number them the same way we value
525 // number phi expressions. For the moment, this seems like overkill. They
526 // can only exist in one of three states: they can be TOP (equal to
527 // everything), Equivalent to something else, or unique. Because we do not
528 // create expressions for them, we need to simulate leader change not just
529 // when they change class, but when they change state. Note: We can do the
530 // same thing for phis, and avoid having phi expressions if we wanted, We
531 // should eventually unify in one direction or the other, so this is a little
532 // bit of an experiment in which turns out easier to maintain.
533 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
534 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
535
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000536 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
537 mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
Davide Italiano7e274e02016-12-22 16:03:48 +0000538 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000539 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000540 ExpressionClassMap ExpressionToClass;
541
Daniel Berline021d2d2017-05-19 20:22:20 +0000542 // We have a single expression that represents currently DeadExpressions.
543 // For dead expressions we can prove will stay dead, we mark them with
544 // DFS number zero. However, it's possible in the case of phi nodes
545 // for us to assume/prove all arguments are dead during fixpointing.
546 // We use DeadExpression for that case.
547 DeadExpression *SingletonDeadExpression = nullptr;
548
Davide Italiano7e274e02016-12-22 16:03:48 +0000549 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000550 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000551
552 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000553 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000554 DenseSet<BlockEdge> ReachableEdges;
555 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
556
557 // This is a bitvector because, on larger functions, we may have
558 // thousands of touched instructions at once (entire blocks,
559 // instructions with hundreds of uses, etc). Even with optimization
560 // for when we mark whole blocks as touched, when this was a
561 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
562 // the time in GVN just managing this list. The bitvector, on the
563 // other hand, efficiently supports test/set/clear of both
564 // individual and ranges, as well as "find next element" This
565 // enables us to use it as a worklist with essentially 0 cost.
566 BitVector TouchedInstructions;
567
568 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000569
570#ifndef NDEBUG
571 // Debugging for how many times each block and instruction got processed.
572 DenseMap<const Value *, unsigned> ProcessedCount;
573#endif
574
575 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000576 // This contains a mapping from Instructions to DFS numbers.
577 // The numbering starts at 1. An instruction with DFS number zero
578 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000579 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000580
581 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000582 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000583
584 // Deletion info.
585 SmallPtrSet<Instruction *, 8> InstructionsToErase;
586
587public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000588 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
589 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
590 const DataLayout &DL)
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000591 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
Daniel Berlinede130d2017-04-26 20:56:14 +0000592 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
593 }
Daniel Berlin64e68992017-03-12 04:46:45 +0000594 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000595
596private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000597 // Expression handling.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000598 const Expression *createExpression(Instruction *) const;
599 const Expression *createBinaryExpression(unsigned, Type *, Value *,
600 Value *) const;
601 PHIExpression *createPHIExpression(Instruction *, bool &HasBackEdge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000602 bool &OriginalOpsConstant) const;
Daniel Berline021d2d2017-05-19 20:22:20 +0000603 const DeadExpression *createDeadExpression() const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000604 const VariableExpression *createVariableExpression(Value *) const;
605 const ConstantExpression *createConstantExpression(Constant *) const;
606 const Expression *createVariableOrConstant(Value *V) const;
607 const UnknownExpression *createUnknownExpression(Instruction *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000608 const StoreExpression *createStoreExpression(StoreInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000609 const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000610 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000611 const MemoryAccess *) const;
612 const CallExpression *createCallExpression(CallInst *,
613 const MemoryAccess *) const;
614 const AggregateValueExpression *
615 createAggregateValueExpression(Instruction *) const;
616 bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000617
618 // Congruence class handling.
619 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000620 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000621 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000622 return result;
623 }
624
Daniel Berlin1316a942017-04-06 18:52:50 +0000625 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
626 auto *CC = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000627 CC->setMemoryLeader(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000628 return CC;
629 }
630 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
631 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +0000632 if (CC->getMemoryLeader() != MA)
Daniel Berlin1316a942017-04-06 18:52:50 +0000633 CC = createMemoryClass(MA);
634 return CC;
635 }
636
Davide Italiano7e274e02016-12-22 16:03:48 +0000637 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000638 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000639 CClass->insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +0000640 ValueToClass[Member] = CClass;
641 return CClass;
642 }
643 void initializeCongruenceClasses(Function &F);
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +0000644 const Expression *makePossiblePhiOfOps(Instruction *,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000645 SmallPtrSetImpl<Value *> &);
646 void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
Davide Italiano5974c312017-08-03 21:17:49 +0000647 void removePhiOfOps(Instruction *I, PHINode *PHITemp);
Davide Italiano7e274e02016-12-22 16:03:48 +0000648
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000649 // Value number an Instruction or MemoryPhi.
650 void valueNumberMemoryPhi(MemoryPhi *);
651 void valueNumberInstruction(Instruction *);
652
Davide Italiano7e274e02016-12-22 16:03:48 +0000653 // Symbolic evaluation.
654 const Expression *checkSimplificationResults(Expression *, Instruction *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000655 Value *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000656 const Expression *performSymbolicEvaluation(Value *,
657 SmallPtrSetImpl<Value *> &) const;
Daniel Berlin07daac82017-04-02 13:23:44 +0000658 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000659 Instruction *,
660 MemoryAccess *) const;
661 const Expression *performSymbolicLoadEvaluation(Instruction *) const;
662 const Expression *performSymbolicStoreEvaluation(Instruction *) const;
663 const Expression *performSymbolicCallEvaluation(Instruction *) const;
664 const Expression *performSymbolicPHIEvaluation(Instruction *) const;
665 const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
666 const Expression *performSymbolicCmpEvaluation(Instruction *) const;
667 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000668
669 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000670 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000671 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000672 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000673 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
674 CongruenceClass *, CongruenceClass *);
675 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
676 CongruenceClass *, CongruenceClass *);
677 Value *getNextValueLeader(CongruenceClass *) const;
678 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
679 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
680 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
681 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000682 bool isMemoryAccessTOP(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000683
Daniel Berlin1c087672017-02-11 15:07:01 +0000684 // Ranking
685 unsigned int getRank(const Value *) const;
686 bool shouldSwapOperands(const Value *, const Value *) const;
687
Davide Italiano7e274e02016-12-22 16:03:48 +0000688 // Reachability handling.
689 void updateReachableEdge(BasicBlock *, BasicBlock *);
690 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000691 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000692
693 // Elimination.
694 struct ValueDFS;
Daniel Berlina8236562017-04-07 18:38:09 +0000695 void convertClassToDFSOrdered(const CongruenceClass &,
Daniel Berline3e69e12017-03-10 00:32:33 +0000696 SmallVectorImpl<ValueDFS> &,
697 DenseMap<const Value *, unsigned int> &,
Daniel Berlina8236562017-04-07 18:38:09 +0000698 SmallPtrSetImpl<Instruction *> &) const;
699 void convertClassToLoadsAndStores(const CongruenceClass &,
700 SmallVectorImpl<ValueDFS> &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000701
702 bool eliminateInstructions(Function &);
703 void replaceInstruction(Instruction *, Value *);
704 void markInstructionForDeletion(Instruction *);
705 void deleteInstructionsInBlock(BasicBlock *);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000706 Value *findPhiOfOpsLeader(const Expression *E, const BasicBlock *BB) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000707
708 // New instruction creation.
709 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000710
711 // Various instruction touch utilities
Daniel Berlin0207cca2017-05-21 23:41:56 +0000712 template <typename Map, typename KeyType, typename Func>
713 void for_each_found(Map &, const KeyType &, Func);
714 template <typename Map, typename KeyType>
715 void touchAndErase(Map &, const KeyType &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000716 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000717 void markMemoryUsersTouched(const MemoryAccess *);
718 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000719 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000720 void markValueLeaderChangeTouched(CongruenceClass *CC);
721 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +0000722 void markPhiOfOpsChanged(const Expression *E);
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000723 void addPredicateUsers(const PredicateBase *, Instruction *) const;
724 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000725 void addAdditionalUsers(Value *To, Value *User) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000726
Daniel Berlin06329a92017-03-18 15:41:40 +0000727 // Main loop of value numbering
728 void iterateTouchedInstructions();
729
Davide Italiano7e274e02016-12-22 16:03:48 +0000730 // Utilities.
731 void cleanupTables();
732 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000733 void updateProcessedCount(const Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000734 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000735 void verifyIterationSettled(Function &F);
Daniel Berlin45403572017-05-16 19:58:47 +0000736 void verifyStoreExpressions() const;
Davide Italianoeab0de22017-05-18 23:22:44 +0000737 bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
738 const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000739 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000740 void deleteExpression(const Expression *E) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000741 MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
742 MemoryAccess *getDefiningAccess(const MemoryAccess *) const;
743 MemoryPhi *getMemoryAccess(const BasicBlock *) const;
744 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin21279bd2017-04-06 18:52:58 +0000745 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000746 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
747 return InstrDFS.lookup(V);
748 }
749
Daniel Berlin21279bd2017-04-06 18:52:58 +0000750 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
751 return MemoryToDFSNum(MA);
752 }
753 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
754 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
755 // This deliberately takes a value so it can be used with Use's, which will
756 // auto-convert to Value's but not to MemoryAccess's.
757 unsigned MemoryToDFSNum(const Value *MA) const {
758 assert(isa<MemoryAccess>(MA) &&
759 "This should not be used with instructions");
760 return isa<MemoryUseOrDef>(MA)
761 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
762 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000763 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000764 bool isCycleFree(const Instruction *) const;
765 bool isBackedge(BasicBlock *From, BasicBlock *To) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000766 // Debug counter info. When verifying, we have to reset the value numbering
767 // debug counter to the same state it started in to get the same results.
768 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000769};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000770} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000771
Davide Italianob1114092016-12-28 13:37:17 +0000772template <typename T>
773static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000774 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000775 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000776 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000777}
778
Davide Italianob1114092016-12-28 13:37:17 +0000779bool LoadExpression::equals(const Expression &Other) const {
780 return equalsLoadStoreHelper(*this, Other);
781}
Davide Italiano7e274e02016-12-22 16:03:48 +0000782
Davide Italianob1114092016-12-28 13:37:17 +0000783bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000784 if (!equalsLoadStoreHelper(*this, Other))
785 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000786 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000787 if (const auto *S = dyn_cast<StoreExpression>(&Other))
788 if (getStoredValue() != S->getStoredValue())
789 return false;
790 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000791}
792
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000793// Determine if the edge From->To is a backedge
794bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
Davide Italianoc2f73b72017-08-02 04:05:49 +0000795 return From == To ||
796 RPOOrdering.lookup(DT->getNode(From)) >=
797 RPOOrdering.lookup(DT->getNode(To));
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000798}
799
Davide Italiano7e274e02016-12-22 16:03:48 +0000800#ifndef NDEBUG
801static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000802 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000803}
804#endif
805
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000806// Get a MemoryAccess for an instruction, fake or real.
807MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
808 auto *Result = MSSA->getMemoryAccess(I);
809 return Result ? Result : TempToMemory.lookup(I);
810}
811
812// Get a MemoryPhi for a basic block. These are all real.
813MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
814 return MSSA->getMemoryAccess(BB);
815}
816
Daniel Berlin06329a92017-03-18 15:41:40 +0000817// Get the basic block from an instruction/memory value.
818BasicBlock *NewGVN::getBlockForValue(Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000819 if (auto *I = dyn_cast<Instruction>(V)) {
820 auto *Parent = I->getParent();
821 if (Parent)
822 return Parent;
823 Parent = TempToBlock.lookup(V);
824 assert(Parent && "Every fake instruction should have a block");
825 return Parent;
826 }
827
828 auto *MP = dyn_cast<MemoryPhi>(V);
829 assert(MP && "Should have been an instruction or a MemoryPhi");
830 return MP->getBlock();
Daniel Berlin06329a92017-03-18 15:41:40 +0000831}
832
Daniel Berlin0e900112017-03-24 06:33:48 +0000833// Delete a definitely dead expression, so it can be reused by the expression
834// allocator. Some of these are not in creation functions, so we have to accept
835// const versions.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000836void NewGVN::deleteExpression(const Expression *E) const {
Daniel Berlin0e900112017-03-24 06:33:48 +0000837 assert(isa<BasicExpression>(E));
838 auto *BE = cast<BasicExpression>(E);
839 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
840 ExpressionAllocator.Deallocate(E);
841}
Daniel Berlin2f72b192017-04-14 02:53:37 +0000842PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000843 bool &OriginalOpsConstant) const {
844 BasicBlock *PHIBlock = getBlockForValue(I);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000845 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000846 auto *E =
847 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000848
849 E->allocateOperands(ArgRecycler, ExpressionAllocator);
850 E->setType(I->getType());
851 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000852
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000853 // NewGVN assumes the operands of a PHI node are in a consistent order across
854 // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix
855 // this in LLVM at some point we don't want GVN to find wrong congruences.
856 // Therefore, here we sort uses in predecessor order.
Davide Italiano63998ec2017-05-09 18:29:37 +0000857 // We're sorting the values by pointer. In theory this might be cause of
858 // non-determinism, but here we don't rely on the ordering for anything
859 // significant, e.g. we don't create new instructions based on it so we're
860 // fine.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000861 SmallVector<const Use *, 4> PHIOperands;
862 for (const Use &U : PN->operands())
863 PHIOperands.push_back(&U);
864 std::sort(PHIOperands.begin(), PHIOperands.end(),
865 [&](const Use *U1, const Use *U2) {
866 return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
867 });
868
Davide Italianob3886dd2017-01-25 23:37:49 +0000869 // Filter out unreachable phi operands.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000870 auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) {
Daniel Berline67c3222017-05-25 15:44:20 +0000871 if (*U == PN)
872 return false;
873 if (!ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock}))
874 return false;
875 // Things in TOPClass are equivalent to everything.
876 if (ValueToClass.lookup(*U) == TOPClass)
877 return false;
Davide Italianoa7a77542017-07-10 20:45:00 +0000878 return lookupOperandLeader(*U) != PN;
Davide Italianob3886dd2017-01-25 23:37:49 +0000879 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000880 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000881 [&](const Use *U) -> Value * {
882 auto *BB = PN->getIncomingBlock(*U);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000883 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
884 OriginalOpsConstant =
885 OriginalOpsConstant && isa<Constant>(*U);
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000886 return lookupOperandLeader(*U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000887 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000888 return E;
889}
890
891// Set basic expression info (Arguments, type, opcode) for Expression
892// E from Instruction I in block B.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000893bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000894 bool AllConstant = true;
895 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
896 E->setType(GEP->getSourceElementType());
897 else
898 E->setType(I->getType());
899 E->setOpcode(I->getOpcode());
900 E->allocateOperands(ArgRecycler, ExpressionAllocator);
901
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000902 // Transform the operand array into an operand leader array, and keep track of
903 // whether all members are constant.
904 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000905 auto Operand = lookupOperandLeader(O);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000906 AllConstant = AllConstant && isa<Constant>(Operand);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000907 return Operand;
908 });
909
Davide Italiano7e274e02016-12-22 16:03:48 +0000910 return AllConstant;
911}
912
913const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000914 Value *Arg1,
915 Value *Arg2) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000916 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000917
918 E->setType(T);
919 E->setOpcode(Opcode);
920 E->allocateOperands(ArgRecycler, ExpressionAllocator);
921 if (Instruction::isCommutative(Opcode)) {
922 // Ensure that commutative instructions that only differ by a permutation
923 // of their operands get the same value number by sorting the operand value
924 // numbers. Since all commutative instructions have two operands it is more
925 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000926 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000927 std::swap(Arg1, Arg2);
928 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000929 E->op_push_back(lookupOperandLeader(Arg1));
930 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000931
Daniel Berlinede130d2017-04-26 20:56:14 +0000932 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000933 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
934 return SimplifiedE;
935 return E;
936}
937
938// Take a Value returned by simplification of Expression E/Instruction
939// I, and see if it resulted in a simpler expression. If so, return
940// that expression.
Davide Italiano7e274e02016-12-22 16:03:48 +0000941const Expression *NewGVN::checkSimplificationResults(Expression *E,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000942 Instruction *I,
943 Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000944 if (!V)
945 return nullptr;
946 if (auto *C = dyn_cast<Constant>(V)) {
947 if (I)
948 DEBUG(dbgs() << "Simplified " << *I << " to "
949 << " constant " << *C << "\n");
950 NumGVNOpsSimplified++;
951 assert(isa<BasicExpression>(E) &&
952 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000953 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000954 return createConstantExpression(C);
955 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
956 if (I)
957 DEBUG(dbgs() << "Simplified " << *I << " to "
958 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000959 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000960 return createVariableExpression(V);
961 }
962
963 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlin7ef26da2017-08-30 19:52:39 +0000964 if (CC) {
965 if (CC->getLeader() && CC->getLeader() != I) {
966 addAdditionalUsers(V, I);
967 return createVariableOrConstant(CC->getLeader());
Daniel Berlinc8ed4042017-05-30 06:42:29 +0000968 }
969
Daniel Berlin7ef26da2017-08-30 19:52:39 +0000970 if (CC->getDefiningExpr()) {
971 // If we simplified to something else, we need to communicate
972 // that we're users of the value we simplified to.
973 if (I != V) {
974 // Don't add temporary instructions to the user lists.
975 if (!AllTempInstructions.count(I))
976 addAdditionalUsers(V, I);
977 }
978
979 if (I)
980 DEBUG(dbgs() << "Simplified " << *I << " to "
981 << " expression " << *CC->getDefiningExpr() << "\n");
982 NumGVNOpsSimplified++;
983 deleteExpression(E);
984 return CC->getDefiningExpr();
985 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000986 }
Daniel Berlin7ef26da2017-08-30 19:52:39 +0000987
Davide Italiano7e274e02016-12-22 16:03:48 +0000988 return nullptr;
989}
990
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000991const Expression *NewGVN::createExpression(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000992 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000993
Daniel Berlin97718e62017-01-31 22:32:03 +0000994 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000995
996 if (I->isCommutative()) {
997 // Ensure that commutative instructions that only differ by a permutation
998 // of their operands get the same value number by sorting the operand value
999 // numbers. Since all commutative instructions have two operands it is more
1000 // efficient to sort by hand rather than using, say, std::sort.
1001 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +00001002 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +00001003 E->swapOperands(0, 1);
1004 }
1005
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001006 // Perform simplification.
Davide Italiano7e274e02016-12-22 16:03:48 +00001007 if (auto *CI = dyn_cast<CmpInst>(I)) {
1008 // Sort the operand value numbers so x<y and y>x get the same value
1009 // number.
1010 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +00001011 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001012 E->swapOperands(0, 1);
1013 Predicate = CmpInst::getSwappedPredicate(Predicate);
1014 }
1015 E->setOpcode((CI->getOpcode() << 8) | Predicate);
1016 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +00001017 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
1018 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +00001019 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
1020 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +00001021 Value *V =
1022 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +00001023 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1024 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001025 } else if (isa<SelectInst>(I)) {
1026 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlinf9486032017-08-24 02:43:17 +00001027 E->getOperand(1) == E->getOperand(2)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001028 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
1029 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +00001030 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +00001031 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001032 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1033 return SimplifiedE;
1034 }
1035 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001036 Value *V =
1037 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001038 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1039 return SimplifiedE;
1040 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001041 Value *V =
1042 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001043 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1044 return SimplifiedE;
1045 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001046 Value *V = SimplifyGEPInst(
1047 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001048 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1049 return SimplifiedE;
1050 } else if (AllConstant) {
1051 // We don't bother trying to simplify unless all of the operands
1052 // were constant.
1053 // TODO: There are a lot of Simplify*'s we could call here, if we
1054 // wanted to. The original motivating case for this code was a
1055 // zext i1 false to i8, which we don't have an interface to
1056 // simplify (IE there is no SimplifyZExt).
1057
1058 SmallVector<Constant *, 8> C;
1059 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001060 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +00001061
Daniel Berlin64e68992017-03-12 04:46:45 +00001062 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +00001063 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1064 return SimplifiedE;
1065 }
1066 return E;
1067}
1068
1069const AggregateValueExpression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001070NewGVN::createAggregateValueExpression(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001071 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001072 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001073 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001074 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001075 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001076 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001077 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001078 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001079 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001080 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001081 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001082 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001083 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001084 return E;
1085 }
1086 llvm_unreachable("Unhandled type of aggregate value operation");
1087}
1088
Daniel Berline021d2d2017-05-19 20:22:20 +00001089const DeadExpression *NewGVN::createDeadExpression() const {
1090 // DeadExpression has no arguments and all DeadExpression's are the same,
1091 // so we only need one of them.
1092 return SingletonDeadExpression;
1093}
1094
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001095const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001096 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001097 E->setOpcode(V->getValueID());
1098 return E;
1099}
1100
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001101const Expression *NewGVN::createVariableOrConstant(Value *V) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001102 if (auto *C = dyn_cast<Constant>(V))
1103 return createConstantExpression(C);
1104 return createVariableExpression(V);
1105}
1106
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001107const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001108 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +00001109 E->setOpcode(C->getValueID());
1110 return E;
1111}
1112
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001113const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001114 auto *E = new (ExpressionAllocator) UnknownExpression(I);
1115 E->setOpcode(I->getOpcode());
1116 return E;
1117}
1118
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001119const CallExpression *
1120NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001121 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001122 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +00001123 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +00001124 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001125 return E;
1126}
1127
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001128// Return true if some equivalent of instruction Inst dominates instruction U.
1129bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1130 const Instruction *U) const {
1131 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +00001132 // This must be an instruction because we are only called from phi nodes
1133 // in the case that the value it needs to check against is an instruction.
1134
1135 // The most likely candiates for dominance are the leader and the next leader.
1136 // The leader or nextleader will dominate in all cases where there is an
1137 // equivalent that is higher up in the dom tree.
1138 // We can't *only* check them, however, because the
1139 // dominator tree could have an infinite number of non-dominating siblings
1140 // with instructions that are in the right congruence class.
1141 // A
1142 // B C D E F G
1143 // |
1144 // H
1145 // Instruction U could be in H, with equivalents in every other sibling.
1146 // Depending on the rpo order picked, the leader could be the equivalent in
1147 // any of these siblings.
1148 if (!CC)
1149 return false;
Daniel Berlina8236562017-04-07 18:38:09 +00001150 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001151 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001152 if (CC->getNextLeader().first &&
1153 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001154 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001155 return llvm::any_of(*CC, [&](const Value *Member) {
1156 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001157 DT->dominates(cast<Instruction>(Member), U);
1158 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001159}
1160
Davide Italiano7e274e02016-12-22 16:03:48 +00001161// See if we have a congruence class and leader for this operand, and if so,
1162// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001163Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001164 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001165 if (CC) {
Daniel Berline021d2d2017-05-19 20:22:20 +00001166 // Everything in TOP is represented by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001167 // We do have to make sure we get the type right though, so we can't set the
1168 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001169 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001170 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001171 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001172 }
1173
Davide Italiano7e274e02016-12-22 16:03:48 +00001174 return V;
1175}
1176
Daniel Berlin1316a942017-04-06 18:52:50 +00001177const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1178 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001179 assert(CC->getMemoryLeader() &&
Davide Italianob60f6e02017-05-12 15:25:56 +00001180 "Every MemoryAccess should be mapped to a congruence class with a "
1181 "representative memory access");
Daniel Berlina8236562017-04-07 18:38:09 +00001182 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001183}
1184
Daniel Berlinc4796862017-01-27 02:37:11 +00001185// Return true if the MemoryAccess is really equivalent to everything. This is
1186// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001187// state of all MemoryAccesses.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001188bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001189 return getMemoryClass(MA) == TOPClass;
1190}
1191
Davide Italiano7e274e02016-12-22 16:03:48 +00001192LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001193 LoadInst *LI,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001194 const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001195 auto *E =
1196 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001197 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1198 E->setType(LoadType);
1199
1200 // Give store and loads same opcode so they value number together.
1201 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001202 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001203 if (LI)
1204 E->setAlignment(LI->getAlignment());
1205
1206 // TODO: Value number heap versions. We may be able to discover
1207 // things alias analysis can't on it's own (IE that a store and a
1208 // load have the same value, and thus, it isn't clobbering the load).
1209 return E;
1210}
1211
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001212const StoreExpression *
1213NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001214 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001215 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001216 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001217 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1218 E->setType(SI->getValueOperand()->getType());
1219
1220 // Give store and loads same opcode so they value number together.
1221 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001222 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001223
1224 // TODO: Value number heap versions. We may be able to discover
1225 // things alias analysis can't on it's own (IE that a store and a
1226 // load have the same value, and thus, it isn't clobbering the load).
1227 return E;
1228}
1229
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001230const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001231 // Unlike loads, we never try to eliminate stores, so we do not check if they
1232 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001233 auto *SI = cast<StoreInst>(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001234 auto *StoreAccess = getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001235 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001236 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1237 if (EnableStoreRefinement)
1238 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1239 // If we bypassed the use-def chains, make sure we add a use.
Daniel Berlinde269f42017-08-26 07:37:11 +00001240 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlin1316a942017-04-06 18:52:50 +00001241 if (StoreRHS != StoreAccess->getDefiningAccess())
1242 addMemoryUsers(StoreRHS, StoreAccess);
Daniel Berlinc4796862017-01-27 02:37:11 +00001243 // If we are defined by ourselves, use the live on entry def.
1244 if (StoreRHS == StoreAccess)
1245 StoreRHS = MSSA->getLiveOnEntryDef();
1246
Daniel Berlin589cecc2017-01-02 18:00:46 +00001247 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001248 // See if we are defined by a previous store expression, it already has a
1249 // value, and it's the same value as our current store. FIXME: Right now, we
1250 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001251 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1252 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlin36b08b22017-06-19 00:24:00 +00001253 // We really want to check whether the expression we matched was a store. No
1254 // easy way to do that. However, we can check that the class we found has a
1255 // store, which, assuming the value numbering state is not corrupt, is
1256 // sufficient, because we must also be equivalent to that store's expression
1257 // for it to be in the same class as the load.
1258 if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
Daniel Berlin1316a942017-04-06 18:52:50 +00001259 return LastStore;
Daniel Berlinc4796862017-01-27 02:37:11 +00001260 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001261 // location, and the memory state is the same as it was then (otherwise, it
1262 // could have been overwritten later. See test32 in
1263 // transforms/DeadStoreElimination/simple.ll).
Daniel Berlin36b08b22017-06-19 00:24:00 +00001264 if (auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
Daniel Berlin203f47b2017-01-31 22:31:53 +00001265 if ((lookupOperandLeader(LI->getPointerOperand()) ==
Daniel Berlin36b08b22017-06-19 00:24:00 +00001266 LastStore->getOperand(0)) &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001267 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
Daniel Berlin1316a942017-04-06 18:52:50 +00001268 StoreRHS))
Daniel Berlin36b08b22017-06-19 00:24:00 +00001269 return LastStore;
1270 deleteExpression(LastStore);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001271 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001272
1273 // If the store is not equivalent to anything, value number it as a store that
1274 // produces a unique memory state (instead of using it's MemoryUse, we use
1275 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001276 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001277}
1278
Daniel Berlin07daac82017-04-02 13:23:44 +00001279// See if we can extract the value of a loaded pointer from a load, a store, or
1280// a memory instruction.
1281const Expression *
1282NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1283 LoadInst *LI, Instruction *DepInst,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001284 MemoryAccess *DefiningAccess) const {
Daniel Berlin07daac82017-04-02 13:23:44 +00001285 assert((!LI || LI->isSimple()) && "Not a simple load");
1286 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1287 // Can't forward from non-atomic to atomic without violating memory model.
1288 // Also don't need to coerce if they are the same type, we will just
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001289 // propagate.
Daniel Berlin07daac82017-04-02 13:23:44 +00001290 if (LI->isAtomic() > DepSI->isAtomic() ||
1291 LoadType == DepSI->getValueOperand()->getType())
1292 return nullptr;
1293 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1294 if (Offset >= 0) {
1295 if (auto *C = dyn_cast<Constant>(
1296 lookupOperandLeader(DepSI->getValueOperand()))) {
1297 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1298 << *C << "\n");
1299 return createConstantExpression(
1300 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1301 }
1302 }
1303
Davide Italiano9bdccb32017-08-26 22:31:10 +00001304 } else if (auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
Daniel Berlin07daac82017-04-02 13:23:44 +00001305 // Can't forward from non-atomic to atomic without violating memory model.
1306 if (LI->isAtomic() > DepLI->isAtomic())
1307 return nullptr;
1308 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1309 if (Offset >= 0) {
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001310 // We can coerce a constant load into a load.
Daniel Berlin07daac82017-04-02 13:23:44 +00001311 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1312 if (auto *PossibleConstant =
1313 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1314 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1315 << *PossibleConstant << "\n");
1316 return createConstantExpression(PossibleConstant);
1317 }
1318 }
1319
Davide Italiano9bdccb32017-08-26 22:31:10 +00001320 } else if (auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
Daniel Berlin07daac82017-04-02 13:23:44 +00001321 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1322 if (Offset >= 0) {
1323 if (auto *PossibleConstant =
1324 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1325 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1326 << " to constant " << *PossibleConstant << "\n");
1327 return createConstantExpression(PossibleConstant);
1328 }
1329 }
1330 }
1331
1332 // All of the below are only true if the loaded pointer is produced
1333 // by the dependent instruction.
1334 if (LoadPtr != lookupOperandLeader(DepInst) &&
1335 !AA->isMustAlias(LoadPtr, DepInst))
1336 return nullptr;
1337 // If this load really doesn't depend on anything, then we must be loading an
1338 // undef value. This can happen when loading for a fresh allocation with no
1339 // intervening stores, for example. Note that this is only true in the case
1340 // that the result of the allocation is pointer equal to the load ptr.
1341 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1342 return createConstantExpression(UndefValue::get(LoadType));
1343 }
1344 // If this load occurs either right after a lifetime begin,
1345 // then the loaded value is undefined.
1346 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1347 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1348 return createConstantExpression(UndefValue::get(LoadType));
1349 }
1350 // If this load follows a calloc (which zero initializes memory),
1351 // then the loaded value is zero
1352 else if (isCallocLikeFn(DepInst, TLI)) {
1353 return createConstantExpression(Constant::getNullValue(LoadType));
1354 }
1355
1356 return nullptr;
1357}
1358
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001359const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001360 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001361
1362 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001363 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001364 if (!LI->isSimple())
1365 return nullptr;
1366
Daniel Berlin203f47b2017-01-31 22:31:53 +00001367 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001368 // Load of undef is undef.
1369 if (isa<UndefValue>(LoadAddressLeader))
1370 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001371 MemoryAccess *OriginalAccess = getMemoryAccess(I);
1372 MemoryAccess *DefiningAccess =
1373 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001374
1375 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1376 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1377 Instruction *DefiningInst = MD->getMemoryInst();
1378 // If the defining instruction is not reachable, replace with undef.
1379 if (!ReachableBlocks.count(DefiningInst->getParent()))
1380 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001381 // This will handle stores and memory insts. We only do if it the
1382 // defining access has a different type, or it is a pointer produced by
1383 // certain memory operations that cause the memory to have a fixed value
1384 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001385 if (const auto *CoercionResult =
1386 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1387 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001388 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001389 }
1390 }
1391
Daniel Berlinde269f42017-08-26 07:37:11 +00001392 const auto *LE = createLoadExpression(LI->getType(), LoadAddressLeader,
Daniel Berlin1316a942017-04-06 18:52:50 +00001393 LI, DefiningAccess);
Daniel Berlinde269f42017-08-26 07:37:11 +00001394 // If our MemoryLeader is not our defining access, add a use to the
1395 // MemoryLeader, so that we get reprocessed when it changes.
1396 if (LE->getMemoryLeader() != DefiningAccess)
1397 addMemoryUsers(LE->getMemoryLeader(), OriginalAccess);
1398 return LE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001399}
1400
Daniel Berlinf7d95802017-02-18 23:06:50 +00001401const Expression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001402NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001403 auto *PI = PredInfo->getPredicateInfoFor(I);
1404 if (!PI)
1405 return nullptr;
1406
1407 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001408
1409 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1410 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001411 return nullptr;
1412
Daniel Berlinfccbda92017-02-22 22:20:58 +00001413 auto *CopyOf = I->getOperand(0);
1414 auto *Cond = PWC->Condition;
1415
Daniel Berlinf7d95802017-02-18 23:06:50 +00001416 // If this a copy of the condition, it must be either true or false depending
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001417 // on the predicate info type and edge.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001418 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001419 // We should not need to add predicate users because the predicate info is
1420 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001421 if (isa<PredicateAssume>(PI))
1422 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1423 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1424 if (PBranch->TrueEdge)
1425 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1426 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1427 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001428 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1429 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001430 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001431
Daniel Berlinf7d95802017-02-18 23:06:50 +00001432 // Not a copy of the condition, so see what the predicates tell us about this
1433 // value. First, though, we check to make sure the value is actually a copy
1434 // of one of the condition operands. It's possible, in certain cases, for it
1435 // to be a copy of a predicateinfo copy. In particular, if two branch
1436 // operations use the same condition, and one branch dominates the other, we
1437 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001438 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001439 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001440
1441 // Everything below relies on the condition being a comparison.
1442 auto *Cmp = dyn_cast<CmpInst>(Cond);
1443 if (!Cmp)
1444 return nullptr;
1445
1446 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Davide Italianoc43a9f82017-05-12 15:28:12 +00001447 DEBUG(dbgs() << "Copy is not of any condition operands!\n");
Daniel Berlinf7d95802017-02-18 23:06:50 +00001448 return nullptr;
1449 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001450 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1451 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001452 bool SwappedOps = false;
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001453 // Sort the ops.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001454 if (shouldSwapOperands(FirstOp, SecondOp)) {
1455 std::swap(FirstOp, SecondOp);
1456 SwappedOps = true;
1457 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001458 CmpInst::Predicate Predicate =
1459 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1460
1461 if (isa<PredicateAssume>(PI)) {
1462 // If the comparison is true when the operands are equal, then we know the
1463 // operands are equal, because assumes must always be true.
1464 if (CmpInst::isTrueWhenEqual(Predicate)) {
1465 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001466 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001467 return createVariableOrConstant(FirstOp);
1468 }
1469 }
1470 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1471 // If we are *not* a copy of the comparison, we may equal to the other
1472 // operand when the predicate implies something about equality of
1473 // operations. In particular, if the comparison is true/false when the
1474 // operands are equal, and we are on the right edge, we know this operation
1475 // is equal to something.
1476 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1477 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1478 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001479 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001480 return createVariableOrConstant(FirstOp);
1481 }
1482 // Handle the special case of floating point.
1483 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1484 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1485 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1486 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001487 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001488 return createConstantExpression(cast<Constant>(FirstOp));
1489 }
1490 }
1491 return nullptr;
1492}
1493
Davide Italiano7e274e02016-12-22 16:03:48 +00001494// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001495const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001496 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001497 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1498 // Instrinsics with the returned attribute are copies of arguments.
1499 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1500 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1501 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1502 return Result;
1503 return createVariableOrConstant(ReturnedValue);
1504 }
1505 }
1506 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001507 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001508 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001509 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001510 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001511 }
1512 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001513}
1514
Daniel Berlin1316a942017-04-06 18:52:50 +00001515// Retrieve the memory class for a given MemoryAccess.
1516CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1517
1518 auto *Result = MemoryAccessToClass.lookup(MA);
1519 assert(Result && "Should have found memory class");
1520 return Result;
1521}
1522
1523// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001524// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001525bool NewGVN::setMemoryClass(const MemoryAccess *From,
1526 CongruenceClass *NewClass) {
1527 assert(NewClass &&
1528 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001529 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001530 DEBUG(dbgs() << " equivalent to congruence class ");
Daniel Berlina8236562017-04-07 18:38:09 +00001531 DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
Davide Italianob7a66982017-05-09 20:02:48 +00001532 DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001533
1534 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001535 bool Changed = false;
1536 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001537 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001538 auto *OldClass = LookupResult->second;
1539 if (OldClass != NewClass) {
1540 // If this is a phi, we have to handle memory member updates.
1541 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001542 OldClass->memory_erase(MP);
1543 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001544 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001545 if (OldClass->getMemoryLeader() == From) {
Davide Italiano41f5c7b2017-05-12 15:22:45 +00001546 if (OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00001547 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001548 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001549 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Daniel Berlin1316a942017-04-06 18:52:50 +00001550 DEBUG(dbgs() << "Memory class leader change for class "
Daniel Berlina8236562017-04-07 18:38:09 +00001551 << OldClass->getID() << " to "
1552 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001553 << " due to removal of a memory member " << *From
1554 << "\n");
1555 markMemoryLeaderChangeTouched(OldClass);
1556 }
1557 }
1558 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001559 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001560 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001561 Changed = true;
1562 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001563 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001564
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001565 return Changed;
1566}
Daniel Berlin0e900112017-03-24 06:33:48 +00001567
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001568// Determine if a instruction is cycle-free. That means the values in the
1569// instruction don't depend on any expressions that can change value as a result
1570// of the instruction. For example, a non-cycle free instruction would be v =
1571// phi(0, v+1).
1572bool NewGVN::isCycleFree(const Instruction *I) const {
1573 // In order to compute cycle-freeness, we do SCC finding on the instruction,
1574 // and see what kind of SCC it ends up in. If it is a singleton, it is
1575 // cycle-free. If it is not in a singleton, it is only cycle free if the
1576 // other members are all phi nodes (as they do not compute anything, they are
1577 // copies).
1578 auto ICS = InstCycleState.lookup(I);
1579 if (ICS == ICS_Unknown) {
1580 SCCFinder.Start(I);
1581 auto &SCC = SCCFinder.getComponentFor(I);
Daniel Berlin2f72b192017-04-14 02:53:37 +00001582 // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1583 if (SCC.size() == 1)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001584 InstCycleState.insert({I, ICS_CycleFree});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001585 else {
1586 bool AllPhis =
1587 llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001588 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
Daniel Berlin2f72b192017-04-14 02:53:37 +00001589 for (auto *Member : SCC)
1590 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001591 InstCycleState.insert({MemberPhi, ICS});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001592 }
1593 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001594 if (ICS == ICS_Cycle)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001595 return false;
1596 return true;
1597}
1598
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001599// Evaluate PHI nodes symbolically and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001600const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001601 // True if one of the incoming phi edges is a backedge.
1602 bool HasBackedge = false;
1603 // All constant tracks the state of whether all the *original* phi operands
Daniel Berline021d2d2017-05-19 20:22:20 +00001604 // This is really shorthand for "this phi cannot cycle due to forward
1605 // change in value of the phi is guaranteed not to later change the value of
1606 // the phi. IE it can't be v = phi(undef, v+1)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001607 bool AllConstant = true;
Daniel Berlinabd632d2017-05-16 06:06:12 +00001608 auto *E =
1609 cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001610 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001611 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001612 // We track if any were undef because they need special handling.
1613 bool HasUndef = false;
Daniel Berline021d2d2017-05-19 20:22:20 +00001614 auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
Daniel Berlind92e7f92017-01-07 00:01:42 +00001615 if (isa<UndefValue>(Arg)) {
1616 HasUndef = true;
1617 return false;
1618 }
1619 return true;
1620 });
Daniel Berline021d2d2017-05-19 20:22:20 +00001621 // If we are left with no operands, it's dead.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001622 if (Filtered.begin() == Filtered.end()) {
Daniel Berline67c3222017-05-25 15:44:20 +00001623 // If it has undef at this point, it means there are no-non-undef arguments,
1624 // and thus, the value of the phi node must be undef.
1625 if (HasUndef) {
1626 DEBUG(dbgs() << "PHI Node " << *I
1627 << " has no non-undef arguments, valuing it as undef\n");
1628 return createConstantExpression(UndefValue::get(I->getType()));
1629 }
1630
Daniel Berline021d2d2017-05-19 20:22:20 +00001631 DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001632 deleteExpression(E);
Daniel Berline021d2d2017-05-19 20:22:20 +00001633 return createDeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00001634 }
Daniel Berlin2f72b192017-04-14 02:53:37 +00001635 unsigned NumOps = 0;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001636 Value *AllSameValue = *(Filtered.begin());
1637 ++Filtered.begin();
1638 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berline021d2d2017-05-19 20:22:20 +00001639 if (llvm::all_of(Filtered, [&](Value *Arg) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001640 ++NumOps;
Daniel Berline021d2d2017-05-19 20:22:20 +00001641 return Arg == AllSameValue;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001642 })) {
1643 // In LLVM's non-standard representation of phi nodes, it's possible to have
1644 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1645 // on the original phi node), especially in weird CFG's where some arguments
1646 // are unreachable, or uninitialized along certain paths. This can cause
1647 // infinite loops during evaluation. We work around this by not trying to
1648 // really evaluate them independently, but instead using a variable
1649 // expression to say if one is equivalent to the other.
1650 // We also special case undef, so that if we have an undef, we can't use the
1651 // common value unless it dominates the phi block.
1652 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001653 // If we have undef and at least one other value, this is really a
1654 // multivalued phi, and we need to know if it's cycle free in order to
1655 // evaluate whether we can ignore the undef. The other parts of this are
1656 // just shortcuts. If there is no backedge, or all operands are
1657 // constants, or all operands are ignored but the undef, it also must be
1658 // cycle free.
1659 if (!AllConstant && HasBackedge && NumOps > 0 &&
Daniel Berline67c3222017-05-25 15:44:20 +00001660 !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
Daniel Berlin2f72b192017-04-14 02:53:37 +00001661 return E;
1662
Daniel Berlind92e7f92017-01-07 00:01:42 +00001663 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001664 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001665 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001666 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001667 }
Daniel Berlineafdd862017-06-06 17:15:28 +00001668 // Can't simplify to something that comes later in the iteration.
1669 // Otherwise, when and if it changes congruence class, we will never catch
1670 // up. We will always be a class behind it.
1671 if (isa<Instruction>(AllSameValue) &&
1672 InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
1673 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001674 NumGVNPhisAllSame++;
1675 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1676 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001677 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001678 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001679 }
1680 return E;
1681}
1682
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001683const Expression *
1684NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001685 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1686 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1687 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1688 unsigned Opcode = 0;
1689 // EI might be an extract from one of our recognised intrinsics. If it
1690 // is we'll synthesize a semantically equivalent expression instead on
1691 // an extract value expression.
1692 switch (II->getIntrinsicID()) {
1693 case Intrinsic::sadd_with_overflow:
1694 case Intrinsic::uadd_with_overflow:
1695 Opcode = Instruction::Add;
1696 break;
1697 case Intrinsic::ssub_with_overflow:
1698 case Intrinsic::usub_with_overflow:
1699 Opcode = Instruction::Sub;
1700 break;
1701 case Intrinsic::smul_with_overflow:
1702 case Intrinsic::umul_with_overflow:
1703 Opcode = Instruction::Mul;
1704 break;
1705 default:
1706 break;
1707 }
1708
1709 if (Opcode != 0) {
1710 // Intrinsic recognized. Grab its args to finish building the
1711 // expression.
1712 assert(II->getNumArgOperands() == 2 &&
1713 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001714 return createBinaryExpression(
1715 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001716 }
1717 }
1718 }
1719
Daniel Berlin97718e62017-01-31 22:32:03 +00001720 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001721}
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001722const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
Chad Rosier4d852592017-08-08 18:41:49 +00001723 assert(isa<CmpInst>(I) && "Expected a cmp instruction.");
1724
1725 auto *CI = cast<CmpInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001726 // See if our operands are equal to those of a previous predicate, and if so,
1727 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001728 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1729 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001730 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001731 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001732 std::swap(Op0, Op1);
1733 OurPredicate = CI->getSwappedPredicate();
1734 }
1735
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001736 // Avoid processing the same info twice.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001737 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001738 // See if we know something about the comparison itself, like it is the target
1739 // of an assume.
1740 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1741 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1742 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1743
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001744 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001745 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001746 if (CI->isTrueWhenEqual())
1747 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1748 else if (CI->isFalseWhenEqual())
1749 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1750 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001751
1752 // NOTE: Because we are comparing both operands here and below, and using
1753 // previous comparisons, we rely on fact that predicateinfo knows to mark
1754 // comparisons that use renamed operands as users of the earlier comparisons.
1755 // It is *not* enough to just mark predicateinfo renamed operands as users of
1756 // the earlier comparisons, because the *other* operand may have changed in a
1757 // previous iteration.
1758 // Example:
1759 // icmp slt %a, %b
1760 // %b.0 = ssa.copy(%b)
1761 // false branch:
1762 // icmp slt %c, %b.0
1763
1764 // %c and %a may start out equal, and thus, the code below will say the second
1765 // %icmp is false. c may become equal to something else, and in that case the
1766 // %second icmp *must* be reexamined, but would not if only the renamed
1767 // %operands are considered users of the icmp.
1768
1769 // *Currently* we only check one level of comparisons back, and only mark one
Sanjay Patel7cf745c2017-08-03 15:18:27 +00001770 // level back as touched when changes happen. If you modify this code to look
Daniel Berlinf7d95802017-02-18 23:06:50 +00001771 // back farther through comparisons, you *must* mark the appropriate
1772 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1773 // we know something just from the operands themselves
1774
1775 // See if our operands have predicate info, so that we may be able to derive
1776 // something from a previous comparison.
1777 for (const auto &Op : CI->operands()) {
1778 auto *PI = PredInfo->getPredicateInfoFor(Op);
1779 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1780 if (PI == LastPredInfo)
1781 continue;
1782 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001783
Daniel Berlinf7d95802017-02-18 23:06:50 +00001784 // TODO: Along the false edge, we may know more things too, like icmp of
1785 // same operands is false.
1786 // TODO: We only handle actual comparison conditions below, not and/or.
1787 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1788 if (!BranchCond)
1789 continue;
1790 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1791 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1792 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001793 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001794 std::swap(BranchOp0, BranchOp1);
1795 BranchPredicate = BranchCond->getSwappedPredicate();
1796 }
1797 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1798 if (PBranch->TrueEdge) {
1799 // If we know the previous predicate is true and we are in the true
1800 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001801 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1802 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001803 addPredicateUsers(PI, I);
1804 return createConstantExpression(
1805 ConstantInt::getTrue(CI->getType()));
1806 }
1807
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001808 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1809 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001810 addPredicateUsers(PI, I);
1811 return createConstantExpression(
1812 ConstantInt::getFalse(CI->getType()));
1813 }
1814
1815 } else {
1816 // Just handle the ne and eq cases, where if we have the same
1817 // operands, we may know something.
1818 if (BranchPredicate == OurPredicate) {
1819 addPredicateUsers(PI, I);
1820 // Same predicate, same ops,we know it was false, so this is false.
1821 return createConstantExpression(
1822 ConstantInt::getFalse(CI->getType()));
1823 } else if (BranchPredicate ==
1824 CmpInst::getInversePredicate(OurPredicate)) {
1825 addPredicateUsers(PI, I);
1826 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001827 return createConstantExpression(
1828 ConstantInt::getTrue(CI->getType()));
1829 }
1830 }
1831 }
1832 }
1833 }
1834 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001835 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001836}
Davide Italiano7e274e02016-12-22 16:03:48 +00001837
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001838// Return true if V is a value that will always be available (IE can
1839// be placed anywhere) in the function. We don't do globals here
1840// because they are often worse to put in place.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001841static bool alwaysAvailable(Value *V) {
1842 return isa<Constant>(V) || isa<Argument>(V);
1843}
1844
Davide Italiano7e274e02016-12-22 16:03:48 +00001845// Substitute and symbolize the value before value numbering.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001846const Expression *
1847NewGVN::performSymbolicEvaluation(Value *V,
1848 SmallPtrSetImpl<Value *> &Visited) const {
Davide Italiano0e714802016-12-28 14:00:11 +00001849 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001850 if (auto *C = dyn_cast<Constant>(V))
1851 E = createConstantExpression(C);
1852 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1853 E = createVariableExpression(V);
1854 } else {
1855 // TODO: memory intrinsics.
1856 // TODO: Some day, we should do the forward propagation and reassociation
1857 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001858 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001859 switch (I->getOpcode()) {
1860 case Instruction::ExtractValue:
1861 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001862 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001863 break;
1864 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001865 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001866 break;
1867 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001868 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001869 break;
1870 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001871 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001872 break;
1873 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001874 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001875 break;
1876 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001877 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001878 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001879 case Instruction::ICmp:
1880 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001881 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001882 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001883 case Instruction::Add:
1884 case Instruction::FAdd:
1885 case Instruction::Sub:
1886 case Instruction::FSub:
1887 case Instruction::Mul:
1888 case Instruction::FMul:
1889 case Instruction::UDiv:
1890 case Instruction::SDiv:
1891 case Instruction::FDiv:
1892 case Instruction::URem:
1893 case Instruction::SRem:
1894 case Instruction::FRem:
1895 case Instruction::Shl:
1896 case Instruction::LShr:
1897 case Instruction::AShr:
1898 case Instruction::And:
1899 case Instruction::Or:
1900 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001901 case Instruction::Trunc:
1902 case Instruction::ZExt:
1903 case Instruction::SExt:
1904 case Instruction::FPToUI:
1905 case Instruction::FPToSI:
1906 case Instruction::UIToFP:
1907 case Instruction::SIToFP:
1908 case Instruction::FPTrunc:
1909 case Instruction::FPExt:
1910 case Instruction::PtrToInt:
1911 case Instruction::IntToPtr:
1912 case Instruction::Select:
1913 case Instruction::ExtractElement:
1914 case Instruction::InsertElement:
1915 case Instruction::ShuffleVector:
1916 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001917 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001918 break;
1919 default:
1920 return nullptr;
1921 }
1922 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001923 return E;
1924}
1925
Daniel Berlin0207cca2017-05-21 23:41:56 +00001926// Look up a container in a map, and then call a function for each thing in the
1927// found container.
1928template <typename Map, typename KeyType, typename Func>
1929void NewGVN::for_each_found(Map &M, const KeyType &Key, Func F) {
1930 const auto Result = M.find_as(Key);
1931 if (Result != M.end())
1932 for (typename Map::mapped_type::value_type Mapped : Result->second)
1933 F(Mapped);
1934}
1935
1936// Look up a container of values/instructions in a map, and touch all the
1937// instructions in the container. Then erase value from the map.
1938template <typename Map, typename KeyType>
1939void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
1940 const auto Result = M.find_as(Key);
1941 if (Result != M.end()) {
1942 for (const typename Map::mapped_type::value_type Mapped : Result->second)
1943 TouchedInstructions.set(InstrToDFSNum(Mapped));
1944 M.erase(Result);
1945 }
1946}
1947
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001948void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00001949 if (isa<Instruction>(To))
1950 AdditionalUsers[To].insert(User);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001951}
1952
Davide Italiano7e274e02016-12-22 16:03:48 +00001953void NewGVN::markUsersTouched(Value *V) {
1954 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001955 for (auto *User : V->users()) {
1956 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001957 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001958 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00001959 touchAndErase(AdditionalUsers, V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001960}
1961
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001962void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001963 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1964 MemoryToUsers[To].insert(U);
1965}
1966
1967void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001968 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00001969}
1970
1971void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1972 if (isa<MemoryUse>(MA))
1973 return;
1974 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00001975 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin0207cca2017-05-21 23:41:56 +00001976 touchAndErase(MemoryToUsers, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001977}
1978
Daniel Berlinf7d95802017-02-18 23:06:50 +00001979// Add I to the set of users of a given predicate.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001980void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001981 // Don't add temporary instructions to the user lists.
1982 if (AllTempInstructions.count(I))
1983 return;
1984
Daniel Berlinf7d95802017-02-18 23:06:50 +00001985 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1986 PredicateToUsers[PBranch->Condition].insert(I);
1987 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1988 PredicateToUsers[PAssume->Condition].insert(I);
1989}
1990
1991// Touch all the predicates that depend on this instruction.
1992void NewGVN::markPredicateUsersTouched(Instruction *I) {
Daniel Berlin0207cca2017-05-21 23:41:56 +00001993 touchAndErase(PredicateToUsers, I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001994}
1995
Daniel Berlin1316a942017-04-06 18:52:50 +00001996// Mark users affected by a memory leader change.
1997void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001998 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00001999 markMemoryDefTouched(M);
2000}
2001
Daniel Berlin32f8d562017-01-07 16:55:14 +00002002// Touch the instructions that need to be updated after a congruence class has a
2003// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00002004void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00002005 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00002006 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002007 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002008 LeaderChanges.insert(M);
2009 }
2010}
2011
Daniel Berlin1316a942017-04-06 18:52:50 +00002012// Give a range of things that have instruction DFS numbers, this will return
2013// the member of the range with the smallest dfs number.
2014template <class T, class Range>
2015T *NewGVN::getMinDFSOfRange(const Range &R) const {
2016 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
2017 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002018 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00002019 if (DFSNum < MinDFS.second)
2020 MinDFS = {X, DFSNum};
2021 }
2022 return MinDFS.first;
2023}
2024
2025// This function returns the MemoryAccess that should be the next leader of
2026// congruence class CC, under the assumption that the current leader is going to
2027// disappear.
2028const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
2029 // TODO: If this ends up to slow, we can maintain a next memory leader like we
2030 // do for regular leaders.
Daniel Berlinde269f42017-08-26 07:37:11 +00002031 // Make sure there will be a leader to find.
Davide Italianodc435322017-05-10 19:57:43 +00002032 assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00002033 if (CC->getStoreCount() > 0) {
2034 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002035 return getMemoryAccess(NL);
Daniel Berlin1316a942017-04-06 18:52:50 +00002036 // Find the store with the minimum DFS number.
2037 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00002038 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002039 return getMemoryAccess(cast<StoreInst>(V));
Daniel Berlin1316a942017-04-06 18:52:50 +00002040 }
Daniel Berlina8236562017-04-07 18:38:09 +00002041 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00002042
2043 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00002044 // !OldClass->memory_empty()
2045 if (CC->memory_size() == 1)
2046 return *CC->memory_begin();
2047 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00002048}
2049
2050// This function returns the next value leader of a congruence class, under the
2051// assumption that the current leader is going away. This should end up being
2052// the next most dominating member.
2053Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
2054 // We don't need to sort members if there is only 1, and we don't care about
2055 // sorting the TOP class because everything either gets out of it or is
2056 // unreachable.
2057
Daniel Berlina8236562017-04-07 18:38:09 +00002058 if (CC->size() == 1 || CC == TOPClass) {
2059 return *(CC->begin());
2060 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002061 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00002062 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00002063 } else {
2064 ++NumGVNSortedLeaderChanges;
2065 // NOTE: If this ends up to slow, we can maintain a dual structure for
2066 // member testing/insertion, or keep things mostly sorted, and sort only
2067 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00002068 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00002069 }
2070}
2071
2072// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
2073// the memory members, etc for the move.
2074//
2075// The invariants of this function are:
2076//
Davide Italianofb4544c2017-07-11 19:15:36 +00002077// - I must be moving to NewClass from OldClass
2078// - The StoreCount of OldClass and NewClass is expected to have been updated
2079// for I already if it is is a store.
2080// - The OldClass memory leader has not been updated yet if I was the leader.
Daniel Berlin1316a942017-04-06 18:52:50 +00002081void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
2082 MemoryAccess *InstMA,
2083 CongruenceClass *OldClass,
2084 CongruenceClass *NewClass) {
2085 // If the leader is I, and we had a represenative MemoryAccess, it should
2086 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00002087 assert((!InstMA || !OldClass->getMemoryLeader() ||
2088 OldClass->getLeader() != I ||
Davide Italianoee1c8212017-07-11 19:49:12 +00002089 MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
2090 MemoryAccessToClass.lookup(InstMA)) &&
Davide Italianof58a30232017-04-10 23:08:35 +00002091 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00002092 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00002093 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002094 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00002095 assert(NewClass->size() == 1 ||
2096 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
2097 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00002098 // Mark it touched if we didn't just create a singleton
Daniel Berlina8236562017-04-07 18:38:09 +00002099 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002100 << " due to new memory instruction becoming leader\n");
2101 markMemoryLeaderChangeTouched(NewClass);
2102 }
2103 setMemoryClass(InstMA, NewClass);
2104 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00002105 if (OldClass->getMemoryLeader() == InstMA) {
Davide Italianodc435322017-05-10 19:57:43 +00002106 if (!OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00002107 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2108 DEBUG(dbgs() << "Memory class leader change for class "
2109 << OldClass->getID() << " to "
2110 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00002111 << " due to removal of old leader " << *InstMA << "\n");
2112 markMemoryLeaderChangeTouched(OldClass);
2113 } else
Daniel Berlina8236562017-04-07 18:38:09 +00002114 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00002115 }
2116}
2117
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002118// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00002119// Update OldClass and NewClass for the move (including changing leaders, etc).
2120void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002121 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002122 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00002123 if (I == OldClass->getNextLeader().first)
2124 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002125
Daniel Berlinff152002017-05-19 19:01:24 +00002126 OldClass->erase(I);
2127 NewClass->insert(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002128
Daniel Berlina8236562017-04-07 18:38:09 +00002129 if (NewClass->getLeader() != I)
2130 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlin1316a942017-04-06 18:52:50 +00002131 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002132 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002133 OldClass->decStoreCount();
2134 // Okay, so when do we want to make a store a leader of a class?
2135 // If we have a store defined by an earlier load, we want the earlier load
2136 // to lead the class.
2137 // If we have a store defined by something else, we want the store to lead
2138 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00002139 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00002140 // as the leader
2141 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002142 // If it's a store expression we are using, it means we are not equivalent
2143 // to something earlier.
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002144 if (auto *SE = dyn_cast<StoreExpression>(E)) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002145 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1316a942017-04-06 18:52:50 +00002146 markValueLeaderChangeTouched(NewClass);
2147 // Shift the new class leader to be the store
Daniel Berlina8236562017-04-07 18:38:09 +00002148 DEBUG(dbgs() << "Changing leader of congruence class "
2149 << NewClass->getID() << " from " << *NewClass->getLeader()
2150 << " to " << *SI << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002151 // If we changed the leader, we have to mark it changed because we don't
Davide Italiano67b0e532017-07-11 19:19:45 +00002152 // know what it will do to symbolic evaluation.
Daniel Berlina8236562017-04-07 18:38:09 +00002153 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002154 }
2155 // We rely on the code below handling the MemoryAccess change.
2156 }
Daniel Berlina8236562017-04-07 18:38:09 +00002157 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002158 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002159 // True if there is no memory instructions left in a class that had memory
2160 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002161
Daniel Berlin1316a942017-04-06 18:52:50 +00002162 // If it's not a memory use, set the MemoryAccess equivalence
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002163 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
Daniel Berlin1316a942017-04-06 18:52:50 +00002164 if (InstMA)
2165 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002166 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002167 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00002168 if (OldClass->empty() && OldClass != TOPClass) {
2169 if (OldClass->getDefiningExpr()) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002170 DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002171 << " from table\n");
Daniel Berlineafdd862017-06-06 17:15:28 +00002172 // We erase it as an exact expression to make sure we don't just erase an
2173 // equivalent one.
2174 auto Iter = ExpressionToClass.find_as(
2175 ExactEqualsExpression(*OldClass->getDefiningExpr()));
2176 if (Iter != ExpressionToClass.end())
2177 ExpressionToClass.erase(Iter);
2178#ifdef EXPENSIVE_CHECKS
2179 assert(
2180 (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
2181 "We erased the expression we just inserted, which should not happen");
2182#endif
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002183 }
Daniel Berlina8236562017-04-07 18:38:09 +00002184 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002185 // When the leader changes, the value numbering of
2186 // everything may change due to symbolization changes, so we need to
2187 // reprocess.
Daniel Berlina8236562017-04-07 18:38:09 +00002188 DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002189 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002190 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00002191 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002192 // Note that this is basically clean up for the expression removal that
2193 // happens below. If we remove stores from a class, we may leave it as a
2194 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002195 if (OldClass->getStoreCount() == 0) {
2196 if (OldClass->getStoredValue())
2197 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002198 }
Daniel Berlina8236562017-04-07 18:38:09 +00002199 OldClass->setLeader(getNextValueLeader(OldClass));
2200 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002201 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002202 }
2203}
2204
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002205// For a given expression, mark the phi of ops instructions that could have
2206// changed as a result.
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002207void NewGVN::markPhiOfOpsChanged(const Expression *E) {
Daniel Berlin51e878e2017-06-14 21:19:28 +00002208 touchAndErase(ExpressionToPhiOfOps, ExactEqualsExpression(*E));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002209}
Daniel Berlin0207cca2017-05-21 23:41:56 +00002210
Davide Italiano7e274e02016-12-22 16:03:48 +00002211// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002212void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002213 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002214 // TOP.
Daniel Berline021d2d2017-05-19 20:22:20 +00002215
2216 CongruenceClass *IClass = ValueToClass.lookup(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002217 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002218 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002219 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002220
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002221 CongruenceClass *EClass = nullptr;
Daniel Berlin02c6b172017-01-02 18:00:53 +00002222 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002223 EClass = ValueToClass.lookup(VE->getVariableValue());
Daniel Berline021d2d2017-05-19 20:22:20 +00002224 } else if (isa<DeadExpression>(E)) {
2225 EClass = TOPClass;
2226 }
2227 if (!EClass) {
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002228 auto lookupResult = ExpressionToClass.insert({E, nullptr});
Davide Italiano7e274e02016-12-22 16:03:48 +00002229
2230 // If it's not in the value table, create a new congruence class.
2231 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002232 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002233 auto place = lookupResult.first;
2234 place->second = NewClass;
2235
2236 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002237 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002238 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002239 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2240 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002241 NewClass->setLeader(SI);
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002242 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002243 // The RepMemoryAccess field will be filled in properly by the
2244 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002245 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002246 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002247 }
2248 assert(!isa<VariableExpression>(E) &&
2249 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002250
2251 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002252 DEBUG(dbgs() << "Created new congruence class for " << *I
Daniel Berlina8236562017-04-07 18:38:09 +00002253 << " using expression " << *E << " at " << NewClass->getID()
2254 << " and leader " << *(NewClass->getLeader()));
2255 if (NewClass->getStoredValue())
2256 DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
Daniel Berlin26addef2017-01-20 21:04:30 +00002257 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002258 } else {
2259 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002260 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002261 assert((isa<Constant>(EClass->getLeader()) ||
2262 (EClass->getStoredValue() &&
2263 isa<Constant>(EClass->getStoredValue()))) &&
2264 "Any class with a constant expression should have a "
2265 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002266
Davide Italiano7e274e02016-12-22 16:03:48 +00002267 assert(EClass && "Somehow don't have an eclass");
2268
Daniel Berlin1316a942017-04-06 18:52:50 +00002269 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002270 }
2271 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002272 bool ClassChanged = IClass != EClass;
2273 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002274 if (ClassChanged || LeaderChanged) {
Daniel Berlina8236562017-04-07 18:38:09 +00002275 DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00002276 << "\n");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002277 if (ClassChanged) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002278 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlin2aa5dc12017-05-30 06:58:18 +00002279 markPhiOfOpsChanged(E);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002280 }
2281
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002282 markUsersTouched(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002283 if (MemoryAccess *MA = getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002284 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002285 if (auto *CI = dyn_cast<CmpInst>(I))
2286 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002287 }
Daniel Berlin45403572017-05-16 19:58:47 +00002288 // If we changed the class of the store, we want to ensure nothing finds the
2289 // old store expression. In particular, loads do not compare against stored
2290 // value, so they will find old store expressions (and associated class
2291 // mappings) if we leave them in the table.
Davide Italianoee49f492017-05-19 04:06:10 +00002292 if (ClassChanged && isa<StoreInst>(I)) {
Daniel Berlin45403572017-05-16 19:58:47 +00002293 auto *OldE = ValueToExpression.lookup(I);
2294 // It could just be that the old class died. We don't want to erase it if we
2295 // just moved classes.
Daniel Berlineafdd862017-06-06 17:15:28 +00002296 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
2297 // Erase this as an exact expression to ensure we don't erase expressions
2298 // equivalent to it.
2299 auto Iter = ExpressionToClass.find_as(ExactEqualsExpression(*OldE));
2300 if (Iter != ExpressionToClass.end())
2301 ExpressionToClass.erase(Iter);
2302 }
Daniel Berlin45403572017-05-16 19:58:47 +00002303 }
2304 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002305}
2306
2307// Process the fact that Edge (from, to) is reachable, including marking
2308// any newly reachable blocks and instructions for processing.
2309void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2310 // Check if the Edge was reachable before.
2311 if (ReachableEdges.insert({From, To}).second) {
2312 // If this block wasn't reachable before, all instructions are touched.
2313 if (ReachableBlocks.insert(To).second) {
2314 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2315 const auto &InstRange = BlockInstRange.lookup(To);
2316 TouchedInstructions.set(InstRange.first, InstRange.second);
2317 } else {
2318 DEBUG(dbgs() << "Block " << getBlockName(To)
2319 << " was reachable, but new edge {" << getBlockName(From)
2320 << "," << getBlockName(To) << "} to it found\n");
2321
2322 // We've made an edge reachable to an existing block, which may
2323 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2324 // they are the only thing that depend on new edges. Anything using their
2325 // values will get propagated to if necessary.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002326 if (MemoryAccess *MemPhi = getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002327 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002328
Davide Italiano7e274e02016-12-22 16:03:48 +00002329 auto BI = To->begin();
2330 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002331 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00002332 ++BI;
2333 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00002334 for_each_found(PHIOfOpsPHIs, To, [&](const PHINode *I) {
2335 TouchedInstructions.set(InstrToDFSNum(I));
2336 });
Davide Italiano7e274e02016-12-22 16:03:48 +00002337 }
2338 }
2339}
2340
2341// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2342// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002343Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002344 auto Result = lookupOperandLeader(Cond);
Davide Italianodaa9c0e2017-06-19 16:46:15 +00002345 return isa<Constant>(Result) ? Result : nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002346}
2347
2348// Process the outgoing edges of a block for reachability.
2349void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2350 // Evaluate reachability of terminator instruction.
2351 BranchInst *BR;
2352 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2353 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002354 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002355 if (!CondEvaluated) {
2356 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002357 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002358 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2359 CondEvaluated = CE->getConstantValue();
2360 }
2361 } else if (isa<ConstantInt>(Cond)) {
2362 CondEvaluated = Cond;
2363 }
2364 }
2365 ConstantInt *CI;
2366 BasicBlock *TrueSucc = BR->getSuccessor(0);
2367 BasicBlock *FalseSucc = BR->getSuccessor(1);
2368 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2369 if (CI->isOne()) {
2370 DEBUG(dbgs() << "Condition for Terminator " << *TI
2371 << " evaluated to true\n");
2372 updateReachableEdge(B, TrueSucc);
2373 } else if (CI->isZero()) {
2374 DEBUG(dbgs() << "Condition for Terminator " << *TI
2375 << " evaluated to false\n");
2376 updateReachableEdge(B, FalseSucc);
2377 }
2378 } else {
2379 updateReachableEdge(B, TrueSucc);
2380 updateReachableEdge(B, FalseSucc);
2381 }
2382 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2383 // For switches, propagate the case values into the case
2384 // destinations.
2385
2386 // Remember how many outgoing edges there are to every successor.
2387 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2388
Davide Italiano7e274e02016-12-22 16:03:48 +00002389 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002390 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002391 // See if we were able to turn this switch statement into a constant.
2392 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002393 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002394 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002395 auto Case = *SI->findCaseValue(CondVal);
2396 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002397 // We proved the value is outside of the range of the case.
2398 // We can't do anything other than mark the default dest as reachable,
2399 // and go home.
2400 updateReachableEdge(B, SI->getDefaultDest());
2401 return;
2402 }
2403 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002404 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002405 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002406 } else {
2407 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2408 BasicBlock *TargetBlock = SI->getSuccessor(i);
2409 ++SwitchEdges[TargetBlock];
2410 updateReachableEdge(B, TargetBlock);
2411 }
2412 }
2413 } else {
2414 // Otherwise this is either unconditional, or a type we have no
2415 // idea about. Just mark successors as reachable.
2416 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2417 BasicBlock *TargetBlock = TI->getSuccessor(i);
2418 updateReachableEdge(B, TargetBlock);
2419 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002420
2421 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002422 // equivalent only to itself.
2423 //
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002424 auto *MA = getMemoryAccess(TI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002425 if (MA && !isa<MemoryUse>(MA)) {
2426 auto *CC = ensureLeaderOfMemoryClass(MA);
2427 if (setMemoryClass(MA, CC))
2428 markMemoryUsersTouched(MA);
2429 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002430 }
2431}
2432
Davide Italiano5974c312017-08-03 21:17:49 +00002433// Remove the PHI of Ops PHI for I
2434void NewGVN::removePhiOfOps(Instruction *I, PHINode *PHITemp) {
2435 InstrDFS.erase(PHITemp);
2436 // It's still a temp instruction. We keep it in the array so it gets erased.
2437 // However, it's no longer used by I, or in the block/
2438 PHIOfOpsPHIs[getBlockForValue(PHITemp)].erase(PHITemp);
2439 TempToBlock.erase(PHITemp);
2440 RealToTemp.erase(I);
2441}
2442
2443// Add PHI Op in BB as a PHI of operations version of ExistingValue.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002444void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
2445 Instruction *ExistingValue) {
2446 InstrDFS[Op] = InstrToDFSNum(ExistingValue);
2447 AllTempInstructions.insert(Op);
Davide Italiano5974c312017-08-03 21:17:49 +00002448 PHIOfOpsPHIs[BB].insert(Op);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002449 TempToBlock[Op] = BB;
Daniel Berlinb779db72017-06-29 17:01:10 +00002450 RealToTemp[ExistingValue] = Op;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002451}
2452
2453static bool okayForPHIOfOps(const Instruction *I) {
Chad Rosiera5508e32017-08-10 14:12:57 +00002454 if (!EnablePhiOfOps)
2455 return false;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002456 return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
2457 isa<LoadInst>(I);
2458}
2459
2460// When we see an instruction that is an op of phis, generate the equivalent phi
2461// of ops form.
2462const Expression *
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002463NewGVN::makePossiblePhiOfOps(Instruction *I,
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002464 SmallPtrSetImpl<Value *> &Visited) {
2465 if (!okayForPHIOfOps(I))
2466 return nullptr;
2467
2468 if (!Visited.insert(I).second)
2469 return nullptr;
2470 // For now, we require the instruction be cycle free because we don't
2471 // *always* create a phi of ops for instructions that could be done as phi
2472 // of ops, we only do it if we think it is useful. If we did do it all the
2473 // time, we could remove the cycle free check.
2474 if (!isCycleFree(I))
2475 return nullptr;
2476
2477 unsigned IDFSNum = InstrToDFSNum(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002478 SmallPtrSet<const Value *, 8> ProcessedPHIs;
2479 // TODO: We don't do phi translation on memory accesses because it's
2480 // complicated. For a load, we'd need to be able to simulate a new memoryuse,
2481 // which we don't have a good way of doing ATM.
2482 auto *MemAccess = getMemoryAccess(I);
2483 // If the memory operation is defined by a memory operation this block that
2484 // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
2485 // can't help, as it would still be killed by that memory operation.
2486 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2487 MemAccess->getDefiningAccess()->getBlock() == I->getParent())
2488 return nullptr;
2489
2490 // Convert op of phis to phi of ops
2491 for (auto &Op : I->operands()) {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002492 // TODO: We can't handle expressions that must be recursively translated
2493 // IE
2494 // a = phi (b, c)
2495 // f = use a
2496 // g = f + phi of something
2497 // To properly make a phi of ops for g, we'd have to properly translate and
2498 // use the instruction for f. We should add this by splitting out the
2499 // instruction creation we do below.
2500 if (isa<Instruction>(Op) && PHINodeUses.count(cast<Instruction>(Op)))
2501 return nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002502 if (!isa<PHINode>(Op))
2503 continue;
2504 auto *OpPHI = cast<PHINode>(Op);
2505 // No point in doing this for one-operand phis.
2506 if (OpPHI->getNumOperands() == 1)
2507 continue;
2508 if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
2509 return nullptr;
2510 SmallVector<std::pair<Value *, BasicBlock *>, 4> Ops;
2511 auto *PHIBlock = getBlockForValue(OpPHI);
2512 for (auto PredBB : OpPHI->blocks()) {
2513 Value *FoundVal = nullptr;
2514 // We could just skip unreachable edges entirely but it's tricky to do
2515 // with rewriting existing phi nodes.
2516 if (ReachableEdges.count({PredBB, PHIBlock})) {
2517 // Clone the instruction, create an expression from it, and see if we
2518 // have a leader.
2519 Instruction *ValueOp = I->clone();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002520 if (MemAccess)
Daniel Berlinc8ed4042017-05-30 06:42:29 +00002521 TempToMemory.insert({ValueOp, MemAccess});
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002522
2523 for (auto &Op : ValueOp->operands()) {
2524 Op = Op->DoPHITranslation(PHIBlock, PredBB);
2525 // When this operand changes, it could change whether there is a
2526 // leader for us or not.
2527 addAdditionalUsers(Op, I);
2528 }
2529 // Make sure it's marked as a temporary instruction.
2530 AllTempInstructions.insert(ValueOp);
2531 // and make sure anything that tries to add it's DFS number is
2532 // redirected to the instruction we are making a phi of ops
2533 // for.
2534 InstrDFS.insert({ValueOp, IDFSNum});
2535 const Expression *E = performSymbolicEvaluation(ValueOp, Visited);
2536 InstrDFS.erase(ValueOp);
2537 AllTempInstructions.erase(ValueOp);
2538 ValueOp->deleteValue();
2539 if (MemAccess)
Daniel Berlinc8ed4042017-05-30 06:42:29 +00002540 TempToMemory.erase(ValueOp);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002541 if (!E)
2542 return nullptr;
2543 FoundVal = findPhiOfOpsLeader(E, PredBB);
2544 if (!FoundVal) {
2545 ExpressionToPhiOfOps[E].insert(I);
2546 return nullptr;
2547 }
2548 if (auto *SI = dyn_cast<StoreInst>(FoundVal))
2549 FoundVal = SI->getValueOperand();
2550 } else {
2551 DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
2552 << getBlockName(PredBB)
2553 << " because the block is unreachable\n");
2554 FoundVal = UndefValue::get(I->getType());
2555 }
2556
2557 Ops.push_back({FoundVal, PredBB});
2558 DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
2559 << getBlockName(PredBB) << "\n");
2560 }
2561 auto *ValuePHI = RealToTemp.lookup(I);
2562 bool NewPHI = false;
2563 if (!ValuePHI) {
2564 ValuePHI = PHINode::Create(I->getType(), OpPHI->getNumOperands());
2565 addPhiOfOps(ValuePHI, PHIBlock, I);
2566 NewPHI = true;
2567 NumGVNPHIOfOpsCreated++;
2568 }
2569 if (NewPHI) {
2570 for (auto PHIOp : Ops)
2571 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2572 } else {
2573 unsigned int i = 0;
2574 for (auto PHIOp : Ops) {
2575 ValuePHI->setIncomingValue(i, PHIOp.first);
2576 ValuePHI->setIncomingBlock(i, PHIOp.second);
2577 ++i;
2578 }
2579 }
2580
2581 DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
2582 << "\n");
2583 return performSymbolicEvaluation(ValuePHI, Visited);
2584 }
2585 return nullptr;
2586}
2587
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002588// The algorithm initially places the values of the routine in the TOP
2589// congruence class. The leader of TOP is the undetermined value `undef`.
2590// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002591void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002592 NextCongruenceNum = 0;
2593
2594 // Note that even though we use the live on entry def as a representative
2595 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2596 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2597 // should be checking whether the MemoryAccess is top if we want to know if it
2598 // is equivalent to everything. Otherwise, what this really signifies is that
2599 // the access "it reaches all the way back to the beginning of the function"
2600
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002601 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002602 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002603 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002604 // The live on entry def gets put into it's own class
2605 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2606 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002607
Daniel Berlinec9deb72017-04-18 17:06:11 +00002608 for (auto DTN : nodes(DT)) {
2609 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002610 // All MemoryAccesses are equivalent to live on entry to start. They must
2611 // be initialized to something so that initial changes are noticed. For
2612 // the maximal answer, we initialize them all to be the same as
2613 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002614 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002615 if (MemoryBlockDefs)
2616 for (const auto &Def : *MemoryBlockDefs) {
2617 MemoryAccessToClass[&Def] = TOPClass;
2618 auto *MD = dyn_cast<MemoryDef>(&Def);
2619 // Insert the memory phis into the member list.
2620 if (!MD) {
2621 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002622 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002623 MemoryPhiState.insert({MP, MPS_TOP});
2624 }
2625
2626 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002627 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002628 }
Daniel Berlinec9deb72017-04-18 17:06:11 +00002629 for (auto &I : *BB) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002630 // TODO: Move to helper
2631 if (isa<PHINode>(&I))
2632 for (auto *U : I.users())
2633 if (auto *UInst = dyn_cast<Instruction>(U))
2634 if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
2635 PHINodeUses.insert(UInst);
Daniel Berlin22a4a012017-02-11 15:20:15 +00002636 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002637 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002638 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2639 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002640 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002641 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002642 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002643 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002644
2645 // Initialize arguments to be in their own unique congruence classes
2646 for (auto &FA : F.args())
2647 createSingletonCongruenceClass(&FA);
2648}
2649
2650void NewGVN::cleanupTables() {
2651 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Daniel Berlina8236562017-04-07 18:38:09 +00002652 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2653 << " has " << CongruenceClasses[i]->size() << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002654 // Make sure we delete the congruence class (probably worth switching to
2655 // a unique_ptr at some point.
2656 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002657 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002658 }
2659
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002660 // Destroy the value expressions
2661 SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
2662 AllTempInstructions.end());
2663 AllTempInstructions.clear();
2664
2665 // We have to drop all references for everything first, so there are no uses
2666 // left as we delete them.
2667 for (auto *I : TempInst) {
2668 I->dropAllReferences();
2669 }
2670
2671 while (!TempInst.empty()) {
2672 auto *I = TempInst.back();
2673 TempInst.pop_back();
2674 I->deleteValue();
2675 }
2676
Davide Italiano7e274e02016-12-22 16:03:48 +00002677 ValueToClass.clear();
2678 ArgRecycler.clear(ExpressionAllocator);
2679 ExpressionAllocator.Reset();
2680 CongruenceClasses.clear();
2681 ExpressionToClass.clear();
2682 ValueToExpression.clear();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002683 RealToTemp.clear();
2684 AdditionalUsers.clear();
2685 ExpressionToPhiOfOps.clear();
2686 TempToBlock.clear();
2687 TempToMemory.clear();
2688 PHIOfOpsPHIs.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002689 ReachableBlocks.clear();
2690 ReachableEdges.clear();
2691#ifndef NDEBUG
2692 ProcessedCount.clear();
2693#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002694 InstrDFS.clear();
2695 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002696 DFSToInstr.clear();
2697 BlockInstRange.clear();
2698 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002699 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002700 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002701 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002702}
2703
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002704// Assign local DFS number mapping to instructions, and leave space for Value
2705// PHI's.
Davide Italiano7e274e02016-12-22 16:03:48 +00002706std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2707 unsigned Start) {
2708 unsigned End = Start;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002709 if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002710 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002711 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002712 }
2713
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002714 // Then the real block goes next.
Davide Italiano7e274e02016-12-22 16:03:48 +00002715 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002716 // There's no need to call isInstructionTriviallyDead more than once on
2717 // an instruction. Therefore, once we know that an instruction is dead
2718 // we change its DFS number so that it doesn't get value numbered.
2719 if (isInstructionTriviallyDead(&I, TLI)) {
2720 InstrDFS[&I] = 0;
2721 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2722 markInstructionForDeletion(&I);
2723 continue;
2724 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002725 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002726 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002727 }
2728
2729 // All of the range functions taken half-open ranges (open on the end side).
2730 // So we do not subtract one from count, because at this point it is one
2731 // greater than the last instruction.
2732 return std::make_pair(Start, End);
2733}
2734
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002735void NewGVN::updateProcessedCount(const Value *V) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002736#ifndef NDEBUG
2737 if (ProcessedCount.count(V) == 0) {
2738 ProcessedCount.insert({V, 1});
2739 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002740 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002741 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002742 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002743 }
2744#endif
2745}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002746// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2747void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2748 // If all the arguments are the same, the MemoryPhi has the same value as the
Daniel Berlind130b6c2017-05-21 23:41:58 +00002749 // argument. Filter out unreachable blocks and self phis from our operands.
2750 // TODO: We could do cycle-checking on the memory phis to allow valueizing for
2751 // self-phi checking.
Daniel Berlin41b39162017-03-18 15:41:36 +00002752 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002753 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlind130b6c2017-05-21 23:41:58 +00002754 return cast<MemoryAccess>(U) != MP &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002755 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002756 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002757 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002758 // If all that is left is nothing, our memoryphi is undef. We keep it as
2759 // InitialClass. Note: The only case this should happen is if we have at
2760 // least one self-argument.
2761 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002762 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002763 markMemoryUsersTouched(MP);
2764 return;
2765 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002766
2767 // Transform the remaining operands into operand leaders.
2768 // FIXME: mapped_iterator should have a range version.
2769 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002770 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002771 };
2772 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2773 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2774
2775 // and now check if all the elements are equal.
2776 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002777 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002778 ++MappedBegin;
2779 bool AllEqual = std::all_of(
2780 MappedBegin, MappedEnd,
2781 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2782
2783 if (AllEqual)
2784 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2785 else
2786 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002787 // If it's equal to something, it's in that class. Otherwise, it has to be in
2788 // a class where it is the leader (other things may be equivalent to it, but
2789 // it needs to start off in its own class, which means it must have been the
2790 // leader, and it can't have stopped being the leader because it was never
2791 // removed).
2792 CongruenceClass *CC =
2793 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2794 auto OldState = MemoryPhiState.lookup(MP);
2795 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2796 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2797 MemoryPhiState[MP] = NewState;
2798 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002799 markMemoryUsersTouched(MP);
2800}
2801
2802// Value number a single instruction, symbolically evaluating, performing
2803// congruence finding, and updating mappings.
2804void NewGVN::valueNumberInstruction(Instruction *I) {
2805 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002806 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002807 const Expression *Symbolized = nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002808 SmallPtrSet<Value *, 2> Visited;
Daniel Berlin283a6082017-03-01 19:59:26 +00002809 if (DebugCounter::shouldExecute(VNCounter)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002810 Symbolized = performSymbolicEvaluation(I, Visited);
2811 // Make a phi of ops if necessary
2812 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
2813 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
Daniel Berlinbe3e7ba2017-05-31 01:47:32 +00002814 auto *PHIE = makePossiblePhiOfOps(I, Visited);
Davide Italiano5974c312017-08-03 21:17:49 +00002815 // If we created a phi of ops, use it.
2816 // If we couldn't create one, make sure we don't leave one lying around
2817 if (PHIE) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002818 Symbolized = PHIE;
Davide Italiano5974c312017-08-03 21:17:49 +00002819 } else if (auto *Op = RealToTemp.lookup(I)) {
2820 removePhiOfOps(I, Op);
2821 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002822 }
2823
Daniel Berlin283a6082017-03-01 19:59:26 +00002824 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002825 // Mark the instruction as unused so we don't value number it again.
2826 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002827 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002828 // If we couldn't come up with a symbolic expression, use the unknown
2829 // expression
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002830 if (Symbolized == nullptr)
Daniel Berlin02c6b172017-01-02 18:00:53 +00002831 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002832 performCongruenceFinding(I, Symbolized);
2833 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002834 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002835 // don't currently understand. We don't place non-value producing
2836 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002837 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002838 auto *Symbolized = createUnknownExpression(I);
2839 performCongruenceFinding(I, Symbolized);
2840 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002841 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2842 }
2843}
Davide Italiano7e274e02016-12-22 16:03:48 +00002844
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002845// Check if there is a path, using single or equal argument phi nodes, from
2846// First to Second.
Davide Italianoeab0de22017-05-18 23:22:44 +00002847bool NewGVN::singleReachablePHIPath(
2848 SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
2849 const MemoryAccess *Second) const {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002850 if (First == Second)
2851 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002852 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002853 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002854
Davide Italianoeab0de22017-05-18 23:22:44 +00002855 // This is not perfect, but as we're just verifying here, we can live with
2856 // the loss of precision. The real solution would be that of doing strongly
2857 // connected component finding in this routine, and it's probably not worth
2858 // the complexity for the time being. So, we just keep a set of visited
2859 // MemoryAccess and return true when we hit a cycle.
2860 if (Visited.count(First))
2861 return true;
2862 Visited.insert(First);
2863
Daniel Berlin871ecd92017-04-01 09:44:24 +00002864 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002865 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002866 if (ChainDef == Second)
2867 return true;
2868 if (MSSA->isLiveOnEntryDef(ChainDef))
2869 return false;
2870 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002871 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002872 auto *MP = cast<MemoryPhi>(EndDef);
2873 auto ReachableOperandPred = [&](const Use &U) {
2874 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2875 };
2876 auto FilteredPhiArgs =
2877 make_filter_range(MP->operands(), ReachableOperandPred);
2878 SmallVector<const Value *, 32> OperandList;
2879 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2880 std::back_inserter(OperandList));
2881 bool Okay = OperandList.size() == 1;
2882 if (!Okay)
2883 Okay =
2884 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2885 if (Okay)
Davide Italianoeab0de22017-05-18 23:22:44 +00002886 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
2887 Second);
Daniel Berlin871ecd92017-04-01 09:44:24 +00002888 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002889}
2890
Daniel Berlin589cecc2017-01-02 18:00:46 +00002891// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002892// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00002893// subject to very rare false negatives. It is only useful for
2894// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002895void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00002896#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002897 // Verify that the memory table equivalence and memory member set match
2898 for (const auto *CC : CongruenceClasses) {
2899 if (CC == TOPClass || CC->isDead())
2900 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002901 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00002902 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002903 "Any class with a store as a leader should have a "
2904 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00002905 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002906 "Any congruence class with a store should have a "
2907 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00002908 }
2909
Daniel Berlina8236562017-04-07 18:38:09 +00002910 if (CC->getMemoryLeader())
2911 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00002912 "Representative MemoryAccess does not appear to be reverse "
2913 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00002914 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002915 assert(MemoryAccessToClass.lookup(M) == CC &&
2916 "Memory member does not appear to be reverse mapped properly");
2917 }
2918
2919 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00002920 // congruence class.
2921
2922 // Filter out the unreachable and trivially dead entries, because they may
2923 // never have been updated if the instructions were not processed.
2924 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002925 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002926 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00002927 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2928 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00002929 return false;
2930 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2931 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Davide Italiano6e7a2122017-05-15 18:50:53 +00002932
2933 // We could have phi nodes which operands are all trivially dead,
2934 // so we don't process them.
2935 if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
2936 for (auto &U : MemPHI->incoming_values()) {
2937 if (Instruction *I = dyn_cast<Instruction>(U.get())) {
2938 if (!isInstructionTriviallyDead(I))
2939 return true;
2940 }
2941 }
2942 return false;
2943 }
2944
Daniel Berlin589cecc2017-01-02 18:00:46 +00002945 return true;
2946 };
2947
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002948 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002949 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002950 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002951 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italianoeab0de22017-05-18 23:22:44 +00002952 if (FirstMUD && SecondMUD) {
2953 SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
2954 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00002955 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2956 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2957 "The instructions for these memory operations should have "
2958 "been in the same congruence class or reachable through"
2959 "a single argument phi");
Davide Italianoeab0de22017-05-18 23:22:44 +00002960 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002961 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002962 // We can only sanely verify that MemoryDefs in the operand list all have
2963 // the same class.
2964 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00002965 return ReachableEdges.count(
2966 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00002967 isa<MemoryDef>(U);
2968
2969 };
2970 // All arguments should in the same class, ignoring unreachable arguments
2971 auto FilteredPhiArgs =
2972 make_filter_range(FirstMP->operands(), ReachableOperandPred);
2973 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2974 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2975 std::back_inserter(PhiOpClasses), [&](const Use &U) {
2976 const MemoryDef *MD = cast<MemoryDef>(U);
2977 return ValueToClass.lookup(MD->getMemoryInst());
2978 });
2979 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2980 PhiOpClasses.begin()) &&
2981 "All MemoryPhi arguments should be in the same class");
2982 }
2983 }
Davide Italianoe9781e72017-03-25 02:40:02 +00002984#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00002985}
2986
Daniel Berlin06329a92017-03-18 15:41:40 +00002987// Verify that the sparse propagation we did actually found the maximal fixpoint
2988// We do this by storing the value to class mapping, touching all instructions,
2989// and redoing the iteration to see if anything changed.
2990void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00002991#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002992 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00002993 if (DebugCounter::isCounterSet(VNCounter))
2994 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2995
2996 // Note that we have to store the actual classes, as we may change existing
2997 // classes during iteration. This is because our memory iteration propagation
2998 // is not perfect, and so may waste a little work. But it should generate
2999 // exactly the same congruence classes we have now, with different IDs.
3000 std::map<const Value *, CongruenceClass> BeforeIteration;
3001
3002 for (auto &KV : ValueToClass) {
3003 if (auto *I = dyn_cast<Instruction>(KV.first))
3004 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003005 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00003006 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00003007 BeforeIteration.insert({KV.first, *KV.second});
3008 }
3009
3010 TouchedInstructions.set();
3011 TouchedInstructions.reset(0);
3012 iterateTouchedInstructions();
3013 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
3014 EqualClasses;
3015 for (const auto &KV : ValueToClass) {
3016 if (auto *I = dyn_cast<Instruction>(KV.first))
3017 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003018 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00003019 continue;
3020 // We could sink these uses, but i think this adds a bit of clarity here as
3021 // to what we are comparing.
3022 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
3023 auto *AfterCC = KV.second;
3024 // Note that the classes can't change at this point, so we memoize the set
3025 // that are equal.
3026 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00003027 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00003028 "Value number changed after main loop completed!");
3029 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00003030 }
3031 }
3032#endif
3033}
3034
Daniel Berlin45403572017-05-16 19:58:47 +00003035// Verify that for each store expression in the expression to class mapping,
3036// only the latest appears, and multiple ones do not appear.
3037// Because loads do not use the stored value when doing equality with stores,
3038// if we don't erase the old store expressions from the table, a load can find
3039// a no-longer valid StoreExpression.
3040void NewGVN::verifyStoreExpressions() const {
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003041#ifndef NDEBUG
Daniel Berlin36b08b22017-06-19 00:24:00 +00003042 // This is the only use of this, and it's not worth defining a complicated
3043 // densemapinfo hash/equality function for it.
3044 std::set<
3045 std::pair<const Value *,
3046 std::tuple<const Value *, const CongruenceClass *, Value *>>>
3047 StoreExpressionSet;
Daniel Berlin45403572017-05-16 19:58:47 +00003048 for (const auto &KV : ExpressionToClass) {
3049 if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3050 // Make sure a version that will conflict with loads is not already there
Daniel Berlin36b08b22017-06-19 00:24:00 +00003051 auto Res = StoreExpressionSet.insert(
3052 {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
3053 SE->getStoredValue())});
3054 bool Okay = Res.second;
3055 // It's okay to have the same expression already in there if it is
3056 // identical in nature.
3057 // This can happen when the leader of the stored value changes over time.
Davide Italiano0ec715b2017-06-20 22:57:40 +00003058 if (!Okay)
3059 Okay = (std::get<1>(Res.first->second) == KV.second) &&
3060 (lookupOperandLeader(std::get<2>(Res.first->second)) ==
3061 lookupOperandLeader(SE->getStoredValue()));
Daniel Berlin36b08b22017-06-19 00:24:00 +00003062 assert(Okay && "Stored expression conflict exists in expression table");
Daniel Berlin45403572017-05-16 19:58:47 +00003063 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3064 assert(ValueExpr && ValueExpr->equals(*SE) &&
3065 "StoreExpression in ExpressionToClass is not latest "
3066 "StoreExpression for value");
3067 }
3068 }
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003069#endif
Daniel Berlin45403572017-05-16 19:58:47 +00003070}
3071
Daniel Berlin06329a92017-03-18 15:41:40 +00003072// This is the main value numbering loop, it iterates over the initial touched
3073// instruction set, propagating value numbers, marking things touched, etc,
3074// until the set of touched instructions is completely empty.
3075void NewGVN::iterateTouchedInstructions() {
3076 unsigned int Iterations = 0;
3077 // Figure out where touchedinstructions starts
3078 int FirstInstr = TouchedInstructions.find_first();
3079 // Nothing set, nothing to iterate, just return.
3080 if (FirstInstr == -1)
3081 return;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003082 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00003083 while (TouchedInstructions.any()) {
3084 ++Iterations;
3085 // Walk through all the instructions in all the blocks in RPO.
3086 // TODO: As we hit a new block, we should push and pop equalities into a
3087 // table lookupOperandLeader can use, to catch things PredicateInfo
3088 // might miss, like edge-only equivalences.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003089 for (unsigned InstrNum : TouchedInstructions.set_bits()) {
Daniel Berlin06329a92017-03-18 15:41:40 +00003090
3091 // This instruction was found to be dead. We don't bother looking
3092 // at it again.
3093 if (InstrNum == 0) {
3094 TouchedInstructions.reset(InstrNum);
3095 continue;
3096 }
3097
Daniel Berlin21279bd2017-04-06 18:52:58 +00003098 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003099 const BasicBlock *CurrBlock = getBlockForValue(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003100
3101 // If we hit a new block, do reachability processing.
3102 if (CurrBlock != LastBlock) {
3103 LastBlock = CurrBlock;
3104 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3105 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3106
3107 // If it's not reachable, erase any touched instructions and move on.
3108 if (!BlockReachable) {
3109 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3110 DEBUG(dbgs() << "Skipping instructions in block "
3111 << getBlockName(CurrBlock)
3112 << " because it is unreachable\n");
3113 continue;
3114 }
3115 updateProcessedCount(CurrBlock);
3116 }
Daniel Berlineafdd862017-06-06 17:15:28 +00003117 // Reset after processing (because we may mark ourselves as touched when
3118 // we propagate equalities).
3119 TouchedInstructions.reset(InstrNum);
Daniel Berlin06329a92017-03-18 15:41:40 +00003120
3121 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
3122 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
3123 valueNumberMemoryPhi(MP);
3124 } else if (auto *I = dyn_cast<Instruction>(V)) {
3125 valueNumberInstruction(I);
3126 } else {
3127 llvm_unreachable("Should have been a MemoryPhi or Instruction");
3128 }
3129 updateProcessedCount(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003130 }
3131 }
3132 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
3133}
3134
Daniel Berlin85f91b02016-12-26 20:06:58 +00003135// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00003136bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00003137 if (DebugCounter::isCounterSet(VNCounter))
3138 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00003139 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00003140 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00003141 MSSAWalker = MSSA->getWalker();
Daniel Berline021d2d2017-05-19 20:22:20 +00003142 SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00003143
3144 // Count number of instructions for sizing of hash tables, and come
3145 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003146 unsigned ICount = 1;
3147 // Add an empty instruction to account for the fact that we start at 1
3148 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00003149 // Note: We want ideal RPO traversal of the blocks, which is not quite the
3150 // same as dominator tree order, particularly with regard whether backedges
3151 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00003152 // If we visit in the wrong order, we will end up performing N times as many
3153 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00003154 // The dominator tree does guarantee that, for a given dom tree node, it's
3155 // parent must occur before it in the RPO ordering. Thus, we only need to sort
3156 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00003157 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00003158 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00003159 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003160 auto *Node = DT->getNode(B);
3161 assert(Node && "RPO and Dominator tree should have same reachability");
3162 RPOOrdering[Node] = ++Counter;
3163 }
3164 // Sort dominator tree children arrays into RPO.
3165 for (auto &B : RPOT) {
3166 auto *Node = DT->getNode(B);
3167 if (Node->getChildren().size() > 1)
3168 std::sort(Node->begin(), Node->end(),
Daniel Berlin2f72b192017-04-14 02:53:37 +00003169 [&](const DomTreeNode *A, const DomTreeNode *B) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003170 return RPOOrdering[A] < RPOOrdering[B];
3171 });
3172 }
3173
3174 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00003175 for (auto DTN : depth_first(DT->getRootNode())) {
3176 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00003177 const auto &BlockRange = assignDFSNumbers(B, ICount);
3178 BlockInstRange.insert({B, BlockRange});
3179 ICount += BlockRange.second - BlockRange.first;
3180 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003181 initializeCongruenceClasses(F);
Davide Italiano7e274e02016-12-22 16:03:48 +00003182
Daniel Berline0bd37e2016-12-29 22:15:12 +00003183 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003184 // Ensure we don't end up resizing the expressionToClass map, as
3185 // that can be quite expensive. At most, we have one expression per
3186 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003187 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003188
3189 // Initialize the touched instructions to include the entry block.
3190 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
3191 TouchedInstructions.set(InstRange.first, InstRange.second);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003192 DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
3193 << " marked reachable\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003194 ReachableBlocks.insert(&F.getEntryBlock());
3195
Daniel Berlin06329a92017-03-18 15:41:40 +00003196 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00003197 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00003198 verifyIterationSettled(F);
Daniel Berlin45403572017-05-16 19:58:47 +00003199 verifyStoreExpressions();
Daniel Berlinf7d95802017-02-18 23:06:50 +00003200
Davide Italiano7e274e02016-12-22 16:03:48 +00003201 Changed |= eliminateInstructions(F);
3202
3203 // Delete all instructions marked for deletion.
3204 for (Instruction *ToErase : InstructionsToErase) {
3205 if (!ToErase->use_empty())
3206 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
3207
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003208 if (ToErase->getParent())
3209 ToErase->eraseFromParent();
Davide Italiano7e274e02016-12-22 16:03:48 +00003210 }
3211
3212 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003213 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
3214 return !ReachableBlocks.count(&BB);
3215 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003216
3217 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
3218 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00003219 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003220 deleteInstructionsInBlock(&BB);
3221 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003222 }
3223
3224 cleanupTables();
3225 return Changed;
3226}
3227
Davide Italiano7e274e02016-12-22 16:03:48 +00003228struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003229 int DFSIn = 0;
3230 int DFSOut = 0;
3231 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003232 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003233 // The bool in the Def tells us whether the Def is the stored value of a
3234 // store.
3235 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003236 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00003237 bool operator<(const ValueDFS &Other) const {
3238 // It's not enough that any given field be less than - we have sets
3239 // of fields that need to be evaluated together to give a proper ordering.
3240 // For example, if you have;
3241 // DFS (1, 3)
3242 // Val 0
3243 // DFS (1, 2)
3244 // Val 50
3245 // We want the second to be less than the first, but if we just go field
3246 // by field, we will get to Val 0 < Val 50 and say the first is less than
3247 // the second. We only want it to be less than if the DFS orders are equal.
3248 //
3249 // Each LLVM instruction only produces one value, and thus the lowest-level
3250 // differentiator that really matters for the stack (and what we use as as a
3251 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003252 // Everything else in the structure is instruction level, and only affects
3253 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00003254 //
3255 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
3256 // the order of replacement of uses does not matter.
3257 // IE given,
3258 // a = 5
3259 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00003260 // When you hit b, you will have two valuedfs with the same dfsin, out, and
3261 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00003262 // The .val will be the same as well.
3263 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003264 // You will replace both, and it does not matter what order you replace them
3265 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
3266 // operand 2).
3267 // Similarly for the case of same dfsin, dfsout, localnum, but different
3268 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00003269 // a = 5
3270 // b = 6
3271 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00003272 // in c, we will a valuedfs for a, and one for b,with everything the same
3273 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00003274 // It does not matter what order we replace these operands in.
3275 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003276 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3277 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00003278 Other.U);
3279 }
3280};
3281
Daniel Berlinc4796862017-01-27 02:37:11 +00003282// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003283// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00003284// reachable uses for each value is stored in UseCount, and instructions that
3285// seem
3286// dead (have no non-dead uses) are stored in ProbablyDead.
3287void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00003288 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00003289 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00003290 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00003291 for (auto D : Dense) {
3292 // First add the value.
3293 BasicBlock *BB = getBlockForValue(D);
3294 // Constants are handled prior to ever calling this function, so
3295 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00003296 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003297 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003298 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003299 VDDef.DFSIn = DomNode->getDFSNumIn();
3300 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003301 // If it's a store, use the leader of the value operand, if it's always
3302 // available, or the value operand. TODO: We could do dominance checks to
3303 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00003304 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00003305 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003306 if (alwaysAvailable(Leader)) {
3307 VDDef.Def.setPointer(Leader);
3308 } else {
3309 VDDef.Def.setPointer(SI->getValueOperand());
3310 VDDef.Def.setInt(true);
3311 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003312 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003313 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00003314 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003315 assert(isa<Instruction>(D) &&
3316 "The dense set member should always be an instruction");
Daniel Berline3e69e12017-03-10 00:32:33 +00003317 Instruction *Def = cast<Instruction>(D);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003318 VDDef.LocalNum = InstrToDFSNum(D);
3319 DFSOrderedSet.push_back(VDDef);
3320 // If there is a phi node equivalent, add it
3321 if (auto *PN = RealToTemp.lookup(Def)) {
3322 auto *PHIE =
3323 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3324 if (PHIE) {
3325 VDDef.Def.setInt(false);
3326 VDDef.Def.setPointer(PN);
3327 VDDef.LocalNum = 0;
3328 DFSOrderedSet.push_back(VDDef);
3329 }
3330 }
3331
Daniel Berline3e69e12017-03-10 00:32:33 +00003332 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003333 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00003334 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003335 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003336 // Don't try to replace into dead uses
3337 if (InstructionsToErase.count(I))
3338 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003339 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00003340 // Put the phi node uses in the incoming block.
3341 BasicBlock *IBlock;
3342 if (auto *P = dyn_cast<PHINode>(I)) {
3343 IBlock = P->getIncomingBlock(U);
3344 // Make phi node users appear last in the incoming block
3345 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003346 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00003347 } else {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003348 IBlock = getBlockForValue(I);
Daniel Berlin21279bd2017-04-06 18:52:58 +00003349 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003350 }
Davide Italianoccbbc832017-01-26 00:42:42 +00003351
3352 // Skip uses in unreachable blocks, as we're going
3353 // to delete them.
3354 if (ReachableBlocks.count(IBlock) == 0)
3355 continue;
3356
Daniel Berlinb66164c2017-01-14 00:24:23 +00003357 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003358 VDUse.DFSIn = DomNode->getDFSNumIn();
3359 VDUse.DFSOut = DomNode->getDFSNumOut();
3360 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00003361 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003362 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00003363 }
3364 }
Daniel Berline3e69e12017-03-10 00:32:33 +00003365
3366 // If there are no uses, it's probably dead (but it may have side-effects,
3367 // so not definitely dead. Otherwise, store the number of uses so we can
3368 // track if it becomes dead later).
3369 if (UseCount == 0)
3370 ProbablyDead.insert(Def);
3371 else
3372 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003373 }
3374}
3375
Daniel Berlinc4796862017-01-27 02:37:11 +00003376// This function converts the set of members for a congruence class from values,
3377// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00003378void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00003379 const CongruenceClass &Dense,
3380 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00003381 for (auto D : Dense) {
3382 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
3383 continue;
3384
3385 BasicBlock *BB = getBlockForValue(D);
3386 ValueDFS VD;
3387 DomTreeNode *DomNode = DT->getNode(BB);
3388 VD.DFSIn = DomNode->getDFSNumIn();
3389 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003390 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00003391
3392 // If it's an instruction, use the real local dfs number.
3393 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00003394 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00003395 else
3396 llvm_unreachable("Should have been an instruction");
3397
3398 LoadsAndStores.emplace_back(VD);
3399 }
3400}
3401
Davide Italiano7e274e02016-12-22 16:03:48 +00003402static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00003403 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00003404 if (!ReplInst)
3405 return;
3406
Davide Italiano7e274e02016-12-22 16:03:48 +00003407 // Patch the replacement so that it is not more restrictive than the value
3408 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00003409 // Note that if 'I' is a load being replaced by some operation,
3410 // for example, by an arithmetic operation, then andIRFlags()
3411 // would just erase all math flags from the original arithmetic
3412 // operation, which is clearly not wanted and not needed.
3413 if (!isa<LoadInst>(I))
3414 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003415
Daniel Berlin86eab152017-02-12 22:25:20 +00003416 // FIXME: If both the original and replacement value are part of the
3417 // same control-flow region (meaning that the execution of one
3418 // guarantees the execution of the other), then we can combine the
3419 // noalias scopes here and do better than the general conservative
3420 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00003421
Daniel Berlin86eab152017-02-12 22:25:20 +00003422 // In general, GVN unifies expressions over different control-flow
3423 // regions, and so we need a conservative combination of the noalias
3424 // scopes.
3425 static const unsigned KnownIDs[] = {
3426 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
3427 LLVMContext::MD_noalias, LLVMContext::MD_range,
3428 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
3429 LLVMContext::MD_invariant_group};
3430 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00003431}
3432
3433static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3434 patchReplacementInstruction(I, Repl);
3435 I->replaceAllUsesWith(Repl);
3436}
3437
3438void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
3439 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
3440 ++NumGVNBlocksDeleted;
3441
Daniel Berline19f0e02017-01-30 17:06:55 +00003442 // Delete the instructions backwards, as it has a reduced likelihood of having
3443 // to update as many def-use and use-def chains. Start after the terminator.
3444 auto StartPoint = BB->rbegin();
3445 ++StartPoint;
3446 // Note that we explicitly recalculate BB->rend() on each iteration,
3447 // as it may change when we remove the first instruction.
3448 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3449 Instruction &Inst = *I++;
3450 if (!Inst.use_empty())
3451 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3452 if (isa<LandingPadInst>(Inst))
3453 continue;
3454
3455 Inst.eraseFromParent();
3456 ++NumGVNInstrDeleted;
3457 }
Daniel Berlina53a7222017-01-30 18:12:56 +00003458 // Now insert something that simplifycfg will turn into an unreachable.
3459 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3460 new StoreInst(UndefValue::get(Int8Ty),
3461 Constant::getNullValue(Int8Ty->getPointerTo()),
3462 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00003463}
3464
3465void NewGVN::markInstructionForDeletion(Instruction *I) {
3466 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3467 InstructionsToErase.insert(I);
3468}
3469
3470void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3471
3472 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3473 patchAndReplaceAllUsesWith(I, V);
3474 // We save the actual erasing to avoid invalidating memory
3475 // dependencies until we are done with everything.
3476 markInstructionForDeletion(I);
3477}
3478
3479namespace {
3480
3481// This is a stack that contains both the value and dfs info of where
3482// that value is valid.
3483class ValueDFSStack {
3484public:
3485 Value *back() const { return ValueStack.back(); }
3486 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3487
3488 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003489 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003490 DFSStack.emplace_back(DFSIn, DFSOut);
3491 }
3492 bool empty() const { return DFSStack.empty(); }
3493 bool isInScope(int DFSIn, int DFSOut) const {
3494 if (empty())
3495 return false;
3496 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3497 }
3498
3499 void popUntilDFSScope(int DFSIn, int DFSOut) {
3500
3501 // These two should always be in sync at this point.
3502 assert(ValueStack.size() == DFSStack.size() &&
3503 "Mismatch between ValueStack and DFSStack");
3504 while (
3505 !DFSStack.empty() &&
3506 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3507 DFSStack.pop_back();
3508 ValueStack.pop_back();
3509 }
3510 }
3511
3512private:
3513 SmallVector<Value *, 8> ValueStack;
3514 SmallVector<std::pair<int, int>, 8> DFSStack;
3515};
3516}
Daniel Berlin04443432017-01-07 03:23:47 +00003517
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003518// Given a value and a basic block we are trying to see if it is available in,
3519// see if the value has a leader available in that block.
3520Value *NewGVN::findPhiOfOpsLeader(const Expression *E,
3521 const BasicBlock *BB) const {
3522 // It would already be constant if we could make it constant
3523 if (auto *CE = dyn_cast<ConstantExpression>(E))
3524 return CE->getConstantValue();
3525 if (auto *VE = dyn_cast<VariableExpression>(E))
3526 return VE->getVariableValue();
3527
3528 auto *CC = ExpressionToClass.lookup(E);
3529 if (!CC)
3530 return nullptr;
3531 if (alwaysAvailable(CC->getLeader()))
3532 return CC->getLeader();
3533
3534 for (auto Member : *CC) {
3535 auto *MemberInst = dyn_cast<Instruction>(Member);
3536 // Anything that isn't an instruction is always available.
3537 if (!MemberInst)
3538 return Member;
3539 // If we are looking for something in the same block as the member, it must
3540 // be a leader because this function is looking for operands for a phi node.
3541 if (MemberInst->getParent() == BB ||
3542 DT->dominates(MemberInst->getParent(), BB)) {
3543 return Member;
3544 }
3545 }
3546 return nullptr;
3547}
3548
Davide Italiano7e274e02016-12-22 16:03:48 +00003549bool NewGVN::eliminateInstructions(Function &F) {
3550 // This is a non-standard eliminator. The normal way to eliminate is
3551 // to walk the dominator tree in order, keeping track of available
3552 // values, and eliminating them. However, this is mildly
3553 // pointless. It requires doing lookups on every instruction,
3554 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003555 // instructions part of most singleton congruence classes, we know we
3556 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003557
3558 // Instead, this eliminator looks at the congruence classes directly, sorts
3559 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003560 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003561 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003562 // last member. This is worst case O(E log E) where E = number of
3563 // instructions in a single congruence class. In theory, this is all
3564 // instructions. In practice, it is much faster, as most instructions are
3565 // either in singleton congruence classes or can't possibly be eliminated
3566 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003567 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003568 // for elimination purposes.
3569 // TODO: If we wanted to be faster, We could remove any members with no
3570 // overlapping ranges while sorting, as we will never eliminate anything
3571 // with those members, as they don't dominate anything else in our set.
3572
Davide Italiano7e274e02016-12-22 16:03:48 +00003573 bool AnythingReplaced = false;
3574
3575 // Since we are going to walk the domtree anyway, and we can't guarantee the
3576 // DFS numbers are updated, we compute some ourselves.
3577 DT->updateDFSNumbers();
3578
Daniel Berlin0207cca2017-05-21 23:41:56 +00003579 // Go through all of our phi nodes, and kill the arguments associated with
3580 // unreachable edges.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003581 auto ReplaceUnreachablePHIArgs = [&](PHINode &PHI, BasicBlock *BB) {
3582 for (auto &Operand : PHI.incoming_values())
3583 if (!ReachableEdges.count({PHI.getIncomingBlock(Operand), BB})) {
3584 DEBUG(dbgs() << "Replacing incoming value of " << PHI << " for block "
3585 << getBlockName(PHI.getIncomingBlock(Operand))
3586 << " with undef due to it being unreachable\n");
3587 Operand.set(UndefValue::get(PHI.getType()));
3588 }
3589 };
3590 SmallPtrSet<BasicBlock *, 8> BlocksWithPhis;
3591 for (auto &B : F)
3592 if ((!B.empty() && isa<PHINode>(*B.begin())) ||
3593 (PHIOfOpsPHIs.find(&B) != PHIOfOpsPHIs.end()))
3594 BlocksWithPhis.insert(&B);
3595 DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
3596 for (auto KV : ReachableEdges)
3597 ReachablePredCount[KV.getEnd()]++;
3598 for (auto *BB : BlocksWithPhis)
3599 // TODO: It would be faster to use getNumIncomingBlocks() on a phi node in
3600 // the block and subtract the pred count, but it's more complicated.
3601 if (ReachablePredCount.lookup(BB) !=
George Burgess IVf6137492017-06-13 01:28:49 +00003602 unsigned(std::distance(pred_begin(BB), pred_end(BB)))) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003603 for (auto II = BB->begin(); isa<PHINode>(II); ++II) {
3604 auto &PHI = cast<PHINode>(*II);
3605 ReplaceUnreachablePHIArgs(PHI, BB);
3606 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00003607 for_each_found(PHIOfOpsPHIs, BB, [&](PHINode *PHI) {
3608 ReplaceUnreachablePHIArgs(*PHI, BB);
3609 });
Davide Italiano7e274e02016-12-22 16:03:48 +00003610 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003611
Daniel Berline3e69e12017-03-10 00:32:33 +00003612 // Map to store the use counts
3613 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003614 for (auto *CC : reverse(CongruenceClasses)) {
Daniel Berline67c3222017-05-25 15:44:20 +00003615 DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID() << "\n");
Daniel Berlinc4796862017-01-27 02:37:11 +00003616 // Track the equivalent store info so we can decide whether to try
3617 // dead store elimination.
3618 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003619 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003620 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003621 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003622 // Everything still in the TOP class is unreachable or dead.
3623 if (CC == TOPClass) {
Daniel Berline021d2d2017-05-19 20:22:20 +00003624 for (auto M : *CC) {
3625 auto *VTE = ValueToExpression.lookup(M);
3626 if (VTE && isa<DeadExpression>(VTE))
3627 markInstructionForDeletion(cast<Instruction>(M));
Daniel Berlinb79f5362017-02-11 12:48:50 +00003628 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3629 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003630 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003631 "point");
Daniel Berline021d2d2017-05-19 20:22:20 +00003632 }
Daniel Berlinb79f5362017-02-11 12:48:50 +00003633 continue;
3634 }
3635
Daniel Berlina8236562017-04-07 18:38:09 +00003636 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003637 // If this is a leader that is always available, and it's a
3638 // constant or has no equivalences, just replace everything with
3639 // it. We then update the congruence class with whatever members
3640 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003641 Value *Leader =
3642 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003643 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003644 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003645 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003646 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003647 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003648 if (Member == Leader || !isa<Instruction>(Member) ||
3649 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003650 MembersLeft.insert(Member);
3651 continue;
3652 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003653 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3654 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003655 auto *I = cast<Instruction>(Member);
3656 assert(Leader != I && "About to accidentally remove our leader");
3657 replaceInstruction(I, Leader);
3658 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003659 }
Daniel Berlina8236562017-04-07 18:38:09 +00003660 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003661 } else {
Davide Italiano7e274e02016-12-22 16:03:48 +00003662 // If this is a singleton, we can skip it.
Davide Italiano5974c312017-08-03 21:17:49 +00003663 if (CC->size() != 1 || RealToTemp.count(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003664 // This is a stack because equality replacement/etc may place
3665 // constants in the middle of the member list, and we want to use
3666 // those constant values in preference to the current leader, over
3667 // the scope of those constants.
3668 ValueDFSStack EliminationStack;
3669
3670 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003671 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003672 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003673
3674 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003675 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003676 for (auto &VD : DFSOrderedSet) {
3677 int MemberDFSIn = VD.DFSIn;
3678 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003679 Value *Def = VD.Def.getPointer();
3680 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003681 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003682 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003683 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003684 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003685 auto *DefInst = dyn_cast_or_null<Instruction>(Def);
3686 if (DefInst && AllTempInstructions.count(DefInst)) {
3687 auto *PN = cast<PHINode>(DefInst);
3688
3689 // If this is a value phi and that's the expression we used, insert
3690 // it into the program
3691 // remove from temp instruction list.
3692 AllTempInstructions.erase(PN);
3693 auto *DefBlock = getBlockForValue(Def);
3694 DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
3695 << " into block "
3696 << getBlockName(getBlockForValue(Def)) << "\n");
3697 PN->insertBefore(&DefBlock->front());
3698 Def = PN;
3699 NumGVNPHIOfOpsEliminations++;
3700 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003701
3702 if (EliminationStack.empty()) {
3703 DEBUG(dbgs() << "Elimination Stack is empty\n");
3704 } else {
3705 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3706 << EliminationStack.dfs_back().first << ","
3707 << EliminationStack.dfs_back().second << ")\n");
3708 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003709
3710 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3711 << MemberDFSOut << ")\n");
3712 // First, we see if we are out of scope or empty. If so,
3713 // and there equivalences, we try to replace the top of
3714 // stack with equivalences (if it's on the stack, it must
3715 // not have been eliminated yet).
3716 // Then we synchronize to our current scope, by
3717 // popping until we are back within a DFS scope that
3718 // dominates the current member.
3719 // Then, what happens depends on a few factors
3720 // If the stack is now empty, we need to push
3721 // If we have a constant or a local equivalence we want to
3722 // start using, we also push.
3723 // Otherwise, we walk along, processing members who are
3724 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003725 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003726 bool OutOfScope =
3727 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3728
3729 if (OutOfScope || ShouldPush) {
3730 // Sync to our current scope.
3731 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003732 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003733 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003734 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003735 }
3736 }
3737
Daniel Berline3e69e12017-03-10 00:32:33 +00003738 // Skip the Def's, we only want to eliminate on their uses. But mark
3739 // dominated defs as dead.
3740 if (Def) {
3741 // For anything in this case, what and how we value number
3742 // guarantees that any side-effets that would have occurred (ie
3743 // throwing, etc) can be proven to either still occur (because it's
3744 // dominated by something that has the same side-effects), or never
3745 // occur. Otherwise, we would not have been able to prove it value
3746 // equivalent to something else. For these things, we can just mark
3747 // it all dead. Note that this is different from the "ProbablyDead"
3748 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003749 // easy to prove dead if they are also side-effect free. Note that
3750 // because stores are put in terms of the stored value, we skip
3751 // stored values here. If the stored value is really dead, it will
3752 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003753 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003754 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003755 markInstructionForDeletion(cast<Instruction>(Def));
3756 continue;
3757 }
3758 // At this point, we know it is a Use we are trying to possibly
3759 // replace.
3760
3761 assert(isa<Instruction>(U->get()) &&
3762 "Current def should have been an instruction");
3763 assert(isa<Instruction>(U->getUser()) &&
3764 "Current user should have been an instruction");
3765
3766 // If the thing we are replacing into is already marked to be dead,
3767 // this use is dead. Note that this is true regardless of whether
3768 // we have anything dominating the use or not. We do this here
3769 // because we are already walking all the uses anyway.
3770 Instruction *InstUse = cast<Instruction>(U->getUser());
3771 if (InstructionsToErase.count(InstUse)) {
3772 auto &UseCount = UseCounts[U->get()];
3773 if (--UseCount == 0) {
3774 ProbablyDead.insert(cast<Instruction>(U->get()));
3775 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003776 }
3777
Davide Italiano7e274e02016-12-22 16:03:48 +00003778 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003779 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003780 if (EliminationStack.empty())
3781 continue;
3782
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003783 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003784
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003785 auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
3786 if (II && II->getIntrinsicID() == Intrinsic::ssa_copy)
3787 DominatingLeader = II->getOperand(0);
3788
Daniel Berlind92e7f92017-01-07 00:01:42 +00003789 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003790 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003791 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003792 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003793 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003794
3795 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003796 // metadata. Skip this if we are replacing predicateinfo with its
3797 // original operand, as we already know we can just drop it.
3798 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003799 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3800 if (!PI || DominatingLeader != PI->OriginalOp)
3801 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003802 U->set(DominatingLeader);
3803 // This is now a use of the dominating leader, which means if the
3804 // dominating leader was dead, it's now live!
3805 auto &LeaderUseCount = UseCounts[DominatingLeader];
3806 // It's about to be alive again.
3807 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3808 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003809 if (LeaderUseCount == 0 && II)
3810 ProbablyDead.insert(II);
Daniel Berline3e69e12017-03-10 00:32:33 +00003811 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003812 AnythingReplaced = true;
3813 }
3814 }
3815 }
3816
Daniel Berline3e69e12017-03-10 00:32:33 +00003817 // At this point, anything still in the ProbablyDead set is actually dead if
3818 // would be trivially dead.
3819 for (auto *I : ProbablyDead)
3820 if (wouldInstructionBeTriviallyDead(I))
3821 markInstructionForDeletion(I);
3822
Davide Italiano7e274e02016-12-22 16:03:48 +00003823 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003824 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003825 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003826 if (!isa<Instruction>(Member) ||
3827 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003828 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003829 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003830
3831 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00003832 if (CC->getStoreCount() > 0) {
3833 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003834 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3835 ValueDFSStack EliminationStack;
3836 for (auto &VD : PossibleDeadStores) {
3837 int MemberDFSIn = VD.DFSIn;
3838 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003839 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003840 if (EliminationStack.empty() ||
3841 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3842 // Sync to our current scope.
3843 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3844 if (EliminationStack.empty()) {
3845 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3846 continue;
3847 }
3848 }
3849 // We already did load elimination, so nothing to do here.
3850 if (isa<LoadInst>(Member))
3851 continue;
3852 assert(!EliminationStack.empty());
3853 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003854 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003855 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3856 // Member is dominater by Leader, and thus dead
3857 DEBUG(dbgs() << "Marking dead store " << *Member
3858 << " that is dominated by " << *Leader << "\n");
3859 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003860 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00003861 ++NumGVNDeadStores;
3862 }
3863 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003864 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003865 return AnythingReplaced;
3866}
Daniel Berlin1c087672017-02-11 15:07:01 +00003867
3868// This function provides global ranking of operations so that we can place them
3869// in a canonical order. Note that rank alone is not necessarily enough for a
3870// complete ordering, as constants all have the same rank. However, generally,
3871// we will simplify an operation with all constants so that it doesn't matter
3872// what order they appear in.
3873unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003874 // Prefer constants to undef to anything else
3875 // Undef is a constant, have to check it first.
3876 // Prefer smaller constants to constantexprs
3877 if (isa<ConstantExpr>(V))
3878 return 2;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003879 if (isa<UndefValue>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003880 return 1;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003881 if (isa<Constant>(V))
3882 return 0;
Daniel Berlin1c087672017-02-11 15:07:01 +00003883 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003884 return 3 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00003885
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003886 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00003887 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003888 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00003889 if (Result > 0)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003890 return 4 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00003891 // Unreachable or something else, just return a really large number.
3892 return ~0;
3893}
3894
3895// This is a function that says whether two commutative operations should
3896// have their order swapped when canonicalizing.
3897bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3898 // Because we only care about a total ordering, and don't rewrite expressions
3899 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003900 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00003901 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00003902}
Daniel Berlin64e68992017-03-12 04:46:45 +00003903
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00003904namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +00003905class NewGVNLegacyPass : public FunctionPass {
3906public:
3907 static char ID; // Pass identification, replacement for typeid.
3908 NewGVNLegacyPass() : FunctionPass(ID) {
3909 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3910 }
3911 bool runOnFunction(Function &F) override;
3912
3913private:
3914 void getAnalysisUsage(AnalysisUsage &AU) const override {
3915 AU.addRequired<AssumptionCacheTracker>();
3916 AU.addRequired<DominatorTreeWrapperPass>();
3917 AU.addRequired<TargetLibraryInfoWrapperPass>();
3918 AU.addRequired<MemorySSAWrapperPass>();
3919 AU.addRequired<AAResultsWrapperPass>();
3920 AU.addPreserved<DominatorTreeWrapperPass>();
3921 AU.addPreserved<GlobalsAAWrapperPass>();
3922 }
3923};
Benjamin Kramerdebb3c32017-05-26 20:09:00 +00003924} // namespace
Daniel Berlin64e68992017-03-12 04:46:45 +00003925
3926bool NewGVNLegacyPass::runOnFunction(Function &F) {
3927 if (skipFunction(F))
3928 return false;
3929 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3930 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3931 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3932 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3933 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3934 F.getParent()->getDataLayout())
3935 .runGVN();
3936}
3937
3938INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3939 false, false)
3940INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3941INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3942INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3943INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3944INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3945INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3946INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3947 false)
3948
3949char NewGVNLegacyPass::ID = 0;
3950
3951// createGVNPass - The public interface to this file.
3952FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3953
3954PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3955 // Apparently the order in which we get these results matter for
3956 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3957 // the same order here, just in case.
3958 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3959 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3960 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3961 auto &AA = AM.getResult<AAManager>(F);
3962 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3963 bool Changed =
3964 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3965 .runGVN();
3966 if (!Changed)
3967 return PreservedAnalyses::all();
3968 PreservedAnalyses PA;
3969 PA.preserve<DominatorTreeAnalysis>();
3970 PA.preserve<GlobalsAA>();
3971 return PA;
3972}