blob: 9dbafec09df683c30e7e4f98700c5b2785d4fe55 [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
33/// something's value number changes. The rest of the algorithm is devoted to
34/// performing symbolic evaluation, forward propagation, and simplification of
35/// operations based on the value numbers deduced so far.
36///
37/// We also do not perform elimination by using any published algorithm. All
38/// published algorithms are O(Instructions). Instead, we use a technique that
39/// is O(number of operations with the same value number), enabling us to skip
40/// trying to eliminate things that have unique value numbers.
Davide Italiano7e274e02016-12-22 16:03:48 +000041//===----------------------------------------------------------------------===//
42
43#include "llvm/Transforms/Scalar/NewGVN.h"
44#include "llvm/ADT/BitVector.h"
45#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/DenseSet.h"
47#include "llvm/ADT/DepthFirstIterator.h"
48#include "llvm/ADT/Hashing.h"
49#include "llvm/ADT/MapVector.h"
50#include "llvm/ADT/PostOrderIterator.h"
Daniel Berlind7c12ee2016-12-25 22:23:49 +000051#include "llvm/ADT/STLExtras.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000052#include "llvm/ADT/SmallPtrSet.h"
53#include "llvm/ADT/SmallSet.h"
54#include "llvm/ADT/SparseBitVector.h"
55#include "llvm/ADT/Statistic.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include "llvm/Analysis/AliasAnalysis.h"
58#include "llvm/Analysis/AssumptionCache.h"
59#include "llvm/Analysis/CFG.h"
60#include "llvm/Analysis/CFGPrinter.h"
61#include "llvm/Analysis/ConstantFolding.h"
62#include "llvm/Analysis/GlobalsModRef.h"
63#include "llvm/Analysis/InstructionSimplify.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000064#include "llvm/Analysis/MemoryBuiltins.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000065#include "llvm/Analysis/MemoryLocation.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000066#include "llvm/Analysis/TargetLibraryInfo.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000067#include "llvm/IR/DataLayout.h"
68#include "llvm/IR/Dominators.h"
69#include "llvm/IR/GlobalVariable.h"
70#include "llvm/IR/IRBuilder.h"
71#include "llvm/IR/IntrinsicInst.h"
72#include "llvm/IR/LLVMContext.h"
73#include "llvm/IR/Metadata.h"
74#include "llvm/IR/PatternMatch.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000075#include "llvm/IR/Type.h"
76#include "llvm/Support/Allocator.h"
77#include "llvm/Support/CommandLine.h"
78#include "llvm/Support/Debug.h"
Daniel Berlin283a6082017-03-01 19:59:26 +000079#include "llvm/Support/DebugCounter.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000080#include "llvm/Transforms/Scalar.h"
81#include "llvm/Transforms/Scalar/GVNExpression.h"
82#include "llvm/Transforms/Utils/BasicBlockUtils.h"
83#include "llvm/Transforms/Utils/Local.h"
84#include "llvm/Transforms/Utils/MemorySSA.h"
Daniel Berlinf7d95802017-02-18 23:06:50 +000085#include "llvm/Transforms/Utils/PredicateInfo.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000086#include <unordered_map>
87#include <utility>
88#include <vector>
89using namespace llvm;
90using namespace PatternMatch;
91using namespace llvm::GVNExpression;
Davide Italiano7e274e02016-12-22 16:03:48 +000092#define DEBUG_TYPE "newgvn"
93
94STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
95STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
96STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
97STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +000098STATISTIC(NumGVNMaxIterations,
99 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000100STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
101STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
102STATISTIC(NumGVNAvoidedSortedLeaderChanges,
103 "Number of avoided sorted leader changes");
Daniel Berlin89fea6f2017-01-20 06:38:41 +0000104STATISTIC(NumGVNNotMostDominatingLeader,
105 "Number of times a member dominated it's new classes' leader");
Daniel Berlinc4796862017-01-27 02:37:11 +0000106STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Daniel Berlin283a6082017-03-01 19:59:26 +0000107DEBUG_COUNTER(VNCounter, "newgvn-vn",
108 "Controls which instructions are value numbered")
Davide Italiano7e274e02016-12-22 16:03:48 +0000109//===----------------------------------------------------------------------===//
110// GVN Pass
111//===----------------------------------------------------------------------===//
112
113// Anchor methods.
114namespace llvm {
115namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000116Expression::~Expression() = default;
117BasicExpression::~BasicExpression() = default;
118CallExpression::~CallExpression() = default;
119LoadExpression::~LoadExpression() = default;
120StoreExpression::~StoreExpression() = default;
121AggregateValueExpression::~AggregateValueExpression() = default;
122PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000123}
124}
125
126// Congruence classes represent the set of expressions/instructions
127// that are all the same *during some scope in the function*.
128// That is, because of the way we perform equality propagation, and
129// because of memory value numbering, it is not correct to assume
130// you can willy-nilly replace any member with any other at any
131// point in the function.
132//
133// For any Value in the Member set, it is valid to replace any dominated member
134// with that Value.
135//
136// Every congruence class has a leader, and the leader is used to
137// symbolize instructions in a canonical way (IE every operand of an
138// instruction that is a member of the same congruence class will
139// always be replaced with leader during symbolization).
140// To simplify symbolization, we keep the leader as a constant if class can be
141// proved to be a constant value.
142// Otherwise, the leader is a randomly chosen member of the value set, it does
143// not matter which one is chosen.
144// Each congruence class also has a defining expression,
145// though the expression may be null. If it exists, it can be used for forward
146// propagation and reassociation of values.
147//
148struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000149 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000150 unsigned ID;
151 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000152 Value *RepLeader = nullptr;
Daniel Berlin26addef2017-01-20 21:04:30 +0000153 // If this is represented by a store, the value.
154 Value *RepStoredValue = nullptr;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000155 // If this class contains MemoryDefs, what is the represented memory state.
156 MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000157 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000158 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000159 // Actual members of this class.
160 MemberSet Members;
161
162 // True if this class has no members left. This is mainly used for assertion
163 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000164 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000165
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000166 // Number of stores in this congruence class.
167 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000168 int StoreCount = 0;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000169
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000170 // The most dominating leader after our current leader, because the member set
171 // is not sorted and is expensive to keep sorted all the time.
172 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
173
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000174 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000175 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000176 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000177};
178
Daniel Berlin06329a92017-03-18 15:41:40 +0000179// Return true if two congruence classes are equivalent to each other. This
180// means
181// that every field but the ID number and the dead field are equivalent.
182bool areClassesEquivalent(const CongruenceClass *A, const CongruenceClass *B) {
183 if (A == B)
184 return true;
185 if ((A && !B) || (B && !A))
186 return false;
187
188 if (std::tie(A->StoreCount, A->RepLeader, A->RepStoredValue,
189 A->RepMemoryAccess) != std::tie(B->StoreCount, B->RepLeader,
190 B->RepStoredValue,
191 B->RepMemoryAccess))
192 return false;
193 if (A->DefiningExpr != B->DefiningExpr)
194 if (!A->DefiningExpr || !B->DefiningExpr ||
195 *A->DefiningExpr != *B->DefiningExpr)
196 return false;
197 // We need some ordered set
198 std::set<Value *> AMembers(A->Members.begin(), A->Members.end());
199 std::set<Value *> BMembers(B->Members.begin(), B->Members.end());
200 return AMembers == BMembers;
201}
202
Davide Italiano7e274e02016-12-22 16:03:48 +0000203namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000204template <> struct DenseMapInfo<const Expression *> {
205 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000206 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000207 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
208 return reinterpret_cast<const Expression *>(Val);
209 }
210 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000211 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000212 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
213 return reinterpret_cast<const Expression *>(Val);
214 }
215 static unsigned getHashValue(const Expression *V) {
216 return static_cast<unsigned>(V->getHashValue());
217 }
218 static bool isEqual(const Expression *LHS, const Expression *RHS) {
219 if (LHS == RHS)
220 return true;
221 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
222 LHS == getEmptyKey() || RHS == getEmptyKey())
223 return false;
224 return *LHS == *RHS;
225 }
226};
Davide Italiano7e274e02016-12-22 16:03:48 +0000227} // end namespace llvm
228
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000229namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000230class NewGVN {
231 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000232 DominatorTree *DT;
Davide Italiano7e274e02016-12-22 16:03:48 +0000233 AssumptionCache *AC;
Daniel Berlin64e68992017-03-12 04:46:45 +0000234 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000235 AliasAnalysis *AA;
236 MemorySSA *MSSA;
237 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000238 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000239 std::unique_ptr<PredicateInfo> PredInfo;
Davide Italiano7e274e02016-12-22 16:03:48 +0000240 BumpPtrAllocator ExpressionAllocator;
241 ArrayRecycler<Value *> ArgRecycler;
242
Daniel Berlin1c087672017-02-11 15:07:01 +0000243 // Number of function arguments, used by ranking
244 unsigned int NumFuncArgs;
245
Davide Italiano7e274e02016-12-22 16:03:48 +0000246 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000247
248 // This class is called INITIAL in the paper. It is the class everything
249 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000250 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000251 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000252 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000253 std::vector<CongruenceClass *> CongruenceClasses;
254 unsigned NextCongruenceNum;
255
256 // Value Mappings.
257 DenseMap<Value *, CongruenceClass *> ValueToClass;
258 DenseMap<Value *, const Expression *> ValueToExpression;
259
Daniel Berlinf7d95802017-02-18 23:06:50 +0000260 // Mapping from predicate info we used to the instructions we used it with.
261 // In order to correctly ensure propagation, we must keep track of what
262 // comparisons we used, so that when the values of the comparisons change, we
263 // propagate the information to the places we used the comparison.
264 DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> PredicateToUsers;
265
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000266 // A table storing which memorydefs/phis represent a memory state provably
267 // equivalent to another memory state.
268 // We could use the congruence class machinery, but the MemoryAccess's are
269 // abstract memory states, so they can only ever be equivalent to each other,
270 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000271 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000272
Davide Italiano7e274e02016-12-22 16:03:48 +0000273 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000274 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000275 ExpressionClassMap ExpressionToClass;
276
277 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000278 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000279
280 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000281 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000282 DenseSet<BlockEdge> ReachableEdges;
283 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
284
285 // This is a bitvector because, on larger functions, we may have
286 // thousands of touched instructions at once (entire blocks,
287 // instructions with hundreds of uses, etc). Even with optimization
288 // for when we mark whole blocks as touched, when this was a
289 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
290 // the time in GVN just managing this list. The bitvector, on the
291 // other hand, efficiently supports test/set/clear of both
292 // individual and ranges, as well as "find next element" This
293 // enables us to use it as a worklist with essentially 0 cost.
294 BitVector TouchedInstructions;
295
296 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
Davide Italiano7e274e02016-12-22 16:03:48 +0000297
298#ifndef NDEBUG
299 // Debugging for how many times each block and instruction got processed.
300 DenseMap<const Value *, unsigned> ProcessedCount;
301#endif
302
303 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000304 // This contains a mapping from Instructions to DFS numbers.
305 // The numbering starts at 1. An instruction with DFS number zero
306 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000307 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000308
309 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000310 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000311
312 // Deletion info.
313 SmallPtrSet<Instruction *, 8> InstructionsToErase;
314
315public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000316 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
317 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
318 const DataLayout &DL)
319 : F(F), DT(DT), AC(AC), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
320 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)) {}
321 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000322
323private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000324 // Expression handling.
Daniel Berlin97718e62017-01-31 22:32:03 +0000325 const Expression *createExpression(Instruction *);
326 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000327 PHIExpression *createPHIExpression(Instruction *);
328 const VariableExpression *createVariableExpression(Value *);
329 const ConstantExpression *createConstantExpression(Constant *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000330 const Expression *createVariableOrConstant(Value *V);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000331 const UnknownExpression *createUnknownExpression(Instruction *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000332 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000333 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin97718e62017-01-31 22:32:03 +0000334 MemoryAccess *);
335 const CallExpression *createCallExpression(CallInst *, MemoryAccess *);
336 const AggregateValueExpression *createAggregateValueExpression(Instruction *);
337 bool setBasicExpressionInfo(Instruction *, BasicExpression *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000338
339 // Congruence class handling.
340 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000341 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000342 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000343 return result;
344 }
345
346 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000347 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000348 CClass->Members.insert(Member);
349 ValueToClass[Member] = CClass;
350 return CClass;
351 }
352 void initializeCongruenceClasses(Function &F);
353
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000354 // Value number an Instruction or MemoryPhi.
355 void valueNumberMemoryPhi(MemoryPhi *);
356 void valueNumberInstruction(Instruction *);
357
Davide Italiano7e274e02016-12-22 16:03:48 +0000358 // Symbolic evaluation.
359 const Expression *checkSimplificationResults(Expression *, Instruction *,
360 Value *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000361 const Expression *performSymbolicEvaluation(Value *);
362 const Expression *performSymbolicLoadEvaluation(Instruction *);
363 const Expression *performSymbolicStoreEvaluation(Instruction *);
364 const Expression *performSymbolicCallEvaluation(Instruction *);
365 const Expression *performSymbolicPHIEvaluation(Instruction *);
366 const Expression *performSymbolicAggrValueEvaluation(Instruction *);
367 const Expression *performSymbolicCmpEvaluation(Instruction *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000368 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000369
370 // Congruence finding.
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000371 bool someEquivalentDominates(const Instruction *, const Instruction *) const;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000372 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000373 void performCongruenceFinding(Instruction *, const Expression *);
374 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000375 CongruenceClass *);
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000376 bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
377 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000378 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1c087672017-02-11 15:07:01 +0000379 // Ranking
380 unsigned int getRank(const Value *) const;
381 bool shouldSwapOperands(const Value *, const Value *) const;
382
Davide Italiano7e274e02016-12-22 16:03:48 +0000383 // Reachability handling.
384 void updateReachableEdge(BasicBlock *, BasicBlock *);
385 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000386 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000387
388 // Elimination.
389 struct ValueDFS;
Daniel Berline3e69e12017-03-10 00:32:33 +0000390 void convertClassToDFSOrdered(const CongruenceClass::MemberSet &,
391 SmallVectorImpl<ValueDFS> &,
392 DenseMap<const Value *, unsigned int> &,
393 SmallPtrSetImpl<Instruction *> &);
394 void convertClassToLoadsAndStores(const CongruenceClass::MemberSet &,
Daniel Berlinc4796862017-01-27 02:37:11 +0000395 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000396
397 bool eliminateInstructions(Function &);
398 void replaceInstruction(Instruction *, Value *);
399 void markInstructionForDeletion(Instruction *);
400 void deleteInstructionsInBlock(BasicBlock *);
401
402 // New instruction creation.
403 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000404
405 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000406 void markUsersTouched(Value *);
407 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000408 void markPredicateUsersTouched(Instruction *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000409 void markLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000410 void addPredicateUsers(const PredicateBase *, Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000411
Daniel Berlin06329a92017-03-18 15:41:40 +0000412 // Main loop of value numbering
413 void iterateTouchedInstructions();
414
Davide Italiano7e274e02016-12-22 16:03:48 +0000415 // Utilities.
416 void cleanupTables();
417 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
418 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000419 void verifyMemoryCongruency() const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000420 void verifyIterationSettled(Function &F);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000421 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Daniel Berlin06329a92017-03-18 15:41:40 +0000422 BasicBlock *getBlockForValue(Value *V) const;
Daniel Berlin0e900112017-03-24 06:33:48 +0000423 void deleteExpression(const Expression *E);
Daniel Berlin06329a92017-03-18 15:41:40 +0000424 // Debug counter info. When verifying, we have to reset the value numbering
425 // debug counter to the same state it started in to get the same results.
426 std::pair<int, int> StartingVNCounter;
Davide Italiano7e274e02016-12-22 16:03:48 +0000427};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000428} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000429
Davide Italianob1114092016-12-28 13:37:17 +0000430template <typename T>
431static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
432 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000433 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000434 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000435 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000436 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000437 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000438 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000439 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000440 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000441 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000442 return true;
443}
444
Davide Italianob1114092016-12-28 13:37:17 +0000445bool LoadExpression::equals(const Expression &Other) const {
446 return equalsLoadStoreHelper(*this, Other);
447}
Davide Italiano7e274e02016-12-22 16:03:48 +0000448
Davide Italianob1114092016-12-28 13:37:17 +0000449bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000450 bool Result = equalsLoadStoreHelper(*this, Other);
451 // Make sure that store vs store includes the value operand.
452 if (Result)
453 if (const auto *S = dyn_cast<StoreExpression>(&Other))
454 if (getStoredValue() != S->getStoredValue())
455 return false;
456 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000457}
458
459#ifndef NDEBUG
460static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000461 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000462}
463#endif
464
Daniel Berlin06329a92017-03-18 15:41:40 +0000465// Get the basic block from an instruction/memory value.
466BasicBlock *NewGVN::getBlockForValue(Value *V) const {
467 if (auto *I = dyn_cast<Instruction>(V))
468 return I->getParent();
469 else if (auto *MP = dyn_cast<MemoryPhi>(V))
470 return MP->getBlock();
471 llvm_unreachable("Should have been able to figure out a block for our value");
472 return nullptr;
473}
474
Daniel Berlin0e900112017-03-24 06:33:48 +0000475// Delete a definitely dead expression, so it can be reused by the expression
476// allocator. Some of these are not in creation functions, so we have to accept
477// const versions.
478void NewGVN::deleteExpression(const Expression *E) {
479 assert(isa<BasicExpression>(E));
480 auto *BE = cast<BasicExpression>(E);
481 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
482 ExpressionAllocator.Deallocate(E);
483}
484
Davide Italiano7e274e02016-12-22 16:03:48 +0000485PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000486 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000487 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000488 auto *E =
489 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000490
491 E->allocateOperands(ArgRecycler, ExpressionAllocator);
492 E->setType(I->getType());
493 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000494
Davide Italianob3886dd2017-01-25 23:37:49 +0000495 // Filter out unreachable phi operands.
496 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +0000497 return ReachableEdges.count({PN->getIncomingBlock(U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000498 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000499
500 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
501 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000502 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000503 if (U == PN)
504 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000505 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000506 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000507 return E;
508}
509
510// Set basic expression info (Arguments, type, opcode) for Expression
511// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000512bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000513 bool AllConstant = true;
514 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
515 E->setType(GEP->getSourceElementType());
516 else
517 E->setType(I->getType());
518 E->setOpcode(I->getOpcode());
519 E->allocateOperands(ArgRecycler, ExpressionAllocator);
520
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000521 // Transform the operand array into an operand leader array, and keep track of
522 // whether all members are constant.
523 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000524 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000525 AllConstant &= isa<Constant>(Operand);
526 return Operand;
527 });
528
Davide Italiano7e274e02016-12-22 16:03:48 +0000529 return AllConstant;
530}
531
532const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000533 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000534 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000535
536 E->setType(T);
537 E->setOpcode(Opcode);
538 E->allocateOperands(ArgRecycler, ExpressionAllocator);
539 if (Instruction::isCommutative(Opcode)) {
540 // Ensure that commutative instructions that only differ by a permutation
541 // of their operands get the same value number by sorting the operand value
542 // numbers. Since all commutative instructions have two operands it is more
543 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000544 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000545 std::swap(Arg1, Arg2);
546 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000547 E->op_push_back(lookupOperandLeader(Arg1));
548 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000549
Daniel Berlin64e68992017-03-12 04:46:45 +0000550 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), DL, TLI,
Davide Italiano7e274e02016-12-22 16:03:48 +0000551 DT, AC);
552 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
553 return SimplifiedE;
554 return E;
555}
556
557// Take a Value returned by simplification of Expression E/Instruction
558// I, and see if it resulted in a simpler expression. If so, return
559// that expression.
560// TODO: Once finished, this should not take an Instruction, we only
561// use it for printing.
562const Expression *NewGVN::checkSimplificationResults(Expression *E,
563 Instruction *I, Value *V) {
564 if (!V)
565 return nullptr;
566 if (auto *C = dyn_cast<Constant>(V)) {
567 if (I)
568 DEBUG(dbgs() << "Simplified " << *I << " to "
569 << " constant " << *C << "\n");
570 NumGVNOpsSimplified++;
571 assert(isa<BasicExpression>(E) &&
572 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000573 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000574 return createConstantExpression(C);
575 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
576 if (I)
577 DEBUG(dbgs() << "Simplified " << *I << " to "
578 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000579 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000580 return createVariableExpression(V);
581 }
582
583 CongruenceClass *CC = ValueToClass.lookup(V);
584 if (CC && CC->DefiningExpr) {
585 if (I)
586 DEBUG(dbgs() << "Simplified " << *I << " to "
587 << " expression " << *V << "\n");
588 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000589 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000590 return CC->DefiningExpr;
591 }
592 return nullptr;
593}
594
Daniel Berlin97718e62017-01-31 22:32:03 +0000595const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000596 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000597
Daniel Berlin97718e62017-01-31 22:32:03 +0000598 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000599
600 if (I->isCommutative()) {
601 // Ensure that commutative instructions that only differ by a permutation
602 // of their operands get the same value number by sorting the operand value
603 // numbers. Since all commutative instructions have two operands it is more
604 // efficient to sort by hand rather than using, say, std::sort.
605 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000606 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000607 E->swapOperands(0, 1);
608 }
609
610 // Perform simplificaiton
611 // TODO: Right now we only check to see if we get a constant result.
612 // We may get a less than constant, but still better, result for
613 // some operations.
614 // IE
615 // add 0, x -> x
616 // and x, x -> x
617 // We should handle this by simply rewriting the expression.
618 if (auto *CI = dyn_cast<CmpInst>(I)) {
619 // Sort the operand value numbers so x<y and y>x get the same value
620 // number.
621 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000622 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000623 E->swapOperands(0, 1);
624 Predicate = CmpInst::getSwappedPredicate(Predicate);
625 }
626 E->setOpcode((CI->getOpcode() << 8) | Predicate);
627 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000628 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
629 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000630 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
631 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000632 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000633 DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000634 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
635 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000636 } else if (isa<SelectInst>(I)) {
637 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000638 E->getOperand(0) == E->getOperand(1)) {
639 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
640 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000641 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000642 E->getOperand(2), DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000643 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
644 return SimplifiedE;
645 }
646 } else if (I->isBinaryOp()) {
647 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000648 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000649 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
650 return SimplifiedE;
651 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin64e68992017-03-12 04:46:45 +0000652 Value *V = SimplifyInstruction(BI, DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000653 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
654 return SimplifiedE;
655 } else if (isa<GetElementPtrInst>(I)) {
656 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000657 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Daniel Berlin64e68992017-03-12 04:46:45 +0000658 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000659 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
660 return SimplifiedE;
661 } else if (AllConstant) {
662 // We don't bother trying to simplify unless all of the operands
663 // were constant.
664 // TODO: There are a lot of Simplify*'s we could call here, if we
665 // wanted to. The original motivating case for this code was a
666 // zext i1 false to i8, which we don't have an interface to
667 // simplify (IE there is no SimplifyZExt).
668
669 SmallVector<Constant *, 8> C;
670 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000671 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000672
Daniel Berlin64e68992017-03-12 04:46:45 +0000673 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +0000674 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
675 return SimplifiedE;
676 }
677 return E;
678}
679
680const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000681NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000682 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000683 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000684 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000685 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000686 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000687 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000688 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000689 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000690 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000691 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000692 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000693 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000694 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000695 return E;
696 }
697 llvm_unreachable("Unhandled type of aggregate value operation");
698}
699
Daniel Berlin85f91b02016-12-26 20:06:58 +0000700const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000701 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000702 E->setOpcode(V->getValueID());
703 return E;
704}
705
Daniel Berlinf7d95802017-02-18 23:06:50 +0000706const Expression *NewGVN::createVariableOrConstant(Value *V) {
707 if (auto *C = dyn_cast<Constant>(V))
708 return createConstantExpression(C);
709 return createVariableExpression(V);
710}
711
Daniel Berlin85f91b02016-12-26 20:06:58 +0000712const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000713 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000714 E->setOpcode(C->getValueID());
715 return E;
716}
717
Daniel Berlin02c6b172017-01-02 18:00:53 +0000718const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
719 auto *E = new (ExpressionAllocator) UnknownExpression(I);
720 E->setOpcode(I->getOpcode());
721 return E;
722}
723
Davide Italiano7e274e02016-12-22 16:03:48 +0000724const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000725 MemoryAccess *HV) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000726 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000727 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000728 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
Daniel Berlin97718e62017-01-31 22:32:03 +0000729 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000730 return E;
731}
732
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000733// Return true if some equivalent of instruction Inst dominates instruction U.
734bool NewGVN::someEquivalentDominates(const Instruction *Inst,
735 const Instruction *U) const {
736 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +0000737 // This must be an instruction because we are only called from phi nodes
738 // in the case that the value it needs to check against is an instruction.
739
740 // The most likely candiates for dominance are the leader and the next leader.
741 // The leader or nextleader will dominate in all cases where there is an
742 // equivalent that is higher up in the dom tree.
743 // We can't *only* check them, however, because the
744 // dominator tree could have an infinite number of non-dominating siblings
745 // with instructions that are in the right congruence class.
746 // A
747 // B C D E F G
748 // |
749 // H
750 // Instruction U could be in H, with equivalents in every other sibling.
751 // Depending on the rpo order picked, the leader could be the equivalent in
752 // any of these siblings.
753 if (!CC)
754 return false;
755 if (DT->dominates(cast<Instruction>(CC->RepLeader), U))
756 return true;
757 if (CC->NextLeader.first &&
758 DT->dominates(cast<Instruction>(CC->NextLeader.first), U))
759 return true;
760 return llvm::any_of(CC->Members, [&](const Value *Member) {
761 return Member != CC->RepLeader &&
762 DT->dominates(cast<Instruction>(Member), U);
763 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000764}
765
Davide Italiano7e274e02016-12-22 16:03:48 +0000766// See if we have a congruence class and leader for this operand, and if so,
767// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000768Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000769 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +0000770 if (CC) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000771 // Everything in TOP is represneted by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000772 // We do have to make sure we get the type right though, so we can't set the
773 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000774 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +0000775 return UndefValue::get(V->getType());
Daniel Berlin26addef2017-01-20 21:04:30 +0000776 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Daniel Berlinb79f5362017-02-11 12:48:50 +0000777 }
778
Davide Italiano7e274e02016-12-22 16:03:48 +0000779 return V;
780}
781
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000782MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000783 auto *CC = MemoryAccessToClass.lookup(MA);
784 if (CC && CC->RepMemoryAccess)
785 return CC->RepMemoryAccess;
786 // FIXME: We need to audit all the places that current set a nullptr To, and
787 // fix them. There should always be *some* congruence class, even if it is
788 // singular. Right now, we don't bother setting congruence classes for
789 // anything but stores, which means we have to return the original access
790 // here. Otherwise, this should be unreachable.
791 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000792}
793
Daniel Berlinc4796862017-01-27 02:37:11 +0000794// Return true if the MemoryAccess is really equivalent to everything. This is
795// equivalent to the lattice value "TOP" in most lattices. This is the initial
796// state of all memory accesses.
797bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000798 return MemoryAccessToClass.lookup(MA) == TOPClass;
Daniel Berlinc4796862017-01-27 02:37:11 +0000799}
800
Davide Italiano7e274e02016-12-22 16:03:48 +0000801LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin97718e62017-01-31 22:32:03 +0000802 LoadInst *LI, MemoryAccess *DA) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000803 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000804 E->allocateOperands(ArgRecycler, ExpressionAllocator);
805 E->setType(LoadType);
806
807 // Give store and loads same opcode so they value number together.
808 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000809 E->op_push_back(lookupOperandLeader(PointerOp));
Davide Italiano7e274e02016-12-22 16:03:48 +0000810 if (LI)
811 E->setAlignment(LI->getAlignment());
812
813 // TODO: Value number heap versions. We may be able to discover
814 // things alias analysis can't on it's own (IE that a store and a
815 // load have the same value, and thus, it isn't clobbering the load).
816 return E;
817}
818
819const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000820 MemoryAccess *DA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000821 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000822 auto *E = new (ExpressionAllocator)
823 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000824 E->allocateOperands(ArgRecycler, ExpressionAllocator);
825 E->setType(SI->getValueOperand()->getType());
826
827 // Give store and loads same opcode so they value number together.
828 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000829 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000830
831 // TODO: Value number heap versions. We may be able to discover
832 // things alias analysis can't on it's own (IE that a store and a
833 // load have the same value, and thus, it isn't clobbering the load).
834 return E;
835}
836
Daniel Berlin97718e62017-01-31 22:32:03 +0000837const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000838 // Unlike loads, we never try to eliminate stores, so we do not check if they
839 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000840 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000841 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000842 // Get the expression, if any, for the RHS of the MemoryDef.
843 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
844 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
845 // If we are defined by ourselves, use the live on entry def.
846 if (StoreRHS == StoreAccess)
847 StoreRHS = MSSA->getLiveOnEntryDef();
848
Daniel Berlin589cecc2017-01-02 18:00:46 +0000849 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000850 // See if we are defined by a previous store expression, it already has a
851 // value, and it's the same value as our current store. FIXME: Right now, we
852 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin97718e62017-01-31 22:32:03 +0000853 const Expression *OldStore = createStoreExpression(SI, StoreRHS);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000854 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000855 // Basically, check if the congruence class the store is in is defined by a
856 // store that isn't us, and has the same value. MemorySSA takes care of
857 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000858 // The RepStoredValue gets nulled if all the stores disappear in a class, so
859 // we don't need to check if the class contains a store besides us.
Daniel Berlin808e3ff2017-01-31 22:31:56 +0000860 if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin0e900112017-03-24 06:33:48 +0000861 return OldStore;
862 deleteExpression(OldStore);
Daniel Berlinc4796862017-01-27 02:37:11 +0000863 // Also check if our value operand is defined by a load of the same memory
864 // location, and the memory state is the same as it was then
865 // (otherwise, it could have been overwritten later. See test32 in
866 // transforms/DeadStoreElimination/simple.ll)
867 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000868 if ((lookupOperandLeader(LI->getPointerOperand()) ==
869 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinc4796862017-01-27 02:37:11 +0000870 (lookupMemoryAccessEquiv(
871 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
872 return createVariableExpression(LI);
873 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000874 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000875 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000876}
877
Daniel Berlin97718e62017-01-31 22:32:03 +0000878const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000879 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000880
881 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000882 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000883 if (!LI->isSimple())
884 return nullptr;
885
Daniel Berlin203f47b2017-01-31 22:31:53 +0000886 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +0000887 // Load of undef is undef.
888 if (isa<UndefValue>(LoadAddressLeader))
889 return createConstantExpression(UndefValue::get(LI->getType()));
890
891 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
892
893 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
894 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
895 Instruction *DefiningInst = MD->getMemoryInst();
896 // If the defining instruction is not reachable, replace with undef.
897 if (!ReachableBlocks.count(DefiningInst->getParent()))
898 return createConstantExpression(UndefValue::get(LI->getType()));
899 }
900 }
901
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000902 const Expression *E =
903 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000904 lookupMemoryAccessEquiv(DefiningAccess));
Davide Italiano7e274e02016-12-22 16:03:48 +0000905 return E;
906}
907
Daniel Berlinf7d95802017-02-18 23:06:50 +0000908const Expression *
909NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
910 auto *PI = PredInfo->getPredicateInfoFor(I);
911 if (!PI)
912 return nullptr;
913
914 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +0000915
916 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
917 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +0000918 return nullptr;
919
Daniel Berlinfccbda92017-02-22 22:20:58 +0000920 auto *CopyOf = I->getOperand(0);
921 auto *Cond = PWC->Condition;
922
Daniel Berlinf7d95802017-02-18 23:06:50 +0000923 // If this a copy of the condition, it must be either true or false depending
924 // on the predicate info type and edge
925 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +0000926 // We should not need to add predicate users because the predicate info is
927 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +0000928 if (isa<PredicateAssume>(PI))
929 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
930 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
931 if (PBranch->TrueEdge)
932 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
933 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
934 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000935 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
936 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000937 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000938
Daniel Berlinf7d95802017-02-18 23:06:50 +0000939 // Not a copy of the condition, so see what the predicates tell us about this
940 // value. First, though, we check to make sure the value is actually a copy
941 // of one of the condition operands. It's possible, in certain cases, for it
942 // to be a copy of a predicateinfo copy. In particular, if two branch
943 // operations use the same condition, and one branch dominates the other, we
944 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +0000945 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +0000946 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000947
948 // Everything below relies on the condition being a comparison.
949 auto *Cmp = dyn_cast<CmpInst>(Cond);
950 if (!Cmp)
951 return nullptr;
952
953 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +0000954 DEBUG(dbgs() << "Copy is not of any condition operands!");
955 return nullptr;
956 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000957 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
958 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000959 bool SwappedOps = false;
960 // Sort the ops
961 if (shouldSwapOperands(FirstOp, SecondOp)) {
962 std::swap(FirstOp, SecondOp);
963 SwappedOps = true;
964 }
Daniel Berlinf7d95802017-02-18 23:06:50 +0000965 CmpInst::Predicate Predicate =
966 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
967
968 if (isa<PredicateAssume>(PI)) {
969 // If the comparison is true when the operands are equal, then we know the
970 // operands are equal, because assumes must always be true.
971 if (CmpInst::isTrueWhenEqual(Predicate)) {
972 addPredicateUsers(PI, I);
973 return createVariableOrConstant(FirstOp);
974 }
975 }
976 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
977 // If we are *not* a copy of the comparison, we may equal to the other
978 // operand when the predicate implies something about equality of
979 // operations. In particular, if the comparison is true/false when the
980 // operands are equal, and we are on the right edge, we know this operation
981 // is equal to something.
982 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
983 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
984 addPredicateUsers(PI, I);
985 return createVariableOrConstant(FirstOp);
986 }
987 // Handle the special case of floating point.
988 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
989 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
990 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
991 addPredicateUsers(PI, I);
992 return createConstantExpression(cast<Constant>(FirstOp));
993 }
994 }
995 return nullptr;
996}
997
Davide Italiano7e274e02016-12-22 16:03:48 +0000998// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000999const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001000 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001001 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1002 // Instrinsics with the returned attribute are copies of arguments.
1003 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1004 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1005 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1006 return Result;
1007 return createVariableOrConstant(ReturnedValue);
1008 }
1009 }
1010 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001011 return createCallExpression(CI, nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001012 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001013 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin97718e62017-01-31 22:32:03 +00001014 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess));
Davide Italianob2225492016-12-27 18:15:39 +00001015 }
1016 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001017}
1018
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001019// Update the memory access equivalence table to say that From is equal to To,
1020// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001021// FIXME: We need to audit all the places that current set a nullptr To, and fix
1022// them. There should always be *some* congruence class, even if it is singular.
1023bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
1024 DEBUG(dbgs() << "Setting " << *From);
1025 if (To) {
1026 DEBUG(dbgs() << " equivalent to congruence class ");
1027 DEBUG(dbgs() << To->ID << " with current memory access leader ");
1028 DEBUG(dbgs() << *To->RepMemoryAccess);
1029 } else {
1030 DEBUG(dbgs() << " equivalent to itself");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001031 }
Daniel Berlin9f376b72017-01-29 10:26:03 +00001032 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001033
1034 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001035 bool Changed = false;
1036 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001037 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001038 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001039 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001040 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001041 Changed = true;
1042 } else if (!To) {
1043 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001044 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001045 Changed = true;
1046 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001047 } else {
1048 assert(!To &&
1049 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001050 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001051
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001052 return Changed;
1053}
Daniel Berlin0e900112017-03-24 06:33:48 +00001054
Davide Italiano7e274e02016-12-22 16:03:48 +00001055// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001056const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001057 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001058 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1059
1060 // See if all arguaments are the same.
1061 // We track if any were undef because they need special handling.
1062 bool HasUndef = false;
1063 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1064 if (Arg == I)
1065 return false;
1066 if (isa<UndefValue>(Arg)) {
1067 HasUndef = true;
1068 return false;
1069 }
1070 return true;
1071 });
1072 // If we are left with no operands, it's undef
1073 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001074 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1075 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001076 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001077 return createConstantExpression(UndefValue::get(I->getType()));
1078 }
Daniel Berlind92e7f92017-01-07 00:01:42 +00001079 Value *AllSameValue = *(Filtered.begin());
1080 ++Filtered.begin();
1081 // Can't use std::equal here, sadly, because filter.begin moves.
1082 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
1083 return V == AllSameValue;
1084 })) {
1085 // In LLVM's non-standard representation of phi nodes, it's possible to have
1086 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1087 // on the original phi node), especially in weird CFG's where some arguments
1088 // are unreachable, or uninitialized along certain paths. This can cause
1089 // infinite loops during evaluation. We work around this by not trying to
1090 // really evaluate them independently, but instead using a variable
1091 // expression to say if one is equivalent to the other.
1092 // We also special case undef, so that if we have an undef, we can't use the
1093 // common value unless it dominates the phi block.
1094 if (HasUndef) {
1095 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001096 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001097 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001098 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001099 }
1100
Davide Italiano7e274e02016-12-22 16:03:48 +00001101 NumGVNPhisAllSame++;
1102 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1103 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001104 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001105 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001106 }
1107 return E;
1108}
1109
Daniel Berlin97718e62017-01-31 22:32:03 +00001110const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001111 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1112 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1113 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1114 unsigned Opcode = 0;
1115 // EI might be an extract from one of our recognised intrinsics. If it
1116 // is we'll synthesize a semantically equivalent expression instead on
1117 // an extract value expression.
1118 switch (II->getIntrinsicID()) {
1119 case Intrinsic::sadd_with_overflow:
1120 case Intrinsic::uadd_with_overflow:
1121 Opcode = Instruction::Add;
1122 break;
1123 case Intrinsic::ssub_with_overflow:
1124 case Intrinsic::usub_with_overflow:
1125 Opcode = Instruction::Sub;
1126 break;
1127 case Intrinsic::smul_with_overflow:
1128 case Intrinsic::umul_with_overflow:
1129 Opcode = Instruction::Mul;
1130 break;
1131 default:
1132 break;
1133 }
1134
1135 if (Opcode != 0) {
1136 // Intrinsic recognized. Grab its args to finish building the
1137 // expression.
1138 assert(II->getNumArgOperands() == 2 &&
1139 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001140 return createBinaryExpression(
1141 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001142 }
1143 }
1144 }
1145
Daniel Berlin97718e62017-01-31 22:32:03 +00001146 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001147}
Daniel Berlin97718e62017-01-31 22:32:03 +00001148const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001149 auto *CI = dyn_cast<CmpInst>(I);
1150 // See if our operands are equal to those of a previous predicate, and if so,
1151 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001152 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1153 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001154 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001155 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001156 std::swap(Op0, Op1);
1157 OurPredicate = CI->getSwappedPredicate();
1158 }
1159
1160 // Avoid processing the same info twice
1161 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001162 // See if we know something about the comparison itself, like it is the target
1163 // of an assume.
1164 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1165 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1166 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1167
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001168 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001169 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001170 if (CI->isTrueWhenEqual())
1171 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1172 else if (CI->isFalseWhenEqual())
1173 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1174 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001175
1176 // NOTE: Because we are comparing both operands here and below, and using
1177 // previous comparisons, we rely on fact that predicateinfo knows to mark
1178 // comparisons that use renamed operands as users of the earlier comparisons.
1179 // It is *not* enough to just mark predicateinfo renamed operands as users of
1180 // the earlier comparisons, because the *other* operand may have changed in a
1181 // previous iteration.
1182 // Example:
1183 // icmp slt %a, %b
1184 // %b.0 = ssa.copy(%b)
1185 // false branch:
1186 // icmp slt %c, %b.0
1187
1188 // %c and %a may start out equal, and thus, the code below will say the second
1189 // %icmp is false. c may become equal to something else, and in that case the
1190 // %second icmp *must* be reexamined, but would not if only the renamed
1191 // %operands are considered users of the icmp.
1192
1193 // *Currently* we only check one level of comparisons back, and only mark one
1194 // level back as touched when changes appen . If you modify this code to look
1195 // back farther through comparisons, you *must* mark the appropriate
1196 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1197 // we know something just from the operands themselves
1198
1199 // See if our operands have predicate info, so that we may be able to derive
1200 // something from a previous comparison.
1201 for (const auto &Op : CI->operands()) {
1202 auto *PI = PredInfo->getPredicateInfoFor(Op);
1203 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1204 if (PI == LastPredInfo)
1205 continue;
1206 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001207
Daniel Berlinf7d95802017-02-18 23:06:50 +00001208 // TODO: Along the false edge, we may know more things too, like icmp of
1209 // same operands is false.
1210 // TODO: We only handle actual comparison conditions below, not and/or.
1211 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1212 if (!BranchCond)
1213 continue;
1214 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1215 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1216 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001217 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001218 std::swap(BranchOp0, BranchOp1);
1219 BranchPredicate = BranchCond->getSwappedPredicate();
1220 }
1221 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1222 if (PBranch->TrueEdge) {
1223 // If we know the previous predicate is true and we are in the true
1224 // edge then we may be implied true or false.
1225 if (CmpInst::isImpliedTrueByMatchingCmp(OurPredicate,
1226 BranchPredicate)) {
1227 addPredicateUsers(PI, I);
1228 return createConstantExpression(
1229 ConstantInt::getTrue(CI->getType()));
1230 }
1231
1232 if (CmpInst::isImpliedFalseByMatchingCmp(OurPredicate,
1233 BranchPredicate)) {
1234 addPredicateUsers(PI, I);
1235 return createConstantExpression(
1236 ConstantInt::getFalse(CI->getType()));
1237 }
1238
1239 } else {
1240 // Just handle the ne and eq cases, where if we have the same
1241 // operands, we may know something.
1242 if (BranchPredicate == OurPredicate) {
1243 addPredicateUsers(PI, I);
1244 // Same predicate, same ops,we know it was false, so this is false.
1245 return createConstantExpression(
1246 ConstantInt::getFalse(CI->getType()));
1247 } else if (BranchPredicate ==
1248 CmpInst::getInversePredicate(OurPredicate)) {
1249 addPredicateUsers(PI, I);
1250 // Inverse predicate, we know the other was false, so this is true.
1251 // FIXME: Double check this
1252 return createConstantExpression(
1253 ConstantInt::getTrue(CI->getType()));
1254 }
1255 }
1256 }
1257 }
1258 }
1259 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001260 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001261}
Davide Italiano7e274e02016-12-22 16:03:48 +00001262
1263// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +00001264const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001265 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001266 if (auto *C = dyn_cast<Constant>(V))
1267 E = createConstantExpression(C);
1268 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1269 E = createVariableExpression(V);
1270 } else {
1271 // TODO: memory intrinsics.
1272 // TODO: Some day, we should do the forward propagation and reassociation
1273 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001274 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001275 switch (I->getOpcode()) {
1276 case Instruction::ExtractValue:
1277 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001278 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001279 break;
1280 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001281 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001282 break;
1283 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001284 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001285 break;
1286 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001287 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001288 break;
1289 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001290 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001291 break;
1292 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001293 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001294 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001295 case Instruction::ICmp:
1296 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001297 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001298 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001299 case Instruction::Add:
1300 case Instruction::FAdd:
1301 case Instruction::Sub:
1302 case Instruction::FSub:
1303 case Instruction::Mul:
1304 case Instruction::FMul:
1305 case Instruction::UDiv:
1306 case Instruction::SDiv:
1307 case Instruction::FDiv:
1308 case Instruction::URem:
1309 case Instruction::SRem:
1310 case Instruction::FRem:
1311 case Instruction::Shl:
1312 case Instruction::LShr:
1313 case Instruction::AShr:
1314 case Instruction::And:
1315 case Instruction::Or:
1316 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001317 case Instruction::Trunc:
1318 case Instruction::ZExt:
1319 case Instruction::SExt:
1320 case Instruction::FPToUI:
1321 case Instruction::FPToSI:
1322 case Instruction::UIToFP:
1323 case Instruction::SIToFP:
1324 case Instruction::FPTrunc:
1325 case Instruction::FPExt:
1326 case Instruction::PtrToInt:
1327 case Instruction::IntToPtr:
1328 case Instruction::Select:
1329 case Instruction::ExtractElement:
1330 case Instruction::InsertElement:
1331 case Instruction::ShuffleVector:
1332 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001333 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001334 break;
1335 default:
1336 return nullptr;
1337 }
1338 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001339 return E;
1340}
1341
Davide Italiano7e274e02016-12-22 16:03:48 +00001342void NewGVN::markUsersTouched(Value *V) {
1343 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001344 for (auto *User : V->users()) {
1345 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001346 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001347 }
1348}
1349
1350void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1351 for (auto U : MA->users()) {
1352 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001353 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001354 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001355 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001356 }
1357}
1358
Daniel Berlinf7d95802017-02-18 23:06:50 +00001359// Add I to the set of users of a given predicate.
1360void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1361 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1362 PredicateToUsers[PBranch->Condition].insert(I);
1363 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1364 PredicateToUsers[PAssume->Condition].insert(I);
1365}
1366
1367// Touch all the predicates that depend on this instruction.
1368void NewGVN::markPredicateUsersTouched(Instruction *I) {
1369 const auto Result = PredicateToUsers.find(I);
Daniel Berlin46b72e62017-03-19 00:07:32 +00001370 if (Result != PredicateToUsers.end()) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001371 for (auto *User : Result->second)
1372 TouchedInstructions.set(InstrDFS.lookup(User));
Daniel Berlin46b72e62017-03-19 00:07:32 +00001373 PredicateToUsers.erase(Result);
1374 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001375}
1376
Daniel Berlin32f8d562017-01-07 16:55:14 +00001377// Touch the instructions that need to be updated after a congruence class has a
1378// leader change, and mark changed values.
1379void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1380 for (auto M : CC->Members) {
1381 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001382 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001383 LeaderChanges.insert(M);
1384 }
1385}
1386
1387// Move a value, currently in OldClass, to be part of NewClass
1388// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001389void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1390 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001391 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001392 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001393 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001394
1395 if (I == OldClass->NextLeader.first)
1396 OldClass->NextLeader = {nullptr, ~0U};
1397
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001398 // It's possible, though unlikely, for us to discover equivalences such
1399 // that the current leader does not dominate the old one.
1400 // This statistic tracks how often this happens.
1401 // We assert on phi nodes when this happens, currently, for debugging, because
1402 // we want to make sure we name phi node cycles properly.
1403 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001404 I != NewClass->RepLeader) {
1405 auto *IBB = I->getParent();
1406 auto *NCBB = cast<Instruction>(NewClass->RepLeader)->getParent();
1407 bool Dominated = IBB == NCBB &&
1408 InstrDFS.lookup(I) < InstrDFS.lookup(NewClass->RepLeader);
1409 Dominated = Dominated || DT->properlyDominates(IBB, NCBB);
1410 if (Dominated) {
1411 ++NumGVNNotMostDominatingLeader;
1412 assert(
1413 !isa<PHINode>(I) &&
1414 "New class for instruction should not be dominated by instruction");
1415 }
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001416 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001417
1418 if (NewClass->RepLeader != I) {
1419 auto DFSNum = InstrDFS.lookup(I);
1420 if (DFSNum < NewClass->NextLeader.second)
1421 NewClass->NextLeader = {I, DFSNum};
1422 }
1423
1424 OldClass->Members.erase(I);
1425 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001426 MemoryAccess *StoreAccess = nullptr;
1427 if (auto *SI = dyn_cast<StoreInst>(I)) {
1428 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001429 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001430 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001431 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001432 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001433 if (!NewClass->RepMemoryAccess) {
1434 // If we don't have a representative memory access, it better be the only
1435 // store in there.
1436 assert(NewClass->StoreCount == 1);
1437 NewClass->RepMemoryAccess = StoreAccess;
1438 }
1439 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001440 }
1441
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001442 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001443 // See if we destroyed the class or need to swap leaders.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001444 if (OldClass->Members.empty() && OldClass != TOPClass) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001445 if (OldClass->DefiningExpr) {
1446 OldClass->Dead = true;
1447 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1448 << " from table\n");
1449 ExpressionToClass.erase(OldClass->DefiningExpr);
1450 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001451 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001452 // When the leader changes, the value numbering of
1453 // everything may change due to symbolization changes, so we need to
1454 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001455 DEBUG(dbgs() << "Leader change!\n");
1456 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001457 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001458 if (OldClass->StoreCount == 0) {
1459 if (OldClass->RepStoredValue != nullptr)
1460 OldClass->RepStoredValue = nullptr;
1461 if (OldClass->RepMemoryAccess != nullptr)
1462 OldClass->RepMemoryAccess = nullptr;
1463 }
1464
1465 // If we destroy the old access leader, we have to effectively destroy the
1466 // congruence class. When it comes to scalars, anything with the same value
1467 // is as good as any other. That means that one leader is as good as
1468 // another, and as long as you have some leader for the value, you are
1469 // good.. When it comes to *memory states*, only one particular thing really
1470 // represents the definition of a given memory state. Once it goes away, we
1471 // need to re-evaluate which pieces of memory are really still
1472 // equivalent. The best way to do this is to re-value number things. The
1473 // only way to really make that happen is to destroy the rest of the class.
1474 // In order to effectively destroy the class, we reset ExpressionToClass for
1475 // each by using the ValueToExpression mapping. The members later get
1476 // marked as touched due to the leader change. We will create new
1477 // congruence classes, and the pieces that are still equivalent will end
1478 // back together in a new class. If this becomes too expensive, it is
1479 // possible to use a versioning scheme for the congruence classes to avoid
1480 // the expressions finding this old class.
1481 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1482 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1483 << " because memory access leader changed");
1484 for (auto Member : OldClass->Members)
1485 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1486 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001487
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001488 // We don't need to sort members if there is only 1, and we don't care about
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001489 // sorting the TOP class because everything either gets out of it or is
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001490 // unreachable.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001491 if (OldClass->Members.size() == 1 || OldClass == TOPClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001492 OldClass->RepLeader = *(OldClass->Members.begin());
1493 } else if (OldClass->NextLeader.first) {
1494 ++NumGVNAvoidedSortedLeaderChanges;
1495 OldClass->RepLeader = OldClass->NextLeader.first;
1496 OldClass->NextLeader = {nullptr, ~0U};
1497 } else {
1498 ++NumGVNSortedLeaderChanges;
1499 // TODO: If this ends up to slow, we can maintain a dual structure for
1500 // member testing/insertion, or keep things mostly sorted, and sort only
1501 // here, or ....
1502 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1503 for (const auto X : OldClass->Members) {
1504 auto DFSNum = InstrDFS.lookup(X);
1505 if (DFSNum < MinDFS.second)
1506 MinDFS = {X, DFSNum};
1507 }
1508 OldClass->RepLeader = MinDFS.first;
1509 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001510 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001511 }
1512}
1513
Davide Italiano7e274e02016-12-22 16:03:48 +00001514// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001515void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1516 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001517 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00001518 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001519
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001520 CongruenceClass *IClass = ValueToClass[I];
1521 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001522 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001523 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001524
1525 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001526 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001527 EClass = ValueToClass[VE->getVariableValue()];
1528 } else {
1529 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1530
1531 // If it's not in the value table, create a new congruence class.
1532 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001533 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001534 auto place = lookupResult.first;
1535 place->second = NewClass;
1536
1537 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001538 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001539 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001540 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1541 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001542 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001543 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001544 // The RepMemoryAccess field will be filled in properly by the
1545 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001546 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001547 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001548 }
1549 assert(!isa<VariableExpression>(E) &&
1550 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001551
1552 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001553 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001554 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001555 << " and leader " << *(NewClass->RepLeader));
1556 if (NewClass->RepStoredValue)
1557 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1558 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001559 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1560 } else {
1561 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001562 if (isa<ConstantExpression>(E))
1563 assert(isa<Constant>(EClass->RepLeader) &&
1564 "Any class with a constant expression should have a "
1565 "constant leader");
1566
Davide Italiano7e274e02016-12-22 16:03:48 +00001567 assert(EClass && "Somehow don't have an eclass");
1568
1569 assert(!EClass->Dead && "We accidentally looked up a dead class");
1570 }
1571 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001572 bool ClassChanged = IClass != EClass;
1573 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001574 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001575 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1576 << "\n");
1577
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001578 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001579 moveValueToNewCongruenceClass(I, IClass, EClass);
1580 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001581 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001582 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001583 if (auto *CI = dyn_cast<CmpInst>(I))
1584 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00001585 }
1586}
1587
1588// Process the fact that Edge (from, to) is reachable, including marking
1589// any newly reachable blocks and instructions for processing.
1590void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1591 // Check if the Edge was reachable before.
1592 if (ReachableEdges.insert({From, To}).second) {
1593 // If this block wasn't reachable before, all instructions are touched.
1594 if (ReachableBlocks.insert(To).second) {
1595 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1596 const auto &InstRange = BlockInstRange.lookup(To);
1597 TouchedInstructions.set(InstRange.first, InstRange.second);
1598 } else {
1599 DEBUG(dbgs() << "Block " << getBlockName(To)
1600 << " was reachable, but new edge {" << getBlockName(From)
1601 << "," << getBlockName(To) << "} to it found\n");
1602
1603 // We've made an edge reachable to an existing block, which may
1604 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1605 // they are the only thing that depend on new edges. Anything using their
1606 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001607 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001608 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001609
Davide Italiano7e274e02016-12-22 16:03:48 +00001610 auto BI = To->begin();
1611 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001612 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001613 ++BI;
1614 }
1615 }
1616 }
1617}
1618
1619// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1620// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001621Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001622 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001623 if (isa<Constant>(Result))
1624 return Result;
1625 return nullptr;
1626}
1627
1628// Process the outgoing edges of a block for reachability.
1629void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1630 // Evaluate reachability of terminator instruction.
1631 BranchInst *BR;
1632 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1633 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001634 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001635 if (!CondEvaluated) {
1636 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001637 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001638 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1639 CondEvaluated = CE->getConstantValue();
1640 }
1641 } else if (isa<ConstantInt>(Cond)) {
1642 CondEvaluated = Cond;
1643 }
1644 }
1645 ConstantInt *CI;
1646 BasicBlock *TrueSucc = BR->getSuccessor(0);
1647 BasicBlock *FalseSucc = BR->getSuccessor(1);
1648 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1649 if (CI->isOne()) {
1650 DEBUG(dbgs() << "Condition for Terminator " << *TI
1651 << " evaluated to true\n");
1652 updateReachableEdge(B, TrueSucc);
1653 } else if (CI->isZero()) {
1654 DEBUG(dbgs() << "Condition for Terminator " << *TI
1655 << " evaluated to false\n");
1656 updateReachableEdge(B, FalseSucc);
1657 }
1658 } else {
1659 updateReachableEdge(B, TrueSucc);
1660 updateReachableEdge(B, FalseSucc);
1661 }
1662 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1663 // For switches, propagate the case values into the case
1664 // destinations.
1665
1666 // Remember how many outgoing edges there are to every successor.
1667 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1668
Davide Italiano7e274e02016-12-22 16:03:48 +00001669 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001670 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001671 // See if we were able to turn this switch statement into a constant.
1672 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001673 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001674 // We should be able to get case value for this.
1675 auto CaseVal = SI->findCaseValue(CondVal);
1676 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1677 // We proved the value is outside of the range of the case.
1678 // We can't do anything other than mark the default dest as reachable,
1679 // and go home.
1680 updateReachableEdge(B, SI->getDefaultDest());
1681 return;
1682 }
1683 // Now get where it goes and mark it reachable.
1684 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1685 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001686 } else {
1687 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1688 BasicBlock *TargetBlock = SI->getSuccessor(i);
1689 ++SwitchEdges[TargetBlock];
1690 updateReachableEdge(B, TargetBlock);
1691 }
1692 }
1693 } else {
1694 // Otherwise this is either unconditional, or a type we have no
1695 // idea about. Just mark successors as reachable.
1696 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1697 BasicBlock *TargetBlock = TI->getSuccessor(i);
1698 updateReachableEdge(B, TargetBlock);
1699 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001700
1701 // This also may be a memory defining terminator, in which case, set it
1702 // equivalent to nothing.
1703 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1704 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001705 }
1706}
1707
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001708// The algorithm initially places the values of the routine in the TOP
1709// congruence class. The leader of TOP is the undetermined value `undef`.
1710// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00001711void NewGVN::initializeCongruenceClasses(Function &F) {
1712 // FIXME now i can't remember why this is 2
1713 NextCongruenceNum = 2;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001714 // Initialize all other instructions to be in TOP class.
Davide Italiano7e274e02016-12-22 16:03:48 +00001715 CongruenceClass::MemberSet InitialValues;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001716 TOPClass = createCongruenceClass(nullptr, nullptr);
1717 TOPClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001718 for (auto &B : F) {
1719 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001720 MemoryAccessToClass[MP] = TOPClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001721
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001722 for (auto &I : B) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00001723 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001724 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00001725 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
1726 continue;
1727 InitialValues.insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001728 ValueToClass[&I] = TOPClass;
Daniel Berlin22a4a012017-02-11 15:20:15 +00001729
Daniel Berlin589cecc2017-01-02 18:00:46 +00001730 // All memory accesses are equivalent to live on entry to start. They must
1731 // be initialized to something so that initial changes are noticed. For
1732 // the maximal answer, we initialize them all to be the same as
1733 // liveOnEntry. Note that to save time, we only initialize the
1734 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1735 // other expression can generate a memory equivalence. If we start
1736 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001737 if (isa<StoreInst>(&I)) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001738 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = TOPClass;
1739 ++TOPClass->StoreCount;
1740 assert(TOPClass->StoreCount > 0);
Davide Italianoeac05f62017-01-11 23:41:24 +00001741 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001742 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001743 }
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001744 TOPClass->Members.swap(InitialValues);
Davide Italiano7e274e02016-12-22 16:03:48 +00001745
1746 // Initialize arguments to be in their own unique congruence classes
1747 for (auto &FA : F.args())
1748 createSingletonCongruenceClass(&FA);
1749}
1750
1751void NewGVN::cleanupTables() {
1752 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1753 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1754 << CongruenceClasses[i]->Members.size() << " members\n");
1755 // Make sure we delete the congruence class (probably worth switching to
1756 // a unique_ptr at some point.
1757 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001758 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001759 }
1760
1761 ValueToClass.clear();
1762 ArgRecycler.clear(ExpressionAllocator);
1763 ExpressionAllocator.Reset();
1764 CongruenceClasses.clear();
1765 ExpressionToClass.clear();
1766 ValueToExpression.clear();
1767 ReachableBlocks.clear();
1768 ReachableEdges.clear();
1769#ifndef NDEBUG
1770 ProcessedCount.clear();
1771#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001772 InstrDFS.clear();
1773 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001774 DFSToInstr.clear();
1775 BlockInstRange.clear();
1776 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001777 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00001778 PredicateToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001779}
1780
1781std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1782 unsigned Start) {
1783 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001784 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1785 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001786 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001787 }
1788
Davide Italiano7e274e02016-12-22 16:03:48 +00001789 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00001790 // There's no need to call isInstructionTriviallyDead more than once on
1791 // an instruction. Therefore, once we know that an instruction is dead
1792 // we change its DFS number so that it doesn't get value numbered.
1793 if (isInstructionTriviallyDead(&I, TLI)) {
1794 InstrDFS[&I] = 0;
1795 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
1796 markInstructionForDeletion(&I);
1797 continue;
1798 }
1799
Davide Italiano7e274e02016-12-22 16:03:48 +00001800 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001801 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001802 }
1803
1804 // All of the range functions taken half-open ranges (open on the end side).
1805 // So we do not subtract one from count, because at this point it is one
1806 // greater than the last instruction.
1807 return std::make_pair(Start, End);
1808}
1809
1810void NewGVN::updateProcessedCount(Value *V) {
1811#ifndef NDEBUG
1812 if (ProcessedCount.count(V) == 0) {
1813 ProcessedCount.insert({V, 1});
1814 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001815 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001816 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001817 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001818 }
1819#endif
1820}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001821// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1822void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1823 // If all the arguments are the same, the MemoryPhi has the same value as the
1824 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001825 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlin41b39162017-03-18 15:41:36 +00001826 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001827 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001828 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1829 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00001830 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001831 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001832 // If all that is left is nothing, our memoryphi is undef. We keep it as
1833 // InitialClass. Note: The only case this should happen is if we have at
1834 // least one self-argument.
1835 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001836 if (setMemoryAccessEquivTo(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00001837 markMemoryUsersTouched(MP);
1838 return;
1839 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001840
1841 // Transform the remaining operands into operand leaders.
1842 // FIXME: mapped_iterator should have a range version.
1843 auto LookupFunc = [&](const Use &U) {
1844 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1845 };
1846 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1847 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1848
1849 // and now check if all the elements are equal.
1850 // Sadly, we can't use std::equals since these are random access iterators.
1851 MemoryAccess *AllSameValue = *MappedBegin;
1852 ++MappedBegin;
1853 bool AllEqual = std::all_of(
1854 MappedBegin, MappedEnd,
1855 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1856
1857 if (AllEqual)
1858 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1859 else
1860 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1861
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001862 if (setMemoryAccessEquivTo(
1863 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001864 markMemoryUsersTouched(MP);
1865}
1866
1867// Value number a single instruction, symbolically evaluating, performing
1868// congruence finding, and updating mappings.
1869void NewGVN::valueNumberInstruction(Instruction *I) {
1870 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001871 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00001872 const Expression *Symbolized = nullptr;
1873 if (DebugCounter::shouldExecute(VNCounter)) {
1874 Symbolized = performSymbolicEvaluation(I);
1875 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00001876 // Mark the instruction as unused so we don't value number it again.
1877 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00001878 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00001879 // If we couldn't come up with a symbolic expression, use the unknown
1880 // expression
1881 if (Symbolized == nullptr)
1882 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001883 performCongruenceFinding(I, Symbolized);
1884 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001885 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00001886 // don't currently understand. We don't place non-value producing
1887 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001888 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001889 auto *Symbolized = createUnknownExpression(I);
1890 performCongruenceFinding(I, Symbolized);
1891 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001892 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1893 }
1894}
Davide Italiano7e274e02016-12-22 16:03:48 +00001895
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001896// Check if there is a path, using single or equal argument phi nodes, from
1897// First to Second.
1898bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1899 const MemoryAccess *Second) const {
1900 if (First == Second)
1901 return true;
1902
1903 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1904 auto *DefAccess = FirstDef->getDefiningAccess();
1905 return singleReachablePHIPath(DefAccess, Second);
1906 } else {
1907 auto *MP = cast<MemoryPhi>(First);
1908 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00001909 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001910 };
1911 auto FilteredPhiArgs =
1912 make_filter_range(MP->operands(), ReachableOperandPred);
1913 SmallVector<const Value *, 32> OperandList;
1914 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1915 std::back_inserter(OperandList));
1916 bool Okay = OperandList.size() == 1;
1917 if (!Okay)
1918 Okay = std::equal(OperandList.begin(), OperandList.end(),
1919 OperandList.begin());
1920 if (Okay)
1921 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1922 return false;
1923 }
1924}
1925
Daniel Berlin589cecc2017-01-02 18:00:46 +00001926// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001927// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001928// subject to very rare false negatives. It is only useful for
1929// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001930void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00001931#ifndef NDEBUG
Daniel Berlin589cecc2017-01-02 18:00:46 +00001932 // Anything equivalent in the memory access table should be in the same
1933 // congruence class.
1934
1935 // Filter out the unreachable and trivially dead entries, because they may
1936 // never have been updated if the instructions were not processed.
1937 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001938 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001939 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1940 if (!Result)
1941 return false;
1942 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1943 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1944 return true;
1945 };
1946
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001947 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001948 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001949 // Unreachable instructions may not have changed because we never process
1950 // them.
1951 if (!ReachableBlocks.count(KV.first->getBlock()))
1952 continue;
1953 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001954 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001955 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001956 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001957 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1958 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1959 "The instructions for these memory operations should have "
1960 "been in the same congruence class or reachable through"
1961 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001962 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1963
1964 // We can only sanely verify that MemoryDefs in the operand list all have
1965 // the same class.
1966 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00001967 return ReachableEdges.count(
1968 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00001969 isa<MemoryDef>(U);
1970
1971 };
1972 // All arguments should in the same class, ignoring unreachable arguments
1973 auto FilteredPhiArgs =
1974 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1975 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1976 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1977 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1978 const MemoryDef *MD = cast<MemoryDef>(U);
1979 return ValueToClass.lookup(MD->getMemoryInst());
1980 });
1981 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1982 PhiOpClasses.begin()) &&
1983 "All MemoryPhi arguments should be in the same class");
1984 }
1985 }
Davide Italianoe9781e72017-03-25 02:40:02 +00001986#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00001987}
1988
Daniel Berlin06329a92017-03-18 15:41:40 +00001989// Verify that the sparse propagation we did actually found the maximal fixpoint
1990// We do this by storing the value to class mapping, touching all instructions,
1991// and redoing the iteration to see if anything changed.
1992void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001993#ifndef NDEBUG
Daniel Berlin06329a92017-03-18 15:41:40 +00001994 if (DebugCounter::isCounterSet(VNCounter))
1995 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
1996
1997 // Note that we have to store the actual classes, as we may change existing
1998 // classes during iteration. This is because our memory iteration propagation
1999 // is not perfect, and so may waste a little work. But it should generate
2000 // exactly the same congruence classes we have now, with different IDs.
2001 std::map<const Value *, CongruenceClass> BeforeIteration;
2002
2003 for (auto &KV : ValueToClass) {
2004 if (auto *I = dyn_cast<Instruction>(KV.first))
2005 // Skip unused/dead instructions.
2006 if (InstrDFS.lookup(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002007 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002008 BeforeIteration.insert({KV.first, *KV.second});
2009 }
2010
2011 TouchedInstructions.set();
2012 TouchedInstructions.reset(0);
2013 iterateTouchedInstructions();
2014 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2015 EqualClasses;
2016 for (const auto &KV : ValueToClass) {
2017 if (auto *I = dyn_cast<Instruction>(KV.first))
2018 // Skip unused/dead instructions.
2019 if (InstrDFS.lookup(I) == 0)
2020 continue;
2021 // We could sink these uses, but i think this adds a bit of clarity here as
2022 // to what we are comparing.
2023 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2024 auto *AfterCC = KV.second;
2025 // Note that the classes can't change at this point, so we memoize the set
2026 // that are equal.
2027 if (!EqualClasses.count({BeforeCC, AfterCC})) {
2028 assert(areClassesEquivalent(BeforeCC, AfterCC) &&
2029 "Value number changed after main loop completed!");
2030 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00002031 }
2032 }
2033#endif
2034}
2035
Daniel Berlin06329a92017-03-18 15:41:40 +00002036// This is the main value numbering loop, it iterates over the initial touched
2037// instruction set, propagating value numbers, marking things touched, etc,
2038// until the set of touched instructions is completely empty.
2039void NewGVN::iterateTouchedInstructions() {
2040 unsigned int Iterations = 0;
2041 // Figure out where touchedinstructions starts
2042 int FirstInstr = TouchedInstructions.find_first();
2043 // Nothing set, nothing to iterate, just return.
2044 if (FirstInstr == -1)
2045 return;
2046 BasicBlock *LastBlock = getBlockForValue(DFSToInstr[FirstInstr]);
2047 while (TouchedInstructions.any()) {
2048 ++Iterations;
2049 // Walk through all the instructions in all the blocks in RPO.
2050 // TODO: As we hit a new block, we should push and pop equalities into a
2051 // table lookupOperandLeader can use, to catch things PredicateInfo
2052 // might miss, like edge-only equivalences.
2053 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2054 InstrNum = TouchedInstructions.find_next(InstrNum)) {
2055
2056 // This instruction was found to be dead. We don't bother looking
2057 // at it again.
2058 if (InstrNum == 0) {
2059 TouchedInstructions.reset(InstrNum);
2060 continue;
2061 }
2062
2063 Value *V = DFSToInstr[InstrNum];
2064 BasicBlock *CurrBlock = getBlockForValue(V);
2065
2066 // If we hit a new block, do reachability processing.
2067 if (CurrBlock != LastBlock) {
2068 LastBlock = CurrBlock;
2069 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2070 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2071
2072 // If it's not reachable, erase any touched instructions and move on.
2073 if (!BlockReachable) {
2074 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2075 DEBUG(dbgs() << "Skipping instructions in block "
2076 << getBlockName(CurrBlock)
2077 << " because it is unreachable\n");
2078 continue;
2079 }
2080 updateProcessedCount(CurrBlock);
2081 }
2082
2083 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
2084 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2085 valueNumberMemoryPhi(MP);
2086 } else if (auto *I = dyn_cast<Instruction>(V)) {
2087 valueNumberInstruction(I);
2088 } else {
2089 llvm_unreachable("Should have been a MemoryPhi or Instruction");
2090 }
2091 updateProcessedCount(V);
2092 // Reset after processing (because we may mark ourselves as touched when
2093 // we propagate equalities).
2094 TouchedInstructions.reset(InstrNum);
2095 }
2096 }
2097 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
2098}
2099
Daniel Berlin85f91b02016-12-26 20:06:58 +00002100// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00002101bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00002102 if (DebugCounter::isCounterSet(VNCounter))
2103 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00002104 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00002105 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00002106 MSSAWalker = MSSA->getWalker();
2107
2108 // Count number of instructions for sizing of hash tables, and come
2109 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002110 unsigned ICount = 1;
2111 // Add an empty instruction to account for the fact that we start at 1
2112 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002113 // Note: We want ideal RPO traversal of the blocks, which is not quite the
2114 // same as dominator tree order, particularly with regard whether backedges
2115 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00002116 // If we visit in the wrong order, we will end up performing N times as many
2117 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002118 // The dominator tree does guarantee that, for a given dom tree node, it's
2119 // parent must occur before it in the RPO ordering. Thus, we only need to sort
2120 // the siblings.
2121 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00002122 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00002123 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002124 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002125 auto *Node = DT->getNode(B);
2126 assert(Node && "RPO and Dominator tree should have same reachability");
2127 RPOOrdering[Node] = ++Counter;
2128 }
2129 // Sort dominator tree children arrays into RPO.
2130 for (auto &B : RPOT) {
2131 auto *Node = DT->getNode(B);
2132 if (Node->getChildren().size() > 1)
2133 std::sort(Node->begin(), Node->end(),
2134 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
2135 return RPOOrdering[A] < RPOOrdering[B];
2136 });
2137 }
2138
2139 // Now a standard depth first ordering of the domtree is equivalent to RPO.
2140 auto DFI = df_begin(DT->getRootNode());
2141 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
2142 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00002143 const auto &BlockRange = assignDFSNumbers(B, ICount);
2144 BlockInstRange.insert({B, BlockRange});
2145 ICount += BlockRange.second - BlockRange.first;
2146 }
2147
2148 // Handle forward unreachable blocks and figure out which blocks
2149 // have single preds.
2150 for (auto &B : F) {
2151 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002152 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002153 const auto &BlockRange = assignDFSNumbers(&B, ICount);
2154 BlockInstRange.insert({&B, BlockRange});
2155 ICount += BlockRange.second - BlockRange.first;
2156 }
2157 }
2158
Daniel Berline0bd37e2016-12-29 22:15:12 +00002159 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002160 // Ensure we don't end up resizing the expressionToClass map, as
2161 // that can be quite expensive. At most, we have one expression per
2162 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002163 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002164
2165 // Initialize the touched instructions to include the entry block.
2166 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2167 TouchedInstructions.set(InstRange.first, InstRange.second);
2168 ReachableBlocks.insert(&F.getEntryBlock());
2169
2170 initializeCongruenceClasses(F);
Daniel Berlin06329a92017-03-18 15:41:40 +00002171 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00002172 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00002173 verifyIterationSettled(F);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002174
Davide Italiano7e274e02016-12-22 16:03:48 +00002175 Changed |= eliminateInstructions(F);
2176
2177 // Delete all instructions marked for deletion.
2178 for (Instruction *ToErase : InstructionsToErase) {
2179 if (!ToErase->use_empty())
2180 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2181
2182 ToErase->eraseFromParent();
2183 }
2184
2185 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002186 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2187 return !ReachableBlocks.count(&BB);
2188 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002189
2190 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2191 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002192 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002193 deleteInstructionsInBlock(&BB);
2194 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002195 }
2196
2197 cleanupTables();
2198 return Changed;
2199}
2200
Davide Italiano7e274e02016-12-22 16:03:48 +00002201// Return true if V is a value that will always be available (IE can
2202// be placed anywhere) in the function. We don't do globals here
2203// because they are often worse to put in place.
2204// TODO: Separate cost from availability
2205static bool alwaysAvailable(Value *V) {
2206 return isa<Constant>(V) || isa<Argument>(V);
2207}
2208
Davide Italiano7e274e02016-12-22 16:03:48 +00002209struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002210 int DFSIn = 0;
2211 int DFSOut = 0;
2212 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002213 // Only one of Def and U will be set.
2214 Value *Def = nullptr;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002215 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002216 bool operator<(const ValueDFS &Other) const {
2217 // It's not enough that any given field be less than - we have sets
2218 // of fields that need to be evaluated together to give a proper ordering.
2219 // For example, if you have;
2220 // DFS (1, 3)
2221 // Val 0
2222 // DFS (1, 2)
2223 // Val 50
2224 // We want the second to be less than the first, but if we just go field
2225 // by field, we will get to Val 0 < Val 50 and say the first is less than
2226 // the second. We only want it to be less than if the DFS orders are equal.
2227 //
2228 // Each LLVM instruction only produces one value, and thus the lowest-level
2229 // differentiator that really matters for the stack (and what we use as as a
2230 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002231 // Everything else in the structure is instruction level, and only affects
2232 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002233 //
2234 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2235 // the order of replacement of uses does not matter.
2236 // IE given,
2237 // a = 5
2238 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002239 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2240 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002241 // The .val will be the same as well.
2242 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002243 // You will replace both, and it does not matter what order you replace them
2244 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2245 // operand 2).
2246 // Similarly for the case of same dfsin, dfsout, localnum, but different
2247 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002248 // a = 5
2249 // b = 6
2250 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002251 // in c, we will a valuedfs for a, and one for b,with everything the same
2252 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002253 // It does not matter what order we replace these operands in.
2254 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002255 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2256 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00002257 Other.U);
2258 }
2259};
2260
Daniel Berlinc4796862017-01-27 02:37:11 +00002261// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002262// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00002263// reachable uses for each value is stored in UseCount, and instructions that
2264// seem
2265// dead (have no non-dead uses) are stored in ProbablyDead.
2266void NewGVN::convertClassToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00002267 const CongruenceClass::MemberSet &Dense,
Daniel Berline3e69e12017-03-10 00:32:33 +00002268 SmallVectorImpl<ValueDFS> &DFSOrderedSet,
2269 DenseMap<const Value *, unsigned int> &UseCounts,
2270 SmallPtrSetImpl<Instruction *> &ProbablyDead) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002271 for (auto D : Dense) {
2272 // First add the value.
2273 BasicBlock *BB = getBlockForValue(D);
2274 // Constants are handled prior to ever calling this function, so
2275 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002276 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002277 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002278 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002279 VDDef.DFSIn = DomNode->getDFSNumIn();
2280 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00002281 // If it's a store, use the leader of the value operand.
2282 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002283 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002284 VDDef.Def = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
Daniel Berlin26addef2017-01-20 21:04:30 +00002285 } else {
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002286 VDDef.Def = D;
Daniel Berlin26addef2017-01-20 21:04:30 +00002287 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002288 assert(isa<Instruction>(D) &&
2289 "The dense set member should always be an instruction");
2290 VDDef.LocalNum = InstrDFS.lookup(D);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002291 DFSOrderedSet.emplace_back(VDDef);
Daniel Berline3e69e12017-03-10 00:32:33 +00002292 Instruction *Def = cast<Instruction>(D);
2293 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002294 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00002295 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002296 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002297 // Don't try to replace into dead uses
2298 if (InstructionsToErase.count(I))
2299 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002300 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00002301 // Put the phi node uses in the incoming block.
2302 BasicBlock *IBlock;
2303 if (auto *P = dyn_cast<PHINode>(I)) {
2304 IBlock = P->getIncomingBlock(U);
2305 // Make phi node users appear last in the incoming block
2306 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002307 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00002308 } else {
2309 IBlock = I->getParent();
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002310 VDUse.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002311 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002312
2313 // Skip uses in unreachable blocks, as we're going
2314 // to delete them.
2315 if (ReachableBlocks.count(IBlock) == 0)
2316 continue;
2317
Daniel Berlinb66164c2017-01-14 00:24:23 +00002318 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002319 VDUse.DFSIn = DomNode->getDFSNumIn();
2320 VDUse.DFSOut = DomNode->getDFSNumOut();
2321 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00002322 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002323 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00002324 }
2325 }
Daniel Berline3e69e12017-03-10 00:32:33 +00002326
2327 // If there are no uses, it's probably dead (but it may have side-effects,
2328 // so not definitely dead. Otherwise, store the number of uses so we can
2329 // track if it becomes dead later).
2330 if (UseCount == 0)
2331 ProbablyDead.insert(Def);
2332 else
2333 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002334 }
2335}
2336
Daniel Berlinc4796862017-01-27 02:37:11 +00002337// This function converts the set of members for a congruence class from values,
2338// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00002339void NewGVN::convertClassToLoadsAndStores(
Daniel Berlinc4796862017-01-27 02:37:11 +00002340 const CongruenceClass::MemberSet &Dense,
2341 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2342 for (auto D : Dense) {
2343 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2344 continue;
2345
2346 BasicBlock *BB = getBlockForValue(D);
2347 ValueDFS VD;
2348 DomTreeNode *DomNode = DT->getNode(BB);
2349 VD.DFSIn = DomNode->getDFSNumIn();
2350 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002351 VD.Def = D;
Daniel Berlinc4796862017-01-27 02:37:11 +00002352
2353 // If it's an instruction, use the real local dfs number.
2354 if (auto *I = dyn_cast<Instruction>(D))
2355 VD.LocalNum = InstrDFS.lookup(I);
2356 else
2357 llvm_unreachable("Should have been an instruction");
2358
2359 LoadsAndStores.emplace_back(VD);
2360 }
2361}
2362
Davide Italiano7e274e02016-12-22 16:03:48 +00002363static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00002364 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00002365 if (!ReplInst)
2366 return;
2367
Davide Italiano7e274e02016-12-22 16:03:48 +00002368 // Patch the replacement so that it is not more restrictive than the value
2369 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00002370 // Note that if 'I' is a load being replaced by some operation,
2371 // for example, by an arithmetic operation, then andIRFlags()
2372 // would just erase all math flags from the original arithmetic
2373 // operation, which is clearly not wanted and not needed.
2374 if (!isa<LoadInst>(I))
2375 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002376
Daniel Berlin86eab152017-02-12 22:25:20 +00002377 // FIXME: If both the original and replacement value are part of the
2378 // same control-flow region (meaning that the execution of one
2379 // guarantees the execution of the other), then we can combine the
2380 // noalias scopes here and do better than the general conservative
2381 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00002382
Daniel Berlin86eab152017-02-12 22:25:20 +00002383 // In general, GVN unifies expressions over different control-flow
2384 // regions, and so we need a conservative combination of the noalias
2385 // scopes.
2386 static const unsigned KnownIDs[] = {
2387 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2388 LLVMContext::MD_noalias, LLVMContext::MD_range,
2389 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2390 LLVMContext::MD_invariant_group};
2391 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00002392}
2393
2394static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2395 patchReplacementInstruction(I, Repl);
2396 I->replaceAllUsesWith(Repl);
2397}
2398
2399void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2400 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2401 ++NumGVNBlocksDeleted;
2402
Daniel Berline19f0e02017-01-30 17:06:55 +00002403 // Delete the instructions backwards, as it has a reduced likelihood of having
2404 // to update as many def-use and use-def chains. Start after the terminator.
2405 auto StartPoint = BB->rbegin();
2406 ++StartPoint;
2407 // Note that we explicitly recalculate BB->rend() on each iteration,
2408 // as it may change when we remove the first instruction.
2409 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2410 Instruction &Inst = *I++;
2411 if (!Inst.use_empty())
2412 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2413 if (isa<LandingPadInst>(Inst))
2414 continue;
2415
2416 Inst.eraseFromParent();
2417 ++NumGVNInstrDeleted;
2418 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002419 // Now insert something that simplifycfg will turn into an unreachable.
2420 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2421 new StoreInst(UndefValue::get(Int8Ty),
2422 Constant::getNullValue(Int8Ty->getPointerTo()),
2423 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002424}
2425
2426void NewGVN::markInstructionForDeletion(Instruction *I) {
2427 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2428 InstructionsToErase.insert(I);
2429}
2430
2431void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2432
2433 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2434 patchAndReplaceAllUsesWith(I, V);
2435 // We save the actual erasing to avoid invalidating memory
2436 // dependencies until we are done with everything.
2437 markInstructionForDeletion(I);
2438}
2439
2440namespace {
2441
2442// This is a stack that contains both the value and dfs info of where
2443// that value is valid.
2444class ValueDFSStack {
2445public:
2446 Value *back() const { return ValueStack.back(); }
2447 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2448
2449 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002450 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002451 DFSStack.emplace_back(DFSIn, DFSOut);
2452 }
2453 bool empty() const { return DFSStack.empty(); }
2454 bool isInScope(int DFSIn, int DFSOut) const {
2455 if (empty())
2456 return false;
2457 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2458 }
2459
2460 void popUntilDFSScope(int DFSIn, int DFSOut) {
2461
2462 // These two should always be in sync at this point.
2463 assert(ValueStack.size() == DFSStack.size() &&
2464 "Mismatch between ValueStack and DFSStack");
2465 while (
2466 !DFSStack.empty() &&
2467 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2468 DFSStack.pop_back();
2469 ValueStack.pop_back();
2470 }
2471 }
2472
2473private:
2474 SmallVector<Value *, 8> ValueStack;
2475 SmallVector<std::pair<int, int>, 8> DFSStack;
2476};
2477}
Daniel Berlin04443432017-01-07 03:23:47 +00002478
Davide Italiano7e274e02016-12-22 16:03:48 +00002479bool NewGVN::eliminateInstructions(Function &F) {
2480 // This is a non-standard eliminator. The normal way to eliminate is
2481 // to walk the dominator tree in order, keeping track of available
2482 // values, and eliminating them. However, this is mildly
2483 // pointless. It requires doing lookups on every instruction,
2484 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002485 // instructions part of most singleton congruence classes, we know we
2486 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002487
2488 // Instead, this eliminator looks at the congruence classes directly, sorts
2489 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002490 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002491 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002492 // last member. This is worst case O(E log E) where E = number of
2493 // instructions in a single congruence class. In theory, this is all
2494 // instructions. In practice, it is much faster, as most instructions are
2495 // either in singleton congruence classes or can't possibly be eliminated
2496 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002497 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002498 // for elimination purposes.
2499 // TODO: If we wanted to be faster, We could remove any members with no
2500 // overlapping ranges while sorting, as we will never eliminate anything
2501 // with those members, as they don't dominate anything else in our set.
2502
Davide Italiano7e274e02016-12-22 16:03:48 +00002503 bool AnythingReplaced = false;
2504
2505 // Since we are going to walk the domtree anyway, and we can't guarantee the
2506 // DFS numbers are updated, we compute some ourselves.
2507 DT->updateDFSNumbers();
2508
2509 for (auto &B : F) {
2510 if (!ReachableBlocks.count(&B)) {
2511 for (const auto S : successors(&B)) {
2512 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002513 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002514 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2515 << getBlockName(&B)
2516 << " with undef due to it being unreachable\n");
2517 for (auto &Operand : Phi.incoming_values())
2518 if (Phi.getIncomingBlock(Operand) == &B)
2519 Operand.set(UndefValue::get(Phi.getType()));
2520 }
2521 }
2522 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002523 }
2524
Daniel Berline3e69e12017-03-10 00:32:33 +00002525 // Map to store the use counts
2526 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlin4d547962017-02-12 23:24:45 +00002527 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002528 // Track the equivalent store info so we can decide whether to try
2529 // dead store elimination.
2530 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00002531 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlinb79f5362017-02-11 12:48:50 +00002532 if (CC->Dead)
Davide Italiano7e274e02016-12-22 16:03:48 +00002533 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002534 // Everything still in the TOP class is unreachable or dead.
2535 if (CC == TOPClass) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00002536#ifndef NDEBUG
2537 for (auto M : CC->Members)
2538 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2539 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002540 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00002541 "point");
2542#endif
2543 continue;
2544 }
2545
Davide Italiano7e274e02016-12-22 16:03:48 +00002546 assert(CC->RepLeader && "We should have had a leader");
2547
2548 // If this is a leader that is always available, and it's a
2549 // constant or has no equivalences, just replace everything with
2550 // it. We then update the congruence class with whatever members
2551 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002552 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2553 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002554 SmallPtrSet<Value *, 4> MembersLeft;
2555 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002556 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002557 // Void things have no uses we can replace.
Daniel Berline3e69e12017-03-10 00:32:33 +00002558 if (Member == Leader || Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002559 MembersLeft.insert(Member);
2560 continue;
2561 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002562 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2563 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002564 // Due to equality propagation, these may not always be
2565 // instructions, they may be real values. We don't really
2566 // care about trying to replace the non-instructions.
2567 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002568 assert(Leader != I && "About to accidentally remove our leader");
2569 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002570 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002571 continue;
2572 } else {
2573 MembersLeft.insert(I);
2574 }
2575 }
2576 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002577 } else {
2578 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2579 // If this is a singleton, we can skip it.
2580 if (CC->Members.size() != 1) {
2581
2582 // This is a stack because equality replacement/etc may place
2583 // constants in the middle of the member list, and we want to use
2584 // those constant values in preference to the current leader, over
2585 // the scope of those constants.
2586 ValueDFSStack EliminationStack;
2587
2588 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002589 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berline3e69e12017-03-10 00:32:33 +00002590 convertClassToDFSOrdered(CC->Members, DFSOrderedSet, UseCounts,
2591 ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00002592
2593 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002594 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002595 for (auto &VD : DFSOrderedSet) {
2596 int MemberDFSIn = VD.DFSIn;
2597 int MemberDFSOut = VD.DFSOut;
Daniel Berline3e69e12017-03-10 00:32:33 +00002598 Value *Def = VD.Def;
2599 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00002600 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00002601 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00002602 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002603
2604 if (EliminationStack.empty()) {
2605 DEBUG(dbgs() << "Elimination Stack is empty\n");
2606 } else {
2607 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2608 << EliminationStack.dfs_back().first << ","
2609 << EliminationStack.dfs_back().second << ")\n");
2610 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002611
2612 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2613 << MemberDFSOut << ")\n");
2614 // First, we see if we are out of scope or empty. If so,
2615 // and there equivalences, we try to replace the top of
2616 // stack with equivalences (if it's on the stack, it must
2617 // not have been eliminated yet).
2618 // Then we synchronize to our current scope, by
2619 // popping until we are back within a DFS scope that
2620 // dominates the current member.
2621 // Then, what happens depends on a few factors
2622 // If the stack is now empty, we need to push
2623 // If we have a constant or a local equivalence we want to
2624 // start using, we also push.
2625 // Otherwise, we walk along, processing members who are
2626 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00002627 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002628 bool OutOfScope =
2629 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2630
2631 if (OutOfScope || ShouldPush) {
2632 // Sync to our current scope.
2633 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00002634 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002635 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002636 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00002637 }
2638 }
2639
Daniel Berline3e69e12017-03-10 00:32:33 +00002640 // Skip the Def's, we only want to eliminate on their uses. But mark
2641 // dominated defs as dead.
2642 if (Def) {
2643 // For anything in this case, what and how we value number
2644 // guarantees that any side-effets that would have occurred (ie
2645 // throwing, etc) can be proven to either still occur (because it's
2646 // dominated by something that has the same side-effects), or never
2647 // occur. Otherwise, we would not have been able to prove it value
2648 // equivalent to something else. For these things, we can just mark
2649 // it all dead. Note that this is different from the "ProbablyDead"
2650 // set, which may not be dominated by anything, and thus, are only
2651 // easy to prove dead if they are also side-effect free.
2652 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
2653 isa<Instruction>(Def))
2654 markInstructionForDeletion(cast<Instruction>(Def));
2655 continue;
2656 }
2657 // At this point, we know it is a Use we are trying to possibly
2658 // replace.
2659
2660 assert(isa<Instruction>(U->get()) &&
2661 "Current def should have been an instruction");
2662 assert(isa<Instruction>(U->getUser()) &&
2663 "Current user should have been an instruction");
2664
2665 // If the thing we are replacing into is already marked to be dead,
2666 // this use is dead. Note that this is true regardless of whether
2667 // we have anything dominating the use or not. We do this here
2668 // because we are already walking all the uses anyway.
2669 Instruction *InstUse = cast<Instruction>(U->getUser());
2670 if (InstructionsToErase.count(InstUse)) {
2671 auto &UseCount = UseCounts[U->get()];
2672 if (--UseCount == 0) {
2673 ProbablyDead.insert(cast<Instruction>(U->get()));
2674 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002675 }
2676
Davide Italiano7e274e02016-12-22 16:03:48 +00002677 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00002678 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00002679 if (EliminationStack.empty())
2680 continue;
2681
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002682 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00002683
Daniel Berlind92e7f92017-01-07 00:01:42 +00002684 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00002685 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00002686 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002687 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00002688 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002689
2690 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00002691 // metadata. Skip this if we are replacing predicateinfo with its
2692 // original operand, as we already know we can just drop it.
2693 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002694 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
2695 if (!PI || DominatingLeader != PI->OriginalOp)
2696 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00002697 U->set(DominatingLeader);
2698 // This is now a use of the dominating leader, which means if the
2699 // dominating leader was dead, it's now live!
2700 auto &LeaderUseCount = UseCounts[DominatingLeader];
2701 // It's about to be alive again.
2702 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
2703 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
2704 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002705 AnythingReplaced = true;
2706 }
2707 }
2708 }
2709
Daniel Berline3e69e12017-03-10 00:32:33 +00002710 // At this point, anything still in the ProbablyDead set is actually dead if
2711 // would be trivially dead.
2712 for (auto *I : ProbablyDead)
2713 if (wouldInstructionBeTriviallyDead(I))
2714 markInstructionForDeletion(I);
2715
Davide Italiano7e274e02016-12-22 16:03:48 +00002716 // Cleanup the congruence class.
2717 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002718 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002719 if (Member->getType()->isVoidTy()) {
2720 MembersLeft.insert(Member);
2721 continue;
2722 }
2723
Davide Italiano7e274e02016-12-22 16:03:48 +00002724 MembersLeft.insert(Member);
2725 }
2726 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002727
2728 // If we have possible dead stores to look at, try to eliminate them.
2729 if (CC->StoreCount > 0) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002730 convertClassToLoadsAndStores(CC->Members, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00002731 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2732 ValueDFSStack EliminationStack;
2733 for (auto &VD : PossibleDeadStores) {
2734 int MemberDFSIn = VD.DFSIn;
2735 int MemberDFSOut = VD.DFSOut;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002736 Instruction *Member = cast<Instruction>(VD.Def);
Daniel Berlinc4796862017-01-27 02:37:11 +00002737 if (EliminationStack.empty() ||
2738 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2739 // Sync to our current scope.
2740 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2741 if (EliminationStack.empty()) {
2742 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2743 continue;
2744 }
2745 }
2746 // We already did load elimination, so nothing to do here.
2747 if (isa<LoadInst>(Member))
2748 continue;
2749 assert(!EliminationStack.empty());
2750 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002751 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002752 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2753 // Member is dominater by Leader, and thus dead
2754 DEBUG(dbgs() << "Marking dead store " << *Member
2755 << " that is dominated by " << *Leader << "\n");
2756 markInstructionForDeletion(Member);
2757 CC->Members.erase(Member);
2758 ++NumGVNDeadStores;
2759 }
2760 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002761 }
2762
2763 return AnythingReplaced;
2764}
Daniel Berlin1c087672017-02-11 15:07:01 +00002765
2766// This function provides global ranking of operations so that we can place them
2767// in a canonical order. Note that rank alone is not necessarily enough for a
2768// complete ordering, as constants all have the same rank. However, generally,
2769// we will simplify an operation with all constants so that it doesn't matter
2770// what order they appear in.
2771unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002772 // Prefer undef to anything else
2773 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00002774 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002775 if (isa<Constant>(V))
2776 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00002777 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002778 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00002779
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002780 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00002781 // the constant and argument ranking above.
2782 unsigned Result = InstrDFS.lookup(V);
2783 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002784 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00002785 // Unreachable or something else, just return a really large number.
2786 return ~0;
2787}
2788
2789// This is a function that says whether two commutative operations should
2790// have their order swapped when canonicalizing.
2791bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
2792 // Because we only care about a total ordering, and don't rewrite expressions
2793 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002794 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002795 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00002796}
Daniel Berlin64e68992017-03-12 04:46:45 +00002797
2798class NewGVNLegacyPass : public FunctionPass {
2799public:
2800 static char ID; // Pass identification, replacement for typeid.
2801 NewGVNLegacyPass() : FunctionPass(ID) {
2802 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
2803 }
2804 bool runOnFunction(Function &F) override;
2805
2806private:
2807 void getAnalysisUsage(AnalysisUsage &AU) const override {
2808 AU.addRequired<AssumptionCacheTracker>();
2809 AU.addRequired<DominatorTreeWrapperPass>();
2810 AU.addRequired<TargetLibraryInfoWrapperPass>();
2811 AU.addRequired<MemorySSAWrapperPass>();
2812 AU.addRequired<AAResultsWrapperPass>();
2813 AU.addPreserved<DominatorTreeWrapperPass>();
2814 AU.addPreserved<GlobalsAAWrapperPass>();
2815 }
2816};
2817
2818bool NewGVNLegacyPass::runOnFunction(Function &F) {
2819 if (skipFunction(F))
2820 return false;
2821 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2822 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2823 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2824 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
2825 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
2826 F.getParent()->getDataLayout())
2827 .runGVN();
2828}
2829
2830INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
2831 false, false)
2832INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2833INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2834INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2835INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2836INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2837INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2838INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
2839 false)
2840
2841char NewGVNLegacyPass::ID = 0;
2842
2843// createGVNPass - The public interface to this file.
2844FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
2845
2846PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
2847 // Apparently the order in which we get these results matter for
2848 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
2849 // the same order here, just in case.
2850 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2851 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2852 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2853 auto &AA = AM.getResult<AAManager>(F);
2854 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2855 bool Changed =
2856 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
2857 .runGVN();
2858 if (!Changed)
2859 return PreservedAnalyses::all();
2860 PreservedAnalyses PA;
2861 PA.preserve<DominatorTreeAnalysis>();
2862 PA.preserve<GlobalsAA>();
2863 return PA;
2864}