blob: 3e45f8da496b928a0fffe617d3ac61dc77e5b0fe [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"
64#include "llvm/ADT/SparseBitVector.h"
65#include "llvm/ADT/Statistic.h"
66#include "llvm/ADT/TinyPtrVector.h"
67#include "llvm/Analysis/AliasAnalysis.h"
68#include "llvm/Analysis/AssumptionCache.h"
69#include "llvm/Analysis/CFG.h"
70#include "llvm/Analysis/CFGPrinter.h"
71#include "llvm/Analysis/ConstantFolding.h"
72#include "llvm/Analysis/GlobalsModRef.h"
73#include "llvm/Analysis/InstructionSimplify.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000074#include "llvm/Analysis/MemoryBuiltins.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000075#include "llvm/Analysis/MemoryLocation.h"
Daniel Berlin2f72b192017-04-14 02:53:37 +000076#include "llvm/Analysis/MemorySSA.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000077#include "llvm/Analysis/TargetLibraryInfo.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000078#include "llvm/IR/DataLayout.h"
79#include "llvm/IR/Dominators.h"
80#include "llvm/IR/GlobalVariable.h"
81#include "llvm/IR/IRBuilder.h"
82#include "llvm/IR/IntrinsicInst.h"
83#include "llvm/IR/LLVMContext.h"
84#include "llvm/IR/Metadata.h"
85#include "llvm/IR/PatternMatch.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000086#include "llvm/IR/Type.h"
87#include "llvm/Support/Allocator.h"
88#include "llvm/Support/CommandLine.h"
89#include "llvm/Support/Debug.h"
Daniel Berlin283a6082017-03-01 19:59:26 +000090#include "llvm/Support/DebugCounter.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000091#include "llvm/Transforms/Scalar.h"
92#include "llvm/Transforms/Scalar/GVNExpression.h"
93#include "llvm/Transforms/Utils/BasicBlockUtils.h"
94#include "llvm/Transforms/Utils/Local.h"
Daniel Berlinf7d95802017-02-18 23:06:50 +000095#include "llvm/Transforms/Utils/PredicateInfo.h"
Daniel Berlin07daac82017-04-02 13:23:44 +000096#include "llvm/Transforms/Utils/VNCoercion.h"
Daniel Berlin1316a942017-04-06 18:52:50 +000097#include <numeric>
Davide Italiano7e274e02016-12-22 16:03:48 +000098#include <unordered_map>
99#include <utility>
100#include <vector>
101using namespace llvm;
102using namespace PatternMatch;
103using namespace llvm::GVNExpression;
Daniel Berlin07daac82017-04-02 13:23:44 +0000104using namespace llvm::VNCoercion;
Davide Italiano7e274e02016-12-22 16:03:48 +0000105#define DEBUG_TYPE "newgvn"
106
107STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
108STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
109STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
110STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +0000111STATISTIC(NumGVNMaxIterations,
112 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000113STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
114STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
115STATISTIC(NumGVNAvoidedSortedLeaderChanges,
116 "Number of avoided sorted leader changes");
Daniel Berlinc4796862017-01-27 02:37:11 +0000117STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000118STATISTIC(NumGVNPHIOfOpsCreated, "Number of PHI of ops created");
119STATISTIC(NumGVNPHIOfOpsEliminations,
120 "Number of things eliminated using PHI of ops");
Daniel Berlin283a6082017-03-01 19:59:26 +0000121DEBUG_COUNTER(VNCounter, "newgvn-vn",
122 "Controls which instructions are value numbered")
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000123DEBUG_COUNTER(PHIOfOpsCounter, "newgvn-phi",
124 "Controls which instructions we create phi of ops for")
Daniel Berlin1316a942017-04-06 18:52:50 +0000125// Currently store defining access refinement is too slow due to basicaa being
126// egregiously slow. This flag lets us keep it working while we work on this
127// issue.
128static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
129 cl::init(false), cl::Hidden);
130
Davide Italiano7e274e02016-12-22 16:03:48 +0000131//===----------------------------------------------------------------------===//
132// GVN Pass
133//===----------------------------------------------------------------------===//
134
135// Anchor methods.
136namespace llvm {
137namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000138Expression::~Expression() = default;
139BasicExpression::~BasicExpression() = default;
140CallExpression::~CallExpression() = default;
141LoadExpression::~LoadExpression() = default;
142StoreExpression::~StoreExpression() = default;
143AggregateValueExpression::~AggregateValueExpression() = default;
144PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000145}
146}
147
Daniel Berlin2f72b192017-04-14 02:53:37 +0000148// Tarjan's SCC finding algorithm with Nuutila's improvements
149// SCCIterator is actually fairly complex for the simple thing we want.
150// It also wants to hand us SCC's that are unrelated to the phi node we ask
151// about, and have us process them there or risk redoing work.
152// Graph traits over a filter iterator also doesn't work that well here.
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000153// This SCC finder is specialized to walk use-def chains, and only follows
154// instructions,
Daniel Berlin2f72b192017-04-14 02:53:37 +0000155// not generic values (arguments, etc).
156struct TarjanSCC {
157
158 TarjanSCC() : Components(1) {}
159
160 void Start(const Instruction *Start) {
161 if (Root.lookup(Start) == 0)
162 FindSCC(Start);
163 }
164
165 const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
166 unsigned ComponentID = ValueToComponent.lookup(V);
167
168 assert(ComponentID > 0 &&
169 "Asking for a component for a value we never processed");
170 return Components[ComponentID];
171 }
172
173private:
174 void FindSCC(const Instruction *I) {
175 Root[I] = ++DFSNum;
176 // Store the DFS Number we had before it possibly gets incremented.
177 unsigned int OurDFS = DFSNum;
178 for (auto &Op : I->operands()) {
179 if (auto *InstOp = dyn_cast<Instruction>(Op)) {
180 if (Root.lookup(Op) == 0)
181 FindSCC(InstOp);
182 if (!InComponent.count(Op))
183 Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
184 }
185 }
Daniel Berlin9d0042b2017-04-18 20:15:47 +0000186 // See if we really were the root of a component, by seeing if we still have
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000187 // our DFSNumber. If we do, we are the root of the component, and we have
188 // completed a component. If we do not, we are not the root of a component,
189 // and belong on the component stack.
Daniel Berlin2f72b192017-04-14 02:53:37 +0000190 if (Root.lookup(I) == OurDFS) {
191 unsigned ComponentID = Components.size();
192 Components.resize(Components.size() + 1);
193 auto &Component = Components.back();
194 Component.insert(I);
195 DEBUG(dbgs() << "Component root is " << *I << "\n");
196 InComponent.insert(I);
197 ValueToComponent[I] = ComponentID;
198 // Pop a component off the stack and label it.
199 while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
200 auto *Member = Stack.back();
201 DEBUG(dbgs() << "Component member is " << *Member << "\n");
202 Component.insert(Member);
203 InComponent.insert(Member);
204 ValueToComponent[Member] = ComponentID;
205 Stack.pop_back();
206 }
207 } else {
208 // Part of a component, push to stack
209 Stack.push_back(I);
210 }
211 }
212 unsigned int DFSNum = 1;
213 SmallPtrSet<const Value *, 8> InComponent;
214 DenseMap<const Value *, unsigned int> Root;
215 SmallVector<const Value *, 8> Stack;
216 // Store the components as vector of ptr sets, because we need the topo order
217 // of SCC's, but not individual member order
218 SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
219 DenseMap<const Value *, unsigned> ValueToComponent;
220};
Davide Italiano7e274e02016-12-22 16:03:48 +0000221// Congruence classes represent the set of expressions/instructions
222// that are all the same *during some scope in the function*.
223// That is, because of the way we perform equality propagation, and
224// because of memory value numbering, it is not correct to assume
225// you can willy-nilly replace any member with any other at any
226// point in the function.
227//
228// For any Value in the Member set, it is valid to replace any dominated member
229// with that Value.
230//
Daniel Berlin1316a942017-04-06 18:52:50 +0000231// Every congruence class has a leader, and the leader is used to symbolize
232// instructions in a canonical way (IE every operand of an instruction that is a
233// member of the same congruence class will always be replaced with leader
234// during symbolization). To simplify symbolization, we keep the leader as a
235// constant if class can be proved to be a constant value. Otherwise, the
236// leader is the member of the value set with the smallest DFS number. Each
237// congruence class also has a defining expression, though the expression may be
238// null. If it exists, it can be used for forward propagation and reassociation
239// of values.
240
241// For memory, we also track a representative MemoryAccess, and a set of memory
242// members for MemoryPhis (which have no real instructions). Note that for
243// memory, it seems tempting to try to split the memory members into a
244// MemoryCongruenceClass or something. Unfortunately, this does not work
245// easily. The value numbering of a given memory expression depends on the
246// leader of the memory congruence class, and the leader of memory congruence
247// class depends on the value numbering of a given memory expression. This
248// leads to wasted propagation, and in some cases, missed optimization. For
249// example: If we had value numbered two stores together before, but now do not,
250// we move them to a new value congruence class. This in turn will move at one
251// of the memorydefs to a new memory congruence class. Which in turn, affects
252// the value numbering of the stores we just value numbered (because the memory
253// congruence class is part of the value number). So while theoretically
254// possible to split them up, it turns out to be *incredibly* complicated to get
255// it to work right, because of the interdependency. While structurally
256// slightly messier, it is algorithmically much simpler and faster to do what we
Daniel Berlina8236562017-04-07 18:38:09 +0000257// do here, and track them both at once in the same class.
258// Note: The default iterators for this class iterate over values
259class CongruenceClass {
260public:
261 using MemberType = Value;
262 using MemberSet = SmallPtrSet<MemberType *, 4>;
263 using MemoryMemberType = MemoryPhi;
264 using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
265
266 explicit CongruenceClass(unsigned ID) : ID(ID) {}
267 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
268 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
269 unsigned getID() const { return ID; }
270 // True if this class has no members left. This is mainly used for assertion
271 // purposes, and for skipping empty classes.
272 bool isDead() const {
273 // If it's both dead from a value perspective, and dead from a memory
274 // perspective, it's really dead.
275 return empty() && memory_empty();
276 }
277 // Leader functions
278 Value *getLeader() const { return RepLeader; }
279 void setLeader(Value *Leader) { RepLeader = Leader; }
280 const std::pair<Value *, unsigned int> &getNextLeader() const {
281 return NextLeader;
282 }
283 void resetNextLeader() { NextLeader = {nullptr, ~0}; }
284
285 void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
286 if (LeaderPair.second < NextLeader.second)
287 NextLeader = LeaderPair;
288 }
289
290 Value *getStoredValue() const { return RepStoredValue; }
291 void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
292 const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
293 void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
294
295 // Forward propagation info
296 const Expression *getDefiningExpr() const { return DefiningExpr; }
Daniel Berlina8236562017-04-07 18:38:09 +0000297
298 // Value member set
299 bool empty() const { return Members.empty(); }
300 unsigned size() const { return Members.size(); }
301 MemberSet::const_iterator begin() const { return Members.begin(); }
302 MemberSet::const_iterator end() const { return Members.end(); }
303 void insert(MemberType *M) { Members.insert(M); }
304 void erase(MemberType *M) { Members.erase(M); }
305 void swap(MemberSet &Other) { Members.swap(Other); }
306
307 // Memory member set
308 bool memory_empty() const { return MemoryMembers.empty(); }
309 unsigned memory_size() const { return MemoryMembers.size(); }
310 MemoryMemberSet::const_iterator memory_begin() const {
311 return MemoryMembers.begin();
312 }
313 MemoryMemberSet::const_iterator memory_end() const {
314 return MemoryMembers.end();
315 }
316 iterator_range<MemoryMemberSet::const_iterator> memory() const {
317 return make_range(memory_begin(), memory_end());
318 }
319 void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
320 void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
321
322 // Store count
323 unsigned getStoreCount() const { return StoreCount; }
324 void incStoreCount() { ++StoreCount; }
325 void decStoreCount() {
326 assert(StoreCount != 0 && "Store count went negative");
327 --StoreCount;
328 }
329
Davide Italianodc435322017-05-10 19:57:43 +0000330 // True if this class has no memory members.
331 bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); }
332
Daniel Berlina8236562017-04-07 18:38:09 +0000333 // Return true if two congruence classes are equivalent to each other. This
334 // means
335 // that every field but the ID number and the dead field are equivalent.
336 bool isEquivalentTo(const CongruenceClass *Other) const {
337 if (!Other)
338 return false;
339 if (this == Other)
340 return true;
341
342 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
343 std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
344 Other->RepMemoryAccess))
345 return false;
346 if (DefiningExpr != Other->DefiningExpr)
347 if (!DefiningExpr || !Other->DefiningExpr ||
348 *DefiningExpr != *Other->DefiningExpr)
349 return false;
350 // We need some ordered set
351 std::set<Value *> AMembers(Members.begin(), Members.end());
352 std::set<Value *> BMembers(Members.begin(), Members.end());
353 return AMembers == BMembers;
354 }
355
356private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000357 unsigned ID;
358 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000359 Value *RepLeader = nullptr;
Daniel Berlina8236562017-04-07 18:38:09 +0000360 // The most dominating leader after our current leader, because the member set
361 // is not sorted and is expensive to keep sorted all the time.
362 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
Daniel Berlin1316a942017-04-06 18:52:50 +0000363 // If this is represented by a store, the value of the store.
Daniel Berlin26addef2017-01-20 21:04:30 +0000364 Value *RepStoredValue = nullptr;
Daniel Berlin1316a942017-04-06 18:52:50 +0000365 // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
366 // access.
367 const MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000368 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000369 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000370 // Actual members of this class.
371 MemberSet Members;
Daniel Berlin1316a942017-04-06 18:52:50 +0000372 // This is the set of MemoryPhis that exist in the class. MemoryDefs and
373 // MemoryUses have real instructions representing them, so we only need to
374 // track MemoryPhis here.
375 MemoryMemberSet MemoryMembers;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000376 // Number of stores in this congruence class.
377 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000378 int StoreCount = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +0000379};
380
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000381struct HashedExpression;
Davide Italiano7e274e02016-12-22 16:03:48 +0000382namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000383template <> struct DenseMapInfo<const Expression *> {
384 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000385 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000386 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
387 return reinterpret_cast<const Expression *>(Val);
388 }
389 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000390 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000391 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
392 return reinterpret_cast<const Expression *>(Val);
393 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000394 static unsigned getHashValue(const Expression *E) {
395 return static_cast<unsigned>(E->getHashValue());
Daniel Berlin85f91b02016-12-26 20:06:58 +0000396 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000397 static unsigned getHashValue(const HashedExpression &HE);
398 static bool isEqual(const HashedExpression &LHS, const Expression *RHS);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000399 static bool isEqual(const Expression *LHS, const Expression *RHS) {
400 if (LHS == RHS)
401 return true;
402 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
403 LHS == getEmptyKey() || RHS == getEmptyKey())
404 return false;
405 return *LHS == *RHS;
406 }
407};
Davide Italiano7e274e02016-12-22 16:03:48 +0000408} // end namespace llvm
409
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000410// This is just a wrapper around Expression that computes the hash value once at
411// creation time. Hash values for an Expression can't change once they are
412// inserted into the DenseMap (it breaks DenseMap), so they must be immutable at
413// that point anyway.
414struct HashedExpression {
415 const Expression *E;
416 unsigned HashVal;
417 HashedExpression(const Expression *E)
418 : E(E), HashVal(DenseMapInfo<const Expression *>::getHashValue(E)) {}
419};
420
421unsigned
422DenseMapInfo<const Expression *>::getHashValue(const HashedExpression &HE) {
423 return HE.HashVal;
424}
425bool DenseMapInfo<const Expression *>::isEqual(const HashedExpression &LHS,
426 const Expression *RHS) {
427 return isEqual(LHS.E, RHS);
428}
429
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000430namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000431class NewGVN {
432 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000433 DominatorTree *DT;
Daniel Berlin64e68992017-03-12 04:46:45 +0000434 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000435 AliasAnalysis *AA;
436 MemorySSA *MSSA;
437 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000438 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000439 std::unique_ptr<PredicateInfo> PredInfo;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000440
441 // These are the only two things the create* functions should have
442 // side-effects on due to allocating memory.
443 mutable BumpPtrAllocator ExpressionAllocator;
444 mutable ArrayRecycler<Value *> ArgRecycler;
445 mutable TarjanSCC SCCFinder;
Daniel Berlinede130d2017-04-26 20:56:14 +0000446 const SimplifyQuery SQ;
Davide Italiano7e274e02016-12-22 16:03:48 +0000447
Daniel Berlin1c087672017-02-11 15:07:01 +0000448 // Number of function arguments, used by ranking
449 unsigned int NumFuncArgs;
450
Daniel Berlin2f72b192017-04-14 02:53:37 +0000451 // RPOOrdering of basic blocks
452 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
453
Davide Italiano7e274e02016-12-22 16:03:48 +0000454 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000455
456 // This class is called INITIAL in the paper. It is the class everything
457 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000458 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000459 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000460 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000461 std::vector<CongruenceClass *> CongruenceClasses;
462 unsigned NextCongruenceNum;
463
464 // Value Mappings.
465 DenseMap<Value *, CongruenceClass *> ValueToClass;
466 DenseMap<Value *, const Expression *> ValueToExpression;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000467 // Value PHI handling, used to make equivalence between phi(op, op) and
468 // op(phi, phi).
469 // These mappings just store various data that would normally be part of the
470 // IR.
471 DenseSet<const Instruction *> PHINodeUses;
472 // Map a temporary instruction we created to a parent block.
473 DenseMap<const Value *, BasicBlock *> TempToBlock;
474 // Map between the temporary phis we created and the real instructions they
475 // are known equivalent to.
476 DenseMap<const Value *, PHINode *> RealToTemp;
477 // In order to know when we should re-process instructions that have
478 // phi-of-ops, we track the set of expressions that they needed as
479 // leaders. When we discover new leaders for those expressions, we process the
480 // associated phi-of-op instructions again in case they have changed. The
481 // other way they may change is if they had leaders, and those leaders
482 // disappear. However, at the point they have leaders, there are uses of the
483 // relevant operands in the created phi node, and so they will get reprocessed
484 // through the normal user marking we perform.
485 mutable DenseMap<const Value *, SmallPtrSet<Value *, 2>> AdditionalUsers;
486 DenseMap<const Expression *, SmallPtrSet<Instruction *, 2>>
487 ExpressionToPhiOfOps;
488 // Map from basic block to the temporary operations we created
Daniel Berlin0207cca2017-05-21 23:41:56 +0000489 DenseMap<const BasicBlock *, SmallVector<PHINode *, 8>> PHIOfOpsPHIs;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000490 // Map from temporary operation to MemoryAccess.
491 DenseMap<const Instruction *, MemoryUseOrDef *> TempToMemory;
492 // Set of all temporary instructions we created.
493 DenseSet<Instruction *> AllTempInstructions;
Davide Italiano7e274e02016-12-22 16:03:48 +0000494
Daniel Berlinf7d95802017-02-18 23:06:50 +0000495 // Mapping from predicate info we used to the instructions we used it with.
496 // In order to correctly ensure propagation, we must keep track of what
497 // comparisons we used, so that when the values of the comparisons change, we
498 // propagate the information to the places we used the comparison.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000499 mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>>
500 PredicateToUsers;
Daniel Berlin1316a942017-04-06 18:52:50 +0000501 // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for
502 // stores, we no longer can rely solely on the def-use chains of MemorySSA.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000503 mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>>
504 MemoryToUsers;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000505
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000506 // A table storing which memorydefs/phis represent a memory state provably
507 // equivalent to another memory state.
508 // We could use the congruence class machinery, but the MemoryAccess's are
509 // abstract memory states, so they can only ever be equivalent to each other,
510 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000511 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000512
Daniel Berlin1316a942017-04-06 18:52:50 +0000513 // We could, if we wanted, build MemoryPhiExpressions and
514 // MemoryVariableExpressions, etc, and value number them the same way we value
515 // number phi expressions. For the moment, this seems like overkill. They
516 // can only exist in one of three states: they can be TOP (equal to
517 // everything), Equivalent to something else, or unique. Because we do not
518 // create expressions for them, we need to simulate leader change not just
519 // when they change class, but when they change state. Note: We can do the
520 // same thing for phis, and avoid having phi expressions if we wanted, We
521 // should eventually unify in one direction or the other, so this is a little
522 // bit of an experiment in which turns out easier to maintain.
523 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
524 DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
525
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000526 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
527 mutable DenseMap<const Instruction *, InstCycleState> InstCycleState;
Davide Italiano7e274e02016-12-22 16:03:48 +0000528 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000529 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000530 ExpressionClassMap ExpressionToClass;
531
Daniel Berline021d2d2017-05-19 20:22:20 +0000532 // We have a single expression that represents currently DeadExpressions.
533 // For dead expressions we can prove will stay dead, we mark them with
534 // DFS number zero. However, it's possible in the case of phi nodes
535 // for us to assume/prove all arguments are dead during fixpointing.
536 // We use DeadExpression for that case.
537 DeadExpression *SingletonDeadExpression = nullptr;
538
Davide Italiano7e274e02016-12-22 16:03:48 +0000539 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000540 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000541
542 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000543 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000544 DenseSet<BlockEdge> ReachableEdges;
545 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
546
547 // This is a bitvector because, on larger functions, we may have
548 // thousands of touched instructions at once (entire blocks,
549 // instructions with hundreds of uses, etc). Even with optimization
550 // for when we mark whole blocks as touched, when this was a
551 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
552 // the time in GVN just managing this list. The bitvector, on the
553 // other hand, efficiently supports test/set/clear of both
554 // individual and ranges, as well as "find next element" This
555 // enables us to use it as a worklist with essentially 0 cost.
556 BitVector TouchedInstructions;
557
558 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000559
560#ifndef NDEBUG
561 // Debugging for how many times each block and instruction got processed.
562 DenseMap<const Value *, unsigned> ProcessedCount;
563#endif
564
565 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000566 // This contains a mapping from Instructions to DFS numbers.
567 // The numbering starts at 1. An instruction with DFS number zero
568 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000569 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000570
571 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000572 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000573
574 // Deletion info.
575 SmallPtrSet<Instruction *, 8> InstructionsToErase;
576
577public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000578 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
579 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
580 const DataLayout &DL)
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000581 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
Daniel Berlinede130d2017-04-26 20:56:14 +0000582 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
583 }
Daniel Berlin64e68992017-03-12 04:46:45 +0000584 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000585
586private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000587 // Expression handling.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000588 const Expression *createExpression(Instruction *) const;
589 const Expression *createBinaryExpression(unsigned, Type *, Value *,
590 Value *) const;
591 PHIExpression *createPHIExpression(Instruction *, bool &HasBackEdge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000592 bool &OriginalOpsConstant) const;
Daniel Berline021d2d2017-05-19 20:22:20 +0000593 const DeadExpression *createDeadExpression() const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000594 const VariableExpression *createVariableExpression(Value *) const;
595 const ConstantExpression *createConstantExpression(Constant *) const;
596 const Expression *createVariableOrConstant(Value *V) const;
597 const UnknownExpression *createUnknownExpression(Instruction *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000598 const StoreExpression *createStoreExpression(StoreInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000599 const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000600 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000601 const MemoryAccess *) const;
602 const CallExpression *createCallExpression(CallInst *,
603 const MemoryAccess *) const;
604 const AggregateValueExpression *
605 createAggregateValueExpression(Instruction *) const;
606 bool setBasicExpressionInfo(Instruction *, BasicExpression *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000607
608 // Congruence class handling.
609 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000610 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000611 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000612 return result;
613 }
614
Daniel Berlin1316a942017-04-06 18:52:50 +0000615 CongruenceClass *createMemoryClass(MemoryAccess *MA) {
616 auto *CC = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000617 CC->setMemoryLeader(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000618 return CC;
619 }
620 CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
621 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +0000622 if (CC->getMemoryLeader() != MA)
Daniel Berlin1316a942017-04-06 18:52:50 +0000623 CC = createMemoryClass(MA);
624 return CC;
625 }
626
Davide Italiano7e274e02016-12-22 16:03:48 +0000627 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000628 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +0000629 CClass->insert(Member);
Davide Italiano7e274e02016-12-22 16:03:48 +0000630 ValueToClass[Member] = CClass;
631 return CClass;
632 }
633 void initializeCongruenceClasses(Function &F);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000634 const Expression *makePossiblePhiOfOps(Instruction *, bool,
635 SmallPtrSetImpl<Value *> &);
636 void addPhiOfOps(PHINode *Op, BasicBlock *BB, Instruction *ExistingValue);
Davide Italiano7e274e02016-12-22 16:03:48 +0000637
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000638 // Value number an Instruction or MemoryPhi.
639 void valueNumberMemoryPhi(MemoryPhi *);
640 void valueNumberInstruction(Instruction *);
641
Davide Italiano7e274e02016-12-22 16:03:48 +0000642 // Symbolic evaluation.
643 const Expression *checkSimplificationResults(Expression *, Instruction *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000644 Value *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000645 const Expression *performSymbolicEvaluation(Value *,
646 SmallPtrSetImpl<Value *> &) const;
Daniel Berlin07daac82017-04-02 13:23:44 +0000647 const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000648 Instruction *,
649 MemoryAccess *) const;
650 const Expression *performSymbolicLoadEvaluation(Instruction *) const;
651 const Expression *performSymbolicStoreEvaluation(Instruction *) const;
652 const Expression *performSymbolicCallEvaluation(Instruction *) const;
653 const Expression *performSymbolicPHIEvaluation(Instruction *) const;
654 const Expression *performSymbolicAggrValueEvaluation(Instruction *) const;
655 const Expression *performSymbolicCmpEvaluation(Instruction *) const;
656 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000657
658 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000659 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000660 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000661 void performCongruenceFinding(Instruction *, const Expression *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000662 void moveValueToNewCongruenceClass(Instruction *, const Expression *,
663 CongruenceClass *, CongruenceClass *);
664 void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
665 CongruenceClass *, CongruenceClass *);
666 Value *getNextValueLeader(CongruenceClass *) const;
667 const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
668 bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
669 CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
670 const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000671 bool isMemoryAccessTOP(const MemoryAccess *) const;
Daniel Berlin1316a942017-04-06 18:52:50 +0000672
Daniel Berlin1c087672017-02-11 15:07:01 +0000673 // Ranking
674 unsigned int getRank(const Value *) const;
675 bool shouldSwapOperands(const Value *, const Value *) const;
676
Davide Italiano7e274e02016-12-22 16:03:48 +0000677 // Reachability handling.
678 void updateReachableEdge(BasicBlock *, BasicBlock *);
679 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000680 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000681
682 // Elimination.
683 struct ValueDFS;
Daniel Berlina8236562017-04-07 18:38:09 +0000684 void convertClassToDFSOrdered(const CongruenceClass &,
Daniel Berline3e69e12017-03-10 00:32:33 +0000685 SmallVectorImpl<ValueDFS> &,
686 DenseMap<const Value *, unsigned int> &,
Daniel Berlina8236562017-04-07 18:38:09 +0000687 SmallPtrSetImpl<Instruction *> &) const;
688 void convertClassToLoadsAndStores(const CongruenceClass &,
689 SmallVectorImpl<ValueDFS> &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000690
691 bool eliminateInstructions(Function &);
692 void replaceInstruction(Instruction *, Value *);
693 void markInstructionForDeletion(Instruction *);
694 void deleteInstructionsInBlock(BasicBlock *);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000695 Value *findPhiOfOpsLeader(const Expression *E, const BasicBlock *BB) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000696
697 // New instruction creation.
698 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000699
700 // Various instruction touch utilities
Daniel Berlin0207cca2017-05-21 23:41:56 +0000701 template <typename Map, typename KeyType, typename Func>
702 void for_each_found(Map &, const KeyType &, Func);
703 template <typename Map, typename KeyType>
704 void touchAndErase(Map &, const KeyType &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000705 void markUsersTouched(Value *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000706 void markMemoryUsersTouched(const MemoryAccess *);
707 void markMemoryDefTouched(const MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000708 void markPredicateUsersTouched(Instruction *);
Daniel Berlin1316a942017-04-06 18:52:50 +0000709 void markValueLeaderChangeTouched(CongruenceClass *CC);
710 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000711 void markPhiOfOpsChanged(const HashedExpression &HE);
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000712 void addPredicateUsers(const PredicateBase *, Instruction *) const;
713 void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000714 void addAdditionalUsers(Value *To, Value *User) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000715
Daniel Berlin06329a92017-03-18 15:41:40 +0000716 // Main loop of value numbering
717 void iterateTouchedInstructions();
718
Davide Italiano7e274e02016-12-22 16:03:48 +0000719 // Utilities.
720 void cleanupTables();
721 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000722 void updateProcessedCount(const Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000723 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000724 void verifyIterationSettled(Function &F);
Daniel Berlin45403572017-05-16 19:58:47 +0000725 void verifyStoreExpressions() const;
Davide Italianoeab0de22017-05-18 23:22:44 +0000726 bool singleReachablePHIPath(SmallPtrSet<const MemoryAccess *, 8> &,
727 const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000728 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000729 void deleteExpression(const Expression *E) const;
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000730 MemoryUseOrDef *getMemoryAccess(const Instruction *) const;
731 MemoryAccess *getDefiningAccess(const MemoryAccess *) const;
732 MemoryPhi *getMemoryAccess(const BasicBlock *) const;
733 template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
Daniel Berlin21279bd2017-04-06 18:52:58 +0000734 unsigned InstrToDFSNum(const Value *V) const {
Daniel Berlin1316a942017-04-06 18:52:50 +0000735 assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
736 return InstrDFS.lookup(V);
737 }
738
Daniel Berlin21279bd2017-04-06 18:52:58 +0000739 unsigned InstrToDFSNum(const MemoryAccess *MA) const {
740 return MemoryToDFSNum(MA);
741 }
742 Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
743 // Given a MemoryAccess, return the relevant instruction DFS number. Note:
744 // This deliberately takes a value so it can be used with Use's, which will
745 // auto-convert to Value's but not to MemoryAccess's.
746 unsigned MemoryToDFSNum(const Value *MA) const {
747 assert(isa<MemoryAccess>(MA) &&
748 "This should not be used with instructions");
749 return isa<MemoryUseOrDef>(MA)
750 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
751 : InstrDFS.lookup(MA);
Daniel Berlin1316a942017-04-06 18:52:50 +0000752 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000753 bool isCycleFree(const Instruction *) const;
754 bool isBackedge(BasicBlock *From, BasicBlock *To) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000755 // Debug counter info. When verifying, we have to reset the value numbering
756 // debug counter to the same state it started in to get the same results.
757 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000758};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000759} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000760
Davide Italianob1114092016-12-28 13:37:17 +0000761template <typename T>
762static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000763 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000764 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000765 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000766}
767
Davide Italianob1114092016-12-28 13:37:17 +0000768bool LoadExpression::equals(const Expression &Other) const {
769 return equalsLoadStoreHelper(*this, Other);
770}
Davide Italiano7e274e02016-12-22 16:03:48 +0000771
Davide Italianob1114092016-12-28 13:37:17 +0000772bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000773 if (!equalsLoadStoreHelper(*this, Other))
774 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000775 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000776 if (const auto *S = dyn_cast<StoreExpression>(&Other))
777 if (getStoredValue() != S->getStoredValue())
778 return false;
779 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000780}
781
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000782// Determine if the edge From->To is a backedge
783bool NewGVN::isBackedge(BasicBlock *From, BasicBlock *To) const {
784 if (From == To)
785 return true;
786 auto *FromDTN = DT->getNode(From);
787 auto *ToDTN = DT->getNode(To);
788 return RPOOrdering.lookup(FromDTN) >= RPOOrdering.lookup(ToDTN);
789}
790
Davide Italiano7e274e02016-12-22 16:03:48 +0000791#ifndef NDEBUG
792static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000793 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000794}
795#endif
796
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000797// Get a MemoryAccess for an instruction, fake or real.
798MemoryUseOrDef *NewGVN::getMemoryAccess(const Instruction *I) const {
799 auto *Result = MSSA->getMemoryAccess(I);
800 return Result ? Result : TempToMemory.lookup(I);
801}
802
803// Get a MemoryPhi for a basic block. These are all real.
804MemoryPhi *NewGVN::getMemoryAccess(const BasicBlock *BB) const {
805 return MSSA->getMemoryAccess(BB);
806}
807
Daniel Berlin06329a92017-03-18 15:41:40 +0000808// Get the basic block from an instruction/memory value.
809BasicBlock *NewGVN::getBlockForValue(Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000810 if (auto *I = dyn_cast<Instruction>(V)) {
811 auto *Parent = I->getParent();
812 if (Parent)
813 return Parent;
814 Parent = TempToBlock.lookup(V);
815 assert(Parent && "Every fake instruction should have a block");
816 return Parent;
817 }
818
819 auto *MP = dyn_cast<MemoryPhi>(V);
820 assert(MP && "Should have been an instruction or a MemoryPhi");
821 return MP->getBlock();
Daniel Berlin06329a92017-03-18 15:41:40 +0000822}
823
Daniel Berlin0e900112017-03-24 06:33:48 +0000824// Delete a definitely dead expression, so it can be reused by the expression
825// allocator. Some of these are not in creation functions, so we have to accept
826// const versions.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000827void NewGVN::deleteExpression(const Expression *E) const {
Daniel Berlin0e900112017-03-24 06:33:48 +0000828 assert(isa<BasicExpression>(E));
829 auto *BE = cast<BasicExpression>(E);
830 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
831 ExpressionAllocator.Deallocate(E);
832}
Daniel Berlin2f72b192017-04-14 02:53:37 +0000833PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000834 bool &OriginalOpsConstant) const {
835 BasicBlock *PHIBlock = getBlockForValue(I);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000836 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000837 auto *E =
838 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000839
840 E->allocateOperands(ArgRecycler, ExpressionAllocator);
841 E->setType(I->getType());
842 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000843
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000844 // NewGVN assumes the operands of a PHI node are in a consistent order across
845 // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix
846 // this in LLVM at some point we don't want GVN to find wrong congruences.
847 // Therefore, here we sort uses in predecessor order.
Davide Italiano63998ec2017-05-09 18:29:37 +0000848 // We're sorting the values by pointer. In theory this might be cause of
849 // non-determinism, but here we don't rely on the ordering for anything
850 // significant, e.g. we don't create new instructions based on it so we're
851 // fine.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000852 SmallVector<const Use *, 4> PHIOperands;
853 for (const Use &U : PN->operands())
854 PHIOperands.push_back(&U);
855 std::sort(PHIOperands.begin(), PHIOperands.end(),
856 [&](const Use *U1, const Use *U2) {
857 return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
858 });
859
Davide Italianob3886dd2017-01-25 23:37:49 +0000860 // Filter out unreachable phi operands.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000861 auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) {
862 return ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000863 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000864 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000865 [&](const Use *U) -> Value * {
866 auto *BB = PN->getIncomingBlock(*U);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000867 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
868 OriginalOpsConstant =
869 OriginalOpsConstant && isa<Constant>(*U);
Daniel Berline021d2d2017-05-19 20:22:20 +0000870 // Use nullptr to distinguish between things that were
871 // originally self-defined and those that have an operand
872 // leader that is self-defined.
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000873 if (*U == PN)
Daniel Berline021d2d2017-05-19 20:22:20 +0000874 return nullptr;
875 // Things in TOPClass are equivalent to everything.
876 if (ValueToClass.lookup(*U) == TOPClass)
877 return nullptr;
Davide Italianod6bb8ca2017-05-09 16:58:28 +0000878 return lookupOperandLeader(*U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000879 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000880 return E;
881}
882
883// Set basic expression info (Arguments, type, opcode) for Expression
884// E from Instruction I in block B.
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000885bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000886 bool AllConstant = true;
887 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
888 E->setType(GEP->getSourceElementType());
889 else
890 E->setType(I->getType());
891 E->setOpcode(I->getOpcode());
892 E->allocateOperands(ArgRecycler, ExpressionAllocator);
893
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000894 // Transform the operand array into an operand leader array, and keep track of
895 // whether all members are constant.
896 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000897 auto Operand = lookupOperandLeader(O);
Daniel Berlinb527b2c2017-05-19 19:01:27 +0000898 AllConstant = AllConstant && isa<Constant>(Operand);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000899 return Operand;
900 });
901
Davide Italiano7e274e02016-12-22 16:03:48 +0000902 return AllConstant;
903}
904
905const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000906 Value *Arg1,
907 Value *Arg2) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000908 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000909
910 E->setType(T);
911 E->setOpcode(Opcode);
912 E->allocateOperands(ArgRecycler, ExpressionAllocator);
913 if (Instruction::isCommutative(Opcode)) {
914 // Ensure that commutative instructions that only differ by a permutation
915 // of their operands get the same value number by sorting the operand value
916 // numbers. Since all commutative instructions have two operands it is more
917 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000918 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000919 std::swap(Arg1, Arg2);
920 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000921 E->op_push_back(lookupOperandLeader(Arg1));
922 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000923
Daniel Berlinede130d2017-04-26 20:56:14 +0000924 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +0000925 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
926 return SimplifiedE;
927 return E;
928}
929
930// Take a Value returned by simplification of Expression E/Instruction
931// I, and see if it resulted in a simpler expression. If so, return
932// that expression.
933// TODO: Once finished, this should not take an Instruction, we only
934// use it for printing.
935const Expression *NewGVN::checkSimplificationResults(Expression *E,
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000936 Instruction *I,
937 Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000938 if (!V)
939 return nullptr;
940 if (auto *C = dyn_cast<Constant>(V)) {
941 if (I)
942 DEBUG(dbgs() << "Simplified " << *I << " to "
943 << " constant " << *C << "\n");
944 NumGVNOpsSimplified++;
945 assert(isa<BasicExpression>(E) &&
946 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000947 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000948 return createConstantExpression(C);
949 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
950 if (I)
951 DEBUG(dbgs() << "Simplified " << *I << " to "
952 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000953 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000954 return createVariableExpression(V);
955 }
956
957 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlina8236562017-04-07 18:38:09 +0000958 if (CC && CC->getDefiningExpr()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000959 if (I)
960 DEBUG(dbgs() << "Simplified " << *I << " to "
Daniel Berlin01939972017-05-21 23:41:53 +0000961 << " expression " << *CC->getDefiningExpr() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +0000962 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000963 deleteExpression(E);
Daniel Berlina8236562017-04-07 18:38:09 +0000964 return CC->getDefiningExpr();
Davide Italiano7e274e02016-12-22 16:03:48 +0000965 }
966 return nullptr;
967}
968
Daniel Berlin6604a2f2017-05-09 16:40:04 +0000969const Expression *NewGVN::createExpression(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000970 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000971
Daniel Berlin97718e62017-01-31 22:32:03 +0000972 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000973
974 if (I->isCommutative()) {
975 // Ensure that commutative instructions that only differ by a permutation
976 // of their operands get the same value number by sorting the operand value
977 // numbers. Since all commutative instructions have two operands it is more
978 // efficient to sort by hand rather than using, say, std::sort.
979 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000980 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000981 E->swapOperands(0, 1);
982 }
983
984 // Perform simplificaiton
985 // TODO: Right now we only check to see if we get a constant result.
986 // We may get a less than constant, but still better, result for
987 // some operations.
988 // IE
989 // add 0, x -> x
990 // and x, x -> x
991 // We should handle this by simply rewriting the expression.
992 if (auto *CI = dyn_cast<CmpInst>(I)) {
993 // Sort the operand value numbers so x<y and y>x get the same value
994 // number.
995 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000996 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000997 E->swapOperands(0, 1);
998 Predicate = CmpInst::getSwappedPredicate(Predicate);
999 }
1000 E->setOpcode((CI->getOpcode() << 8) | Predicate);
1001 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +00001002 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
1003 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +00001004 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
1005 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinede130d2017-04-26 20:56:14 +00001006 Value *V =
1007 SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
Daniel Berlinff12c922017-01-31 22:32:01 +00001008 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1009 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +00001010 } else if (isa<SelectInst>(I)) {
1011 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +00001012 E->getOperand(0) == E->getOperand(1)) {
1013 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
1014 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +00001015 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlinede130d2017-04-26 20:56:14 +00001016 E->getOperand(2), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001017 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1018 return SimplifiedE;
1019 }
1020 } else if (I->isBinaryOp()) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001021 Value *V =
1022 SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001023 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1024 return SimplifiedE;
1025 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001026 Value *V =
1027 SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001028 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1029 return SimplifiedE;
1030 } else if (isa<GetElementPtrInst>(I)) {
Daniel Berlinede130d2017-04-26 20:56:14 +00001031 Value *V = SimplifyGEPInst(
1032 E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
Davide Italiano7e274e02016-12-22 16:03:48 +00001033 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1034 return SimplifiedE;
1035 } else if (AllConstant) {
1036 // We don't bother trying to simplify unless all of the operands
1037 // were constant.
1038 // TODO: There are a lot of Simplify*'s we could call here, if we
1039 // wanted to. The original motivating case for this code was a
1040 // zext i1 false to i8, which we don't have an interface to
1041 // simplify (IE there is no SimplifyZExt).
1042
1043 SmallVector<Constant *, 8> C;
1044 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001045 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +00001046
Daniel Berlin64e68992017-03-12 04:46:45 +00001047 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +00001048 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1049 return SimplifiedE;
1050 }
1051 return E;
1052}
1053
1054const AggregateValueExpression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001055NewGVN::createAggregateValueExpression(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001056 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001057 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001058 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001059 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001060 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001061 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001062 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001063 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001064 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +00001065 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +00001066 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001067 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001068 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +00001069 return E;
1070 }
1071 llvm_unreachable("Unhandled type of aggregate value operation");
1072}
1073
Daniel Berline021d2d2017-05-19 20:22:20 +00001074const DeadExpression *NewGVN::createDeadExpression() const {
1075 // DeadExpression has no arguments and all DeadExpression's are the same,
1076 // so we only need one of them.
1077 return SingletonDeadExpression;
1078}
1079
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001080const VariableExpression *NewGVN::createVariableExpression(Value *V) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001081 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001082 E->setOpcode(V->getValueID());
1083 return E;
1084}
1085
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001086const Expression *NewGVN::createVariableOrConstant(Value *V) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001087 if (auto *C = dyn_cast<Constant>(V))
1088 return createConstantExpression(C);
1089 return createVariableExpression(V);
1090}
1091
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001092const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001093 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +00001094 E->setOpcode(C->getValueID());
1095 return E;
1096}
1097
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001098const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001099 auto *E = new (ExpressionAllocator) UnknownExpression(I);
1100 E->setOpcode(I->getOpcode());
1101 return E;
1102}
1103
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001104const CallExpression *
1105NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001106 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001107 auto *E =
Daniel Berlin1316a942017-04-06 18:52:50 +00001108 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
Daniel Berlin97718e62017-01-31 22:32:03 +00001109 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001110 return E;
1111}
1112
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001113// Return true if some equivalent of instruction Inst dominates instruction U.
1114bool NewGVN::someEquivalentDominates(const Instruction *Inst,
1115 const Instruction *U) const {
1116 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +00001117 // This must be an instruction because we are only called from phi nodes
1118 // in the case that the value it needs to check against is an instruction.
1119
1120 // The most likely candiates for dominance are the leader and the next leader.
1121 // The leader or nextleader will dominate in all cases where there is an
1122 // equivalent that is higher up in the dom tree.
1123 // We can't *only* check them, however, because the
1124 // dominator tree could have an infinite number of non-dominating siblings
1125 // with instructions that are in the right congruence class.
1126 // A
1127 // B C D E F G
1128 // |
1129 // H
1130 // Instruction U could be in H, with equivalents in every other sibling.
1131 // Depending on the rpo order picked, the leader could be the equivalent in
1132 // any of these siblings.
1133 if (!CC)
1134 return false;
Daniel Berlina8236562017-04-07 18:38:09 +00001135 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001136 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001137 if (CC->getNextLeader().first &&
1138 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
Daniel Berlinffc30782017-03-24 06:33:51 +00001139 return true;
Daniel Berlina8236562017-04-07 18:38:09 +00001140 return llvm::any_of(*CC, [&](const Value *Member) {
1141 return Member != CC->getLeader() &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001142 DT->dominates(cast<Instruction>(Member), U);
1143 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001144}
1145
Davide Italiano7e274e02016-12-22 16:03:48 +00001146// See if we have a congruence class and leader for this operand, and if so,
1147// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +00001148Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001149 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +00001150 if (CC) {
Daniel Berline021d2d2017-05-19 20:22:20 +00001151 // Everything in TOP is represented by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +00001152 // We do have to make sure we get the type right though, so we can't set the
1153 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001154 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +00001155 return UndefValue::get(V->getType());
Daniel Berlina8236562017-04-07 18:38:09 +00001156 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlinb79f5362017-02-11 12:48:50 +00001157 }
1158
Davide Italiano7e274e02016-12-22 16:03:48 +00001159 return V;
1160}
1161
Daniel Berlin1316a942017-04-06 18:52:50 +00001162const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1163 auto *CC = getMemoryClass(MA);
Daniel Berlina8236562017-04-07 18:38:09 +00001164 assert(CC->getMemoryLeader() &&
Davide Italianob60f6e02017-05-12 15:25:56 +00001165 "Every MemoryAccess should be mapped to a congruence class with a "
1166 "representative memory access");
Daniel Berlina8236562017-04-07 18:38:09 +00001167 return CC->getMemoryLeader();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001168}
1169
Daniel Berlinc4796862017-01-27 02:37:11 +00001170// Return true if the MemoryAccess is really equivalent to everything. This is
1171// equivalent to the lattice value "TOP" in most lattices. This is the initial
Daniel Berlin1316a942017-04-06 18:52:50 +00001172// state of all MemoryAccesses.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001173bool NewGVN::isMemoryAccessTOP(const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001174 return getMemoryClass(MA) == TOPClass;
1175}
1176
Davide Italiano7e274e02016-12-22 16:03:48 +00001177LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin1316a942017-04-06 18:52:50 +00001178 LoadInst *LI,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001179 const MemoryAccess *MA) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001180 auto *E =
1181 new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
Davide Italiano7e274e02016-12-22 16:03:48 +00001182 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1183 E->setType(LoadType);
1184
1185 // Give store and loads same opcode so they value number together.
1186 E->setOpcode(0);
Daniel Berlin1316a942017-04-06 18:52:50 +00001187 E->op_push_back(PointerOp);
Davide Italiano7e274e02016-12-22 16:03:48 +00001188 if (LI)
1189 E->setAlignment(LI->getAlignment());
1190
1191 // TODO: Value number heap versions. We may be able to discover
1192 // things alias analysis can't on it's own (IE that a store and a
1193 // load have the same value, and thus, it isn't clobbering the load).
1194 return E;
1195}
1196
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001197const StoreExpression *
1198NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001199 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001200 auto *E = new (ExpressionAllocator)
Daniel Berlin1316a942017-04-06 18:52:50 +00001201 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001202 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1203 E->setType(SI->getValueOperand()->getType());
1204
1205 // Give store and loads same opcode so they value number together.
1206 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +00001207 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001208
1209 // TODO: Value number heap versions. We may be able to discover
1210 // things alias analysis can't on it's own (IE that a store and a
1211 // load have the same value, and thus, it isn't clobbering the load).
1212 return E;
1213}
1214
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001215const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001216 // Unlike loads, we never try to eliminate stores, so we do not check if they
1217 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001218 auto *SI = cast<StoreInst>(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001219 auto *StoreAccess = getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +00001220 // Get the expression, if any, for the RHS of the MemoryDef.
Daniel Berlin1316a942017-04-06 18:52:50 +00001221 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1222 if (EnableStoreRefinement)
1223 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1224 // If we bypassed the use-def chains, make sure we add a use.
1225 if (StoreRHS != StoreAccess->getDefiningAccess())
1226 addMemoryUsers(StoreRHS, StoreAccess);
1227
1228 StoreRHS = lookupMemoryLeader(StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001229 // If we are defined by ourselves, use the live on entry def.
1230 if (StoreRHS == StoreAccess)
1231 StoreRHS = MSSA->getLiveOnEntryDef();
1232
Daniel Berlin589cecc2017-01-02 18:00:46 +00001233 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001234 // See if we are defined by a previous store expression, it already has a
1235 // value, and it's the same value as our current store. FIXME: Right now, we
1236 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin1316a942017-04-06 18:52:50 +00001237 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1238 const auto *LastCC = ExpressionToClass.lookup(LastStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +00001239 // Basically, check if the congruence class the store is in is defined by a
1240 // store that isn't us, and has the same value. MemorySSA takes care of
1241 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +00001242 // The RepStoredValue gets nulled if all the stores disappear in a class, so
1243 // we don't need to check if the class contains a store besides us.
Daniel Berlin1316a942017-04-06 18:52:50 +00001244 if (LastCC &&
Daniel Berlina8236562017-04-07 18:38:09 +00001245 LastCC->getStoredValue() == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin1316a942017-04-06 18:52:50 +00001246 return LastStore;
1247 deleteExpression(LastStore);
Daniel Berlinc4796862017-01-27 02:37:11 +00001248 // Also check if our value operand is defined by a load of the same memory
Daniel Berlin1316a942017-04-06 18:52:50 +00001249 // location, and the memory state is the same as it was then (otherwise, it
1250 // could have been overwritten later. See test32 in
1251 // transforms/DeadStoreElimination/simple.ll).
1252 if (auto *LI =
1253 dyn_cast<LoadInst>(lookupOperandLeader(SI->getValueOperand()))) {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001254 if ((lookupOperandLeader(LI->getPointerOperand()) ==
1255 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001256 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
Daniel Berlin1316a942017-04-06 18:52:50 +00001257 StoreRHS))
Davide Italiano9a0f5422017-05-20 00:46:54 +00001258 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +00001259 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001260 }
Daniel Berlin1316a942017-04-06 18:52:50 +00001261
1262 // If the store is not equivalent to anything, value number it as a store that
1263 // produces a unique memory state (instead of using it's MemoryUse, we use
1264 // it's MemoryDef).
Daniel Berlin97718e62017-01-31 22:32:03 +00001265 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001266}
1267
Daniel Berlin07daac82017-04-02 13:23:44 +00001268// See if we can extract the value of a loaded pointer from a load, a store, or
1269// a memory instruction.
1270const Expression *
1271NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1272 LoadInst *LI, Instruction *DepInst,
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001273 MemoryAccess *DefiningAccess) const {
Daniel Berlin07daac82017-04-02 13:23:44 +00001274 assert((!LI || LI->isSimple()) && "Not a simple load");
1275 if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1276 // Can't forward from non-atomic to atomic without violating memory model.
1277 // Also don't need to coerce if they are the same type, we will just
1278 // propogate..
1279 if (LI->isAtomic() > DepSI->isAtomic() ||
1280 LoadType == DepSI->getValueOperand()->getType())
1281 return nullptr;
1282 int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1283 if (Offset >= 0) {
1284 if (auto *C = dyn_cast<Constant>(
1285 lookupOperandLeader(DepSI->getValueOperand()))) {
1286 DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1287 << *C << "\n");
1288 return createConstantExpression(
1289 getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1290 }
1291 }
1292
1293 } else if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1294 // Can't forward from non-atomic to atomic without violating memory model.
1295 if (LI->isAtomic() > DepLI->isAtomic())
1296 return nullptr;
1297 int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1298 if (Offset >= 0) {
1299 // We can coerce a constant load into a load
1300 if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1301 if (auto *PossibleConstant =
1302 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1303 DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1304 << *PossibleConstant << "\n");
1305 return createConstantExpression(PossibleConstant);
1306 }
1307 }
1308
1309 } else if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1310 int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1311 if (Offset >= 0) {
1312 if (auto *PossibleConstant =
1313 getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1314 DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1315 << " to constant " << *PossibleConstant << "\n");
1316 return createConstantExpression(PossibleConstant);
1317 }
1318 }
1319 }
1320
1321 // All of the below are only true if the loaded pointer is produced
1322 // by the dependent instruction.
1323 if (LoadPtr != lookupOperandLeader(DepInst) &&
1324 !AA->isMustAlias(LoadPtr, DepInst))
1325 return nullptr;
1326 // If this load really doesn't depend on anything, then we must be loading an
1327 // undef value. This can happen when loading for a fresh allocation with no
1328 // intervening stores, for example. Note that this is only true in the case
1329 // that the result of the allocation is pointer equal to the load ptr.
1330 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1331 return createConstantExpression(UndefValue::get(LoadType));
1332 }
1333 // If this load occurs either right after a lifetime begin,
1334 // then the loaded value is undefined.
1335 else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1336 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1337 return createConstantExpression(UndefValue::get(LoadType));
1338 }
1339 // If this load follows a calloc (which zero initializes memory),
1340 // then the loaded value is zero
1341 else if (isCallocLikeFn(DepInst, TLI)) {
1342 return createConstantExpression(Constant::getNullValue(LoadType));
1343 }
1344
1345 return nullptr;
1346}
1347
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001348const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001349 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001350
1351 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +00001352 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +00001353 if (!LI->isSimple())
1354 return nullptr;
1355
Daniel Berlin203f47b2017-01-31 22:31:53 +00001356 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +00001357 // Load of undef is undef.
1358 if (isa<UndefValue>(LoadAddressLeader))
1359 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001360 MemoryAccess *OriginalAccess = getMemoryAccess(I);
1361 MemoryAccess *DefiningAccess =
1362 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001363
1364 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1365 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1366 Instruction *DefiningInst = MD->getMemoryInst();
1367 // If the defining instruction is not reachable, replace with undef.
1368 if (!ReachableBlocks.count(DefiningInst->getParent()))
1369 return createConstantExpression(UndefValue::get(LI->getType()));
Daniel Berlin07daac82017-04-02 13:23:44 +00001370 // This will handle stores and memory insts. We only do if it the
1371 // defining access has a different type, or it is a pointer produced by
1372 // certain memory operations that cause the memory to have a fixed value
1373 // (IE things like calloc).
Daniel Berlin5845e052017-04-06 18:52:53 +00001374 if (const auto *CoercionResult =
1375 performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1376 DefiningInst, DefiningAccess))
Daniel Berlin07daac82017-04-02 13:23:44 +00001377 return CoercionResult;
Davide Italiano7e274e02016-12-22 16:03:48 +00001378 }
1379 }
1380
Daniel Berlin1316a942017-04-06 18:52:50 +00001381 const Expression *E = createLoadExpression(LI->getType(), LoadAddressLeader,
1382 LI, DefiningAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +00001383 return E;
1384}
1385
Daniel Berlinf7d95802017-02-18 23:06:50 +00001386const Expression *
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001387NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001388 auto *PI = PredInfo->getPredicateInfoFor(I);
1389 if (!PI)
1390 return nullptr;
1391
1392 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +00001393
1394 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1395 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001396 return nullptr;
1397
Daniel Berlinfccbda92017-02-22 22:20:58 +00001398 auto *CopyOf = I->getOperand(0);
1399 auto *Cond = PWC->Condition;
1400
Daniel Berlinf7d95802017-02-18 23:06:50 +00001401 // If this a copy of the condition, it must be either true or false depending
1402 // on the predicate info type and edge
1403 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +00001404 // We should not need to add predicate users because the predicate info is
1405 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001406 if (isa<PredicateAssume>(PI))
1407 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1408 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1409 if (PBranch->TrueEdge)
1410 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1411 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1412 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001413 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1414 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001415 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001416
Daniel Berlinf7d95802017-02-18 23:06:50 +00001417 // Not a copy of the condition, so see what the predicates tell us about this
1418 // value. First, though, we check to make sure the value is actually a copy
1419 // of one of the condition operands. It's possible, in certain cases, for it
1420 // to be a copy of a predicateinfo copy. In particular, if two branch
1421 // operations use the same condition, and one branch dominates the other, we
1422 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +00001423 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +00001424 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +00001425
1426 // Everything below relies on the condition being a comparison.
1427 auto *Cmp = dyn_cast<CmpInst>(Cond);
1428 if (!Cmp)
1429 return nullptr;
1430
1431 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Davide Italianoc43a9f82017-05-12 15:28:12 +00001432 DEBUG(dbgs() << "Copy is not of any condition operands!\n");
Daniel Berlinf7d95802017-02-18 23:06:50 +00001433 return nullptr;
1434 }
Daniel Berlinfccbda92017-02-22 22:20:58 +00001435 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1436 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001437 bool SwappedOps = false;
1438 // Sort the ops
1439 if (shouldSwapOperands(FirstOp, SecondOp)) {
1440 std::swap(FirstOp, SecondOp);
1441 SwappedOps = true;
1442 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001443 CmpInst::Predicate Predicate =
1444 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1445
1446 if (isa<PredicateAssume>(PI)) {
1447 // If the comparison is true when the operands are equal, then we know the
1448 // operands are equal, because assumes must always be true.
1449 if (CmpInst::isTrueWhenEqual(Predicate)) {
1450 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001451 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001452 return createVariableOrConstant(FirstOp);
1453 }
1454 }
1455 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1456 // If we are *not* a copy of the comparison, we may equal to the other
1457 // operand when the predicate implies something about equality of
1458 // operations. In particular, if the comparison is true/false when the
1459 // operands are equal, and we are on the right edge, we know this operation
1460 // is equal to something.
1461 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1462 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1463 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001464 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001465 return createVariableOrConstant(FirstOp);
1466 }
1467 // Handle the special case of floating point.
1468 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1469 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1470 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1471 addPredicateUsers(PI, I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001472 addAdditionalUsers(Cmp->getOperand(0), I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001473 return createConstantExpression(cast<Constant>(FirstOp));
1474 }
1475 }
1476 return nullptr;
1477}
1478
Davide Italiano7e274e02016-12-22 16:03:48 +00001479// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001480const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001481 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001482 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1483 // Instrinsics with the returned attribute are copies of arguments.
1484 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1485 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1486 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1487 return Result;
1488 return createVariableOrConstant(ReturnedValue);
1489 }
1490 }
1491 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001492 return createCallExpression(CI, TOPClass->getMemoryLeader());
Daniel Berlinf7d95802017-02-18 23:06:50 +00001493 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001494 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin1316a942017-04-06 18:52:50 +00001495 return createCallExpression(CI, DefiningAccess);
Davide Italianob2225492016-12-27 18:15:39 +00001496 }
1497 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001498}
1499
Daniel Berlin1316a942017-04-06 18:52:50 +00001500// Retrieve the memory class for a given MemoryAccess.
1501CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1502
1503 auto *Result = MemoryAccessToClass.lookup(MA);
1504 assert(Result && "Should have found memory class");
1505 return Result;
1506}
1507
1508// Update the MemoryAccess equivalence table to say that From is equal to To,
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001509// and return true if this is different from what already existed in the table.
Daniel Berlin1316a942017-04-06 18:52:50 +00001510bool NewGVN::setMemoryClass(const MemoryAccess *From,
1511 CongruenceClass *NewClass) {
1512 assert(NewClass &&
1513 "Every MemoryAccess should be getting mapped to a non-null class");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001514 DEBUG(dbgs() << "Setting " << *From);
Daniel Berlin1316a942017-04-06 18:52:50 +00001515 DEBUG(dbgs() << " equivalent to congruence class ");
Daniel Berlina8236562017-04-07 18:38:09 +00001516 DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
Davide Italianob7a66982017-05-09 20:02:48 +00001517 DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001518
1519 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001520 bool Changed = false;
1521 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001522 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00001523 auto *OldClass = LookupResult->second;
1524 if (OldClass != NewClass) {
1525 // If this is a phi, we have to handle memory member updates.
1526 if (auto *MP = dyn_cast<MemoryPhi>(From)) {
Daniel Berlina8236562017-04-07 18:38:09 +00001527 OldClass->memory_erase(MP);
1528 NewClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00001529 // This may have killed the class if it had no non-memory members
Daniel Berlina8236562017-04-07 18:38:09 +00001530 if (OldClass->getMemoryLeader() == From) {
Davide Italiano41f5c7b2017-05-12 15:22:45 +00001531 if (OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00001532 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00001533 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00001534 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
Daniel Berlin1316a942017-04-06 18:52:50 +00001535 DEBUG(dbgs() << "Memory class leader change for class "
Daniel Berlina8236562017-04-07 18:38:09 +00001536 << OldClass->getID() << " to "
1537 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00001538 << " due to removal of a memory member " << *From
1539 << "\n");
1540 markMemoryLeaderChangeTouched(OldClass);
1541 }
1542 }
1543 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001544 // It wasn't equivalent before, and now it is.
Daniel Berlin1316a942017-04-06 18:52:50 +00001545 LookupResult->second = NewClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001546 Changed = true;
1547 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001548 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001549
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001550 return Changed;
1551}
Daniel Berlin0e900112017-03-24 06:33:48 +00001552
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001553// Determine if a instruction is cycle-free. That means the values in the
1554// instruction don't depend on any expressions that can change value as a result
1555// of the instruction. For example, a non-cycle free instruction would be v =
1556// phi(0, v+1).
1557bool NewGVN::isCycleFree(const Instruction *I) const {
1558 // In order to compute cycle-freeness, we do SCC finding on the instruction,
1559 // and see what kind of SCC it ends up in. If it is a singleton, it is
1560 // cycle-free. If it is not in a singleton, it is only cycle free if the
1561 // other members are all phi nodes (as they do not compute anything, they are
1562 // copies).
1563 auto ICS = InstCycleState.lookup(I);
1564 if (ICS == ICS_Unknown) {
1565 SCCFinder.Start(I);
1566 auto &SCC = SCCFinder.getComponentFor(I);
Daniel Berlin2f72b192017-04-14 02:53:37 +00001567 // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1568 if (SCC.size() == 1)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001569 InstCycleState.insert({I, ICS_CycleFree});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001570 else {
1571 bool AllPhis =
1572 llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001573 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
Daniel Berlin2f72b192017-04-14 02:53:37 +00001574 for (auto *Member : SCC)
1575 if (auto *MemberPhi = dyn_cast<PHINode>(Member))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001576 InstCycleState.insert({MemberPhi, ICS});
Daniel Berlin2f72b192017-04-14 02:53:37 +00001577 }
1578 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001579 if (ICS == ICS_Cycle)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001580 return false;
1581 return true;
1582}
1583
Davide Italiano7e274e02016-12-22 16:03:48 +00001584// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001585const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001586 // True if one of the incoming phi edges is a backedge.
1587 bool HasBackedge = false;
1588 // All constant tracks the state of whether all the *original* phi operands
Daniel Berline021d2d2017-05-19 20:22:20 +00001589 // This is really shorthand for "this phi cannot cycle due to forward
1590 // change in value of the phi is guaranteed not to later change the value of
1591 // the phi. IE it can't be v = phi(undef, v+1)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001592 bool AllConstant = true;
Daniel Berlinabd632d2017-05-16 06:06:12 +00001593 auto *E =
1594 cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001595 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
Davide Italiano839c7e62017-05-02 21:11:40 +00001596 // See if all arguments are the same.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001597 // We track if any were undef because they need special handling.
1598 bool HasUndef = false;
Daniel Berline021d2d2017-05-19 20:22:20 +00001599 bool CycleFree = isCycleFree(cast<PHINode>(I));
1600 auto Filtered = make_filter_range(E->operands(), [&](Value *Arg) {
1601 if (Arg == nullptr)
1602 return false;
1603 // Original self-operands are already eliminated during expression creation.
1604 // We can only eliminate value-wise self-operands if it's cycle
1605 // free. Otherwise, eliminating the operand can cause our value to change,
1606 // which can cause us to not eliminate the operand, which changes the value
1607 // back to what it was before, cycling forever.
1608 if (CycleFree && Arg == I)
Daniel Berlind92e7f92017-01-07 00:01:42 +00001609 return false;
1610 if (isa<UndefValue>(Arg)) {
1611 HasUndef = true;
1612 return false;
1613 }
1614 return true;
1615 });
Daniel Berline021d2d2017-05-19 20:22:20 +00001616 // If we are left with no operands, it's dead.
Daniel Berlind92e7f92017-01-07 00:01:42 +00001617 if (Filtered.begin() == Filtered.end()) {
Daniel Berline021d2d2017-05-19 20:22:20 +00001618 DEBUG(dbgs() << "No arguments of PHI node " << *I << " are live\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001619 deleteExpression(E);
Daniel Berline021d2d2017-05-19 20:22:20 +00001620 return createDeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00001621 }
Daniel Berlin2f72b192017-04-14 02:53:37 +00001622 unsigned NumOps = 0;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001623 Value *AllSameValue = *(Filtered.begin());
1624 ++Filtered.begin();
1625 // Can't use std::equal here, sadly, because filter.begin moves.
Daniel Berline021d2d2017-05-19 20:22:20 +00001626 if (llvm::all_of(Filtered, [&](Value *Arg) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001627 ++NumOps;
Daniel Berline021d2d2017-05-19 20:22:20 +00001628 return Arg == AllSameValue;
Daniel Berlind92e7f92017-01-07 00:01:42 +00001629 })) {
1630 // In LLVM's non-standard representation of phi nodes, it's possible to have
1631 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1632 // on the original phi node), especially in weird CFG's where some arguments
1633 // are unreachable, or uninitialized along certain paths. This can cause
1634 // infinite loops during evaluation. We work around this by not trying to
1635 // really evaluate them independently, but instead using a variable
1636 // expression to say if one is equivalent to the other.
1637 // We also special case undef, so that if we have an undef, we can't use the
1638 // common value unless it dominates the phi block.
1639 if (HasUndef) {
Daniel Berlin2f72b192017-04-14 02:53:37 +00001640 // If we have undef and at least one other value, this is really a
1641 // multivalued phi, and we need to know if it's cycle free in order to
1642 // evaluate whether we can ignore the undef. The other parts of this are
1643 // just shortcuts. If there is no backedge, or all operands are
1644 // constants, or all operands are ignored but the undef, it also must be
1645 // cycle free.
1646 if (!AllConstant && HasBackedge && NumOps > 0 &&
Daniel Berline021d2d2017-05-19 20:22:20 +00001647 !isa<UndefValue>(AllSameValue) && !CycleFree)
Daniel Berlin2f72b192017-04-14 02:53:37 +00001648 return E;
1649
Daniel Berlind92e7f92017-01-07 00:01:42 +00001650 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001651 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001652 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001653 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001654 }
1655
Davide Italiano7e274e02016-12-22 16:03:48 +00001656 NumGVNPhisAllSame++;
1657 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1658 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001659 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001660 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001661 }
1662 return E;
1663}
1664
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001665const Expression *
1666NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001667 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1668 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1669 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1670 unsigned Opcode = 0;
1671 // EI might be an extract from one of our recognised intrinsics. If it
1672 // is we'll synthesize a semantically equivalent expression instead on
1673 // an extract value expression.
1674 switch (II->getIntrinsicID()) {
1675 case Intrinsic::sadd_with_overflow:
1676 case Intrinsic::uadd_with_overflow:
1677 Opcode = Instruction::Add;
1678 break;
1679 case Intrinsic::ssub_with_overflow:
1680 case Intrinsic::usub_with_overflow:
1681 Opcode = Instruction::Sub;
1682 break;
1683 case Intrinsic::smul_with_overflow:
1684 case Intrinsic::umul_with_overflow:
1685 Opcode = Instruction::Mul;
1686 break;
1687 default:
1688 break;
1689 }
1690
1691 if (Opcode != 0) {
1692 // Intrinsic recognized. Grab its args to finish building the
1693 // expression.
1694 assert(II->getNumArgOperands() == 2 &&
1695 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001696 return createBinaryExpression(
1697 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001698 }
1699 }
1700 }
1701
Daniel Berlin97718e62017-01-31 22:32:03 +00001702 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001703}
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001704const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001705 auto *CI = dyn_cast<CmpInst>(I);
1706 // See if our operands are equal to those of a previous predicate, and if so,
1707 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001708 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1709 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001710 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001711 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001712 std::swap(Op0, Op1);
1713 OurPredicate = CI->getSwappedPredicate();
1714 }
1715
1716 // Avoid processing the same info twice
1717 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001718 // See if we know something about the comparison itself, like it is the target
1719 // of an assume.
1720 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1721 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1722 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1723
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001724 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001725 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001726 if (CI->isTrueWhenEqual())
1727 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1728 else if (CI->isFalseWhenEqual())
1729 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1730 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001731
1732 // NOTE: Because we are comparing both operands here and below, and using
1733 // previous comparisons, we rely on fact that predicateinfo knows to mark
1734 // comparisons that use renamed operands as users of the earlier comparisons.
1735 // It is *not* enough to just mark predicateinfo renamed operands as users of
1736 // the earlier comparisons, because the *other* operand may have changed in a
1737 // previous iteration.
1738 // Example:
1739 // icmp slt %a, %b
1740 // %b.0 = ssa.copy(%b)
1741 // false branch:
1742 // icmp slt %c, %b.0
1743
1744 // %c and %a may start out equal, and thus, the code below will say the second
1745 // %icmp is false. c may become equal to something else, and in that case the
1746 // %second icmp *must* be reexamined, but would not if only the renamed
1747 // %operands are considered users of the icmp.
1748
1749 // *Currently* we only check one level of comparisons back, and only mark one
1750 // level back as touched when changes appen . If you modify this code to look
1751 // back farther through comparisons, you *must* mark the appropriate
1752 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1753 // we know something just from the operands themselves
1754
1755 // See if our operands have predicate info, so that we may be able to derive
1756 // something from a previous comparison.
1757 for (const auto &Op : CI->operands()) {
1758 auto *PI = PredInfo->getPredicateInfoFor(Op);
1759 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1760 if (PI == LastPredInfo)
1761 continue;
1762 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001763
Daniel Berlinf7d95802017-02-18 23:06:50 +00001764 // TODO: Along the false edge, we may know more things too, like icmp of
1765 // same operands is false.
1766 // TODO: We only handle actual comparison conditions below, not and/or.
1767 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1768 if (!BranchCond)
1769 continue;
1770 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1771 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1772 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001773 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001774 std::swap(BranchOp0, BranchOp1);
1775 BranchPredicate = BranchCond->getSwappedPredicate();
1776 }
1777 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1778 if (PBranch->TrueEdge) {
1779 // If we know the previous predicate is true and we are in the true
1780 // edge then we may be implied true or false.
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001781 if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1782 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001783 addPredicateUsers(PI, I);
1784 return createConstantExpression(
1785 ConstantInt::getTrue(CI->getType()));
1786 }
1787
Davide Italiano2dfd46b2017-05-01 22:26:28 +00001788 if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1789 OurPredicate)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001790 addPredicateUsers(PI, I);
1791 return createConstantExpression(
1792 ConstantInt::getFalse(CI->getType()));
1793 }
1794
1795 } else {
1796 // Just handle the ne and eq cases, where if we have the same
1797 // operands, we may know something.
1798 if (BranchPredicate == OurPredicate) {
1799 addPredicateUsers(PI, I);
1800 // Same predicate, same ops,we know it was false, so this is false.
1801 return createConstantExpression(
1802 ConstantInt::getFalse(CI->getType()));
1803 } else if (BranchPredicate ==
1804 CmpInst::getInversePredicate(OurPredicate)) {
1805 addPredicateUsers(PI, I);
1806 // Inverse predicate, we know the other was false, so this is true.
Daniel Berlinf7d95802017-02-18 23:06:50 +00001807 return createConstantExpression(
1808 ConstantInt::getTrue(CI->getType()));
1809 }
1810 }
1811 }
1812 }
1813 }
1814 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001815 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001816}
Davide Italiano7e274e02016-12-22 16:03:48 +00001817
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001818// Return true if V is a value that will always be available (IE can
1819// be placed anywhere) in the function. We don't do globals here
1820// because they are often worse to put in place.
1821// TODO: Separate cost from availability
1822static bool alwaysAvailable(Value *V) {
1823 return isa<Constant>(V) || isa<Argument>(V);
1824}
1825
Davide Italiano7e274e02016-12-22 16:03:48 +00001826// Substitute and symbolize the value before value numbering.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001827const Expression *
1828NewGVN::performSymbolicEvaluation(Value *V,
1829 SmallPtrSetImpl<Value *> &Visited) const {
Davide Italiano0e714802016-12-28 14:00:11 +00001830 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001831 if (auto *C = dyn_cast<Constant>(V))
1832 E = createConstantExpression(C);
1833 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1834 E = createVariableExpression(V);
1835 } else {
1836 // TODO: memory intrinsics.
1837 // TODO: Some day, we should do the forward propagation and reassociation
1838 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001839 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001840 switch (I->getOpcode()) {
1841 case Instruction::ExtractValue:
1842 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001843 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001844 break;
1845 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001846 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001847 break;
1848 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001849 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001850 break;
1851 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001852 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001853 break;
1854 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001855 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001856 break;
1857 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001858 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001859 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001860 case Instruction::ICmp:
1861 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001862 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001863 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001864 case Instruction::Add:
1865 case Instruction::FAdd:
1866 case Instruction::Sub:
1867 case Instruction::FSub:
1868 case Instruction::Mul:
1869 case Instruction::FMul:
1870 case Instruction::UDiv:
1871 case Instruction::SDiv:
1872 case Instruction::FDiv:
1873 case Instruction::URem:
1874 case Instruction::SRem:
1875 case Instruction::FRem:
1876 case Instruction::Shl:
1877 case Instruction::LShr:
1878 case Instruction::AShr:
1879 case Instruction::And:
1880 case Instruction::Or:
1881 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001882 case Instruction::Trunc:
1883 case Instruction::ZExt:
1884 case Instruction::SExt:
1885 case Instruction::FPToUI:
1886 case Instruction::FPToSI:
1887 case Instruction::UIToFP:
1888 case Instruction::SIToFP:
1889 case Instruction::FPTrunc:
1890 case Instruction::FPExt:
1891 case Instruction::PtrToInt:
1892 case Instruction::IntToPtr:
1893 case Instruction::Select:
1894 case Instruction::ExtractElement:
1895 case Instruction::InsertElement:
1896 case Instruction::ShuffleVector:
1897 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001898 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001899 break;
1900 default:
1901 return nullptr;
1902 }
1903 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001904 return E;
1905}
1906
Daniel Berlin0207cca2017-05-21 23:41:56 +00001907// Look up a container in a map, and then call a function for each thing in the
1908// found container.
1909template <typename Map, typename KeyType, typename Func>
1910void NewGVN::for_each_found(Map &M, const KeyType &Key, Func F) {
1911 const auto Result = M.find_as(Key);
1912 if (Result != M.end())
1913 for (typename Map::mapped_type::value_type Mapped : Result->second)
1914 F(Mapped);
1915}
1916
1917// Look up a container of values/instructions in a map, and touch all the
1918// instructions in the container. Then erase value from the map.
1919template <typename Map, typename KeyType>
1920void NewGVN::touchAndErase(Map &M, const KeyType &Key) {
1921 const auto Result = M.find_as(Key);
1922 if (Result != M.end()) {
1923 for (const typename Map::mapped_type::value_type Mapped : Result->second)
1924 TouchedInstructions.set(InstrToDFSNum(Mapped));
1925 M.erase(Result);
1926 }
1927}
1928
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001929void NewGVN::addAdditionalUsers(Value *To, Value *User) const {
1930 AdditionalUsers[To].insert(User);
1931}
1932
Davide Italiano7e274e02016-12-22 16:03:48 +00001933void NewGVN::markUsersTouched(Value *V) {
1934 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001935 for (auto *User : V->users()) {
1936 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlin21279bd2017-04-06 18:52:58 +00001937 TouchedInstructions.set(InstrToDFSNum(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001938 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00001939 touchAndErase(AdditionalUsers, V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001940}
1941
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001942void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const {
Daniel Berlin1316a942017-04-06 18:52:50 +00001943 DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1944 MemoryToUsers[To].insert(U);
1945}
1946
1947void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001948 TouchedInstructions.set(MemoryToDFSNum(MA));
Daniel Berlin1316a942017-04-06 18:52:50 +00001949}
1950
1951void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1952 if (isa<MemoryUse>(MA))
1953 return;
1954 for (auto U : MA->users())
Daniel Berlin21279bd2017-04-06 18:52:58 +00001955 TouchedInstructions.set(MemoryToDFSNum(U));
Daniel Berlin0207cca2017-05-21 23:41:56 +00001956 touchAndErase(MemoryToUsers, MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001957}
1958
Daniel Berlinf7d95802017-02-18 23:06:50 +00001959// Add I to the set of users of a given predicate.
Daniel Berlin6604a2f2017-05-09 16:40:04 +00001960void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00001961 // Don't add temporary instructions to the user lists.
1962 if (AllTempInstructions.count(I))
1963 return;
1964
Daniel Berlinf7d95802017-02-18 23:06:50 +00001965 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1966 PredicateToUsers[PBranch->Condition].insert(I);
1967 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1968 PredicateToUsers[PAssume->Condition].insert(I);
1969}
1970
1971// Touch all the predicates that depend on this instruction.
1972void NewGVN::markPredicateUsersTouched(Instruction *I) {
Daniel Berlin0207cca2017-05-21 23:41:56 +00001973 touchAndErase(PredicateToUsers, I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001974}
1975
Daniel Berlin1316a942017-04-06 18:52:50 +00001976// Mark users affected by a memory leader change.
1977void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001978 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00001979 markMemoryDefTouched(M);
1980}
1981
Daniel Berlin32f8d562017-01-07 16:55:14 +00001982// Touch the instructions that need to be updated after a congruence class has a
1983// leader change, and mark changed values.
Daniel Berlin1316a942017-04-06 18:52:50 +00001984void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
Daniel Berlina8236562017-04-07 18:38:09 +00001985 for (auto M : *CC) {
Daniel Berlin32f8d562017-01-07 16:55:14 +00001986 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlin21279bd2017-04-06 18:52:58 +00001987 TouchedInstructions.set(InstrToDFSNum(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001988 LeaderChanges.insert(M);
1989 }
1990}
1991
Daniel Berlin1316a942017-04-06 18:52:50 +00001992// Give a range of things that have instruction DFS numbers, this will return
1993// the member of the range with the smallest dfs number.
1994template <class T, class Range>
1995T *NewGVN::getMinDFSOfRange(const Range &R) const {
1996 std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
1997 for (const auto X : R) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00001998 auto DFSNum = InstrToDFSNum(X);
Daniel Berlin1316a942017-04-06 18:52:50 +00001999 if (DFSNum < MinDFS.second)
2000 MinDFS = {X, DFSNum};
2001 }
2002 return MinDFS.first;
2003}
2004
2005// This function returns the MemoryAccess that should be the next leader of
2006// congruence class CC, under the assumption that the current leader is going to
2007// disappear.
2008const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
2009 // TODO: If this ends up to slow, we can maintain a next memory leader like we
2010 // do for regular leaders.
2011 // Make sure there will be a leader to find
Davide Italianodc435322017-05-10 19:57:43 +00002012 assert(!CC->definesNoMemory() && "Can't get next leader if there is none");
Daniel Berlina8236562017-04-07 18:38:09 +00002013 if (CC->getStoreCount() > 0) {
2014 if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002015 return getMemoryAccess(NL);
Daniel Berlin1316a942017-04-06 18:52:50 +00002016 // Find the store with the minimum DFS number.
2017 auto *V = getMinDFSOfRange<Value>(make_filter_range(
Daniel Berlina8236562017-04-07 18:38:09 +00002018 *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002019 return getMemoryAccess(cast<StoreInst>(V));
Daniel Berlin1316a942017-04-06 18:52:50 +00002020 }
Daniel Berlina8236562017-04-07 18:38:09 +00002021 assert(CC->getStoreCount() == 0);
Daniel Berlin1316a942017-04-06 18:52:50 +00002022
2023 // Given our assertion, hitting this part must mean
Daniel Berlina8236562017-04-07 18:38:09 +00002024 // !OldClass->memory_empty()
2025 if (CC->memory_size() == 1)
2026 return *CC->memory_begin();
2027 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
Daniel Berlin1316a942017-04-06 18:52:50 +00002028}
2029
2030// This function returns the next value leader of a congruence class, under the
2031// assumption that the current leader is going away. This should end up being
2032// the next most dominating member.
2033Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
2034 // We don't need to sort members if there is only 1, and we don't care about
2035 // sorting the TOP class because everything either gets out of it or is
2036 // unreachable.
2037
Daniel Berlina8236562017-04-07 18:38:09 +00002038 if (CC->size() == 1 || CC == TOPClass) {
2039 return *(CC->begin());
2040 } else if (CC->getNextLeader().first) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002041 ++NumGVNAvoidedSortedLeaderChanges;
Daniel Berlina8236562017-04-07 18:38:09 +00002042 return CC->getNextLeader().first;
Daniel Berlin1316a942017-04-06 18:52:50 +00002043 } else {
2044 ++NumGVNSortedLeaderChanges;
2045 // NOTE: If this ends up to slow, we can maintain a dual structure for
2046 // member testing/insertion, or keep things mostly sorted, and sort only
2047 // here, or use SparseBitVector or ....
Daniel Berlina8236562017-04-07 18:38:09 +00002048 return getMinDFSOfRange<Value>(*CC);
Daniel Berlin1316a942017-04-06 18:52:50 +00002049 }
2050}
2051
2052// Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
2053// the memory members, etc for the move.
2054//
2055// The invariants of this function are:
2056//
2057// I must be moving to NewClass from OldClass The StoreCount of OldClass and
2058// NewClass is expected to have been updated for I already if it is is a store.
2059// The OldClass memory leader has not been updated yet if I was the leader.
2060void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
2061 MemoryAccess *InstMA,
2062 CongruenceClass *OldClass,
2063 CongruenceClass *NewClass) {
2064 // If the leader is I, and we had a represenative MemoryAccess, it should
2065 // be the MemoryAccess of OldClass.
Davide Italianof58a30232017-04-10 23:08:35 +00002066 assert((!InstMA || !OldClass->getMemoryLeader() ||
2067 OldClass->getLeader() != I ||
2068 OldClass->getMemoryLeader() == InstMA) &&
2069 "Representative MemoryAccess mismatch");
Daniel Berlin1316a942017-04-06 18:52:50 +00002070 // First, see what happens to the new class
Daniel Berlina8236562017-04-07 18:38:09 +00002071 if (!NewClass->getMemoryLeader()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002072 // Should be a new class, or a store becoming a leader of a new class.
Daniel Berlina8236562017-04-07 18:38:09 +00002073 assert(NewClass->size() == 1 ||
2074 (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
2075 NewClass->setMemoryLeader(InstMA);
Daniel Berlin1316a942017-04-06 18:52:50 +00002076 // Mark it touched if we didn't just create a singleton
Daniel Berlina8236562017-04-07 18:38:09 +00002077 DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002078 << " due to new memory instruction becoming leader\n");
2079 markMemoryLeaderChangeTouched(NewClass);
2080 }
2081 setMemoryClass(InstMA, NewClass);
2082 // Now, fixup the old class if necessary
Daniel Berlina8236562017-04-07 18:38:09 +00002083 if (OldClass->getMemoryLeader() == InstMA) {
Davide Italianodc435322017-05-10 19:57:43 +00002084 if (!OldClass->definesNoMemory()) {
Daniel Berlina8236562017-04-07 18:38:09 +00002085 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2086 DEBUG(dbgs() << "Memory class leader change for class "
2087 << OldClass->getID() << " to "
2088 << *OldClass->getMemoryLeader()
Daniel Berlin1316a942017-04-06 18:52:50 +00002089 << " due to removal of old leader " << *InstMA << "\n");
2090 markMemoryLeaderChangeTouched(OldClass);
2091 } else
Daniel Berlina8236562017-04-07 18:38:09 +00002092 OldClass->setMemoryLeader(nullptr);
Daniel Berlin1316a942017-04-06 18:52:50 +00002093 }
2094}
2095
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002096// Move a value, currently in OldClass, to be part of NewClass
Daniel Berlin1316a942017-04-06 18:52:50 +00002097// Update OldClass and NewClass for the move (including changing leaders, etc).
2098void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002099 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002100 CongruenceClass *NewClass) {
Daniel Berlina8236562017-04-07 18:38:09 +00002101 if (I == OldClass->getNextLeader().first)
2102 OldClass->resetNextLeader();
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002103
Daniel Berlinff152002017-05-19 19:01:24 +00002104 OldClass->erase(I);
2105 NewClass->insert(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002106
Daniel Berlina8236562017-04-07 18:38:09 +00002107 if (NewClass->getLeader() != I)
2108 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
Daniel Berlin1316a942017-04-06 18:52:50 +00002109 // Handle our special casing of stores.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002110 if (auto *SI = dyn_cast<StoreInst>(I)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002111 OldClass->decStoreCount();
2112 // Okay, so when do we want to make a store a leader of a class?
2113 // If we have a store defined by an earlier load, we want the earlier load
2114 // to lead the class.
2115 // If we have a store defined by something else, we want the store to lead
2116 // the class so everything else gets the "something else" as a value.
Daniel Berlin1316a942017-04-06 18:52:50 +00002117 // If we have a store as the single member of the class, we want the store
Daniel Berlina8236562017-04-07 18:38:09 +00002118 // as the leader
2119 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002120 // If it's a store expression we are using, it means we are not equivalent
2121 // to something earlier.
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002122 if (auto *SE = dyn_cast<StoreExpression>(E)) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002123 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1316a942017-04-06 18:52:50 +00002124 markValueLeaderChangeTouched(NewClass);
2125 // Shift the new class leader to be the store
Daniel Berlina8236562017-04-07 18:38:09 +00002126 DEBUG(dbgs() << "Changing leader of congruence class "
2127 << NewClass->getID() << " from " << *NewClass->getLeader()
2128 << " to " << *SI << " because store joined class\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002129 // If we changed the leader, we have to mark it changed because we don't
2130 // know what it will do to symbolic evlauation.
Daniel Berlina8236562017-04-07 18:38:09 +00002131 NewClass->setLeader(SI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002132 }
2133 // We rely on the code below handling the MemoryAccess change.
2134 }
Daniel Berlina8236562017-04-07 18:38:09 +00002135 NewClass->incStoreCount();
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002136 }
Daniel Berlin1316a942017-04-06 18:52:50 +00002137 // True if there is no memory instructions left in a class that had memory
2138 // instructions before.
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002139
Daniel Berlin1316a942017-04-06 18:52:50 +00002140 // If it's not a memory use, set the MemoryAccess equivalence
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002141 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
Daniel Berlin1316a942017-04-06 18:52:50 +00002142 if (InstMA)
2143 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002144 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002145 // See if we destroyed the class or need to swap leaders.
Daniel Berlina8236562017-04-07 18:38:09 +00002146 if (OldClass->empty() && OldClass != TOPClass) {
2147 if (OldClass->getDefiningExpr()) {
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002148 DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr()
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002149 << " from table\n");
Daniel Berlina8236562017-04-07 18:38:09 +00002150 ExpressionToClass.erase(OldClass->getDefiningExpr());
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002151 }
Daniel Berlina8236562017-04-07 18:38:09 +00002152 } else if (OldClass->getLeader() == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002153 // When the leader changes, the value numbering of
2154 // everything may change due to symbolization changes, so we need to
2155 // reprocess.
Daniel Berlina8236562017-04-07 18:38:09 +00002156 DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
Daniel Berlin1316a942017-04-06 18:52:50 +00002157 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002158 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00002159 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1316a942017-04-06 18:52:50 +00002160 // Note that this is basically clean up for the expression removal that
2161 // happens below. If we remove stores from a class, we may leave it as a
2162 // class of equivalent memory phis.
Daniel Berlina8236562017-04-07 18:38:09 +00002163 if (OldClass->getStoreCount() == 0) {
2164 if (OldClass->getStoredValue())
2165 OldClass->setStoredValue(nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002166 }
Daniel Berlina8236562017-04-07 18:38:09 +00002167 OldClass->setLeader(getNextValueLeader(OldClass));
2168 OldClass->resetNextLeader();
Daniel Berlin1316a942017-04-06 18:52:50 +00002169 markValueLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002170 }
2171}
2172
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002173// For a given expression, mark the phi of ops instructions that could have
2174// changed as a result.
2175void NewGVN::markPhiOfOpsChanged(const HashedExpression &HE) {
Daniel Berlin0207cca2017-05-21 23:41:56 +00002176 touchAndErase(ExpressionToPhiOfOps, HE);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002177}
Daniel Berlin0207cca2017-05-21 23:41:56 +00002178
Davide Italiano7e274e02016-12-22 16:03:48 +00002179// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002180void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002181 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00002182 // TOP.
Daniel Berline021d2d2017-05-19 20:22:20 +00002183
2184 CongruenceClass *IClass = ValueToClass.lookup(I);
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002185 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00002186 // Dead classes should have been eliminated from the mapping.
Daniel Berlin1316a942017-04-06 18:52:50 +00002187 assert(!IClass->isDead() && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002188
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002189 CongruenceClass *EClass = nullptr;
2190 HashedExpression HE(E);
Daniel Berlin02c6b172017-01-02 18:00:53 +00002191 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002192 EClass = ValueToClass.lookup(VE->getVariableValue());
Daniel Berline021d2d2017-05-19 20:22:20 +00002193 } else if (isa<DeadExpression>(E)) {
2194 EClass = TOPClass;
2195 }
2196 if (!EClass) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002197 auto lookupResult = ExpressionToClass.insert_as({E, nullptr}, HE);
Davide Italiano7e274e02016-12-22 16:03:48 +00002198
2199 // If it's not in the value table, create a new congruence class.
2200 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00002201 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00002202 auto place = lookupResult.first;
2203 place->second = NewClass;
2204
2205 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002206 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002207 NewClass->setLeader(CE->getConstantValue());
Daniel Berlin32f8d562017-01-07 16:55:14 +00002208 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2209 StoreInst *SI = SE->getStoreInst();
Daniel Berlina8236562017-04-07 18:38:09 +00002210 NewClass->setLeader(SI);
Daniel Berlin629e1ff2017-05-16 06:06:15 +00002211 NewClass->setStoredValue(SE->getStoredValue());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002212 // The RepMemoryAccess field will be filled in properly by the
2213 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00002214 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00002215 NewClass->setLeader(I);
Daniel Berlin32f8d562017-01-07 16:55:14 +00002216 }
2217 assert(!isa<VariableExpression>(E) &&
2218 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00002219
2220 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002221 DEBUG(dbgs() << "Created new congruence class for " << *I
Daniel Berlina8236562017-04-07 18:38:09 +00002222 << " using expression " << *E << " at " << NewClass->getID()
2223 << " and leader " << *(NewClass->getLeader()));
2224 if (NewClass->getStoredValue())
2225 DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
Daniel Berlin26addef2017-01-20 21:04:30 +00002226 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002227 } else {
2228 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00002229 if (isa<ConstantExpression>(E))
Davide Italianof58a30232017-04-10 23:08:35 +00002230 assert((isa<Constant>(EClass->getLeader()) ||
2231 (EClass->getStoredValue() &&
2232 isa<Constant>(EClass->getStoredValue()))) &&
2233 "Any class with a constant expression should have a "
2234 "constant leader");
Daniel Berlin589cecc2017-01-02 18:00:46 +00002235
Davide Italiano7e274e02016-12-22 16:03:48 +00002236 assert(EClass && "Somehow don't have an eclass");
2237
Daniel Berlin1316a942017-04-06 18:52:50 +00002238 assert(!EClass->isDead() && "We accidentally looked up a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00002239 }
2240 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002241 bool ClassChanged = IClass != EClass;
2242 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00002243 if (ClassChanged || LeaderChanged) {
Daniel Berlina8236562017-04-07 18:38:09 +00002244 DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
Davide Italiano7e274e02016-12-22 16:03:48 +00002245 << "\n");
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002246 if (ClassChanged) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002247 moveValueToNewCongruenceClass(I, E, IClass, EClass);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002248 markPhiOfOpsChanged(HE);
2249 }
2250
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002251 markUsersTouched(I);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002252 if (MemoryAccess *MA = getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00002253 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002254 if (auto *CI = dyn_cast<CmpInst>(I))
2255 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00002256 }
Daniel Berlin45403572017-05-16 19:58:47 +00002257 // If we changed the class of the store, we want to ensure nothing finds the
2258 // old store expression. In particular, loads do not compare against stored
2259 // value, so they will find old store expressions (and associated class
2260 // mappings) if we leave them in the table.
Davide Italianoee49f492017-05-19 04:06:10 +00002261 if (ClassChanged && isa<StoreInst>(I)) {
Daniel Berlin45403572017-05-16 19:58:47 +00002262 auto *OldE = ValueToExpression.lookup(I);
2263 // It could just be that the old class died. We don't want to erase it if we
2264 // just moved classes.
Davide Italianoee49f492017-05-19 04:06:10 +00002265 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE)
Daniel Berlin45403572017-05-16 19:58:47 +00002266 ExpressionToClass.erase(OldE);
2267 }
2268 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00002269}
2270
2271// Process the fact that Edge (from, to) is reachable, including marking
2272// any newly reachable blocks and instructions for processing.
2273void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2274 // Check if the Edge was reachable before.
2275 if (ReachableEdges.insert({From, To}).second) {
2276 // If this block wasn't reachable before, all instructions are touched.
2277 if (ReachableBlocks.insert(To).second) {
2278 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2279 const auto &InstRange = BlockInstRange.lookup(To);
2280 TouchedInstructions.set(InstRange.first, InstRange.second);
2281 } else {
2282 DEBUG(dbgs() << "Block " << getBlockName(To)
2283 << " was reachable, but new edge {" << getBlockName(From)
2284 << "," << getBlockName(To) << "} to it found\n");
2285
2286 // We've made an edge reachable to an existing block, which may
2287 // impact predicates. Otherwise, only mark the phi nodes as touched, as
2288 // they are the only thing that depend on new edges. Anything using their
2289 // values will get propagated to if necessary.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002290 if (MemoryAccess *MemPhi = getMemoryAccess(To))
Daniel Berlin21279bd2017-04-06 18:52:58 +00002291 TouchedInstructions.set(InstrToDFSNum(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00002292
Davide Italiano7e274e02016-12-22 16:03:48 +00002293 auto BI = To->begin();
2294 while (isa<PHINode>(BI)) {
Daniel Berlin21279bd2017-04-06 18:52:58 +00002295 TouchedInstructions.set(InstrToDFSNum(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00002296 ++BI;
2297 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00002298 for_each_found(PHIOfOpsPHIs, To, [&](const PHINode *I) {
2299 TouchedInstructions.set(InstrToDFSNum(I));
2300 });
Davide Italiano7e274e02016-12-22 16:03:48 +00002301 }
2302 }
2303}
2304
2305// Given a predicate condition (from a switch, cmp, or whatever) and a block,
2306// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00002307Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00002308 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002309 if (isa<Constant>(Result))
2310 return Result;
2311 return nullptr;
2312}
2313
2314// Process the outgoing edges of a block for reachability.
2315void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2316 // Evaluate reachability of terminator instruction.
2317 BranchInst *BR;
2318 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2319 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002320 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002321 if (!CondEvaluated) {
2322 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00002323 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002324 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2325 CondEvaluated = CE->getConstantValue();
2326 }
2327 } else if (isa<ConstantInt>(Cond)) {
2328 CondEvaluated = Cond;
2329 }
2330 }
2331 ConstantInt *CI;
2332 BasicBlock *TrueSucc = BR->getSuccessor(0);
2333 BasicBlock *FalseSucc = BR->getSuccessor(1);
2334 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2335 if (CI->isOne()) {
2336 DEBUG(dbgs() << "Condition for Terminator " << *TI
2337 << " evaluated to true\n");
2338 updateReachableEdge(B, TrueSucc);
2339 } else if (CI->isZero()) {
2340 DEBUG(dbgs() << "Condition for Terminator " << *TI
2341 << " evaluated to false\n");
2342 updateReachableEdge(B, FalseSucc);
2343 }
2344 } else {
2345 updateReachableEdge(B, TrueSucc);
2346 updateReachableEdge(B, FalseSucc);
2347 }
2348 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2349 // For switches, propagate the case values into the case
2350 // destinations.
2351
2352 // Remember how many outgoing edges there are to every successor.
2353 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2354
Davide Italiano7e274e02016-12-22 16:03:48 +00002355 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00002356 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00002357 // See if we were able to turn this switch statement into a constant.
2358 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002359 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00002360 // We should be able to get case value for this.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002361 auto Case = *SI->findCaseValue(CondVal);
2362 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002363 // We proved the value is outside of the range of the case.
2364 // We can't do anything other than mark the default dest as reachable,
2365 // and go home.
2366 updateReachableEdge(B, SI->getDefaultDest());
2367 return;
2368 }
2369 // Now get where it goes and mark it reachable.
Chandler Carruth927d8e62017-04-12 07:27:28 +00002370 BasicBlock *TargetBlock = Case.getCaseSuccessor();
Davide Italiano7e274e02016-12-22 16:03:48 +00002371 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00002372 } else {
2373 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2374 BasicBlock *TargetBlock = SI->getSuccessor(i);
2375 ++SwitchEdges[TargetBlock];
2376 updateReachableEdge(B, TargetBlock);
2377 }
2378 }
2379 } else {
2380 // Otherwise this is either unconditional, or a type we have no
2381 // idea about. Just mark successors as reachable.
2382 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2383 BasicBlock *TargetBlock = TI->getSuccessor(i);
2384 updateReachableEdge(B, TargetBlock);
2385 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002386
2387 // This also may be a memory defining terminator, in which case, set it
Daniel Berlin1316a942017-04-06 18:52:50 +00002388 // equivalent only to itself.
2389 //
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002390 auto *MA = getMemoryAccess(TI);
Daniel Berlin1316a942017-04-06 18:52:50 +00002391 if (MA && !isa<MemoryUse>(MA)) {
2392 auto *CC = ensureLeaderOfMemoryClass(MA);
2393 if (setMemoryClass(MA, CC))
2394 markMemoryUsersTouched(MA);
2395 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002396 }
2397}
2398
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002399void NewGVN::addPhiOfOps(PHINode *Op, BasicBlock *BB,
2400 Instruction *ExistingValue) {
2401 InstrDFS[Op] = InstrToDFSNum(ExistingValue);
2402 AllTempInstructions.insert(Op);
2403 PHIOfOpsPHIs[BB].push_back(Op);
2404 TempToBlock[Op] = BB;
2405 if (ExistingValue)
2406 RealToTemp[ExistingValue] = Op;
2407}
2408
2409static bool okayForPHIOfOps(const Instruction *I) {
2410 return isa<BinaryOperator>(I) || isa<SelectInst>(I) || isa<CmpInst>(I) ||
2411 isa<LoadInst>(I);
2412}
2413
2414// When we see an instruction that is an op of phis, generate the equivalent phi
2415// of ops form.
2416const Expression *
2417NewGVN::makePossiblePhiOfOps(Instruction *I, bool HasBackedge,
2418 SmallPtrSetImpl<Value *> &Visited) {
2419 if (!okayForPHIOfOps(I))
2420 return nullptr;
2421
2422 if (!Visited.insert(I).second)
2423 return nullptr;
2424 // For now, we require the instruction be cycle free because we don't
2425 // *always* create a phi of ops for instructions that could be done as phi
2426 // of ops, we only do it if we think it is useful. If we did do it all the
2427 // time, we could remove the cycle free check.
2428 if (!isCycleFree(I))
2429 return nullptr;
2430
2431 unsigned IDFSNum = InstrToDFSNum(I);
2432 // Pretty much all of the instructions we can convert to phi of ops over a
2433 // backedge that are adds, are really induction variables, and those are
2434 // pretty much pointless to convert. This is very coarse-grained for a
2435 // test, so if we do find some value, we can change it later.
2436 // But otherwise, what can happen is we convert the induction variable from
2437 //
2438 // i = phi (0, tmp)
2439 // tmp = i + 1
2440 //
2441 // to
2442 // i = phi (0, tmpphi)
2443 // tmpphi = phi(1, tmpphi+1)
2444 //
2445 // Which we don't want to happen. We could just avoid this for all non-cycle
2446 // free phis, and we made go that route.
2447 if (HasBackedge && I->getOpcode() == Instruction::Add)
2448 return nullptr;
2449
2450 SmallPtrSet<const Value *, 8> ProcessedPHIs;
2451 // TODO: We don't do phi translation on memory accesses because it's
2452 // complicated. For a load, we'd need to be able to simulate a new memoryuse,
2453 // which we don't have a good way of doing ATM.
2454 auto *MemAccess = getMemoryAccess(I);
2455 // If the memory operation is defined by a memory operation this block that
2456 // isn't a MemoryPhi, transforming the pointer backwards through a scalar phi
2457 // can't help, as it would still be killed by that memory operation.
2458 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2459 MemAccess->getDefiningAccess()->getBlock() == I->getParent())
2460 return nullptr;
2461
2462 // Convert op of phis to phi of ops
2463 for (auto &Op : I->operands()) {
2464 if (!isa<PHINode>(Op))
2465 continue;
2466 auto *OpPHI = cast<PHINode>(Op);
2467 // No point in doing this for one-operand phis.
2468 if (OpPHI->getNumOperands() == 1)
2469 continue;
2470 if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
2471 return nullptr;
2472 SmallVector<std::pair<Value *, BasicBlock *>, 4> Ops;
2473 auto *PHIBlock = getBlockForValue(OpPHI);
2474 for (auto PredBB : OpPHI->blocks()) {
2475 Value *FoundVal = nullptr;
2476 // We could just skip unreachable edges entirely but it's tricky to do
2477 // with rewriting existing phi nodes.
2478 if (ReachableEdges.count({PredBB, PHIBlock})) {
2479 // Clone the instruction, create an expression from it, and see if we
2480 // have a leader.
2481 Instruction *ValueOp = I->clone();
2482 auto Iter = TempToMemory.end();
2483 if (MemAccess)
2484 Iter = TempToMemory.insert({ValueOp, MemAccess}).first;
2485
2486 for (auto &Op : ValueOp->operands()) {
2487 Op = Op->DoPHITranslation(PHIBlock, PredBB);
2488 // When this operand changes, it could change whether there is a
2489 // leader for us or not.
2490 addAdditionalUsers(Op, I);
2491 }
2492 // Make sure it's marked as a temporary instruction.
2493 AllTempInstructions.insert(ValueOp);
2494 // and make sure anything that tries to add it's DFS number is
2495 // redirected to the instruction we are making a phi of ops
2496 // for.
2497 InstrDFS.insert({ValueOp, IDFSNum});
2498 const Expression *E = performSymbolicEvaluation(ValueOp, Visited);
2499 InstrDFS.erase(ValueOp);
2500 AllTempInstructions.erase(ValueOp);
2501 ValueOp->deleteValue();
2502 if (MemAccess)
2503 TempToMemory.erase(Iter);
2504 if (!E)
2505 return nullptr;
2506 FoundVal = findPhiOfOpsLeader(E, PredBB);
2507 if (!FoundVal) {
2508 ExpressionToPhiOfOps[E].insert(I);
2509 return nullptr;
2510 }
2511 if (auto *SI = dyn_cast<StoreInst>(FoundVal))
2512 FoundVal = SI->getValueOperand();
2513 } else {
2514 DEBUG(dbgs() << "Skipping phi of ops operand for incoming block "
2515 << getBlockName(PredBB)
2516 << " because the block is unreachable\n");
2517 FoundVal = UndefValue::get(I->getType());
2518 }
2519
2520 Ops.push_back({FoundVal, PredBB});
2521 DEBUG(dbgs() << "Found phi of ops operand " << *FoundVal << " in "
2522 << getBlockName(PredBB) << "\n");
2523 }
2524 auto *ValuePHI = RealToTemp.lookup(I);
2525 bool NewPHI = false;
2526 if (!ValuePHI) {
2527 ValuePHI = PHINode::Create(I->getType(), OpPHI->getNumOperands());
2528 addPhiOfOps(ValuePHI, PHIBlock, I);
2529 NewPHI = true;
2530 NumGVNPHIOfOpsCreated++;
2531 }
2532 if (NewPHI) {
2533 for (auto PHIOp : Ops)
2534 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2535 } else {
2536 unsigned int i = 0;
2537 for (auto PHIOp : Ops) {
2538 ValuePHI->setIncomingValue(i, PHIOp.first);
2539 ValuePHI->setIncomingBlock(i, PHIOp.second);
2540 ++i;
2541 }
2542 }
2543
2544 DEBUG(dbgs() << "Created phi of ops " << *ValuePHI << " for " << *I
2545 << "\n");
2546 return performSymbolicEvaluation(ValuePHI, Visited);
2547 }
2548 return nullptr;
2549}
2550
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002551// The algorithm initially places the values of the routine in the TOP
2552// congruence class. The leader of TOP is the undetermined value `undef`.
2553// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00002554void NewGVN::initializeCongruenceClasses(Function &F) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002555 NextCongruenceNum = 0;
2556
2557 // Note that even though we use the live on entry def as a representative
2558 // MemoryAccess, it is *not* the same as the actual live on entry def. We
2559 // have no real equivalemnt to undef for MemoryAccesses, and so we really
2560 // should be checking whether the MemoryAccess is top if we want to know if it
2561 // is equivalent to everything. Otherwise, what this really signifies is that
2562 // the access "it reaches all the way back to the beginning of the function"
2563
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002564 // Initialize all other instructions to be in TOP class.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002565 TOPClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlina8236562017-04-07 18:38:09 +00002566 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
Daniel Berlin1316a942017-04-06 18:52:50 +00002567 // The live on entry def gets put into it's own class
2568 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2569 createMemoryClass(MSSA->getLiveOnEntryDef());
Daniel Berlin589cecc2017-01-02 18:00:46 +00002570
Daniel Berlinec9deb72017-04-18 17:06:11 +00002571 for (auto DTN : nodes(DT)) {
2572 BasicBlock *BB = DTN->getBlock();
Daniel Berlin1316a942017-04-06 18:52:50 +00002573 // All MemoryAccesses are equivalent to live on entry to start. They must
2574 // be initialized to something so that initial changes are noticed. For
2575 // the maximal answer, we initialize them all to be the same as
2576 // liveOnEntry.
Daniel Berlinec9deb72017-04-18 17:06:11 +00002577 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
Daniel Berlin1316a942017-04-06 18:52:50 +00002578 if (MemoryBlockDefs)
2579 for (const auto &Def : *MemoryBlockDefs) {
2580 MemoryAccessToClass[&Def] = TOPClass;
2581 auto *MD = dyn_cast<MemoryDef>(&Def);
2582 // Insert the memory phis into the member list.
2583 if (!MD) {
2584 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
Daniel Berlina8236562017-04-07 18:38:09 +00002585 TOPClass->memory_insert(MP);
Daniel Berlin1316a942017-04-06 18:52:50 +00002586 MemoryPhiState.insert({MP, MPS_TOP});
2587 }
2588
2589 if (MD && isa<StoreInst>(MD->getMemoryInst()))
Daniel Berlina8236562017-04-07 18:38:09 +00002590 TOPClass->incStoreCount();
Daniel Berlin1316a942017-04-06 18:52:50 +00002591 }
Daniel Berlinec9deb72017-04-18 17:06:11 +00002592 for (auto &I : *BB) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002593 // TODO: Move to helper
2594 if (isa<PHINode>(&I))
2595 for (auto *U : I.users())
2596 if (auto *UInst = dyn_cast<Instruction>(U))
2597 if (InstrToDFSNum(UInst) != 0 && okayForPHIOfOps(UInst))
2598 PHINodeUses.insert(UInst);
Daniel Berlin22a4a012017-02-11 15:20:15 +00002599 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002600 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00002601 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2602 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002603 TOPClass->insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002604 ValueToClass[&I] = TOPClass;
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002605 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002606 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002607
2608 // Initialize arguments to be in their own unique congruence classes
2609 for (auto &FA : F.args())
2610 createSingletonCongruenceClass(&FA);
2611}
2612
2613void NewGVN::cleanupTables() {
2614 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
Daniel Berlina8236562017-04-07 18:38:09 +00002615 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2616 << " has " << CongruenceClasses[i]->size() << " members\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002617 // Make sure we delete the congruence class (probably worth switching to
2618 // a unique_ptr at some point.
2619 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00002620 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002621 }
2622
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002623 // Destroy the value expressions
2624 SmallVector<Instruction *, 8> TempInst(AllTempInstructions.begin(),
2625 AllTempInstructions.end());
2626 AllTempInstructions.clear();
2627
2628 // We have to drop all references for everything first, so there are no uses
2629 // left as we delete them.
2630 for (auto *I : TempInst) {
2631 I->dropAllReferences();
2632 }
2633
2634 while (!TempInst.empty()) {
2635 auto *I = TempInst.back();
2636 TempInst.pop_back();
2637 I->deleteValue();
2638 }
2639
Davide Italiano7e274e02016-12-22 16:03:48 +00002640 ValueToClass.clear();
2641 ArgRecycler.clear(ExpressionAllocator);
2642 ExpressionAllocator.Reset();
2643 CongruenceClasses.clear();
2644 ExpressionToClass.clear();
2645 ValueToExpression.clear();
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002646 RealToTemp.clear();
2647 AdditionalUsers.clear();
2648 ExpressionToPhiOfOps.clear();
2649 TempToBlock.clear();
2650 TempToMemory.clear();
2651 PHIOfOpsPHIs.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002652 ReachableBlocks.clear();
2653 ReachableEdges.clear();
2654#ifndef NDEBUG
2655 ProcessedCount.clear();
2656#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00002657 InstrDFS.clear();
2658 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002659 DFSToInstr.clear();
2660 BlockInstRange.clear();
2661 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002662 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002663 PredicateToUsers.clear();
Daniel Berlin1316a942017-04-06 18:52:50 +00002664 MemoryToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00002665}
2666
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002667// Assign local DFS number mapping to instructions, and leave space for Value
2668// PHI's.
Davide Italiano7e274e02016-12-22 16:03:48 +00002669std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2670 unsigned Start) {
2671 unsigned End = Start;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002672 if (MemoryAccess *MemPhi = getMemoryAccess(B)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002673 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002674 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002675 }
2676
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002677 // Then the real block goes next.
Davide Italiano7e274e02016-12-22 16:03:48 +00002678 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00002679 // There's no need to call isInstructionTriviallyDead more than once on
2680 // an instruction. Therefore, once we know that an instruction is dead
2681 // we change its DFS number so that it doesn't get value numbered.
2682 if (isInstructionTriviallyDead(&I, TLI)) {
2683 InstrDFS[&I] = 0;
2684 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2685 markInstructionForDeletion(&I);
2686 continue;
2687 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002688 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002689 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002690 }
2691
2692 // All of the range functions taken half-open ranges (open on the end side).
2693 // So we do not subtract one from count, because at this point it is one
2694 // greater than the last instruction.
2695 return std::make_pair(Start, End);
2696}
2697
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002698void NewGVN::updateProcessedCount(const Value *V) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002699#ifndef NDEBUG
2700 if (ProcessedCount.count(V) == 0) {
2701 ProcessedCount.insert({V, 1});
2702 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00002703 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00002704 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00002705 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00002706 }
2707#endif
2708}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002709// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2710void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2711 // If all the arguments are the same, the MemoryPhi has the same value as the
2712 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00002713 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlin41b39162017-03-18 15:41:36 +00002714 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002715 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002716 return lookupMemoryLeader(cast<MemoryAccess>(U)) != MP &&
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002717 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00002718 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002719 });
Daniel Berlinc4796862017-01-27 02:37:11 +00002720 // If all that is left is nothing, our memoryphi is undef. We keep it as
2721 // InitialClass. Note: The only case this should happen is if we have at
2722 // least one self-argument.
2723 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002724 if (setMemoryClass(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00002725 markMemoryUsersTouched(MP);
2726 return;
2727 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002728
2729 // Transform the remaining operands into operand leaders.
2730 // FIXME: mapped_iterator should have a range version.
2731 auto LookupFunc = [&](const Use &U) {
Daniel Berlin1316a942017-04-06 18:52:50 +00002732 return lookupMemoryLeader(cast<MemoryAccess>(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002733 };
2734 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2735 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2736
2737 // and now check if all the elements are equal.
2738 // Sadly, we can't use std::equals since these are random access iterators.
Daniel Berlin1316a942017-04-06 18:52:50 +00002739 const auto *AllSameValue = *MappedBegin;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002740 ++MappedBegin;
2741 bool AllEqual = std::all_of(
2742 MappedBegin, MappedEnd,
2743 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2744
2745 if (AllEqual)
2746 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2747 else
2748 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
Daniel Berlin1316a942017-04-06 18:52:50 +00002749 // If it's equal to something, it's in that class. Otherwise, it has to be in
2750 // a class where it is the leader (other things may be equivalent to it, but
2751 // it needs to start off in its own class, which means it must have been the
2752 // leader, and it can't have stopped being the leader because it was never
2753 // removed).
2754 CongruenceClass *CC =
2755 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2756 auto OldState = MemoryPhiState.lookup(MP);
2757 assert(OldState != MPS_Invalid && "Invalid memory phi state");
2758 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2759 MemoryPhiState[MP] = NewState;
2760 if (setMemoryClass(MP, CC) || OldState != NewState)
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002761 markMemoryUsersTouched(MP);
2762}
2763
2764// Value number a single instruction, symbolically evaluating, performing
2765// congruence finding, and updating mappings.
2766void NewGVN::valueNumberInstruction(Instruction *I) {
2767 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002768 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00002769 const Expression *Symbolized = nullptr;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002770 SmallPtrSet<Value *, 2> Visited;
Daniel Berlin283a6082017-03-01 19:59:26 +00002771 if (DebugCounter::shouldExecute(VNCounter)) {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002772 Symbolized = performSymbolicEvaluation(I, Visited);
2773 // Make a phi of ops if necessary
2774 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
2775 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
2776 // FIXME: Backedge argument
2777 auto *PHIE = makePossiblePhiOfOps(I, false, Visited);
2778 if (PHIE)
2779 Symbolized = PHIE;
2780 }
2781
Daniel Berlin283a6082017-03-01 19:59:26 +00002782 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00002783 // Mark the instruction as unused so we don't value number it again.
2784 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00002785 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00002786 // If we couldn't come up with a symbolic expression, use the unknown
2787 // expression
Daniel Berlinb527b2c2017-05-19 19:01:27 +00002788 if (Symbolized == nullptr)
Daniel Berlin02c6b172017-01-02 18:00:53 +00002789 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002790 performCongruenceFinding(I, Symbolized);
2791 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002792 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00002793 // don't currently understand. We don't place non-value producing
2794 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00002795 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00002796 auto *Symbolized = createUnknownExpression(I);
2797 performCongruenceFinding(I, Symbolized);
2798 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002799 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2800 }
2801}
Davide Italiano7e274e02016-12-22 16:03:48 +00002802
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002803// Check if there is a path, using single or equal argument phi nodes, from
2804// First to Second.
Davide Italianoeab0de22017-05-18 23:22:44 +00002805bool NewGVN::singleReachablePHIPath(
2806 SmallPtrSet<const MemoryAccess *, 8> &Visited, const MemoryAccess *First,
2807 const MemoryAccess *Second) const {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002808 if (First == Second)
2809 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00002810 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002811 return false;
Daniel Berlin1316a942017-04-06 18:52:50 +00002812
Davide Italianoeab0de22017-05-18 23:22:44 +00002813 // This is not perfect, but as we're just verifying here, we can live with
2814 // the loss of precision. The real solution would be that of doing strongly
2815 // connected component finding in this routine, and it's probably not worth
2816 // the complexity for the time being. So, we just keep a set of visited
2817 // MemoryAccess and return true when we hit a cycle.
2818 if (Visited.count(First))
2819 return true;
2820 Visited.insert(First);
2821
Daniel Berlin871ecd92017-04-01 09:44:24 +00002822 const auto *EndDef = First;
Daniel Berlin3082b8e2017-04-05 17:26:25 +00002823 for (auto *ChainDef : optimized_def_chain(First)) {
Daniel Berlin871ecd92017-04-01 09:44:24 +00002824 if (ChainDef == Second)
2825 return true;
2826 if (MSSA->isLiveOnEntryDef(ChainDef))
2827 return false;
2828 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002829 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00002830 auto *MP = cast<MemoryPhi>(EndDef);
2831 auto ReachableOperandPred = [&](const Use &U) {
2832 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2833 };
2834 auto FilteredPhiArgs =
2835 make_filter_range(MP->operands(), ReachableOperandPred);
2836 SmallVector<const Value *, 32> OperandList;
2837 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2838 std::back_inserter(OperandList));
2839 bool Okay = OperandList.size() == 1;
2840 if (!Okay)
2841 Okay =
2842 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2843 if (Okay)
Davide Italianoeab0de22017-05-18 23:22:44 +00002844 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
2845 Second);
Daniel Berlin871ecd92017-04-01 09:44:24 +00002846 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002847}
2848
Daniel Berlin589cecc2017-01-02 18:00:46 +00002849// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002850// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00002851// subject to very rare false negatives. It is only useful for
2852// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00002853void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00002854#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002855 // Verify that the memory table equivalence and memory member set match
2856 for (const auto *CC : CongruenceClasses) {
2857 if (CC == TOPClass || CC->isDead())
2858 continue;
Daniel Berlina8236562017-04-07 18:38:09 +00002859 if (CC->getStoreCount() != 0) {
Davide Italianof58a30232017-04-10 23:08:35 +00002860 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002861 "Any class with a store as a leader should have a "
2862 "representative stored value");
Daniel Berlina8236562017-04-07 18:38:09 +00002863 assert(CC->getMemoryLeader() &&
Davide Italiano94bf7842017-05-04 17:26:15 +00002864 "Any congruence class with a store should have a "
2865 "representative access");
Daniel Berlin1316a942017-04-06 18:52:50 +00002866 }
2867
Daniel Berlina8236562017-04-07 18:38:09 +00002868 if (CC->getMemoryLeader())
2869 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
Daniel Berlin1316a942017-04-06 18:52:50 +00002870 "Representative MemoryAccess does not appear to be reverse "
2871 "mapped properly");
Daniel Berlina8236562017-04-07 18:38:09 +00002872 for (auto M : CC->memory())
Daniel Berlin1316a942017-04-06 18:52:50 +00002873 assert(MemoryAccessToClass.lookup(M) == CC &&
2874 "Memory member does not appear to be reverse mapped properly");
2875 }
2876
2877 // Anything equivalent in the MemoryAccess table should be in the same
Daniel Berlin589cecc2017-01-02 18:00:46 +00002878 // congruence class.
2879
2880 // Filter out the unreachable and trivially dead entries, because they may
2881 // never have been updated if the instructions were not processed.
2882 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002883 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002884 bool Result = ReachableBlocks.count(Pair.first->getBlock());
Daniel Berlin9d0042b2017-04-18 20:15:47 +00002885 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2886 MemoryToDFSNum(Pair.first) == 0)
Daniel Berlin589cecc2017-01-02 18:00:46 +00002887 return false;
2888 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2889 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
Davide Italiano6e7a2122017-05-15 18:50:53 +00002890
2891 // We could have phi nodes which operands are all trivially dead,
2892 // so we don't process them.
2893 if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
2894 for (auto &U : MemPHI->incoming_values()) {
2895 if (Instruction *I = dyn_cast<Instruction>(U.get())) {
2896 if (!isInstructionTriviallyDead(I))
2897 return true;
2898 }
2899 }
2900 return false;
2901 }
2902
Daniel Berlin589cecc2017-01-02 18:00:46 +00002903 return true;
2904 };
2905
Daniel Berlin1ea5f322017-01-26 22:21:48 +00002906 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002907 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002908 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlina8236562017-04-07 18:38:09 +00002909 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
Davide Italianoeab0de22017-05-18 23:22:44 +00002910 if (FirstMUD && SecondMUD) {
2911 SmallPtrSet<const MemoryAccess *, 8> VisitedMAS;
2912 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00002913 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2914 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2915 "The instructions for these memory operations should have "
2916 "been in the same congruence class or reachable through"
2917 "a single argument phi");
Davide Italianoeab0de22017-05-18 23:22:44 +00002918 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00002919 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00002920 // We can only sanely verify that MemoryDefs in the operand list all have
2921 // the same class.
2922 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00002923 return ReachableEdges.count(
2924 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00002925 isa<MemoryDef>(U);
2926
2927 };
2928 // All arguments should in the same class, ignoring unreachable arguments
2929 auto FilteredPhiArgs =
2930 make_filter_range(FirstMP->operands(), ReachableOperandPred);
2931 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2932 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2933 std::back_inserter(PhiOpClasses), [&](const Use &U) {
2934 const MemoryDef *MD = cast<MemoryDef>(U);
2935 return ValueToClass.lookup(MD->getMemoryInst());
2936 });
2937 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2938 PhiOpClasses.begin()) &&
2939 "All MemoryPhi arguments should be in the same class");
2940 }
2941 }
Davide Italianoe9781e72017-03-25 02:40:02 +00002942#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00002943}
2944
Daniel Berlin06329a92017-03-18 15:41:40 +00002945// Verify that the sparse propagation we did actually found the maximal fixpoint
2946// We do this by storing the value to class mapping, touching all instructions,
2947// and redoing the iteration to see if anything changed.
2948void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00002949#ifndef NDEBUG
Daniel Berlin1316a942017-04-06 18:52:50 +00002950 DEBUG(dbgs() << "Beginning iteration verification\n");
Daniel Berlin06329a92017-03-18 15:41:40 +00002951 if (DebugCounter::isCounterSet(VNCounter))
2952 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2953
2954 // Note that we have to store the actual classes, as we may change existing
2955 // classes during iteration. This is because our memory iteration propagation
2956 // is not perfect, and so may waste a little work. But it should generate
2957 // exactly the same congruence classes we have now, with different IDs.
2958 std::map<const Value *, CongruenceClass> BeforeIteration;
2959
2960 for (auto &KV : ValueToClass) {
2961 if (auto *I = dyn_cast<Instruction>(KV.first))
2962 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002963 if (InstrToDFSNum(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002964 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002965 BeforeIteration.insert({KV.first, *KV.second});
2966 }
2967
2968 TouchedInstructions.set();
2969 TouchedInstructions.reset(0);
2970 iterateTouchedInstructions();
2971 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2972 EqualClasses;
2973 for (const auto &KV : ValueToClass) {
2974 if (auto *I = dyn_cast<Instruction>(KV.first))
2975 // Skip unused/dead instructions.
Daniel Berlin21279bd2017-04-06 18:52:58 +00002976 if (InstrToDFSNum(I) == 0)
Daniel Berlin06329a92017-03-18 15:41:40 +00002977 continue;
2978 // We could sink these uses, but i think this adds a bit of clarity here as
2979 // to what we are comparing.
2980 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2981 auto *AfterCC = KV.second;
2982 // Note that the classes can't change at this point, so we memoize the set
2983 // that are equal.
2984 if (!EqualClasses.count({BeforeCC, AfterCC})) {
Daniel Berlina8236562017-04-07 18:38:09 +00002985 assert(BeforeCC->isEquivalentTo(AfterCC) &&
Daniel Berlin06329a92017-03-18 15:41:40 +00002986 "Value number changed after main loop completed!");
2987 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00002988 }
2989 }
2990#endif
2991}
2992
Daniel Berlin45403572017-05-16 19:58:47 +00002993// Verify that for each store expression in the expression to class mapping,
2994// only the latest appears, and multiple ones do not appear.
2995// Because loads do not use the stored value when doing equality with stores,
2996// if we don't erase the old store expressions from the table, a load can find
2997// a no-longer valid StoreExpression.
2998void NewGVN::verifyStoreExpressions() const {
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00002999#ifndef NDEBUG
Daniel Berlin45403572017-05-16 19:58:47 +00003000 DenseSet<std::pair<const Value *, const Value *>> StoreExpressionSet;
3001 for (const auto &KV : ExpressionToClass) {
3002 if (auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3003 // Make sure a version that will conflict with loads is not already there
3004 auto Res =
3005 StoreExpressionSet.insert({SE->getOperand(0), SE->getMemoryLeader()});
3006 assert(Res.second &&
3007 "Stored expression conflict exists in expression table");
3008 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3009 assert(ValueExpr && ValueExpr->equals(*SE) &&
3010 "StoreExpression in ExpressionToClass is not latest "
3011 "StoreExpression for value");
3012 }
3013 }
Daniel Berlin6c66e9a2017-05-16 20:02:45 +00003014#endif
Daniel Berlin45403572017-05-16 19:58:47 +00003015}
3016
Daniel Berlin06329a92017-03-18 15:41:40 +00003017// This is the main value numbering loop, it iterates over the initial touched
3018// instruction set, propagating value numbers, marking things touched, etc,
3019// until the set of touched instructions is completely empty.
3020void NewGVN::iterateTouchedInstructions() {
3021 unsigned int Iterations = 0;
3022 // Figure out where touchedinstructions starts
3023 int FirstInstr = TouchedInstructions.find_first();
3024 // Nothing set, nothing to iterate, just return.
3025 if (FirstInstr == -1)
3026 return;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003027 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
Daniel Berlin06329a92017-03-18 15:41:40 +00003028 while (TouchedInstructions.any()) {
3029 ++Iterations;
3030 // Walk through all the instructions in all the blocks in RPO.
3031 // TODO: As we hit a new block, we should push and pop equalities into a
3032 // table lookupOperandLeader can use, to catch things PredicateInfo
3033 // might miss, like edge-only equivalences.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003034 for (unsigned InstrNum : TouchedInstructions.set_bits()) {
Daniel Berlin06329a92017-03-18 15:41:40 +00003035
3036 // This instruction was found to be dead. We don't bother looking
3037 // at it again.
3038 if (InstrNum == 0) {
3039 TouchedInstructions.reset(InstrNum);
3040 continue;
3041 }
3042
Daniel Berlin21279bd2017-04-06 18:52:58 +00003043 Value *V = InstrFromDFSNum(InstrNum);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003044 const BasicBlock *CurrBlock = getBlockForValue(V);
Daniel Berlin06329a92017-03-18 15:41:40 +00003045
3046 // If we hit a new block, do reachability processing.
3047 if (CurrBlock != LastBlock) {
3048 LastBlock = CurrBlock;
3049 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3050 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3051
3052 // If it's not reachable, erase any touched instructions and move on.
3053 if (!BlockReachable) {
3054 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3055 DEBUG(dbgs() << "Skipping instructions in block "
3056 << getBlockName(CurrBlock)
3057 << " because it is unreachable\n");
3058 continue;
3059 }
3060 updateProcessedCount(CurrBlock);
3061 }
3062
3063 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
3064 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
3065 valueNumberMemoryPhi(MP);
3066 } else if (auto *I = dyn_cast<Instruction>(V)) {
3067 valueNumberInstruction(I);
3068 } else {
3069 llvm_unreachable("Should have been a MemoryPhi or Instruction");
3070 }
3071 updateProcessedCount(V);
3072 // Reset after processing (because we may mark ourselves as touched when
3073 // we propagate equalities).
3074 TouchedInstructions.reset(InstrNum);
3075 }
3076 }
3077 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
3078}
3079
Daniel Berlin85f91b02016-12-26 20:06:58 +00003080// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00003081bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00003082 if (DebugCounter::isCounterSet(VNCounter))
3083 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00003084 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00003085 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00003086 MSSAWalker = MSSA->getWalker();
Daniel Berline021d2d2017-05-19 20:22:20 +00003087 SingletonDeadExpression = new (ExpressionAllocator) DeadExpression();
Davide Italiano7e274e02016-12-22 16:03:48 +00003088
3089 // Count number of instructions for sizing of hash tables, and come
3090 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003091 unsigned ICount = 1;
3092 // Add an empty instruction to account for the fact that we start at 1
3093 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00003094 // Note: We want ideal RPO traversal of the blocks, which is not quite the
3095 // same as dominator tree order, particularly with regard whether backedges
3096 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00003097 // If we visit in the wrong order, we will end up performing N times as many
3098 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00003099 // The dominator tree does guarantee that, for a given dom tree node, it's
3100 // parent must occur before it in the RPO ordering. Thus, we only need to sort
3101 // the siblings.
Davide Italiano7e274e02016-12-22 16:03:48 +00003102 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00003103 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00003104 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003105 auto *Node = DT->getNode(B);
3106 assert(Node && "RPO and Dominator tree should have same reachability");
3107 RPOOrdering[Node] = ++Counter;
3108 }
3109 // Sort dominator tree children arrays into RPO.
3110 for (auto &B : RPOT) {
3111 auto *Node = DT->getNode(B);
3112 if (Node->getChildren().size() > 1)
3113 std::sort(Node->begin(), Node->end(),
Daniel Berlin2f72b192017-04-14 02:53:37 +00003114 [&](const DomTreeNode *A, const DomTreeNode *B) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00003115 return RPOOrdering[A] < RPOOrdering[B];
3116 });
3117 }
3118
3119 // Now a standard depth first ordering of the domtree is equivalent to RPO.
Daniel Berlinec9deb72017-04-18 17:06:11 +00003120 for (auto DTN : depth_first(DT->getRootNode())) {
3121 BasicBlock *B = DTN->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00003122 const auto &BlockRange = assignDFSNumbers(B, ICount);
3123 BlockInstRange.insert({B, BlockRange});
3124 ICount += BlockRange.second - BlockRange.first;
3125 }
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003126 initializeCongruenceClasses(F);
Davide Italiano7e274e02016-12-22 16:03:48 +00003127
Daniel Berline0bd37e2016-12-29 22:15:12 +00003128 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003129 // Ensure we don't end up resizing the expressionToClass map, as
3130 // that can be quite expensive. At most, we have one expression per
3131 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00003132 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00003133
3134 // Initialize the touched instructions to include the entry block.
3135 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
3136 TouchedInstructions.set(InstRange.first, InstRange.second);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003137 DEBUG(dbgs() << "Block " << getBlockName(&F.getEntryBlock())
3138 << " marked reachable\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003139 ReachableBlocks.insert(&F.getEntryBlock());
3140
Daniel Berlin06329a92017-03-18 15:41:40 +00003141 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00003142 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00003143 verifyIterationSettled(F);
Daniel Berlin45403572017-05-16 19:58:47 +00003144 verifyStoreExpressions();
Daniel Berlinf7d95802017-02-18 23:06:50 +00003145
Davide Italiano7e274e02016-12-22 16:03:48 +00003146 Changed |= eliminateInstructions(F);
3147
3148 // Delete all instructions marked for deletion.
3149 for (Instruction *ToErase : InstructionsToErase) {
3150 if (!ToErase->use_empty())
3151 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
3152
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003153 if (ToErase->getParent())
3154 ToErase->eraseFromParent();
Davide Italiano7e274e02016-12-22 16:03:48 +00003155 }
3156
3157 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003158 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
3159 return !ReachableBlocks.count(&BB);
3160 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003161
3162 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
3163 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00003164 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003165 deleteInstructionsInBlock(&BB);
3166 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003167 }
3168
3169 cleanupTables();
3170 return Changed;
3171}
3172
Davide Italiano7e274e02016-12-22 16:03:48 +00003173struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003174 int DFSIn = 0;
3175 int DFSOut = 0;
3176 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003177 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003178 // The bool in the Def tells us whether the Def is the stored value of a
3179 // store.
3180 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00003181 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00003182 bool operator<(const ValueDFS &Other) const {
3183 // It's not enough that any given field be less than - we have sets
3184 // of fields that need to be evaluated together to give a proper ordering.
3185 // For example, if you have;
3186 // DFS (1, 3)
3187 // Val 0
3188 // DFS (1, 2)
3189 // Val 50
3190 // We want the second to be less than the first, but if we just go field
3191 // by field, we will get to Val 0 < Val 50 and say the first is less than
3192 // the second. We only want it to be less than if the DFS orders are equal.
3193 //
3194 // Each LLVM instruction only produces one value, and thus the lowest-level
3195 // differentiator that really matters for the stack (and what we use as as a
3196 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003197 // Everything else in the structure is instruction level, and only affects
3198 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00003199 //
3200 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
3201 // the order of replacement of uses does not matter.
3202 // IE given,
3203 // a = 5
3204 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00003205 // When you hit b, you will have two valuedfs with the same dfsin, out, and
3206 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00003207 // The .val will be the same as well.
3208 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00003209 // You will replace both, and it does not matter what order you replace them
3210 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
3211 // operand 2).
3212 // Similarly for the case of same dfsin, dfsout, localnum, but different
3213 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00003214 // a = 5
3215 // b = 6
3216 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00003217 // in c, we will a valuedfs for a, and one for b,with everything the same
3218 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00003219 // It does not matter what order we replace these operands in.
3220 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003221 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3222 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00003223 Other.U);
3224 }
3225};
3226
Daniel Berlinc4796862017-01-27 02:37:11 +00003227// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003228// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00003229// reachable uses for each value is stored in UseCount, and instructions that
3230// seem
3231// dead (have no non-dead uses) are stored in ProbablyDead.
3232void NewGVN::convertClassToDFSOrdered(
Daniel Berlina8236562017-04-07 18:38:09 +00003233 const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
Daniel Berline3e69e12017-03-10 00:32:33 +00003234 DenseMap<const Value *, unsigned int> &UseCounts,
Daniel Berlina8236562017-04-07 18:38:09 +00003235 SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00003236 for (auto D : Dense) {
3237 // First add the value.
3238 BasicBlock *BB = getBlockForValue(D);
3239 // Constants are handled prior to ever calling this function, so
3240 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00003241 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003242 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003243 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003244 VDDef.DFSIn = DomNode->getDFSNumIn();
3245 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003246 // If it's a store, use the leader of the value operand, if it's always
3247 // available, or the value operand. TODO: We could do dominance checks to
3248 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00003249 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00003250 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003251 if (alwaysAvailable(Leader)) {
3252 VDDef.Def.setPointer(Leader);
3253 } else {
3254 VDDef.Def.setPointer(SI->getValueOperand());
3255 VDDef.Def.setInt(true);
3256 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003257 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003258 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00003259 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003260 assert(isa<Instruction>(D) &&
3261 "The dense set member should always be an instruction");
Daniel Berline3e69e12017-03-10 00:32:33 +00003262 Instruction *Def = cast<Instruction>(D);
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003263 VDDef.LocalNum = InstrToDFSNum(D);
3264 DFSOrderedSet.push_back(VDDef);
3265 // If there is a phi node equivalent, add it
3266 if (auto *PN = RealToTemp.lookup(Def)) {
3267 auto *PHIE =
3268 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3269 if (PHIE) {
3270 VDDef.Def.setInt(false);
3271 VDDef.Def.setPointer(PN);
3272 VDDef.LocalNum = 0;
3273 DFSOrderedSet.push_back(VDDef);
3274 }
3275 }
3276
Daniel Berline3e69e12017-03-10 00:32:33 +00003277 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00003278 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00003279 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003280 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003281 // Don't try to replace into dead uses
3282 if (InstructionsToErase.count(I))
3283 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003284 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00003285 // Put the phi node uses in the incoming block.
3286 BasicBlock *IBlock;
3287 if (auto *P = dyn_cast<PHINode>(I)) {
3288 IBlock = P->getIncomingBlock(U);
3289 // Make phi node users appear last in the incoming block
3290 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003291 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00003292 } else {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003293 IBlock = getBlockForValue(I);
Daniel Berlin21279bd2017-04-06 18:52:58 +00003294 VDUse.LocalNum = InstrToDFSNum(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003295 }
Davide Italianoccbbc832017-01-26 00:42:42 +00003296
3297 // Skip uses in unreachable blocks, as we're going
3298 // to delete them.
3299 if (ReachableBlocks.count(IBlock) == 0)
3300 continue;
3301
Daniel Berlinb66164c2017-01-14 00:24:23 +00003302 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003303 VDUse.DFSIn = DomNode->getDFSNumIn();
3304 VDUse.DFSOut = DomNode->getDFSNumOut();
3305 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00003306 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003307 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00003308 }
3309 }
Daniel Berline3e69e12017-03-10 00:32:33 +00003310
3311 // If there are no uses, it's probably dead (but it may have side-effects,
3312 // so not definitely dead. Otherwise, store the number of uses so we can
3313 // track if it becomes dead later).
3314 if (UseCount == 0)
3315 ProbablyDead.insert(Def);
3316 else
3317 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003318 }
3319}
3320
Daniel Berlinc4796862017-01-27 02:37:11 +00003321// This function converts the set of members for a congruence class from values,
3322// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00003323void NewGVN::convertClassToLoadsAndStores(
Daniel Berlina8236562017-04-07 18:38:09 +00003324 const CongruenceClass &Dense,
3325 SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
Daniel Berlinc4796862017-01-27 02:37:11 +00003326 for (auto D : Dense) {
3327 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
3328 continue;
3329
3330 BasicBlock *BB = getBlockForValue(D);
3331 ValueDFS VD;
3332 DomTreeNode *DomNode = DT->getNode(BB);
3333 VD.DFSIn = DomNode->getDFSNumIn();
3334 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003335 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00003336
3337 // If it's an instruction, use the real local dfs number.
3338 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlin21279bd2017-04-06 18:52:58 +00003339 VD.LocalNum = InstrToDFSNum(I);
Daniel Berlinc4796862017-01-27 02:37:11 +00003340 else
3341 llvm_unreachable("Should have been an instruction");
3342
3343 LoadsAndStores.emplace_back(VD);
3344 }
3345}
3346
Davide Italiano7e274e02016-12-22 16:03:48 +00003347static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00003348 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00003349 if (!ReplInst)
3350 return;
3351
Davide Italiano7e274e02016-12-22 16:03:48 +00003352 // Patch the replacement so that it is not more restrictive than the value
3353 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00003354 // Note that if 'I' is a load being replaced by some operation,
3355 // for example, by an arithmetic operation, then andIRFlags()
3356 // would just erase all math flags from the original arithmetic
3357 // operation, which is clearly not wanted and not needed.
3358 if (!isa<LoadInst>(I))
3359 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00003360
Daniel Berlin86eab152017-02-12 22:25:20 +00003361 // FIXME: If both the original and replacement value are part of the
3362 // same control-flow region (meaning that the execution of one
3363 // guarantees the execution of the other), then we can combine the
3364 // noalias scopes here and do better than the general conservative
3365 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00003366
Daniel Berlin86eab152017-02-12 22:25:20 +00003367 // In general, GVN unifies expressions over different control-flow
3368 // regions, and so we need a conservative combination of the noalias
3369 // scopes.
3370 static const unsigned KnownIDs[] = {
3371 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
3372 LLVMContext::MD_noalias, LLVMContext::MD_range,
3373 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
3374 LLVMContext::MD_invariant_group};
3375 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00003376}
3377
3378static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
3379 patchReplacementInstruction(I, Repl);
3380 I->replaceAllUsesWith(Repl);
3381}
3382
3383void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
3384 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
3385 ++NumGVNBlocksDeleted;
3386
Daniel Berline19f0e02017-01-30 17:06:55 +00003387 // Delete the instructions backwards, as it has a reduced likelihood of having
3388 // to update as many def-use and use-def chains. Start after the terminator.
3389 auto StartPoint = BB->rbegin();
3390 ++StartPoint;
3391 // Note that we explicitly recalculate BB->rend() on each iteration,
3392 // as it may change when we remove the first instruction.
3393 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
3394 Instruction &Inst = *I++;
3395 if (!Inst.use_empty())
3396 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
3397 if (isa<LandingPadInst>(Inst))
3398 continue;
3399
3400 Inst.eraseFromParent();
3401 ++NumGVNInstrDeleted;
3402 }
Daniel Berlina53a7222017-01-30 18:12:56 +00003403 // Now insert something that simplifycfg will turn into an unreachable.
3404 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
3405 new StoreInst(UndefValue::get(Int8Ty),
3406 Constant::getNullValue(Int8Ty->getPointerTo()),
3407 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00003408}
3409
3410void NewGVN::markInstructionForDeletion(Instruction *I) {
3411 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3412 InstructionsToErase.insert(I);
3413}
3414
3415void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3416
3417 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3418 patchAndReplaceAllUsesWith(I, V);
3419 // We save the actual erasing to avoid invalidating memory
3420 // dependencies until we are done with everything.
3421 markInstructionForDeletion(I);
3422}
3423
3424namespace {
3425
3426// This is a stack that contains both the value and dfs info of where
3427// that value is valid.
3428class ValueDFSStack {
3429public:
3430 Value *back() const { return ValueStack.back(); }
3431 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3432
3433 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00003434 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00003435 DFSStack.emplace_back(DFSIn, DFSOut);
3436 }
3437 bool empty() const { return DFSStack.empty(); }
3438 bool isInScope(int DFSIn, int DFSOut) const {
3439 if (empty())
3440 return false;
3441 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3442 }
3443
3444 void popUntilDFSScope(int DFSIn, int DFSOut) {
3445
3446 // These two should always be in sync at this point.
3447 assert(ValueStack.size() == DFSStack.size() &&
3448 "Mismatch between ValueStack and DFSStack");
3449 while (
3450 !DFSStack.empty() &&
3451 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3452 DFSStack.pop_back();
3453 ValueStack.pop_back();
3454 }
3455 }
3456
3457private:
3458 SmallVector<Value *, 8> ValueStack;
3459 SmallVector<std::pair<int, int>, 8> DFSStack;
3460};
3461}
Daniel Berlin04443432017-01-07 03:23:47 +00003462
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003463// Given a value and a basic block we are trying to see if it is available in,
3464// see if the value has a leader available in that block.
3465Value *NewGVN::findPhiOfOpsLeader(const Expression *E,
3466 const BasicBlock *BB) const {
3467 // It would already be constant if we could make it constant
3468 if (auto *CE = dyn_cast<ConstantExpression>(E))
3469 return CE->getConstantValue();
3470 if (auto *VE = dyn_cast<VariableExpression>(E))
3471 return VE->getVariableValue();
3472
3473 auto *CC = ExpressionToClass.lookup(E);
3474 if (!CC)
3475 return nullptr;
3476 if (alwaysAvailable(CC->getLeader()))
3477 return CC->getLeader();
3478
3479 for (auto Member : *CC) {
3480 auto *MemberInst = dyn_cast<Instruction>(Member);
3481 // Anything that isn't an instruction is always available.
3482 if (!MemberInst)
3483 return Member;
3484 // If we are looking for something in the same block as the member, it must
3485 // be a leader because this function is looking for operands for a phi node.
3486 if (MemberInst->getParent() == BB ||
3487 DT->dominates(MemberInst->getParent(), BB)) {
3488 return Member;
3489 }
3490 }
3491 return nullptr;
3492}
3493
Davide Italiano7e274e02016-12-22 16:03:48 +00003494bool NewGVN::eliminateInstructions(Function &F) {
3495 // This is a non-standard eliminator. The normal way to eliminate is
3496 // to walk the dominator tree in order, keeping track of available
3497 // values, and eliminating them. However, this is mildly
3498 // pointless. It requires doing lookups on every instruction,
3499 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003500 // instructions part of most singleton congruence classes, we know we
3501 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00003502
3503 // Instead, this eliminator looks at the congruence classes directly, sorts
3504 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003505 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00003506 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003507 // last member. This is worst case O(E log E) where E = number of
3508 // instructions in a single congruence class. In theory, this is all
3509 // instructions. In practice, it is much faster, as most instructions are
3510 // either in singleton congruence classes or can't possibly be eliminated
3511 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00003512 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00003513 // for elimination purposes.
3514 // TODO: If we wanted to be faster, We could remove any members with no
3515 // overlapping ranges while sorting, as we will never eliminate anything
3516 // with those members, as they don't dominate anything else in our set.
3517
Davide Italiano7e274e02016-12-22 16:03:48 +00003518 bool AnythingReplaced = false;
3519
3520 // Since we are going to walk the domtree anyway, and we can't guarantee the
3521 // DFS numbers are updated, we compute some ourselves.
3522 DT->updateDFSNumbers();
3523
Daniel Berlin0207cca2017-05-21 23:41:56 +00003524 // Go through all of our phi nodes, and kill the arguments associated with
3525 // unreachable edges.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003526 auto ReplaceUnreachablePHIArgs = [&](PHINode &PHI, BasicBlock *BB) {
3527 for (auto &Operand : PHI.incoming_values())
3528 if (!ReachableEdges.count({PHI.getIncomingBlock(Operand), BB})) {
3529 DEBUG(dbgs() << "Replacing incoming value of " << PHI << " for block "
3530 << getBlockName(PHI.getIncomingBlock(Operand))
3531 << " with undef due to it being unreachable\n");
3532 Operand.set(UndefValue::get(PHI.getType()));
3533 }
3534 };
3535 SmallPtrSet<BasicBlock *, 8> BlocksWithPhis;
3536 for (auto &B : F)
3537 if ((!B.empty() && isa<PHINode>(*B.begin())) ||
3538 (PHIOfOpsPHIs.find(&B) != PHIOfOpsPHIs.end()))
3539 BlocksWithPhis.insert(&B);
3540 DenseMap<const BasicBlock *, unsigned> ReachablePredCount;
3541 for (auto KV : ReachableEdges)
3542 ReachablePredCount[KV.getEnd()]++;
3543 for (auto *BB : BlocksWithPhis)
3544 // TODO: It would be faster to use getNumIncomingBlocks() on a phi node in
3545 // the block and subtract the pred count, but it's more complicated.
3546 if (ReachablePredCount.lookup(BB) !=
3547 std::distance(pred_begin(BB), pred_end(BB))) {
3548 for (auto II = BB->begin(); isa<PHINode>(II); ++II) {
3549 auto &PHI = cast<PHINode>(*II);
3550 ReplaceUnreachablePHIArgs(PHI, BB);
3551 }
Daniel Berlin0207cca2017-05-21 23:41:56 +00003552 for_each_found(PHIOfOpsPHIs, BB, [&](PHINode *PHI) {
3553 ReplaceUnreachablePHIArgs(*PHI, BB);
3554 });
Davide Italiano7e274e02016-12-22 16:03:48 +00003555 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003556
Daniel Berline3e69e12017-03-10 00:32:33 +00003557 // Map to store the use counts
3558 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003559 for (auto *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00003560 // Track the equivalent store info so we can decide whether to try
3561 // dead store elimination.
3562 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00003563 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlina8236562017-04-07 18:38:09 +00003564 if (CC->isDead() || CC->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00003565 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003566 // Everything still in the TOP class is unreachable or dead.
3567 if (CC == TOPClass) {
Daniel Berline021d2d2017-05-19 20:22:20 +00003568 for (auto M : *CC) {
3569 auto *VTE = ValueToExpression.lookup(M);
3570 if (VTE && isa<DeadExpression>(VTE))
3571 markInstructionForDeletion(cast<Instruction>(M));
Daniel Berlinb79f5362017-02-11 12:48:50 +00003572 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3573 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00003574 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00003575 "point");
Daniel Berline021d2d2017-05-19 20:22:20 +00003576 }
Daniel Berlinb79f5362017-02-11 12:48:50 +00003577 continue;
3578 }
3579
Daniel Berlina8236562017-04-07 18:38:09 +00003580 assert(CC->getLeader() && "We should have had a leader");
Davide Italiano7e274e02016-12-22 16:03:48 +00003581 // If this is a leader that is always available, and it's a
3582 // constant or has no equivalences, just replace everything with
3583 // it. We then update the congruence class with whatever members
3584 // are left.
Daniel Berlina8236562017-04-07 18:38:09 +00003585 Value *Leader =
3586 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
Daniel Berlin26addef2017-01-20 21:04:30 +00003587 if (alwaysAvailable(Leader)) {
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003588 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003589 for (auto M : *CC) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003590 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00003591 // Void things have no uses we can replace.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003592 if (Member == Leader || !isa<Instruction>(Member) ||
3593 Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003594 MembersLeft.insert(Member);
3595 continue;
3596 }
Daniel Berlin26addef2017-01-20 21:04:30 +00003597 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3598 << "\n");
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003599 auto *I = cast<Instruction>(Member);
3600 assert(Leader != I && "About to accidentally remove our leader");
3601 replaceInstruction(I, Leader);
3602 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00003603 }
Daniel Berlina8236562017-04-07 18:38:09 +00003604 CC->swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00003605 } else {
Daniel Berlina8236562017-04-07 18:38:09 +00003606 DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
3607 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003608 // If this is a singleton, we can skip it.
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003609 if (CC->size() != 1 || RealToTemp.lookup(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00003610 // This is a stack because equality replacement/etc may place
3611 // constants in the middle of the member list, and we want to use
3612 // those constant values in preference to the current leader, over
3613 // the scope of those constants.
3614 ValueDFSStack EliminationStack;
3615
3616 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003617 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berlina8236562017-04-07 18:38:09 +00003618 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00003619
3620 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003621 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00003622 for (auto &VD : DFSOrderedSet) {
3623 int MemberDFSIn = VD.DFSIn;
3624 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003625 Value *Def = VD.Def.getPointer();
3626 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00003627 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00003628 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003629 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00003630 continue;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003631 auto *DefInst = dyn_cast_or_null<Instruction>(Def);
3632 if (DefInst && AllTempInstructions.count(DefInst)) {
3633 auto *PN = cast<PHINode>(DefInst);
3634
3635 // If this is a value phi and that's the expression we used, insert
3636 // it into the program
3637 // remove from temp instruction list.
3638 AllTempInstructions.erase(PN);
3639 auto *DefBlock = getBlockForValue(Def);
3640 DEBUG(dbgs() << "Inserting fully real phi of ops" << *Def
3641 << " into block "
3642 << getBlockName(getBlockForValue(Def)) << "\n");
3643 PN->insertBefore(&DefBlock->front());
3644 Def = PN;
3645 NumGVNPHIOfOpsEliminations++;
3646 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003647
3648 if (EliminationStack.empty()) {
3649 DEBUG(dbgs() << "Elimination Stack is empty\n");
3650 } else {
3651 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3652 << EliminationStack.dfs_back().first << ","
3653 << EliminationStack.dfs_back().second << ")\n");
3654 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003655
3656 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3657 << MemberDFSOut << ")\n");
3658 // First, we see if we are out of scope or empty. If so,
3659 // and there equivalences, we try to replace the top of
3660 // stack with equivalences (if it's on the stack, it must
3661 // not have been eliminated yet).
3662 // Then we synchronize to our current scope, by
3663 // popping until we are back within a DFS scope that
3664 // dominates the current member.
3665 // Then, what happens depends on a few factors
3666 // If the stack is now empty, we need to push
3667 // If we have a constant or a local equivalence we want to
3668 // start using, we also push.
3669 // Otherwise, we walk along, processing members who are
3670 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00003671 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003672 bool OutOfScope =
3673 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3674
3675 if (OutOfScope || ShouldPush) {
3676 // Sync to our current scope.
3677 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00003678 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00003679 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00003680 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00003681 }
3682 }
3683
Daniel Berline3e69e12017-03-10 00:32:33 +00003684 // Skip the Def's, we only want to eliminate on their uses. But mark
3685 // dominated defs as dead.
3686 if (Def) {
3687 // For anything in this case, what and how we value number
3688 // guarantees that any side-effets that would have occurred (ie
3689 // throwing, etc) can be proven to either still occur (because it's
3690 // dominated by something that has the same side-effects), or never
3691 // occur. Otherwise, we would not have been able to prove it value
3692 // equivalent to something else. For these things, we can just mark
3693 // it all dead. Note that this is different from the "ProbablyDead"
3694 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003695 // easy to prove dead if they are also side-effect free. Note that
3696 // because stores are put in terms of the stored value, we skip
3697 // stored values here. If the stored value is really dead, it will
3698 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00003699 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003700 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00003701 markInstructionForDeletion(cast<Instruction>(Def));
3702 continue;
3703 }
3704 // At this point, we know it is a Use we are trying to possibly
3705 // replace.
3706
3707 assert(isa<Instruction>(U->get()) &&
3708 "Current def should have been an instruction");
3709 assert(isa<Instruction>(U->getUser()) &&
3710 "Current user should have been an instruction");
3711
3712 // If the thing we are replacing into is already marked to be dead,
3713 // this use is dead. Note that this is true regardless of whether
3714 // we have anything dominating the use or not. We do this here
3715 // because we are already walking all the uses anyway.
3716 Instruction *InstUse = cast<Instruction>(U->getUser());
3717 if (InstructionsToErase.count(InstUse)) {
3718 auto &UseCount = UseCounts[U->get()];
3719 if (--UseCount == 0) {
3720 ProbablyDead.insert(cast<Instruction>(U->get()));
3721 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003722 }
3723
Davide Italiano7e274e02016-12-22 16:03:48 +00003724 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00003725 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00003726 if (EliminationStack.empty())
3727 continue;
3728
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003729 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00003730
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003731 auto *II = dyn_cast<IntrinsicInst>(DominatingLeader);
3732 if (II && II->getIntrinsicID() == Intrinsic::ssa_copy)
3733 DominatingLeader = II->getOperand(0);
3734
Daniel Berlind92e7f92017-01-07 00:01:42 +00003735 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00003736 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00003737 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003738 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00003739 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00003740
3741 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00003742 // metadata. Skip this if we are replacing predicateinfo with its
3743 // original operand, as we already know we can just drop it.
3744 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00003745 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3746 if (!PI || DominatingLeader != PI->OriginalOp)
3747 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00003748 U->set(DominatingLeader);
3749 // This is now a use of the dominating leader, which means if the
3750 // dominating leader was dead, it's now live!
3751 auto &LeaderUseCount = UseCounts[DominatingLeader];
3752 // It's about to be alive again.
3753 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3754 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
Davide Italianoa76e5fa2017-05-18 21:43:23 +00003755 if (LeaderUseCount == 0 && II)
3756 ProbablyDead.insert(II);
Daniel Berline3e69e12017-03-10 00:32:33 +00003757 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00003758 AnythingReplaced = true;
3759 }
3760 }
3761 }
3762
Daniel Berline3e69e12017-03-10 00:32:33 +00003763 // At this point, anything still in the ProbablyDead set is actually dead if
3764 // would be trivially dead.
3765 for (auto *I : ProbablyDead)
3766 if (wouldInstructionBeTriviallyDead(I))
3767 markInstructionForDeletion(I);
3768
Davide Italiano7e274e02016-12-22 16:03:48 +00003769 // Cleanup the congruence class.
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003770 CongruenceClass::MemberSet MembersLeft;
Daniel Berlina8236562017-04-07 18:38:09 +00003771 for (auto *Member : *CC)
Daniel Berlin08fe6e02017-04-06 18:52:55 +00003772 if (!isa<Instruction>(Member) ||
3773 !InstructionsToErase.count(cast<Instruction>(Member)))
Davide Italiano7e274e02016-12-22 16:03:48 +00003774 MembersLeft.insert(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003775 CC->swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00003776
3777 // If we have possible dead stores to look at, try to eliminate them.
Daniel Berlina8236562017-04-07 18:38:09 +00003778 if (CC->getStoreCount() > 0) {
3779 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00003780 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3781 ValueDFSStack EliminationStack;
3782 for (auto &VD : PossibleDeadStores) {
3783 int MemberDFSIn = VD.DFSIn;
3784 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00003785 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00003786 if (EliminationStack.empty() ||
3787 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3788 // Sync to our current scope.
3789 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3790 if (EliminationStack.empty()) {
3791 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3792 continue;
3793 }
3794 }
3795 // We already did load elimination, so nothing to do here.
3796 if (isa<LoadInst>(Member))
3797 continue;
3798 assert(!EliminationStack.empty());
3799 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00003800 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00003801 assert(DT->dominates(Leader->getParent(), Member->getParent()));
3802 // Member is dominater by Leader, and thus dead
3803 DEBUG(dbgs() << "Marking dead store " << *Member
3804 << " that is dominated by " << *Leader << "\n");
3805 markInstructionForDeletion(Member);
Daniel Berlina8236562017-04-07 18:38:09 +00003806 CC->erase(Member);
Daniel Berlinc4796862017-01-27 02:37:11 +00003807 ++NumGVNDeadStores;
3808 }
3809 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003810 }
Davide Italiano7e274e02016-12-22 16:03:48 +00003811 return AnythingReplaced;
3812}
Daniel Berlin1c087672017-02-11 15:07:01 +00003813
3814// This function provides global ranking of operations so that we can place them
3815// in a canonical order. Note that rank alone is not necessarily enough for a
3816// complete ordering, as constants all have the same rank. However, generally,
3817// we will simplify an operation with all constants so that it doesn't matter
3818// what order they appear in.
3819unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003820 // Prefer constants to undef to anything else
3821 // Undef is a constant, have to check it first.
3822 // Prefer smaller constants to constantexprs
3823 if (isa<ConstantExpr>(V))
3824 return 2;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003825 if (isa<UndefValue>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003826 return 1;
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003827 if (isa<Constant>(V))
3828 return 0;
Daniel Berlin1c087672017-02-11 15:07:01 +00003829 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003830 return 3 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00003831
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003832 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00003833 // the constant and argument ranking above.
Daniel Berlin21279bd2017-04-06 18:52:58 +00003834 unsigned Result = InstrToDFSNum(V);
Daniel Berlin1c087672017-02-11 15:07:01 +00003835 if (Result > 0)
Daniel Berlinb527b2c2017-05-19 19:01:27 +00003836 return 4 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00003837 // Unreachable or something else, just return a really large number.
3838 return ~0;
3839}
3840
3841// This is a function that says whether two commutative operations should
3842// have their order swapped when canonicalizing.
3843bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3844 // Because we only care about a total ordering, and don't rewrite expressions
3845 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00003846 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00003847 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00003848}
Daniel Berlin64e68992017-03-12 04:46:45 +00003849
3850class NewGVNLegacyPass : public FunctionPass {
3851public:
3852 static char ID; // Pass identification, replacement for typeid.
3853 NewGVNLegacyPass() : FunctionPass(ID) {
3854 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3855 }
3856 bool runOnFunction(Function &F) override;
3857
3858private:
3859 void getAnalysisUsage(AnalysisUsage &AU) const override {
3860 AU.addRequired<AssumptionCacheTracker>();
3861 AU.addRequired<DominatorTreeWrapperPass>();
3862 AU.addRequired<TargetLibraryInfoWrapperPass>();
3863 AU.addRequired<MemorySSAWrapperPass>();
3864 AU.addRequired<AAResultsWrapperPass>();
3865 AU.addPreserved<DominatorTreeWrapperPass>();
3866 AU.addPreserved<GlobalsAAWrapperPass>();
3867 }
3868};
3869
3870bool NewGVNLegacyPass::runOnFunction(Function &F) {
3871 if (skipFunction(F))
3872 return false;
3873 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3874 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3875 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3876 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3877 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3878 F.getParent()->getDataLayout())
3879 .runGVN();
3880}
3881
3882INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3883 false, false)
3884INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3885INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3886INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3887INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3888INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3889INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3890INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3891 false)
3892
3893char NewGVNLegacyPass::ID = 0;
3894
3895// createGVNPass - The public interface to this file.
3896FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3897
3898PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3899 // Apparently the order in which we get these results matter for
3900 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3901 // the same order here, just in case.
3902 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3903 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3904 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3905 auto &AA = AM.getResult<AAManager>(F);
3906 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3907 bool Changed =
3908 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3909 .runGVN();
3910 if (!Changed)
3911 return PreservedAnalyses::all();
3912 PreservedAnalyses PA;
3913 PA.preserve<DominatorTreeAnalysis>();
3914 PA.preserve<GlobalsAA>();
3915 return PA;
3916}