blob: 2872e4a2aa6103033db75e55c2f8f7e7361a6fb4 [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) {
Daniel Berlin9b498492017-04-01 09:44:29 +0000432 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000433 return false;
Daniel Berlin9b498492017-04-01 09:44:29 +0000434 return LHS.MemoryExpression::equals(RHS);
Davide Italiano7e274e02016-12-22 16:03:48 +0000435}
436
Davide Italianob1114092016-12-28 13:37:17 +0000437bool LoadExpression::equals(const Expression &Other) const {
438 return equalsLoadStoreHelper(*this, Other);
439}
Davide Italiano7e274e02016-12-22 16:03:48 +0000440
Davide Italianob1114092016-12-28 13:37:17 +0000441bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin9b498492017-04-01 09:44:29 +0000442 if (!equalsLoadStoreHelper(*this, Other))
443 return false;
Daniel Berlin26addef2017-01-20 21:04:30 +0000444 // Make sure that store vs store includes the value operand.
Daniel Berlin9b498492017-04-01 09:44:29 +0000445 if (const auto *S = dyn_cast<StoreExpression>(&Other))
446 if (getStoredValue() != S->getStoredValue())
447 return false;
448 return true;
Davide Italiano7e274e02016-12-22 16:03:48 +0000449}
450
451#ifndef NDEBUG
452static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000453 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000454}
455#endif
456
Daniel Berlin06329a92017-03-18 15:41:40 +0000457// Get the basic block from an instruction/memory value.
458BasicBlock *NewGVN::getBlockForValue(Value *V) const {
459 if (auto *I = dyn_cast<Instruction>(V))
460 return I->getParent();
461 else if (auto *MP = dyn_cast<MemoryPhi>(V))
462 return MP->getBlock();
463 llvm_unreachable("Should have been able to figure out a block for our value");
464 return nullptr;
465}
466
Daniel Berlin0e900112017-03-24 06:33:48 +0000467// Delete a definitely dead expression, so it can be reused by the expression
468// allocator. Some of these are not in creation functions, so we have to accept
469// const versions.
470void NewGVN::deleteExpression(const Expression *E) {
471 assert(isa<BasicExpression>(E));
472 auto *BE = cast<BasicExpression>(E);
473 const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
474 ExpressionAllocator.Deallocate(E);
475}
476
Davide Italiano7e274e02016-12-22 16:03:48 +0000477PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000478 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000479 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000480 auto *E =
481 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000482
483 E->allocateOperands(ArgRecycler, ExpressionAllocator);
484 E->setType(I->getType());
485 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000486
Davide Italianob3886dd2017-01-25 23:37:49 +0000487 // Filter out unreachable phi operands.
488 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +0000489 return ReachableEdges.count({PN->getIncomingBlock(U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000490 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000491
492 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
493 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000494 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000495 if (U == PN)
496 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000497 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000498 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000499 return E;
500}
501
502// Set basic expression info (Arguments, type, opcode) for Expression
503// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000504bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000505 bool AllConstant = true;
506 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
507 E->setType(GEP->getSourceElementType());
508 else
509 E->setType(I->getType());
510 E->setOpcode(I->getOpcode());
511 E->allocateOperands(ArgRecycler, ExpressionAllocator);
512
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000513 // Transform the operand array into an operand leader array, and keep track of
514 // whether all members are constant.
515 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000516 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000517 AllConstant &= isa<Constant>(Operand);
518 return Operand;
519 });
520
Davide Italiano7e274e02016-12-22 16:03:48 +0000521 return AllConstant;
522}
523
524const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000525 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000526 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000527
528 E->setType(T);
529 E->setOpcode(Opcode);
530 E->allocateOperands(ArgRecycler, ExpressionAllocator);
531 if (Instruction::isCommutative(Opcode)) {
532 // Ensure that commutative instructions that only differ by a permutation
533 // of their operands get the same value number by sorting the operand value
534 // numbers. Since all commutative instructions have two operands it is more
535 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000536 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000537 std::swap(Arg1, Arg2);
538 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000539 E->op_push_back(lookupOperandLeader(Arg1));
540 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000541
Daniel Berlin64e68992017-03-12 04:46:45 +0000542 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), DL, TLI,
Davide Italiano7e274e02016-12-22 16:03:48 +0000543 DT, AC);
544 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
545 return SimplifiedE;
546 return E;
547}
548
549// Take a Value returned by simplification of Expression E/Instruction
550// I, and see if it resulted in a simpler expression. If so, return
551// that expression.
552// TODO: Once finished, this should not take an Instruction, we only
553// use it for printing.
554const Expression *NewGVN::checkSimplificationResults(Expression *E,
555 Instruction *I, Value *V) {
556 if (!V)
557 return nullptr;
558 if (auto *C = dyn_cast<Constant>(V)) {
559 if (I)
560 DEBUG(dbgs() << "Simplified " << *I << " to "
561 << " constant " << *C << "\n");
562 NumGVNOpsSimplified++;
563 assert(isa<BasicExpression>(E) &&
564 "We should always have had a basic expression here");
Daniel Berlin0e900112017-03-24 06:33:48 +0000565 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000566 return createConstantExpression(C);
567 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
568 if (I)
569 DEBUG(dbgs() << "Simplified " << *I << " to "
570 << " variable " << *V << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +0000571 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000572 return createVariableExpression(V);
573 }
574
575 CongruenceClass *CC = ValueToClass.lookup(V);
576 if (CC && CC->DefiningExpr) {
577 if (I)
578 DEBUG(dbgs() << "Simplified " << *I << " to "
579 << " expression " << *V << "\n");
580 NumGVNOpsSimplified++;
Daniel Berlin0e900112017-03-24 06:33:48 +0000581 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000582 return CC->DefiningExpr;
583 }
584 return nullptr;
585}
586
Daniel Berlin97718e62017-01-31 22:32:03 +0000587const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000588 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000589
Daniel Berlin97718e62017-01-31 22:32:03 +0000590 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000591
592 if (I->isCommutative()) {
593 // Ensure that commutative instructions that only differ by a permutation
594 // of their operands get the same value number by sorting the operand value
595 // numbers. Since all commutative instructions have two operands it is more
596 // efficient to sort by hand rather than using, say, std::sort.
597 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000598 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000599 E->swapOperands(0, 1);
600 }
601
602 // Perform simplificaiton
603 // TODO: Right now we only check to see if we get a constant result.
604 // We may get a less than constant, but still better, result for
605 // some operations.
606 // IE
607 // add 0, x -> x
608 // and x, x -> x
609 // We should handle this by simply rewriting the expression.
610 if (auto *CI = dyn_cast<CmpInst>(I)) {
611 // Sort the operand value numbers so x<y and y>x get the same value
612 // number.
613 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000614 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000615 E->swapOperands(0, 1);
616 Predicate = CmpInst::getSwappedPredicate(Predicate);
617 }
618 E->setOpcode((CI->getOpcode() << 8) | Predicate);
619 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000620 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
621 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000622 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
623 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000624 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000625 DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000626 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
627 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000628 } else if (isa<SelectInst>(I)) {
629 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000630 E->getOperand(0) == E->getOperand(1)) {
631 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
632 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000633 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000634 E->getOperand(2), DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000635 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
636 return SimplifiedE;
637 }
638 } else if (I->isBinaryOp()) {
639 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000640 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000641 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
642 return SimplifiedE;
643 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin64e68992017-03-12 04:46:45 +0000644 Value *V = SimplifyInstruction(BI, DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000645 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
646 return SimplifiedE;
647 } else if (isa<GetElementPtrInst>(I)) {
648 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000649 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Daniel Berlin64e68992017-03-12 04:46:45 +0000650 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000651 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
652 return SimplifiedE;
653 } else if (AllConstant) {
654 // We don't bother trying to simplify unless all of the operands
655 // were constant.
656 // TODO: There are a lot of Simplify*'s we could call here, if we
657 // wanted to. The original motivating case for this code was a
658 // zext i1 false to i8, which we don't have an interface to
659 // simplify (IE there is no SimplifyZExt).
660
661 SmallVector<Constant *, 8> C;
662 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000663 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000664
Daniel Berlin64e68992017-03-12 04:46:45 +0000665 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +0000666 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
667 return SimplifiedE;
668 }
669 return E;
670}
671
672const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000673NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000674 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000675 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000676 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000677 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000678 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000679 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000680 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000681 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000682 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000683 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000684 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000685 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000686 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000687 return E;
688 }
689 llvm_unreachable("Unhandled type of aggregate value operation");
690}
691
Daniel Berlin85f91b02016-12-26 20:06:58 +0000692const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000693 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000694 E->setOpcode(V->getValueID());
695 return E;
696}
697
Daniel Berlinf7d95802017-02-18 23:06:50 +0000698const Expression *NewGVN::createVariableOrConstant(Value *V) {
699 if (auto *C = dyn_cast<Constant>(V))
700 return createConstantExpression(C);
701 return createVariableExpression(V);
702}
703
Daniel Berlin85f91b02016-12-26 20:06:58 +0000704const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000705 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000706 E->setOpcode(C->getValueID());
707 return E;
708}
709
Daniel Berlin02c6b172017-01-02 18:00:53 +0000710const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
711 auto *E = new (ExpressionAllocator) UnknownExpression(I);
712 E->setOpcode(I->getOpcode());
713 return E;
714}
715
Davide Italiano7e274e02016-12-22 16:03:48 +0000716const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000717 MemoryAccess *HV) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000718 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000719 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000720 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
Daniel Berlin97718e62017-01-31 22:32:03 +0000721 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000722 return E;
723}
724
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000725// Return true if some equivalent of instruction Inst dominates instruction U.
726bool NewGVN::someEquivalentDominates(const Instruction *Inst,
727 const Instruction *U) const {
728 auto *CC = ValueToClass.lookup(Inst);
Daniel Berlinffc30782017-03-24 06:33:51 +0000729 // This must be an instruction because we are only called from phi nodes
730 // in the case that the value it needs to check against is an instruction.
731
732 // The most likely candiates for dominance are the leader and the next leader.
733 // The leader or nextleader will dominate in all cases where there is an
734 // equivalent that is higher up in the dom tree.
735 // We can't *only* check them, however, because the
736 // dominator tree could have an infinite number of non-dominating siblings
737 // with instructions that are in the right congruence class.
738 // A
739 // B C D E F G
740 // |
741 // H
742 // Instruction U could be in H, with equivalents in every other sibling.
743 // Depending on the rpo order picked, the leader could be the equivalent in
744 // any of these siblings.
745 if (!CC)
746 return false;
747 if (DT->dominates(cast<Instruction>(CC->RepLeader), U))
748 return true;
749 if (CC->NextLeader.first &&
750 DT->dominates(cast<Instruction>(CC->NextLeader.first), U))
751 return true;
752 return llvm::any_of(CC->Members, [&](const Value *Member) {
753 return Member != CC->RepLeader &&
754 DT->dominates(cast<Instruction>(Member), U);
755 });
Daniel Berlin9d0796e2017-03-24 05:30:34 +0000756}
757
Davide Italiano7e274e02016-12-22 16:03:48 +0000758// See if we have a congruence class and leader for this operand, and if so,
759// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000760Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000761 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +0000762 if (CC) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000763 // Everything in TOP is represneted by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000764 // We do have to make sure we get the type right though, so we can't set the
765 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000766 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +0000767 return UndefValue::get(V->getType());
Daniel Berlin26addef2017-01-20 21:04:30 +0000768 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Daniel Berlinb79f5362017-02-11 12:48:50 +0000769 }
770
Davide Italiano7e274e02016-12-22 16:03:48 +0000771 return V;
772}
773
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000774MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000775 auto *CC = MemoryAccessToClass.lookup(MA);
776 if (CC && CC->RepMemoryAccess)
777 return CC->RepMemoryAccess;
778 // FIXME: We need to audit all the places that current set a nullptr To, and
779 // fix them. There should always be *some* congruence class, even if it is
780 // singular. Right now, we don't bother setting congruence classes for
781 // anything but stores, which means we have to return the original access
782 // here. Otherwise, this should be unreachable.
783 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000784}
785
Daniel Berlinc4796862017-01-27 02:37:11 +0000786// Return true if the MemoryAccess is really equivalent to everything. This is
787// equivalent to the lattice value "TOP" in most lattices. This is the initial
788// state of all memory accesses.
789bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000790 return MemoryAccessToClass.lookup(MA) == TOPClass;
Daniel Berlinc4796862017-01-27 02:37:11 +0000791}
792
Davide Italiano7e274e02016-12-22 16:03:48 +0000793LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin97718e62017-01-31 22:32:03 +0000794 LoadInst *LI, MemoryAccess *DA) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000795 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000796 E->allocateOperands(ArgRecycler, ExpressionAllocator);
797 E->setType(LoadType);
798
799 // Give store and loads same opcode so they value number together.
800 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000801 E->op_push_back(lookupOperandLeader(PointerOp));
Davide Italiano7e274e02016-12-22 16:03:48 +0000802 if (LI)
803 E->setAlignment(LI->getAlignment());
804
805 // TODO: Value number heap versions. We may be able to discover
806 // things alias analysis can't on it's own (IE that a store and a
807 // load have the same value, and thus, it isn't clobbering the load).
808 return E;
809}
810
811const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000812 MemoryAccess *DA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000813 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000814 auto *E = new (ExpressionAllocator)
815 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000816 E->allocateOperands(ArgRecycler, ExpressionAllocator);
817 E->setType(SI->getValueOperand()->getType());
818
819 // Give store and loads same opcode so they value number together.
820 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000821 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000822
823 // TODO: Value number heap versions. We may be able to discover
824 // things alias analysis can't on it's own (IE that a store and a
825 // load have the same value, and thus, it isn't clobbering the load).
826 return E;
827}
828
Daniel Berlin97718e62017-01-31 22:32:03 +0000829const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000830 // Unlike loads, we never try to eliminate stores, so we do not check if they
831 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000832 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000833 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000834 // Get the expression, if any, for the RHS of the MemoryDef.
835 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
836 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
837 // If we are defined by ourselves, use the live on entry def.
838 if (StoreRHS == StoreAccess)
839 StoreRHS = MSSA->getLiveOnEntryDef();
840
Daniel Berlin589cecc2017-01-02 18:00:46 +0000841 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000842 // See if we are defined by a previous store expression, it already has a
843 // value, and it's the same value as our current store. FIXME: Right now, we
844 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin97718e62017-01-31 22:32:03 +0000845 const Expression *OldStore = createStoreExpression(SI, StoreRHS);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000846 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000847 // Basically, check if the congruence class the store is in is defined by a
848 // store that isn't us, and has the same value. MemorySSA takes care of
849 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000850 // The RepStoredValue gets nulled if all the stores disappear in a class, so
851 // we don't need to check if the class contains a store besides us.
Daniel Berlin808e3ff2017-01-31 22:31:56 +0000852 if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin0e900112017-03-24 06:33:48 +0000853 return OldStore;
854 deleteExpression(OldStore);
Daniel Berlinc4796862017-01-27 02:37:11 +0000855 // Also check if our value operand is defined by a load of the same memory
856 // location, and the memory state is the same as it was then
857 // (otherwise, it could have been overwritten later. See test32 in
858 // transforms/DeadStoreElimination/simple.ll)
859 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000860 if ((lookupOperandLeader(LI->getPointerOperand()) ==
861 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinc4796862017-01-27 02:37:11 +0000862 (lookupMemoryAccessEquiv(
863 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
864 return createVariableExpression(LI);
865 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000866 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000867 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000868}
869
Daniel Berlin97718e62017-01-31 22:32:03 +0000870const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000871 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000872
873 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000874 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000875 if (!LI->isSimple())
876 return nullptr;
877
Daniel Berlin203f47b2017-01-31 22:31:53 +0000878 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +0000879 // Load of undef is undef.
880 if (isa<UndefValue>(LoadAddressLeader))
881 return createConstantExpression(UndefValue::get(LI->getType()));
882
883 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
884
885 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
886 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
887 Instruction *DefiningInst = MD->getMemoryInst();
888 // If the defining instruction is not reachable, replace with undef.
889 if (!ReachableBlocks.count(DefiningInst->getParent()))
890 return createConstantExpression(UndefValue::get(LI->getType()));
891 }
892 }
893
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000894 const Expression *E =
895 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000896 lookupMemoryAccessEquiv(DefiningAccess));
Davide Italiano7e274e02016-12-22 16:03:48 +0000897 return E;
898}
899
Daniel Berlinf7d95802017-02-18 23:06:50 +0000900const Expression *
901NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
902 auto *PI = PredInfo->getPredicateInfoFor(I);
903 if (!PI)
904 return nullptr;
905
906 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +0000907
908 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
909 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +0000910 return nullptr;
911
Daniel Berlinfccbda92017-02-22 22:20:58 +0000912 auto *CopyOf = I->getOperand(0);
913 auto *Cond = PWC->Condition;
914
Daniel Berlinf7d95802017-02-18 23:06:50 +0000915 // If this a copy of the condition, it must be either true or false depending
916 // on the predicate info type and edge
917 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +0000918 // We should not need to add predicate users because the predicate info is
919 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +0000920 if (isa<PredicateAssume>(PI))
921 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
922 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
923 if (PBranch->TrueEdge)
924 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
925 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
926 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000927 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
928 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000929 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000930
Daniel Berlinf7d95802017-02-18 23:06:50 +0000931 // Not a copy of the condition, so see what the predicates tell us about this
932 // value. First, though, we check to make sure the value is actually a copy
933 // of one of the condition operands. It's possible, in certain cases, for it
934 // to be a copy of a predicateinfo copy. In particular, if two branch
935 // operations use the same condition, and one branch dominates the other, we
936 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +0000937 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +0000938 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000939
940 // Everything below relies on the condition being a comparison.
941 auto *Cmp = dyn_cast<CmpInst>(Cond);
942 if (!Cmp)
943 return nullptr;
944
945 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +0000946 DEBUG(dbgs() << "Copy is not of any condition operands!");
947 return nullptr;
948 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000949 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
950 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000951 bool SwappedOps = false;
952 // Sort the ops
953 if (shouldSwapOperands(FirstOp, SecondOp)) {
954 std::swap(FirstOp, SecondOp);
955 SwappedOps = true;
956 }
Daniel Berlinf7d95802017-02-18 23:06:50 +0000957 CmpInst::Predicate Predicate =
958 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
959
960 if (isa<PredicateAssume>(PI)) {
961 // If the comparison is true when the operands are equal, then we know the
962 // operands are equal, because assumes must always be true.
963 if (CmpInst::isTrueWhenEqual(Predicate)) {
964 addPredicateUsers(PI, I);
965 return createVariableOrConstant(FirstOp);
966 }
967 }
968 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
969 // If we are *not* a copy of the comparison, we may equal to the other
970 // operand when the predicate implies something about equality of
971 // operations. In particular, if the comparison is true/false when the
972 // operands are equal, and we are on the right edge, we know this operation
973 // is equal to something.
974 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
975 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
976 addPredicateUsers(PI, I);
977 return createVariableOrConstant(FirstOp);
978 }
979 // Handle the special case of floating point.
980 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
981 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
982 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
983 addPredicateUsers(PI, I);
984 return createConstantExpression(cast<Constant>(FirstOp));
985 }
986 }
987 return nullptr;
988}
989
Davide Italiano7e274e02016-12-22 16:03:48 +0000990// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000991const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000992 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000993 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
994 // Instrinsics with the returned attribute are copies of arguments.
995 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
996 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
997 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
998 return Result;
999 return createVariableOrConstant(ReturnedValue);
1000 }
1001 }
1002 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001003 return createCallExpression(CI, nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001004 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001005 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin97718e62017-01-31 22:32:03 +00001006 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess));
Davide Italianob2225492016-12-27 18:15:39 +00001007 }
1008 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001009}
1010
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001011// Update the memory access equivalence table to say that From is equal to To,
1012// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001013// FIXME: We need to audit all the places that current set a nullptr To, and fix
1014// them. There should always be *some* congruence class, even if it is singular.
1015bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
1016 DEBUG(dbgs() << "Setting " << *From);
1017 if (To) {
1018 DEBUG(dbgs() << " equivalent to congruence class ");
1019 DEBUG(dbgs() << To->ID << " with current memory access leader ");
1020 DEBUG(dbgs() << *To->RepMemoryAccess);
1021 } else {
1022 DEBUG(dbgs() << " equivalent to itself");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001023 }
Daniel Berlin9f376b72017-01-29 10:26:03 +00001024 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001025
1026 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001027 bool Changed = false;
1028 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001029 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001030 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001031 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001032 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001033 Changed = true;
1034 } else if (!To) {
1035 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001036 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001037 Changed = true;
1038 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001039 } else {
1040 assert(!To &&
1041 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001042 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001043
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001044 return Changed;
1045}
Daniel Berlin0e900112017-03-24 06:33:48 +00001046
Davide Italiano7e274e02016-12-22 16:03:48 +00001047// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001048const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001049 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001050 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1051
1052 // See if all arguaments are the same.
1053 // We track if any were undef because they need special handling.
1054 bool HasUndef = false;
1055 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1056 if (Arg == I)
1057 return false;
1058 if (isa<UndefValue>(Arg)) {
1059 HasUndef = true;
1060 return false;
1061 }
1062 return true;
1063 });
1064 // If we are left with no operands, it's undef
1065 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001066 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1067 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001068 deleteExpression(E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001069 return createConstantExpression(UndefValue::get(I->getType()));
1070 }
Daniel Berlind92e7f92017-01-07 00:01:42 +00001071 Value *AllSameValue = *(Filtered.begin());
1072 ++Filtered.begin();
1073 // Can't use std::equal here, sadly, because filter.begin moves.
1074 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
1075 return V == AllSameValue;
1076 })) {
1077 // In LLVM's non-standard representation of phi nodes, it's possible to have
1078 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1079 // on the original phi node), especially in weird CFG's where some arguments
1080 // are unreachable, or uninitialized along certain paths. This can cause
1081 // infinite loops during evaluation. We work around this by not trying to
1082 // really evaluate them independently, but instead using a variable
1083 // expression to say if one is equivalent to the other.
1084 // We also special case undef, so that if we have an undef, we can't use the
1085 // common value unless it dominates the phi block.
1086 if (HasUndef) {
1087 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001088 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlin9d0796e2017-03-24 05:30:34 +00001089 if (!someEquivalentDominates(AllSameInst, I))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001090 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001091 }
1092
Davide Italiano7e274e02016-12-22 16:03:48 +00001093 NumGVNPhisAllSame++;
1094 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1095 << "\n");
Daniel Berlin0e900112017-03-24 06:33:48 +00001096 deleteExpression(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001097 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001098 }
1099 return E;
1100}
1101
Daniel Berlin97718e62017-01-31 22:32:03 +00001102const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001103 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1104 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1105 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1106 unsigned Opcode = 0;
1107 // EI might be an extract from one of our recognised intrinsics. If it
1108 // is we'll synthesize a semantically equivalent expression instead on
1109 // an extract value expression.
1110 switch (II->getIntrinsicID()) {
1111 case Intrinsic::sadd_with_overflow:
1112 case Intrinsic::uadd_with_overflow:
1113 Opcode = Instruction::Add;
1114 break;
1115 case Intrinsic::ssub_with_overflow:
1116 case Intrinsic::usub_with_overflow:
1117 Opcode = Instruction::Sub;
1118 break;
1119 case Intrinsic::smul_with_overflow:
1120 case Intrinsic::umul_with_overflow:
1121 Opcode = Instruction::Mul;
1122 break;
1123 default:
1124 break;
1125 }
1126
1127 if (Opcode != 0) {
1128 // Intrinsic recognized. Grab its args to finish building the
1129 // expression.
1130 assert(II->getNumArgOperands() == 2 &&
1131 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001132 return createBinaryExpression(
1133 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001134 }
1135 }
1136 }
1137
Daniel Berlin97718e62017-01-31 22:32:03 +00001138 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001139}
Daniel Berlin97718e62017-01-31 22:32:03 +00001140const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001141 auto *CI = dyn_cast<CmpInst>(I);
1142 // See if our operands are equal to those of a previous predicate, and if so,
1143 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001144 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1145 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001146 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001147 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001148 std::swap(Op0, Op1);
1149 OurPredicate = CI->getSwappedPredicate();
1150 }
1151
1152 // Avoid processing the same info twice
1153 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001154 // See if we know something about the comparison itself, like it is the target
1155 // of an assume.
1156 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1157 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1158 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1159
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001160 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001161 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001162 if (CI->isTrueWhenEqual())
1163 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1164 else if (CI->isFalseWhenEqual())
1165 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1166 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001167
1168 // NOTE: Because we are comparing both operands here and below, and using
1169 // previous comparisons, we rely on fact that predicateinfo knows to mark
1170 // comparisons that use renamed operands as users of the earlier comparisons.
1171 // It is *not* enough to just mark predicateinfo renamed operands as users of
1172 // the earlier comparisons, because the *other* operand may have changed in a
1173 // previous iteration.
1174 // Example:
1175 // icmp slt %a, %b
1176 // %b.0 = ssa.copy(%b)
1177 // false branch:
1178 // icmp slt %c, %b.0
1179
1180 // %c and %a may start out equal, and thus, the code below will say the second
1181 // %icmp is false. c may become equal to something else, and in that case the
1182 // %second icmp *must* be reexamined, but would not if only the renamed
1183 // %operands are considered users of the icmp.
1184
1185 // *Currently* we only check one level of comparisons back, and only mark one
1186 // level back as touched when changes appen . If you modify this code to look
1187 // back farther through comparisons, you *must* mark the appropriate
1188 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1189 // we know something just from the operands themselves
1190
1191 // See if our operands have predicate info, so that we may be able to derive
1192 // something from a previous comparison.
1193 for (const auto &Op : CI->operands()) {
1194 auto *PI = PredInfo->getPredicateInfoFor(Op);
1195 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1196 if (PI == LastPredInfo)
1197 continue;
1198 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001199
Daniel Berlinf7d95802017-02-18 23:06:50 +00001200 // TODO: Along the false edge, we may know more things too, like icmp of
1201 // same operands is false.
1202 // TODO: We only handle actual comparison conditions below, not and/or.
1203 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1204 if (!BranchCond)
1205 continue;
1206 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1207 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1208 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001209 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001210 std::swap(BranchOp0, BranchOp1);
1211 BranchPredicate = BranchCond->getSwappedPredicate();
1212 }
1213 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1214 if (PBranch->TrueEdge) {
1215 // If we know the previous predicate is true and we are in the true
1216 // edge then we may be implied true or false.
1217 if (CmpInst::isImpliedTrueByMatchingCmp(OurPredicate,
1218 BranchPredicate)) {
1219 addPredicateUsers(PI, I);
1220 return createConstantExpression(
1221 ConstantInt::getTrue(CI->getType()));
1222 }
1223
1224 if (CmpInst::isImpliedFalseByMatchingCmp(OurPredicate,
1225 BranchPredicate)) {
1226 addPredicateUsers(PI, I);
1227 return createConstantExpression(
1228 ConstantInt::getFalse(CI->getType()));
1229 }
1230
1231 } else {
1232 // Just handle the ne and eq cases, where if we have the same
1233 // operands, we may know something.
1234 if (BranchPredicate == OurPredicate) {
1235 addPredicateUsers(PI, I);
1236 // Same predicate, same ops,we know it was false, so this is false.
1237 return createConstantExpression(
1238 ConstantInt::getFalse(CI->getType()));
1239 } else if (BranchPredicate ==
1240 CmpInst::getInversePredicate(OurPredicate)) {
1241 addPredicateUsers(PI, I);
1242 // Inverse predicate, we know the other was false, so this is true.
1243 // FIXME: Double check this
1244 return createConstantExpression(
1245 ConstantInt::getTrue(CI->getType()));
1246 }
1247 }
1248 }
1249 }
1250 }
1251 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001252 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001253}
Davide Italiano7e274e02016-12-22 16:03:48 +00001254
1255// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +00001256const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001257 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001258 if (auto *C = dyn_cast<Constant>(V))
1259 E = createConstantExpression(C);
1260 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1261 E = createVariableExpression(V);
1262 } else {
1263 // TODO: memory intrinsics.
1264 // TODO: Some day, we should do the forward propagation and reassociation
1265 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001266 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001267 switch (I->getOpcode()) {
1268 case Instruction::ExtractValue:
1269 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001270 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001271 break;
1272 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001273 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001274 break;
1275 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001276 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001277 break;
1278 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001279 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001280 break;
1281 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001282 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001283 break;
1284 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001285 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001286 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001287 case Instruction::ICmp:
1288 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001289 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001290 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001291 case Instruction::Add:
1292 case Instruction::FAdd:
1293 case Instruction::Sub:
1294 case Instruction::FSub:
1295 case Instruction::Mul:
1296 case Instruction::FMul:
1297 case Instruction::UDiv:
1298 case Instruction::SDiv:
1299 case Instruction::FDiv:
1300 case Instruction::URem:
1301 case Instruction::SRem:
1302 case Instruction::FRem:
1303 case Instruction::Shl:
1304 case Instruction::LShr:
1305 case Instruction::AShr:
1306 case Instruction::And:
1307 case Instruction::Or:
1308 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001309 case Instruction::Trunc:
1310 case Instruction::ZExt:
1311 case Instruction::SExt:
1312 case Instruction::FPToUI:
1313 case Instruction::FPToSI:
1314 case Instruction::UIToFP:
1315 case Instruction::SIToFP:
1316 case Instruction::FPTrunc:
1317 case Instruction::FPExt:
1318 case Instruction::PtrToInt:
1319 case Instruction::IntToPtr:
1320 case Instruction::Select:
1321 case Instruction::ExtractElement:
1322 case Instruction::InsertElement:
1323 case Instruction::ShuffleVector:
1324 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001325 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001326 break;
1327 default:
1328 return nullptr;
1329 }
1330 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001331 return E;
1332}
1333
Davide Italiano7e274e02016-12-22 16:03:48 +00001334void NewGVN::markUsersTouched(Value *V) {
1335 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001336 for (auto *User : V->users()) {
1337 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001338 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001339 }
1340}
1341
1342void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1343 for (auto U : MA->users()) {
1344 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001345 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001346 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001347 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001348 }
1349}
1350
Daniel Berlinf7d95802017-02-18 23:06:50 +00001351// Add I to the set of users of a given predicate.
1352void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1353 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1354 PredicateToUsers[PBranch->Condition].insert(I);
1355 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1356 PredicateToUsers[PAssume->Condition].insert(I);
1357}
1358
1359// Touch all the predicates that depend on this instruction.
1360void NewGVN::markPredicateUsersTouched(Instruction *I) {
1361 const auto Result = PredicateToUsers.find(I);
Daniel Berlin46b72e62017-03-19 00:07:32 +00001362 if (Result != PredicateToUsers.end()) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001363 for (auto *User : Result->second)
1364 TouchedInstructions.set(InstrDFS.lookup(User));
Daniel Berlin46b72e62017-03-19 00:07:32 +00001365 PredicateToUsers.erase(Result);
1366 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001367}
1368
Daniel Berlin32f8d562017-01-07 16:55:14 +00001369// Touch the instructions that need to be updated after a congruence class has a
1370// leader change, and mark changed values.
1371void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1372 for (auto M : CC->Members) {
1373 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001374 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001375 LeaderChanges.insert(M);
1376 }
1377}
1378
1379// Move a value, currently in OldClass, to be part of NewClass
1380// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001381void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1382 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001383 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001384 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001385 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001386
1387 if (I == OldClass->NextLeader.first)
1388 OldClass->NextLeader = {nullptr, ~0U};
1389
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001390 // It's possible, though unlikely, for us to discover equivalences such
1391 // that the current leader does not dominate the old one.
1392 // This statistic tracks how often this happens.
1393 // We assert on phi nodes when this happens, currently, for debugging, because
1394 // we want to make sure we name phi node cycles properly.
1395 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
Daniel Berlinffc30782017-03-24 06:33:51 +00001396 I != NewClass->RepLeader) {
1397 auto *IBB = I->getParent();
1398 auto *NCBB = cast<Instruction>(NewClass->RepLeader)->getParent();
1399 bool Dominated = IBB == NCBB &&
1400 InstrDFS.lookup(I) < InstrDFS.lookup(NewClass->RepLeader);
1401 Dominated = Dominated || DT->properlyDominates(IBB, NCBB);
1402 if (Dominated) {
1403 ++NumGVNNotMostDominatingLeader;
1404 assert(
1405 !isa<PHINode>(I) &&
1406 "New class for instruction should not be dominated by instruction");
1407 }
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001408 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001409
1410 if (NewClass->RepLeader != I) {
1411 auto DFSNum = InstrDFS.lookup(I);
1412 if (DFSNum < NewClass->NextLeader.second)
1413 NewClass->NextLeader = {I, DFSNum};
1414 }
1415
1416 OldClass->Members.erase(I);
1417 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001418 MemoryAccess *StoreAccess = nullptr;
1419 if (auto *SI = dyn_cast<StoreInst>(I)) {
1420 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001421 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001422 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001423 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001424 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001425 if (!NewClass->RepMemoryAccess) {
1426 // If we don't have a representative memory access, it better be the only
1427 // store in there.
1428 assert(NewClass->StoreCount == 1);
1429 NewClass->RepMemoryAccess = StoreAccess;
1430 }
1431 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001432 }
1433
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001434 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001435 // See if we destroyed the class or need to swap leaders.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001436 if (OldClass->Members.empty() && OldClass != TOPClass) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001437 if (OldClass->DefiningExpr) {
1438 OldClass->Dead = true;
1439 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1440 << " from table\n");
1441 ExpressionToClass.erase(OldClass->DefiningExpr);
1442 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001443 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001444 // When the leader changes, the value numbering of
1445 // everything may change due to symbolization changes, so we need to
1446 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001447 DEBUG(dbgs() << "Leader change!\n");
1448 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001449 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001450 if (OldClass->StoreCount == 0) {
1451 if (OldClass->RepStoredValue != nullptr)
1452 OldClass->RepStoredValue = nullptr;
1453 if (OldClass->RepMemoryAccess != nullptr)
1454 OldClass->RepMemoryAccess = nullptr;
1455 }
1456
1457 // If we destroy the old access leader, we have to effectively destroy the
1458 // congruence class. When it comes to scalars, anything with the same value
1459 // is as good as any other. That means that one leader is as good as
1460 // another, and as long as you have some leader for the value, you are
1461 // good.. When it comes to *memory states*, only one particular thing really
1462 // represents the definition of a given memory state. Once it goes away, we
1463 // need to re-evaluate which pieces of memory are really still
1464 // equivalent. The best way to do this is to re-value number things. The
1465 // only way to really make that happen is to destroy the rest of the class.
1466 // In order to effectively destroy the class, we reset ExpressionToClass for
1467 // each by using the ValueToExpression mapping. The members later get
1468 // marked as touched due to the leader change. We will create new
1469 // congruence classes, and the pieces that are still equivalent will end
1470 // back together in a new class. If this becomes too expensive, it is
1471 // possible to use a versioning scheme for the congruence classes to avoid
1472 // the expressions finding this old class.
1473 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1474 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1475 << " because memory access leader changed");
1476 for (auto Member : OldClass->Members)
1477 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1478 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001479
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001480 // 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 +00001481 // sorting the TOP class because everything either gets out of it or is
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001482 // unreachable.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001483 if (OldClass->Members.size() == 1 || OldClass == TOPClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001484 OldClass->RepLeader = *(OldClass->Members.begin());
1485 } else if (OldClass->NextLeader.first) {
1486 ++NumGVNAvoidedSortedLeaderChanges;
1487 OldClass->RepLeader = OldClass->NextLeader.first;
1488 OldClass->NextLeader = {nullptr, ~0U};
1489 } else {
1490 ++NumGVNSortedLeaderChanges;
1491 // TODO: If this ends up to slow, we can maintain a dual structure for
1492 // member testing/insertion, or keep things mostly sorted, and sort only
1493 // here, or ....
1494 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1495 for (const auto X : OldClass->Members) {
1496 auto DFSNum = InstrDFS.lookup(X);
1497 if (DFSNum < MinDFS.second)
1498 MinDFS = {X, DFSNum};
1499 }
1500 OldClass->RepLeader = MinDFS.first;
1501 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001502 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001503 }
1504}
1505
Davide Italiano7e274e02016-12-22 16:03:48 +00001506// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001507void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1508 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001509 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00001510 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001511
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001512 CongruenceClass *IClass = ValueToClass[I];
1513 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001514 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001515 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001516
1517 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001518 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001519 EClass = ValueToClass[VE->getVariableValue()];
1520 } else {
1521 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1522
1523 // If it's not in the value table, create a new congruence class.
1524 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001525 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001526 auto place = lookupResult.first;
1527 place->second = NewClass;
1528
1529 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001530 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001531 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001532 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1533 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001534 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001535 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001536 // The RepMemoryAccess field will be filled in properly by the
1537 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001538 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001539 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001540 }
1541 assert(!isa<VariableExpression>(E) &&
1542 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001543
1544 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001545 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001546 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001547 << " and leader " << *(NewClass->RepLeader));
1548 if (NewClass->RepStoredValue)
1549 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1550 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001551 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1552 } else {
1553 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001554 if (isa<ConstantExpression>(E))
1555 assert(isa<Constant>(EClass->RepLeader) &&
1556 "Any class with a constant expression should have a "
1557 "constant leader");
1558
Davide Italiano7e274e02016-12-22 16:03:48 +00001559 assert(EClass && "Somehow don't have an eclass");
1560
1561 assert(!EClass->Dead && "We accidentally looked up a dead class");
1562 }
1563 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001564 bool ClassChanged = IClass != EClass;
1565 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001566 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001567 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1568 << "\n");
1569
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001570 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001571 moveValueToNewCongruenceClass(I, IClass, EClass);
1572 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001573 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001574 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001575 if (auto *CI = dyn_cast<CmpInst>(I))
1576 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00001577 }
1578}
1579
1580// Process the fact that Edge (from, to) is reachable, including marking
1581// any newly reachable blocks and instructions for processing.
1582void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1583 // Check if the Edge was reachable before.
1584 if (ReachableEdges.insert({From, To}).second) {
1585 // If this block wasn't reachable before, all instructions are touched.
1586 if (ReachableBlocks.insert(To).second) {
1587 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1588 const auto &InstRange = BlockInstRange.lookup(To);
1589 TouchedInstructions.set(InstRange.first, InstRange.second);
1590 } else {
1591 DEBUG(dbgs() << "Block " << getBlockName(To)
1592 << " was reachable, but new edge {" << getBlockName(From)
1593 << "," << getBlockName(To) << "} to it found\n");
1594
1595 // We've made an edge reachable to an existing block, which may
1596 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1597 // they are the only thing that depend on new edges. Anything using their
1598 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001599 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001600 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001601
Davide Italiano7e274e02016-12-22 16:03:48 +00001602 auto BI = To->begin();
1603 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001604 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001605 ++BI;
1606 }
1607 }
1608 }
1609}
1610
1611// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1612// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001613Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001614 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001615 if (isa<Constant>(Result))
1616 return Result;
1617 return nullptr;
1618}
1619
1620// Process the outgoing edges of a block for reachability.
1621void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1622 // Evaluate reachability of terminator instruction.
1623 BranchInst *BR;
1624 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1625 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001626 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001627 if (!CondEvaluated) {
1628 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001629 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001630 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1631 CondEvaluated = CE->getConstantValue();
1632 }
1633 } else if (isa<ConstantInt>(Cond)) {
1634 CondEvaluated = Cond;
1635 }
1636 }
1637 ConstantInt *CI;
1638 BasicBlock *TrueSucc = BR->getSuccessor(0);
1639 BasicBlock *FalseSucc = BR->getSuccessor(1);
1640 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1641 if (CI->isOne()) {
1642 DEBUG(dbgs() << "Condition for Terminator " << *TI
1643 << " evaluated to true\n");
1644 updateReachableEdge(B, TrueSucc);
1645 } else if (CI->isZero()) {
1646 DEBUG(dbgs() << "Condition for Terminator " << *TI
1647 << " evaluated to false\n");
1648 updateReachableEdge(B, FalseSucc);
1649 }
1650 } else {
1651 updateReachableEdge(B, TrueSucc);
1652 updateReachableEdge(B, FalseSucc);
1653 }
1654 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1655 // For switches, propagate the case values into the case
1656 // destinations.
1657
1658 // Remember how many outgoing edges there are to every successor.
1659 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1660
Davide Italiano7e274e02016-12-22 16:03:48 +00001661 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001662 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001663 // See if we were able to turn this switch statement into a constant.
1664 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001665 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001666 // We should be able to get case value for this.
1667 auto CaseVal = SI->findCaseValue(CondVal);
1668 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1669 // We proved the value is outside of the range of the case.
1670 // We can't do anything other than mark the default dest as reachable,
1671 // and go home.
1672 updateReachableEdge(B, SI->getDefaultDest());
1673 return;
1674 }
1675 // Now get where it goes and mark it reachable.
1676 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1677 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001678 } else {
1679 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1680 BasicBlock *TargetBlock = SI->getSuccessor(i);
1681 ++SwitchEdges[TargetBlock];
1682 updateReachableEdge(B, TargetBlock);
1683 }
1684 }
1685 } else {
1686 // Otherwise this is either unconditional, or a type we have no
1687 // idea about. Just mark successors as reachable.
1688 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1689 BasicBlock *TargetBlock = TI->getSuccessor(i);
1690 updateReachableEdge(B, TargetBlock);
1691 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001692
1693 // This also may be a memory defining terminator, in which case, set it
1694 // equivalent to nothing.
1695 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1696 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001697 }
1698}
1699
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001700// The algorithm initially places the values of the routine in the TOP
1701// congruence class. The leader of TOP is the undetermined value `undef`.
1702// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00001703void NewGVN::initializeCongruenceClasses(Function &F) {
1704 // FIXME now i can't remember why this is 2
1705 NextCongruenceNum = 2;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001706 // Initialize all other instructions to be in TOP class.
Davide Italiano7e274e02016-12-22 16:03:48 +00001707 CongruenceClass::MemberSet InitialValues;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001708 TOPClass = createCongruenceClass(nullptr, nullptr);
1709 TOPClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001710 for (auto &B : F) {
1711 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001712 MemoryAccessToClass[MP] = TOPClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001713
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001714 for (auto &I : B) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00001715 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001716 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00001717 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
1718 continue;
1719 InitialValues.insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001720 ValueToClass[&I] = TOPClass;
Daniel Berlin22a4a012017-02-11 15:20:15 +00001721
Daniel Berlin589cecc2017-01-02 18:00:46 +00001722 // All memory accesses are equivalent to live on entry to start. They must
1723 // be initialized to something so that initial changes are noticed. For
1724 // the maximal answer, we initialize them all to be the same as
1725 // liveOnEntry. Note that to save time, we only initialize the
1726 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1727 // other expression can generate a memory equivalence. If we start
1728 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001729 if (isa<StoreInst>(&I)) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001730 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = TOPClass;
1731 ++TOPClass->StoreCount;
1732 assert(TOPClass->StoreCount > 0);
Davide Italianoeac05f62017-01-11 23:41:24 +00001733 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001734 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001735 }
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001736 TOPClass->Members.swap(InitialValues);
Davide Italiano7e274e02016-12-22 16:03:48 +00001737
1738 // Initialize arguments to be in their own unique congruence classes
1739 for (auto &FA : F.args())
1740 createSingletonCongruenceClass(&FA);
1741}
1742
1743void NewGVN::cleanupTables() {
1744 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1745 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1746 << CongruenceClasses[i]->Members.size() << " members\n");
1747 // Make sure we delete the congruence class (probably worth switching to
1748 // a unique_ptr at some point.
1749 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001750 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001751 }
1752
1753 ValueToClass.clear();
1754 ArgRecycler.clear(ExpressionAllocator);
1755 ExpressionAllocator.Reset();
1756 CongruenceClasses.clear();
1757 ExpressionToClass.clear();
1758 ValueToExpression.clear();
1759 ReachableBlocks.clear();
1760 ReachableEdges.clear();
1761#ifndef NDEBUG
1762 ProcessedCount.clear();
1763#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001764 InstrDFS.clear();
1765 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001766 DFSToInstr.clear();
1767 BlockInstRange.clear();
1768 TouchedInstructions.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001769 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00001770 PredicateToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001771}
1772
1773std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1774 unsigned Start) {
1775 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001776 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1777 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001778 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001779 }
1780
Davide Italiano7e274e02016-12-22 16:03:48 +00001781 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00001782 // There's no need to call isInstructionTriviallyDead more than once on
1783 // an instruction. Therefore, once we know that an instruction is dead
1784 // we change its DFS number so that it doesn't get value numbered.
1785 if (isInstructionTriviallyDead(&I, TLI)) {
1786 InstrDFS[&I] = 0;
1787 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
1788 markInstructionForDeletion(&I);
1789 continue;
1790 }
1791
Davide Italiano7e274e02016-12-22 16:03:48 +00001792 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001793 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001794 }
1795
1796 // All of the range functions taken half-open ranges (open on the end side).
1797 // So we do not subtract one from count, because at this point it is one
1798 // greater than the last instruction.
1799 return std::make_pair(Start, End);
1800}
1801
1802void NewGVN::updateProcessedCount(Value *V) {
1803#ifndef NDEBUG
1804 if (ProcessedCount.count(V) == 0) {
1805 ProcessedCount.insert({V, 1});
1806 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001807 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001808 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001809 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001810 }
1811#endif
1812}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001813// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1814void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1815 // If all the arguments are the same, the MemoryPhi has the same value as the
1816 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001817 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlin41b39162017-03-18 15:41:36 +00001818 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001819 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001820 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1821 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00001822 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001823 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001824 // If all that is left is nothing, our memoryphi is undef. We keep it as
1825 // InitialClass. Note: The only case this should happen is if we have at
1826 // least one self-argument.
1827 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001828 if (setMemoryAccessEquivTo(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00001829 markMemoryUsersTouched(MP);
1830 return;
1831 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001832
1833 // Transform the remaining operands into operand leaders.
1834 // FIXME: mapped_iterator should have a range version.
1835 auto LookupFunc = [&](const Use &U) {
1836 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1837 };
1838 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1839 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1840
1841 // and now check if all the elements are equal.
1842 // Sadly, we can't use std::equals since these are random access iterators.
1843 MemoryAccess *AllSameValue = *MappedBegin;
1844 ++MappedBegin;
1845 bool AllEqual = std::all_of(
1846 MappedBegin, MappedEnd,
1847 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1848
1849 if (AllEqual)
1850 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1851 else
1852 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1853
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001854 if (setMemoryAccessEquivTo(
1855 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001856 markMemoryUsersTouched(MP);
1857}
1858
1859// Value number a single instruction, symbolically evaluating, performing
1860// congruence finding, and updating mappings.
1861void NewGVN::valueNumberInstruction(Instruction *I) {
1862 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001863 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00001864 const Expression *Symbolized = nullptr;
1865 if (DebugCounter::shouldExecute(VNCounter)) {
1866 Symbolized = performSymbolicEvaluation(I);
1867 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00001868 // Mark the instruction as unused so we don't value number it again.
1869 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00001870 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00001871 // If we couldn't come up with a symbolic expression, use the unknown
1872 // expression
1873 if (Symbolized == nullptr)
1874 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001875 performCongruenceFinding(I, Symbolized);
1876 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001877 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00001878 // don't currently understand. We don't place non-value producing
1879 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001880 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001881 auto *Symbolized = createUnknownExpression(I);
1882 performCongruenceFinding(I, Symbolized);
1883 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001884 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1885 }
1886}
Davide Italiano7e274e02016-12-22 16:03:48 +00001887
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001888// Check if there is a path, using single or equal argument phi nodes, from
1889// First to Second.
1890bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1891 const MemoryAccess *Second) const {
1892 if (First == Second)
1893 return true;
Daniel Berlin871ecd92017-04-01 09:44:24 +00001894 if (MSSA->isLiveOnEntryDef(First))
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001895 return false;
Daniel Berlin871ecd92017-04-01 09:44:24 +00001896 const auto *EndDef = First;
1897 for (auto *ChainDef : def_chain(First)) {
1898 if (ChainDef == Second)
1899 return true;
1900 if (MSSA->isLiveOnEntryDef(ChainDef))
1901 return false;
1902 EndDef = ChainDef;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001903 }
Daniel Berlin871ecd92017-04-01 09:44:24 +00001904 auto *MP = cast<MemoryPhi>(EndDef);
1905 auto ReachableOperandPred = [&](const Use &U) {
1906 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
1907 };
1908 auto FilteredPhiArgs =
1909 make_filter_range(MP->operands(), ReachableOperandPred);
1910 SmallVector<const Value *, 32> OperandList;
1911 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1912 std::back_inserter(OperandList));
1913 bool Okay = OperandList.size() == 1;
1914 if (!Okay)
1915 Okay =
1916 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
1917 if (Okay)
1918 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1919 return false;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001920}
1921
Daniel Berlin589cecc2017-01-02 18:00:46 +00001922// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001923// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001924// subject to very rare false negatives. It is only useful for
1925// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001926void NewGVN::verifyMemoryCongruency() const {
Davide Italianoe9781e72017-03-25 02:40:02 +00001927#ifndef NDEBUG
Daniel Berlin589cecc2017-01-02 18:00:46 +00001928 // Anything equivalent in the memory access table should be in the same
1929 // congruence class.
1930
1931 // Filter out the unreachable and trivially dead entries, because they may
1932 // never have been updated if the instructions were not processed.
1933 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001934 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001935 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1936 if (!Result)
1937 return false;
1938 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1939 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1940 return true;
1941 };
1942
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001943 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001944 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001945 // Unreachable instructions may not have changed because we never process
1946 // them.
1947 if (!ReachableBlocks.count(KV.first->getBlock()))
1948 continue;
1949 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001950 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001951 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001952 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001953 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1954 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1955 "The instructions for these memory operations should have "
1956 "been in the same congruence class or reachable through"
1957 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001958 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1959
1960 // We can only sanely verify that MemoryDefs in the operand list all have
1961 // the same class.
1962 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00001963 return ReachableEdges.count(
1964 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00001965 isa<MemoryDef>(U);
1966
1967 };
1968 // All arguments should in the same class, ignoring unreachable arguments
1969 auto FilteredPhiArgs =
1970 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1971 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1972 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1973 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1974 const MemoryDef *MD = cast<MemoryDef>(U);
1975 return ValueToClass.lookup(MD->getMemoryInst());
1976 });
1977 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1978 PhiOpClasses.begin()) &&
1979 "All MemoryPhi arguments should be in the same class");
1980 }
1981 }
Davide Italianoe9781e72017-03-25 02:40:02 +00001982#endif
Daniel Berlin589cecc2017-01-02 18:00:46 +00001983}
1984
Daniel Berlin06329a92017-03-18 15:41:40 +00001985// Verify that the sparse propagation we did actually found the maximal fixpoint
1986// We do this by storing the value to class mapping, touching all instructions,
1987// and redoing the iteration to see if anything changed.
1988void NewGVN::verifyIterationSettled(Function &F) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001989#ifndef NDEBUG
Daniel Berlin06329a92017-03-18 15:41:40 +00001990 if (DebugCounter::isCounterSet(VNCounter))
1991 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
1992
1993 // Note that we have to store the actual classes, as we may change existing
1994 // classes during iteration. This is because our memory iteration propagation
1995 // is not perfect, and so may waste a little work. But it should generate
1996 // exactly the same congruence classes we have now, with different IDs.
1997 std::map<const Value *, CongruenceClass> BeforeIteration;
1998
1999 for (auto &KV : ValueToClass) {
2000 if (auto *I = dyn_cast<Instruction>(KV.first))
2001 // Skip unused/dead instructions.
2002 if (InstrDFS.lookup(I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00002003 continue;
Daniel Berlin06329a92017-03-18 15:41:40 +00002004 BeforeIteration.insert({KV.first, *KV.second});
2005 }
2006
2007 TouchedInstructions.set();
2008 TouchedInstructions.reset(0);
2009 iterateTouchedInstructions();
2010 DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2011 EqualClasses;
2012 for (const auto &KV : ValueToClass) {
2013 if (auto *I = dyn_cast<Instruction>(KV.first))
2014 // Skip unused/dead instructions.
2015 if (InstrDFS.lookup(I) == 0)
2016 continue;
2017 // We could sink these uses, but i think this adds a bit of clarity here as
2018 // to what we are comparing.
2019 auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2020 auto *AfterCC = KV.second;
2021 // Note that the classes can't change at this point, so we memoize the set
2022 // that are equal.
2023 if (!EqualClasses.count({BeforeCC, AfterCC})) {
2024 assert(areClassesEquivalent(BeforeCC, AfterCC) &&
2025 "Value number changed after main loop completed!");
2026 EqualClasses.insert({BeforeCC, AfterCC});
Daniel Berlinf7d95802017-02-18 23:06:50 +00002027 }
2028 }
2029#endif
2030}
2031
Daniel Berlin06329a92017-03-18 15:41:40 +00002032// This is the main value numbering loop, it iterates over the initial touched
2033// instruction set, propagating value numbers, marking things touched, etc,
2034// until the set of touched instructions is completely empty.
2035void NewGVN::iterateTouchedInstructions() {
2036 unsigned int Iterations = 0;
2037 // Figure out where touchedinstructions starts
2038 int FirstInstr = TouchedInstructions.find_first();
2039 // Nothing set, nothing to iterate, just return.
2040 if (FirstInstr == -1)
2041 return;
2042 BasicBlock *LastBlock = getBlockForValue(DFSToInstr[FirstInstr]);
2043 while (TouchedInstructions.any()) {
2044 ++Iterations;
2045 // Walk through all the instructions in all the blocks in RPO.
2046 // TODO: As we hit a new block, we should push and pop equalities into a
2047 // table lookupOperandLeader can use, to catch things PredicateInfo
2048 // might miss, like edge-only equivalences.
2049 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2050 InstrNum = TouchedInstructions.find_next(InstrNum)) {
2051
2052 // This instruction was found to be dead. We don't bother looking
2053 // at it again.
2054 if (InstrNum == 0) {
2055 TouchedInstructions.reset(InstrNum);
2056 continue;
2057 }
2058
2059 Value *V = DFSToInstr[InstrNum];
2060 BasicBlock *CurrBlock = getBlockForValue(V);
2061
2062 // If we hit a new block, do reachability processing.
2063 if (CurrBlock != LastBlock) {
2064 LastBlock = CurrBlock;
2065 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2066 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2067
2068 // If it's not reachable, erase any touched instructions and move on.
2069 if (!BlockReachable) {
2070 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2071 DEBUG(dbgs() << "Skipping instructions in block "
2072 << getBlockName(CurrBlock)
2073 << " because it is unreachable\n");
2074 continue;
2075 }
2076 updateProcessedCount(CurrBlock);
2077 }
2078
2079 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
2080 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2081 valueNumberMemoryPhi(MP);
2082 } else if (auto *I = dyn_cast<Instruction>(V)) {
2083 valueNumberInstruction(I);
2084 } else {
2085 llvm_unreachable("Should have been a MemoryPhi or Instruction");
2086 }
2087 updateProcessedCount(V);
2088 // Reset after processing (because we may mark ourselves as touched when
2089 // we propagate equalities).
2090 TouchedInstructions.reset(InstrNum);
2091 }
2092 }
2093 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
2094}
2095
Daniel Berlin85f91b02016-12-26 20:06:58 +00002096// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00002097bool NewGVN::runGVN() {
Daniel Berlin06329a92017-03-18 15:41:40 +00002098 if (DebugCounter::isCounterSet(VNCounter))
2099 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
Davide Italiano7e274e02016-12-22 16:03:48 +00002100 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00002101 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00002102 MSSAWalker = MSSA->getWalker();
2103
2104 // Count number of instructions for sizing of hash tables, and come
2105 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002106 unsigned ICount = 1;
2107 // Add an empty instruction to account for the fact that we start at 1
2108 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002109 // Note: We want ideal RPO traversal of the blocks, which is not quite the
2110 // same as dominator tree order, particularly with regard whether backedges
2111 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00002112 // If we visit in the wrong order, we will end up performing N times as many
2113 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002114 // The dominator tree does guarantee that, for a given dom tree node, it's
2115 // parent must occur before it in the RPO ordering. Thus, we only need to sort
2116 // the siblings.
2117 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00002118 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00002119 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002120 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00002121 auto *Node = DT->getNode(B);
2122 assert(Node && "RPO and Dominator tree should have same reachability");
2123 RPOOrdering[Node] = ++Counter;
2124 }
2125 // Sort dominator tree children arrays into RPO.
2126 for (auto &B : RPOT) {
2127 auto *Node = DT->getNode(B);
2128 if (Node->getChildren().size() > 1)
2129 std::sort(Node->begin(), Node->end(),
2130 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
2131 return RPOOrdering[A] < RPOOrdering[B];
2132 });
2133 }
2134
2135 // Now a standard depth first ordering of the domtree is equivalent to RPO.
2136 auto DFI = df_begin(DT->getRootNode());
2137 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
2138 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00002139 const auto &BlockRange = assignDFSNumbers(B, ICount);
2140 BlockInstRange.insert({B, BlockRange});
2141 ICount += BlockRange.second - BlockRange.first;
2142 }
2143
2144 // Handle forward unreachable blocks and figure out which blocks
2145 // have single preds.
2146 for (auto &B : F) {
2147 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002148 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002149 const auto &BlockRange = assignDFSNumbers(&B, ICount);
2150 BlockInstRange.insert({&B, BlockRange});
2151 ICount += BlockRange.second - BlockRange.first;
2152 }
2153 }
2154
Daniel Berline0bd37e2016-12-29 22:15:12 +00002155 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002156 // Ensure we don't end up resizing the expressionToClass map, as
2157 // that can be quite expensive. At most, we have one expression per
2158 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002159 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002160
2161 // Initialize the touched instructions to include the entry block.
2162 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2163 TouchedInstructions.set(InstRange.first, InstRange.second);
2164 ReachableBlocks.insert(&F.getEntryBlock());
2165
2166 initializeCongruenceClasses(F);
Daniel Berlin06329a92017-03-18 15:41:40 +00002167 iterateTouchedInstructions();
Daniel Berlin589cecc2017-01-02 18:00:46 +00002168 verifyMemoryCongruency();
Daniel Berlin06329a92017-03-18 15:41:40 +00002169 verifyIterationSettled(F);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002170
Davide Italiano7e274e02016-12-22 16:03:48 +00002171 Changed |= eliminateInstructions(F);
2172
2173 // Delete all instructions marked for deletion.
2174 for (Instruction *ToErase : InstructionsToErase) {
2175 if (!ToErase->use_empty())
2176 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2177
2178 ToErase->eraseFromParent();
2179 }
2180
2181 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002182 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2183 return !ReachableBlocks.count(&BB);
2184 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002185
2186 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2187 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002188 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002189 deleteInstructionsInBlock(&BB);
2190 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002191 }
2192
2193 cleanupTables();
2194 return Changed;
2195}
2196
Davide Italiano7e274e02016-12-22 16:03:48 +00002197// Return true if V is a value that will always be available (IE can
2198// be placed anywhere) in the function. We don't do globals here
2199// because they are often worse to put in place.
2200// TODO: Separate cost from availability
2201static bool alwaysAvailable(Value *V) {
2202 return isa<Constant>(V) || isa<Argument>(V);
2203}
2204
Davide Italiano7e274e02016-12-22 16:03:48 +00002205struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002206 int DFSIn = 0;
2207 int DFSOut = 0;
2208 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002209 // Only one of Def and U will be set.
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002210 // The bool in the Def tells us whether the Def is the stored value of a
2211 // store.
2212 PointerIntPair<Value *, 1, bool> Def;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002213 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002214 bool operator<(const ValueDFS &Other) const {
2215 // It's not enough that any given field be less than - we have sets
2216 // of fields that need to be evaluated together to give a proper ordering.
2217 // For example, if you have;
2218 // DFS (1, 3)
2219 // Val 0
2220 // DFS (1, 2)
2221 // Val 50
2222 // We want the second to be less than the first, but if we just go field
2223 // by field, we will get to Val 0 < Val 50 and say the first is less than
2224 // the second. We only want it to be less than if the DFS orders are equal.
2225 //
2226 // Each LLVM instruction only produces one value, and thus the lowest-level
2227 // differentiator that really matters for the stack (and what we use as as a
2228 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002229 // Everything else in the structure is instruction level, and only affects
2230 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002231 //
2232 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2233 // the order of replacement of uses does not matter.
2234 // IE given,
2235 // a = 5
2236 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002237 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2238 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002239 // The .val will be the same as well.
2240 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002241 // You will replace both, and it does not matter what order you replace them
2242 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2243 // operand 2).
2244 // Similarly for the case of same dfsin, dfsout, localnum, but different
2245 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002246 // a = 5
2247 // b = 6
2248 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002249 // in c, we will a valuedfs for a, and one for b,with everything the same
2250 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002251 // It does not matter what order we replace these operands in.
2252 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002253 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2254 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00002255 Other.U);
2256 }
2257};
2258
Daniel Berlinc4796862017-01-27 02:37:11 +00002259// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002260// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00002261// reachable uses for each value is stored in UseCount, and instructions that
2262// seem
2263// dead (have no non-dead uses) are stored in ProbablyDead.
2264void NewGVN::convertClassToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00002265 const CongruenceClass::MemberSet &Dense,
Daniel Berline3e69e12017-03-10 00:32:33 +00002266 SmallVectorImpl<ValueDFS> &DFSOrderedSet,
2267 DenseMap<const Value *, unsigned int> &UseCounts,
2268 SmallPtrSetImpl<Instruction *> &ProbablyDead) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002269 for (auto D : Dense) {
2270 // First add the value.
2271 BasicBlock *BB = getBlockForValue(D);
2272 // Constants are handled prior to ever calling this function, so
2273 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002274 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002275 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002276 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002277 VDDef.DFSIn = DomNode->getDFSNumIn();
2278 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002279 // If it's a store, use the leader of the value operand, if it's always
2280 // available, or the value operand. TODO: We could do dominance checks to
2281 // find a dominating leader, but not worth it ATM.
Daniel Berlin26addef2017-01-20 21:04:30 +00002282 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002283 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002284 if (alwaysAvailable(Leader)) {
2285 VDDef.Def.setPointer(Leader);
2286 } else {
2287 VDDef.Def.setPointer(SI->getValueOperand());
2288 VDDef.Def.setInt(true);
2289 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002290 } else {
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002291 VDDef.Def.setPointer(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00002292 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002293 assert(isa<Instruction>(D) &&
2294 "The dense set member should always be an instruction");
2295 VDDef.LocalNum = InstrDFS.lookup(D);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002296 DFSOrderedSet.emplace_back(VDDef);
Daniel Berline3e69e12017-03-10 00:32:33 +00002297 Instruction *Def = cast<Instruction>(D);
2298 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002299 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00002300 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002301 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002302 // Don't try to replace into dead uses
2303 if (InstructionsToErase.count(I))
2304 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002305 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00002306 // Put the phi node uses in the incoming block.
2307 BasicBlock *IBlock;
2308 if (auto *P = dyn_cast<PHINode>(I)) {
2309 IBlock = P->getIncomingBlock(U);
2310 // Make phi node users appear last in the incoming block
2311 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002312 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00002313 } else {
2314 IBlock = I->getParent();
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002315 VDUse.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002316 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002317
2318 // Skip uses in unreachable blocks, as we're going
2319 // to delete them.
2320 if (ReachableBlocks.count(IBlock) == 0)
2321 continue;
2322
Daniel Berlinb66164c2017-01-14 00:24:23 +00002323 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002324 VDUse.DFSIn = DomNode->getDFSNumIn();
2325 VDUse.DFSOut = DomNode->getDFSNumOut();
2326 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00002327 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002328 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00002329 }
2330 }
Daniel Berline3e69e12017-03-10 00:32:33 +00002331
2332 // If there are no uses, it's probably dead (but it may have side-effects,
2333 // so not definitely dead. Otherwise, store the number of uses so we can
2334 // track if it becomes dead later).
2335 if (UseCount == 0)
2336 ProbablyDead.insert(Def);
2337 else
2338 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002339 }
2340}
2341
Daniel Berlinc4796862017-01-27 02:37:11 +00002342// This function converts the set of members for a congruence class from values,
2343// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00002344void NewGVN::convertClassToLoadsAndStores(
Daniel Berlinc4796862017-01-27 02:37:11 +00002345 const CongruenceClass::MemberSet &Dense,
2346 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2347 for (auto D : Dense) {
2348 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2349 continue;
2350
2351 BasicBlock *BB = getBlockForValue(D);
2352 ValueDFS VD;
2353 DomTreeNode *DomNode = DT->getNode(BB);
2354 VD.DFSIn = DomNode->getDFSNumIn();
2355 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002356 VD.Def.setPointer(D);
Daniel Berlinc4796862017-01-27 02:37:11 +00002357
2358 // If it's an instruction, use the real local dfs number.
2359 if (auto *I = dyn_cast<Instruction>(D))
2360 VD.LocalNum = InstrDFS.lookup(I);
2361 else
2362 llvm_unreachable("Should have been an instruction");
2363
2364 LoadsAndStores.emplace_back(VD);
2365 }
2366}
2367
Davide Italiano7e274e02016-12-22 16:03:48 +00002368static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00002369 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00002370 if (!ReplInst)
2371 return;
2372
Davide Italiano7e274e02016-12-22 16:03:48 +00002373 // Patch the replacement so that it is not more restrictive than the value
2374 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00002375 // Note that if 'I' is a load being replaced by some operation,
2376 // for example, by an arithmetic operation, then andIRFlags()
2377 // would just erase all math flags from the original arithmetic
2378 // operation, which is clearly not wanted and not needed.
2379 if (!isa<LoadInst>(I))
2380 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002381
Daniel Berlin86eab152017-02-12 22:25:20 +00002382 // FIXME: If both the original and replacement value are part of the
2383 // same control-flow region (meaning that the execution of one
2384 // guarantees the execution of the other), then we can combine the
2385 // noalias scopes here and do better than the general conservative
2386 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00002387
Daniel Berlin86eab152017-02-12 22:25:20 +00002388 // In general, GVN unifies expressions over different control-flow
2389 // regions, and so we need a conservative combination of the noalias
2390 // scopes.
2391 static const unsigned KnownIDs[] = {
2392 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2393 LLVMContext::MD_noalias, LLVMContext::MD_range,
2394 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2395 LLVMContext::MD_invariant_group};
2396 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00002397}
2398
2399static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2400 patchReplacementInstruction(I, Repl);
2401 I->replaceAllUsesWith(Repl);
2402}
2403
2404void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2405 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2406 ++NumGVNBlocksDeleted;
2407
Daniel Berline19f0e02017-01-30 17:06:55 +00002408 // Delete the instructions backwards, as it has a reduced likelihood of having
2409 // to update as many def-use and use-def chains. Start after the terminator.
2410 auto StartPoint = BB->rbegin();
2411 ++StartPoint;
2412 // Note that we explicitly recalculate BB->rend() on each iteration,
2413 // as it may change when we remove the first instruction.
2414 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2415 Instruction &Inst = *I++;
2416 if (!Inst.use_empty())
2417 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2418 if (isa<LandingPadInst>(Inst))
2419 continue;
2420
2421 Inst.eraseFromParent();
2422 ++NumGVNInstrDeleted;
2423 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002424 // Now insert something that simplifycfg will turn into an unreachable.
2425 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2426 new StoreInst(UndefValue::get(Int8Ty),
2427 Constant::getNullValue(Int8Ty->getPointerTo()),
2428 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002429}
2430
2431void NewGVN::markInstructionForDeletion(Instruction *I) {
2432 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2433 InstructionsToErase.insert(I);
2434}
2435
2436void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2437
2438 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2439 patchAndReplaceAllUsesWith(I, V);
2440 // We save the actual erasing to avoid invalidating memory
2441 // dependencies until we are done with everything.
2442 markInstructionForDeletion(I);
2443}
2444
2445namespace {
2446
2447// This is a stack that contains both the value and dfs info of where
2448// that value is valid.
2449class ValueDFSStack {
2450public:
2451 Value *back() const { return ValueStack.back(); }
2452 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2453
2454 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002455 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002456 DFSStack.emplace_back(DFSIn, DFSOut);
2457 }
2458 bool empty() const { return DFSStack.empty(); }
2459 bool isInScope(int DFSIn, int DFSOut) const {
2460 if (empty())
2461 return false;
2462 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2463 }
2464
2465 void popUntilDFSScope(int DFSIn, int DFSOut) {
2466
2467 // These two should always be in sync at this point.
2468 assert(ValueStack.size() == DFSStack.size() &&
2469 "Mismatch between ValueStack and DFSStack");
2470 while (
2471 !DFSStack.empty() &&
2472 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2473 DFSStack.pop_back();
2474 ValueStack.pop_back();
2475 }
2476 }
2477
2478private:
2479 SmallVector<Value *, 8> ValueStack;
2480 SmallVector<std::pair<int, int>, 8> DFSStack;
2481};
2482}
Daniel Berlin04443432017-01-07 03:23:47 +00002483
Davide Italiano7e274e02016-12-22 16:03:48 +00002484bool NewGVN::eliminateInstructions(Function &F) {
2485 // This is a non-standard eliminator. The normal way to eliminate is
2486 // to walk the dominator tree in order, keeping track of available
2487 // values, and eliminating them. However, this is mildly
2488 // pointless. It requires doing lookups on every instruction,
2489 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002490 // instructions part of most singleton congruence classes, we know we
2491 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002492
2493 // Instead, this eliminator looks at the congruence classes directly, sorts
2494 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002495 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002496 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002497 // last member. This is worst case O(E log E) where E = number of
2498 // instructions in a single congruence class. In theory, this is all
2499 // instructions. In practice, it is much faster, as most instructions are
2500 // either in singleton congruence classes or can't possibly be eliminated
2501 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002502 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002503 // for elimination purposes.
2504 // TODO: If we wanted to be faster, We could remove any members with no
2505 // overlapping ranges while sorting, as we will never eliminate anything
2506 // with those members, as they don't dominate anything else in our set.
2507
Davide Italiano7e274e02016-12-22 16:03:48 +00002508 bool AnythingReplaced = false;
2509
2510 // Since we are going to walk the domtree anyway, and we can't guarantee the
2511 // DFS numbers are updated, we compute some ourselves.
2512 DT->updateDFSNumbers();
2513
2514 for (auto &B : F) {
2515 if (!ReachableBlocks.count(&B)) {
2516 for (const auto S : successors(&B)) {
2517 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002518 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002519 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2520 << getBlockName(&B)
2521 << " with undef due to it being unreachable\n");
2522 for (auto &Operand : Phi.incoming_values())
2523 if (Phi.getIncomingBlock(Operand) == &B)
2524 Operand.set(UndefValue::get(Phi.getType()));
2525 }
2526 }
2527 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002528 }
2529
Daniel Berline3e69e12017-03-10 00:32:33 +00002530 // Map to store the use counts
2531 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlin4d547962017-02-12 23:24:45 +00002532 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002533 // Track the equivalent store info so we can decide whether to try
2534 // dead store elimination.
2535 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00002536 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlinb79f5362017-02-11 12:48:50 +00002537 if (CC->Dead)
Davide Italiano7e274e02016-12-22 16:03:48 +00002538 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002539 // Everything still in the TOP class is unreachable or dead.
2540 if (CC == TOPClass) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00002541#ifndef NDEBUG
2542 for (auto M : CC->Members)
2543 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2544 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002545 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00002546 "point");
2547#endif
2548 continue;
2549 }
2550
Davide Italiano7e274e02016-12-22 16:03:48 +00002551 assert(CC->RepLeader && "We should have had a leader");
2552
2553 // If this is a leader that is always available, and it's a
2554 // constant or has no equivalences, just replace everything with
2555 // it. We then update the congruence class with whatever members
2556 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002557 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2558 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002559 SmallPtrSet<Value *, 4> MembersLeft;
2560 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002561 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002562 // Void things have no uses we can replace.
Daniel Berline3e69e12017-03-10 00:32:33 +00002563 if (Member == Leader || Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002564 MembersLeft.insert(Member);
2565 continue;
2566 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002567 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2568 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002569 // Due to equality propagation, these may not always be
2570 // instructions, they may be real values. We don't really
2571 // care about trying to replace the non-instructions.
2572 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002573 assert(Leader != I && "About to accidentally remove our leader");
2574 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002575 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002576 continue;
2577 } else {
2578 MembersLeft.insert(I);
2579 }
2580 }
2581 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002582 } else {
2583 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2584 // If this is a singleton, we can skip it.
2585 if (CC->Members.size() != 1) {
2586
2587 // This is a stack because equality replacement/etc may place
2588 // constants in the middle of the member list, and we want to use
2589 // those constant values in preference to the current leader, over
2590 // the scope of those constants.
2591 ValueDFSStack EliminationStack;
2592
2593 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002594 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berline3e69e12017-03-10 00:32:33 +00002595 convertClassToDFSOrdered(CC->Members, DFSOrderedSet, UseCounts,
2596 ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00002597
2598 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002599 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002600 for (auto &VD : DFSOrderedSet) {
2601 int MemberDFSIn = VD.DFSIn;
2602 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002603 Value *Def = VD.Def.getPointer();
2604 bool FromStore = VD.Def.getInt();
Daniel Berline3e69e12017-03-10 00:32:33 +00002605 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00002606 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00002607 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00002608 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002609
2610 if (EliminationStack.empty()) {
2611 DEBUG(dbgs() << "Elimination Stack is empty\n");
2612 } else {
2613 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2614 << EliminationStack.dfs_back().first << ","
2615 << EliminationStack.dfs_back().second << ")\n");
2616 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002617
2618 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2619 << MemberDFSOut << ")\n");
2620 // First, we see if we are out of scope or empty. If so,
2621 // and there equivalences, we try to replace the top of
2622 // stack with equivalences (if it's on the stack, it must
2623 // not have been eliminated yet).
2624 // Then we synchronize to our current scope, by
2625 // popping until we are back within a DFS scope that
2626 // dominates the current member.
2627 // Then, what happens depends on a few factors
2628 // If the stack is now empty, we need to push
2629 // If we have a constant or a local equivalence we want to
2630 // start using, we also push.
2631 // Otherwise, we walk along, processing members who are
2632 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00002633 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002634 bool OutOfScope =
2635 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2636
2637 if (OutOfScope || ShouldPush) {
2638 // Sync to our current scope.
2639 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00002640 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002641 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002642 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00002643 }
2644 }
2645
Daniel Berline3e69e12017-03-10 00:32:33 +00002646 // Skip the Def's, we only want to eliminate on their uses. But mark
2647 // dominated defs as dead.
2648 if (Def) {
2649 // For anything in this case, what and how we value number
2650 // guarantees that any side-effets that would have occurred (ie
2651 // throwing, etc) can be proven to either still occur (because it's
2652 // dominated by something that has the same side-effects), or never
2653 // occur. Otherwise, we would not have been able to prove it value
2654 // equivalent to something else. For these things, we can just mark
2655 // it all dead. Note that this is different from the "ProbablyDead"
2656 // set, which may not be dominated by anything, and thus, are only
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002657 // easy to prove dead if they are also side-effect free. Note that
2658 // because stores are put in terms of the stored value, we skip
2659 // stored values here. If the stored value is really dead, it will
2660 // still be marked for deletion when we process it in its own class.
Daniel Berline3e69e12017-03-10 00:32:33 +00002661 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002662 isa<Instruction>(Def) && !FromStore)
Daniel Berline3e69e12017-03-10 00:32:33 +00002663 markInstructionForDeletion(cast<Instruction>(Def));
2664 continue;
2665 }
2666 // At this point, we know it is a Use we are trying to possibly
2667 // replace.
2668
2669 assert(isa<Instruction>(U->get()) &&
2670 "Current def should have been an instruction");
2671 assert(isa<Instruction>(U->getUser()) &&
2672 "Current user should have been an instruction");
2673
2674 // If the thing we are replacing into is already marked to be dead,
2675 // this use is dead. Note that this is true regardless of whether
2676 // we have anything dominating the use or not. We do this here
2677 // because we are already walking all the uses anyway.
2678 Instruction *InstUse = cast<Instruction>(U->getUser());
2679 if (InstructionsToErase.count(InstUse)) {
2680 auto &UseCount = UseCounts[U->get()];
2681 if (--UseCount == 0) {
2682 ProbablyDead.insert(cast<Instruction>(U->get()));
2683 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002684 }
2685
Davide Italiano7e274e02016-12-22 16:03:48 +00002686 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00002687 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00002688 if (EliminationStack.empty())
2689 continue;
2690
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002691 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00002692
Daniel Berlind92e7f92017-01-07 00:01:42 +00002693 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00002694 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00002695 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002696 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00002697 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002698
2699 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00002700 // metadata. Skip this if we are replacing predicateinfo with its
2701 // original operand, as we already know we can just drop it.
2702 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002703 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
2704 if (!PI || DominatingLeader != PI->OriginalOp)
2705 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00002706 U->set(DominatingLeader);
2707 // This is now a use of the dominating leader, which means if the
2708 // dominating leader was dead, it's now live!
2709 auto &LeaderUseCount = UseCounts[DominatingLeader];
2710 // It's about to be alive again.
2711 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
2712 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
2713 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002714 AnythingReplaced = true;
2715 }
2716 }
2717 }
2718
Daniel Berline3e69e12017-03-10 00:32:33 +00002719 // At this point, anything still in the ProbablyDead set is actually dead if
2720 // would be trivially dead.
2721 for (auto *I : ProbablyDead)
2722 if (wouldInstructionBeTriviallyDead(I))
2723 markInstructionForDeletion(I);
2724
Davide Italiano7e274e02016-12-22 16:03:48 +00002725 // Cleanup the congruence class.
2726 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002727 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002728 if (Member->getType()->isVoidTy()) {
2729 MembersLeft.insert(Member);
2730 continue;
2731 }
2732
Davide Italiano7e274e02016-12-22 16:03:48 +00002733 MembersLeft.insert(Member);
2734 }
2735 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002736
2737 // If we have possible dead stores to look at, try to eliminate them.
2738 if (CC->StoreCount > 0) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002739 convertClassToLoadsAndStores(CC->Members, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00002740 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2741 ValueDFSStack EliminationStack;
2742 for (auto &VD : PossibleDeadStores) {
2743 int MemberDFSIn = VD.DFSIn;
2744 int MemberDFSOut = VD.DFSOut;
Daniel Berlin9a9c9ff2017-04-01 09:44:33 +00002745 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
Daniel Berlinc4796862017-01-27 02:37:11 +00002746 if (EliminationStack.empty() ||
2747 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2748 // Sync to our current scope.
2749 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2750 if (EliminationStack.empty()) {
2751 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2752 continue;
2753 }
2754 }
2755 // We already did load elimination, so nothing to do here.
2756 if (isa<LoadInst>(Member))
2757 continue;
2758 assert(!EliminationStack.empty());
2759 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002760 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002761 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2762 // Member is dominater by Leader, and thus dead
2763 DEBUG(dbgs() << "Marking dead store " << *Member
2764 << " that is dominated by " << *Leader << "\n");
2765 markInstructionForDeletion(Member);
2766 CC->Members.erase(Member);
2767 ++NumGVNDeadStores;
2768 }
2769 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002770 }
2771
2772 return AnythingReplaced;
2773}
Daniel Berlin1c087672017-02-11 15:07:01 +00002774
2775// This function provides global ranking of operations so that we can place them
2776// in a canonical order. Note that rank alone is not necessarily enough for a
2777// complete ordering, as constants all have the same rank. However, generally,
2778// we will simplify an operation with all constants so that it doesn't matter
2779// what order they appear in.
2780unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002781 // Prefer undef to anything else
2782 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00002783 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002784 if (isa<Constant>(V))
2785 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00002786 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002787 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00002788
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002789 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00002790 // the constant and argument ranking above.
2791 unsigned Result = InstrDFS.lookup(V);
2792 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002793 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00002794 // Unreachable or something else, just return a really large number.
2795 return ~0;
2796}
2797
2798// This is a function that says whether two commutative operations should
2799// have their order swapped when canonicalizing.
2800bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
2801 // Because we only care about a total ordering, and don't rewrite expressions
2802 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002803 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002804 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00002805}
Daniel Berlin64e68992017-03-12 04:46:45 +00002806
2807class NewGVNLegacyPass : public FunctionPass {
2808public:
2809 static char ID; // Pass identification, replacement for typeid.
2810 NewGVNLegacyPass() : FunctionPass(ID) {
2811 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
2812 }
2813 bool runOnFunction(Function &F) override;
2814
2815private:
2816 void getAnalysisUsage(AnalysisUsage &AU) const override {
2817 AU.addRequired<AssumptionCacheTracker>();
2818 AU.addRequired<DominatorTreeWrapperPass>();
2819 AU.addRequired<TargetLibraryInfoWrapperPass>();
2820 AU.addRequired<MemorySSAWrapperPass>();
2821 AU.addRequired<AAResultsWrapperPass>();
2822 AU.addPreserved<DominatorTreeWrapperPass>();
2823 AU.addPreserved<GlobalsAAWrapperPass>();
2824 }
2825};
2826
2827bool NewGVNLegacyPass::runOnFunction(Function &F) {
2828 if (skipFunction(F))
2829 return false;
2830 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2831 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2832 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2833 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
2834 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
2835 F.getParent()->getDataLayout())
2836 .runGVN();
2837}
2838
2839INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
2840 false, false)
2841INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2842INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2843INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2844INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2845INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2846INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2847INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
2848 false)
2849
2850char NewGVNLegacyPass::ID = 0;
2851
2852// createGVNPass - The public interface to this file.
2853FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
2854
2855PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
2856 // Apparently the order in which we get these results matter for
2857 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
2858 // the same order here, just in case.
2859 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2860 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2861 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2862 auto &AA = AM.getResult<AAManager>(F);
2863 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2864 bool Changed =
2865 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
2866 .runGVN();
2867 if (!Changed)
2868 return PreservedAnalyses::all();
2869 PreservedAnalyses PA;
2870 PA.preserve<DominatorTreeAnalysis>();
2871 PA.preserve<GlobalsAA>();
2872 return PA;
2873}