blob: 0fa9b1d714a1f113e0b95e48113a5eb40ecc7486 [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
179namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000180template <> struct DenseMapInfo<const Expression *> {
181 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000182 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000183 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
184 return reinterpret_cast<const Expression *>(Val);
185 }
186 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000187 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000188 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
189 return reinterpret_cast<const Expression *>(Val);
190 }
191 static unsigned getHashValue(const Expression *V) {
192 return static_cast<unsigned>(V->getHashValue());
193 }
194 static bool isEqual(const Expression *LHS, const Expression *RHS) {
195 if (LHS == RHS)
196 return true;
197 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
198 LHS == getEmptyKey() || RHS == getEmptyKey())
199 return false;
200 return *LHS == *RHS;
201 }
202};
Davide Italiano7e274e02016-12-22 16:03:48 +0000203} // end namespace llvm
204
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000205namespace {
Daniel Berlin64e68992017-03-12 04:46:45 +0000206class NewGVN {
207 Function &F;
Davide Italiano7e274e02016-12-22 16:03:48 +0000208 DominatorTree *DT;
Davide Italiano7e274e02016-12-22 16:03:48 +0000209 AssumptionCache *AC;
Daniel Berlin64e68992017-03-12 04:46:45 +0000210 const TargetLibraryInfo *TLI;
Davide Italiano7e274e02016-12-22 16:03:48 +0000211 AliasAnalysis *AA;
212 MemorySSA *MSSA;
213 MemorySSAWalker *MSSAWalker;
Daniel Berlin64e68992017-03-12 04:46:45 +0000214 const DataLayout &DL;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000215 std::unique_ptr<PredicateInfo> PredInfo;
Davide Italiano7e274e02016-12-22 16:03:48 +0000216 BumpPtrAllocator ExpressionAllocator;
217 ArrayRecycler<Value *> ArgRecycler;
218
Daniel Berlin1c087672017-02-11 15:07:01 +0000219 // Number of function arguments, used by ranking
220 unsigned int NumFuncArgs;
221
Davide Italiano7e274e02016-12-22 16:03:48 +0000222 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000223
224 // This class is called INITIAL in the paper. It is the class everything
225 // startsout in, and represents any value. Being an optimistic analysis,
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000226 // anything in the TOP class has the value TOP, which is indeterminate and
Daniel Berlinb79f5362017-02-11 12:48:50 +0000227 // equivalent to everything.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000228 CongruenceClass *TOPClass;
Davide Italiano7e274e02016-12-22 16:03:48 +0000229 std::vector<CongruenceClass *> CongruenceClasses;
230 unsigned NextCongruenceNum;
231
232 // Value Mappings.
233 DenseMap<Value *, CongruenceClass *> ValueToClass;
234 DenseMap<Value *, const Expression *> ValueToExpression;
235
Daniel Berlinf7d95802017-02-18 23:06:50 +0000236 // Mapping from predicate info we used to the instructions we used it with.
237 // In order to correctly ensure propagation, we must keep track of what
238 // comparisons we used, so that when the values of the comparisons change, we
239 // propagate the information to the places we used the comparison.
240 DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> PredicateToUsers;
241
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000242 // A table storing which memorydefs/phis represent a memory state provably
243 // equivalent to another memory state.
244 // We could use the congruence class machinery, but the MemoryAccess's are
245 // abstract memory states, so they can only ever be equivalent to each other,
246 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000247 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000248
Davide Italiano7e274e02016-12-22 16:03:48 +0000249 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000250 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000251 ExpressionClassMap ExpressionToClass;
252
253 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000254 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000255
256 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000257 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000258 DenseSet<BlockEdge> ReachableEdges;
259 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
260
261 // This is a bitvector because, on larger functions, we may have
262 // thousands of touched instructions at once (entire blocks,
263 // instructions with hundreds of uses, etc). Even with optimization
264 // for when we mark whole blocks as touched, when this was a
265 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
266 // the time in GVN just managing this list. The bitvector, on the
267 // other hand, efficiently supports test/set/clear of both
268 // individual and ranges, as well as "find next element" This
269 // enables us to use it as a worklist with essentially 0 cost.
270 BitVector TouchedInstructions;
271
272 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
273 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
274 DominatedInstRange;
275
276#ifndef NDEBUG
277 // Debugging for how many times each block and instruction got processed.
278 DenseMap<const Value *, unsigned> ProcessedCount;
279#endif
280
281 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000282 // This contains a mapping from Instructions to DFS numbers.
283 // The numbering starts at 1. An instruction with DFS number zero
284 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000285 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000286
287 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000288 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000289
290 // Deletion info.
291 SmallPtrSet<Instruction *, 8> InstructionsToErase;
292
293public:
Daniel Berlin64e68992017-03-12 04:46:45 +0000294 NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
295 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
296 const DataLayout &DL)
297 : F(F), DT(DT), AC(AC), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
298 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)) {}
299 bool runGVN();
Davide Italiano7e274e02016-12-22 16:03:48 +0000300
301private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000302 // Expression handling.
Daniel Berlin97718e62017-01-31 22:32:03 +0000303 const Expression *createExpression(Instruction *);
304 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000305 PHIExpression *createPHIExpression(Instruction *);
306 const VariableExpression *createVariableExpression(Value *);
307 const ConstantExpression *createConstantExpression(Constant *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000308 const Expression *createVariableOrConstant(Value *V);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000309 const UnknownExpression *createUnknownExpression(Instruction *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000310 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000311 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin97718e62017-01-31 22:32:03 +0000312 MemoryAccess *);
313 const CallExpression *createCallExpression(CallInst *, MemoryAccess *);
314 const AggregateValueExpression *createAggregateValueExpression(Instruction *);
315 bool setBasicExpressionInfo(Instruction *, BasicExpression *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000316
317 // Congruence class handling.
318 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000319 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000320 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000321 return result;
322 }
323
324 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000325 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000326 CClass->Members.insert(Member);
327 ValueToClass[Member] = CClass;
328 return CClass;
329 }
330 void initializeCongruenceClasses(Function &F);
331
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000332 // Value number an Instruction or MemoryPhi.
333 void valueNumberMemoryPhi(MemoryPhi *);
334 void valueNumberInstruction(Instruction *);
335
Davide Italiano7e274e02016-12-22 16:03:48 +0000336 // Symbolic evaluation.
337 const Expression *checkSimplificationResults(Expression *, Instruction *,
338 Value *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000339 const Expression *performSymbolicEvaluation(Value *);
340 const Expression *performSymbolicLoadEvaluation(Instruction *);
341 const Expression *performSymbolicStoreEvaluation(Instruction *);
342 const Expression *performSymbolicCallEvaluation(Instruction *);
343 const Expression *performSymbolicPHIEvaluation(Instruction *);
344 const Expression *performSymbolicAggrValueEvaluation(Instruction *);
345 const Expression *performSymbolicCmpEvaluation(Instruction *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000346 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000347
348 // Congruence finding.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000349 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000350 void performCongruenceFinding(Instruction *, const Expression *);
351 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000352 CongruenceClass *);
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000353 bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
354 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000355 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000356
Daniel Berlin1c087672017-02-11 15:07:01 +0000357 // Ranking
358 unsigned int getRank(const Value *) const;
359 bool shouldSwapOperands(const Value *, const Value *) const;
360
Davide Italiano7e274e02016-12-22 16:03:48 +0000361 // Reachability handling.
362 void updateReachableEdge(BasicBlock *, BasicBlock *);
363 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000364 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000365
366 // Elimination.
367 struct ValueDFS;
Daniel Berline3e69e12017-03-10 00:32:33 +0000368 void convertClassToDFSOrdered(const CongruenceClass::MemberSet &,
369 SmallVectorImpl<ValueDFS> &,
370 DenseMap<const Value *, unsigned int> &,
371 SmallPtrSetImpl<Instruction *> &);
372 void convertClassToLoadsAndStores(const CongruenceClass::MemberSet &,
Daniel Berlinc4796862017-01-27 02:37:11 +0000373 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000374
375 bool eliminateInstructions(Function &);
376 void replaceInstruction(Instruction *, Value *);
377 void markInstructionForDeletion(Instruction *);
378 void deleteInstructionsInBlock(BasicBlock *);
379
380 // New instruction creation.
381 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000382
383 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000384 void markUsersTouched(Value *);
385 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000386 void markPredicateUsersTouched(Instruction *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000387 void markLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000388 void addPredicateUsers(const PredicateBase *, Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000389
390 // Utilities.
391 void cleanupTables();
392 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
393 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000394 void verifyMemoryCongruency() const;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000395 void verifyComparisons(Function &F);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000396 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000397};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000398} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000399
Davide Italianob1114092016-12-28 13:37:17 +0000400template <typename T>
401static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
402 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000403 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000404 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000405 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000406 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000407 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000408 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000409 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000410 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000411 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000412 return true;
413}
414
Davide Italianob1114092016-12-28 13:37:17 +0000415bool LoadExpression::equals(const Expression &Other) const {
416 return equalsLoadStoreHelper(*this, Other);
417}
Davide Italiano7e274e02016-12-22 16:03:48 +0000418
Davide Italianob1114092016-12-28 13:37:17 +0000419bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000420 bool Result = equalsLoadStoreHelper(*this, Other);
421 // Make sure that store vs store includes the value operand.
422 if (Result)
423 if (const auto *S = dyn_cast<StoreExpression>(&Other))
424 if (getStoredValue() != S->getStoredValue())
425 return false;
426 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000427}
428
429#ifndef NDEBUG
430static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000431 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000432}
433#endif
434
Davide Italiano7e274e02016-12-22 16:03:48 +0000435PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000436 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000437 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000438 auto *E =
439 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000440
441 E->allocateOperands(ArgRecycler, ExpressionAllocator);
442 E->setType(I->getType());
443 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000444
Davide Italianob3886dd2017-01-25 23:37:49 +0000445 // Filter out unreachable phi operands.
446 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +0000447 return ReachableEdges.count({PN->getIncomingBlock(U), PHIBlock});
Davide Italianob3886dd2017-01-25 23:37:49 +0000448 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000449
450 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
451 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000452 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000453 if (U == PN)
454 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000455 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000456 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000457 return E;
458}
459
460// Set basic expression info (Arguments, type, opcode) for Expression
461// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000462bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000463 bool AllConstant = true;
464 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
465 E->setType(GEP->getSourceElementType());
466 else
467 E->setType(I->getType());
468 E->setOpcode(I->getOpcode());
469 E->allocateOperands(ArgRecycler, ExpressionAllocator);
470
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000471 // Transform the operand array into an operand leader array, and keep track of
472 // whether all members are constant.
473 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000474 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000475 AllConstant &= isa<Constant>(Operand);
476 return Operand;
477 });
478
Davide Italiano7e274e02016-12-22 16:03:48 +0000479 return AllConstant;
480}
481
482const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000483 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000484 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000485
486 E->setType(T);
487 E->setOpcode(Opcode);
488 E->allocateOperands(ArgRecycler, ExpressionAllocator);
489 if (Instruction::isCommutative(Opcode)) {
490 // Ensure that commutative instructions that only differ by a permutation
491 // of their operands get the same value number by sorting the operand value
492 // numbers. Since all commutative instructions have two operands it is more
493 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000494 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000495 std::swap(Arg1, Arg2);
496 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000497 E->op_push_back(lookupOperandLeader(Arg1));
498 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000499
Daniel Berlin64e68992017-03-12 04:46:45 +0000500 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), DL, TLI,
Davide Italiano7e274e02016-12-22 16:03:48 +0000501 DT, AC);
502 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
503 return SimplifiedE;
504 return E;
505}
506
507// Take a Value returned by simplification of Expression E/Instruction
508// I, and see if it resulted in a simpler expression. If so, return
509// that expression.
510// TODO: Once finished, this should not take an Instruction, we only
511// use it for printing.
512const Expression *NewGVN::checkSimplificationResults(Expression *E,
513 Instruction *I, Value *V) {
514 if (!V)
515 return nullptr;
516 if (auto *C = dyn_cast<Constant>(V)) {
517 if (I)
518 DEBUG(dbgs() << "Simplified " << *I << " to "
519 << " constant " << *C << "\n");
520 NumGVNOpsSimplified++;
521 assert(isa<BasicExpression>(E) &&
522 "We should always have had a basic expression here");
523
524 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
525 ExpressionAllocator.Deallocate(E);
526 return createConstantExpression(C);
527 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
528 if (I)
529 DEBUG(dbgs() << "Simplified " << *I << " to "
530 << " variable " << *V << "\n");
531 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
532 ExpressionAllocator.Deallocate(E);
533 return createVariableExpression(V);
534 }
535
536 CongruenceClass *CC = ValueToClass.lookup(V);
537 if (CC && CC->DefiningExpr) {
538 if (I)
539 DEBUG(dbgs() << "Simplified " << *I << " to "
540 << " expression " << *V << "\n");
541 NumGVNOpsSimplified++;
542 assert(isa<BasicExpression>(E) &&
543 "We should always have had a basic expression here");
544 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
545 ExpressionAllocator.Deallocate(E);
546 return CC->DefiningExpr;
547 }
548 return nullptr;
549}
550
Daniel Berlin97718e62017-01-31 22:32:03 +0000551const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000552 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000553
Daniel Berlin97718e62017-01-31 22:32:03 +0000554 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000555
556 if (I->isCommutative()) {
557 // Ensure that commutative instructions that only differ by a permutation
558 // of their operands get the same value number by sorting the operand value
559 // numbers. Since all commutative instructions have two operands it is more
560 // efficient to sort by hand rather than using, say, std::sort.
561 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000562 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000563 E->swapOperands(0, 1);
564 }
565
566 // Perform simplificaiton
567 // TODO: Right now we only check to see if we get a constant result.
568 // We may get a less than constant, but still better, result for
569 // some operations.
570 // IE
571 // add 0, x -> x
572 // and x, x -> x
573 // We should handle this by simply rewriting the expression.
574 if (auto *CI = dyn_cast<CmpInst>(I)) {
575 // Sort the operand value numbers so x<y and y>x get the same value
576 // number.
577 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000578 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000579 E->swapOperands(0, 1);
580 Predicate = CmpInst::getSwappedPredicate(Predicate);
581 }
582 E->setOpcode((CI->getOpcode() << 8) | Predicate);
583 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000584 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
585 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000586 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
587 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000588 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000589 DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000590 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
591 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000592 } else if (isa<SelectInst>(I)) {
593 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000594 E->getOperand(0) == E->getOperand(1)) {
595 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
596 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000597 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000598 E->getOperand(2), DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000599 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
600 return SimplifiedE;
601 }
602 } else if (I->isBinaryOp()) {
603 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
Daniel Berlin64e68992017-03-12 04:46:45 +0000604 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000605 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
606 return SimplifiedE;
607 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
Daniel Berlin64e68992017-03-12 04:46:45 +0000608 Value *V = SimplifyInstruction(BI, DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000609 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
610 return SimplifiedE;
611 } else if (isa<GetElementPtrInst>(I)) {
612 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000613 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Daniel Berlin64e68992017-03-12 04:46:45 +0000614 DL, TLI, DT, AC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000615 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
616 return SimplifiedE;
617 } else if (AllConstant) {
618 // We don't bother trying to simplify unless all of the operands
619 // were constant.
620 // TODO: There are a lot of Simplify*'s we could call here, if we
621 // wanted to. The original motivating case for this code was a
622 // zext i1 false to i8, which we don't have an interface to
623 // simplify (IE there is no SimplifyZExt).
624
625 SmallVector<Constant *, 8> C;
626 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000627 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000628
Daniel Berlin64e68992017-03-12 04:46:45 +0000629 if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
Davide Italiano7e274e02016-12-22 16:03:48 +0000630 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
631 return SimplifiedE;
632 }
633 return E;
634}
635
636const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000637NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000638 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000639 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000640 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000641 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000642 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000643 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000644 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000645 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000646 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000647 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000648 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000649 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000650 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000651 return E;
652 }
653 llvm_unreachable("Unhandled type of aggregate value operation");
654}
655
Daniel Berlin85f91b02016-12-26 20:06:58 +0000656const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000657 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000658 E->setOpcode(V->getValueID());
659 return E;
660}
661
Daniel Berlinf7d95802017-02-18 23:06:50 +0000662const Expression *NewGVN::createVariableOrConstant(Value *V) {
663 if (auto *C = dyn_cast<Constant>(V))
664 return createConstantExpression(C);
665 return createVariableExpression(V);
666}
667
Daniel Berlin85f91b02016-12-26 20:06:58 +0000668const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000669 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000670 E->setOpcode(C->getValueID());
671 return E;
672}
673
Daniel Berlin02c6b172017-01-02 18:00:53 +0000674const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
675 auto *E = new (ExpressionAllocator) UnknownExpression(I);
676 E->setOpcode(I->getOpcode());
677 return E;
678}
679
Davide Italiano7e274e02016-12-22 16:03:48 +0000680const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000681 MemoryAccess *HV) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000682 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000683 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000684 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
Daniel Berlin97718e62017-01-31 22:32:03 +0000685 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000686 return E;
687}
688
689// See if we have a congruence class and leader for this operand, and if so,
690// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000691Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000692 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +0000693 if (CC) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000694 // Everything in TOP is represneted by undef, as it can be any value.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000695 // We do have to make sure we get the type right though, so we can't set the
696 // RepLeader to undef.
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000697 if (CC == TOPClass)
Daniel Berlinb79f5362017-02-11 12:48:50 +0000698 return UndefValue::get(V->getType());
Daniel Berlin26addef2017-01-20 21:04:30 +0000699 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Daniel Berlinb79f5362017-02-11 12:48:50 +0000700 }
701
Davide Italiano7e274e02016-12-22 16:03:48 +0000702 return V;
703}
704
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000705MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000706 auto *CC = MemoryAccessToClass.lookup(MA);
707 if (CC && CC->RepMemoryAccess)
708 return CC->RepMemoryAccess;
709 // FIXME: We need to audit all the places that current set a nullptr To, and
710 // fix them. There should always be *some* congruence class, even if it is
711 // singular. Right now, we don't bother setting congruence classes for
712 // anything but stores, which means we have to return the original access
713 // here. Otherwise, this should be unreachable.
714 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000715}
716
Daniel Berlinc4796862017-01-27 02:37:11 +0000717// Return true if the MemoryAccess is really equivalent to everything. This is
718// equivalent to the lattice value "TOP" in most lattices. This is the initial
719// state of all memory accesses.
720bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
Daniel Berlin5c338ff2017-03-10 19:05:04 +0000721 return MemoryAccessToClass.lookup(MA) == TOPClass;
Daniel Berlinc4796862017-01-27 02:37:11 +0000722}
723
Davide Italiano7e274e02016-12-22 16:03:48 +0000724LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin97718e62017-01-31 22:32:03 +0000725 LoadInst *LI, MemoryAccess *DA) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000726 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000727 E->allocateOperands(ArgRecycler, ExpressionAllocator);
728 E->setType(LoadType);
729
730 // Give store and loads same opcode so they value number together.
731 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000732 E->op_push_back(lookupOperandLeader(PointerOp));
Davide Italiano7e274e02016-12-22 16:03:48 +0000733 if (LI)
734 E->setAlignment(LI->getAlignment());
735
736 // TODO: Value number heap versions. We may be able to discover
737 // things alias analysis can't on it's own (IE that a store and a
738 // load have the same value, and thus, it isn't clobbering the load).
739 return E;
740}
741
742const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000743 MemoryAccess *DA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000744 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000745 auto *E = new (ExpressionAllocator)
746 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000747 E->allocateOperands(ArgRecycler, ExpressionAllocator);
748 E->setType(SI->getValueOperand()->getType());
749
750 // Give store and loads same opcode so they value number together.
751 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000752 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000753
754 // TODO: Value number heap versions. We may be able to discover
755 // things alias analysis can't on it's own (IE that a store and a
756 // load have the same value, and thus, it isn't clobbering the load).
757 return E;
758}
759
Daniel Berlin97718e62017-01-31 22:32:03 +0000760const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000761 // Unlike loads, we never try to eliminate stores, so we do not check if they
762 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000763 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000764 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000765 // Get the expression, if any, for the RHS of the MemoryDef.
766 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
767 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
768 // If we are defined by ourselves, use the live on entry def.
769 if (StoreRHS == StoreAccess)
770 StoreRHS = MSSA->getLiveOnEntryDef();
771
Daniel Berlin589cecc2017-01-02 18:00:46 +0000772 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000773 // See if we are defined by a previous store expression, it already has a
774 // value, and it's the same value as our current store. FIXME: Right now, we
775 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin97718e62017-01-31 22:32:03 +0000776 const Expression *OldStore = createStoreExpression(SI, StoreRHS);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000777 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000778 // Basically, check if the congruence class the store is in is defined by a
779 // store that isn't us, and has the same value. MemorySSA takes care of
780 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000781 // The RepStoredValue gets nulled if all the stores disappear in a class, so
782 // we don't need to check if the class contains a store besides us.
Daniel Berlin808e3ff2017-01-31 22:31:56 +0000783 if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin97718e62017-01-31 22:32:03 +0000784 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +0000785 // Also check if our value operand is defined by a load of the same memory
786 // location, and the memory state is the same as it was then
787 // (otherwise, it could have been overwritten later. See test32 in
788 // transforms/DeadStoreElimination/simple.ll)
789 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000790 if ((lookupOperandLeader(LI->getPointerOperand()) ==
791 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinc4796862017-01-27 02:37:11 +0000792 (lookupMemoryAccessEquiv(
793 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
794 return createVariableExpression(LI);
795 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000796 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000797 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000798}
799
Daniel Berlin97718e62017-01-31 22:32:03 +0000800const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000801 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000802
803 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000804 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000805 if (!LI->isSimple())
806 return nullptr;
807
Daniel Berlin203f47b2017-01-31 22:31:53 +0000808 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +0000809 // Load of undef is undef.
810 if (isa<UndefValue>(LoadAddressLeader))
811 return createConstantExpression(UndefValue::get(LI->getType()));
812
813 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
814
815 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
816 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
817 Instruction *DefiningInst = MD->getMemoryInst();
818 // If the defining instruction is not reachable, replace with undef.
819 if (!ReachableBlocks.count(DefiningInst->getParent()))
820 return createConstantExpression(UndefValue::get(LI->getType()));
821 }
822 }
823
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000824 const Expression *E =
825 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000826 lookupMemoryAccessEquiv(DefiningAccess));
Davide Italiano7e274e02016-12-22 16:03:48 +0000827 return E;
828}
829
Daniel Berlinf7d95802017-02-18 23:06:50 +0000830const Expression *
831NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
832 auto *PI = PredInfo->getPredicateInfoFor(I);
833 if (!PI)
834 return nullptr;
835
836 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +0000837
838 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
839 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +0000840 return nullptr;
841
Daniel Berlinfccbda92017-02-22 22:20:58 +0000842 auto *CopyOf = I->getOperand(0);
843 auto *Cond = PWC->Condition;
844
Daniel Berlinf7d95802017-02-18 23:06:50 +0000845 // If this a copy of the condition, it must be either true or false depending
846 // on the predicate info type and edge
847 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +0000848 // We should not need to add predicate users because the predicate info is
849 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +0000850 if (isa<PredicateAssume>(PI))
851 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
852 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
853 if (PBranch->TrueEdge)
854 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
855 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
856 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000857 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
858 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000859 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000860
Daniel Berlinf7d95802017-02-18 23:06:50 +0000861 // Not a copy of the condition, so see what the predicates tell us about this
862 // value. First, though, we check to make sure the value is actually a copy
863 // of one of the condition operands. It's possible, in certain cases, for it
864 // to be a copy of a predicateinfo copy. In particular, if two branch
865 // operations use the same condition, and one branch dominates the other, we
866 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +0000867 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +0000868 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000869
870 // Everything below relies on the condition being a comparison.
871 auto *Cmp = dyn_cast<CmpInst>(Cond);
872 if (!Cmp)
873 return nullptr;
874
875 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +0000876 DEBUG(dbgs() << "Copy is not of any condition operands!");
877 return nullptr;
878 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000879 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
880 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000881 bool SwappedOps = false;
882 // Sort the ops
883 if (shouldSwapOperands(FirstOp, SecondOp)) {
884 std::swap(FirstOp, SecondOp);
885 SwappedOps = true;
886 }
Daniel Berlinf7d95802017-02-18 23:06:50 +0000887 CmpInst::Predicate Predicate =
888 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
889
890 if (isa<PredicateAssume>(PI)) {
891 // If the comparison is true when the operands are equal, then we know the
892 // operands are equal, because assumes must always be true.
893 if (CmpInst::isTrueWhenEqual(Predicate)) {
894 addPredicateUsers(PI, I);
895 return createVariableOrConstant(FirstOp);
896 }
897 }
898 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
899 // If we are *not* a copy of the comparison, we may equal to the other
900 // operand when the predicate implies something about equality of
901 // operations. In particular, if the comparison is true/false when the
902 // operands are equal, and we are on the right edge, we know this operation
903 // is equal to something.
904 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
905 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
906 addPredicateUsers(PI, I);
907 return createVariableOrConstant(FirstOp);
908 }
909 // Handle the special case of floating point.
910 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
911 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
912 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
913 addPredicateUsers(PI, I);
914 return createConstantExpression(cast<Constant>(FirstOp));
915 }
916 }
917 return nullptr;
918}
919
Davide Italiano7e274e02016-12-22 16:03:48 +0000920// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000921const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000922 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000923 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
924 // Instrinsics with the returned attribute are copies of arguments.
925 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
926 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
927 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
928 return Result;
929 return createVariableOrConstant(ReturnedValue);
930 }
931 }
932 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlin97718e62017-01-31 22:32:03 +0000933 return createCallExpression(CI, nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000934 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000935 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin97718e62017-01-31 22:32:03 +0000936 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess));
Davide Italianob2225492016-12-27 18:15:39 +0000937 }
938 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000939}
940
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000941// Update the memory access equivalence table to say that From is equal to To,
942// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000943// FIXME: We need to audit all the places that current set a nullptr To, and fix
944// them. There should always be *some* congruence class, even if it is singular.
945bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
946 DEBUG(dbgs() << "Setting " << *From);
947 if (To) {
948 DEBUG(dbgs() << " equivalent to congruence class ");
949 DEBUG(dbgs() << To->ID << " with current memory access leader ");
950 DEBUG(dbgs() << *To->RepMemoryAccess);
951 } else {
952 DEBUG(dbgs() << " equivalent to itself");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000953 }
Daniel Berlin9f376b72017-01-29 10:26:03 +0000954 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000955
956 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000957 bool Changed = false;
958 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000959 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000960 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000961 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000962 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000963 Changed = true;
964 } else if (!To) {
965 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000966 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000967 Changed = true;
968 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000969 } else {
970 assert(!To &&
971 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000972 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000973
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000974 return Changed;
975}
Davide Italiano7e274e02016-12-22 16:03:48 +0000976// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000977const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000978 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +0000979 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
980
981 // See if all arguaments are the same.
982 // We track if any were undef because they need special handling.
983 bool HasUndef = false;
984 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
985 if (Arg == I)
986 return false;
987 if (isa<UndefValue>(Arg)) {
988 HasUndef = true;
989 return false;
990 }
991 return true;
992 });
993 // If we are left with no operands, it's undef
994 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000995 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
996 << "\n");
997 E->deallocateOperands(ArgRecycler);
998 ExpressionAllocator.Deallocate(E);
999 return createConstantExpression(UndefValue::get(I->getType()));
1000 }
Daniel Berlind92e7f92017-01-07 00:01:42 +00001001 Value *AllSameValue = *(Filtered.begin());
1002 ++Filtered.begin();
1003 // Can't use std::equal here, sadly, because filter.begin moves.
1004 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
1005 return V == AllSameValue;
1006 })) {
1007 // In LLVM's non-standard representation of phi nodes, it's possible to have
1008 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1009 // on the original phi node), especially in weird CFG's where some arguments
1010 // are unreachable, or uninitialized along certain paths. This can cause
1011 // infinite loops during evaluation. We work around this by not trying to
1012 // really evaluate them independently, but instead using a variable
1013 // expression to say if one is equivalent to the other.
1014 // We also special case undef, so that if we have an undef, we can't use the
1015 // common value unless it dominates the phi block.
1016 if (HasUndef) {
1017 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001018 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001019 if (!DT->dominates(AllSameInst, I))
1020 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001021 }
1022
Davide Italiano7e274e02016-12-22 16:03:48 +00001023 NumGVNPhisAllSame++;
1024 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1025 << "\n");
1026 E->deallocateOperands(ArgRecycler);
1027 ExpressionAllocator.Deallocate(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001028 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001029 }
1030 return E;
1031}
1032
Daniel Berlin97718e62017-01-31 22:32:03 +00001033const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001034 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1035 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1036 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1037 unsigned Opcode = 0;
1038 // EI might be an extract from one of our recognised intrinsics. If it
1039 // is we'll synthesize a semantically equivalent expression instead on
1040 // an extract value expression.
1041 switch (II->getIntrinsicID()) {
1042 case Intrinsic::sadd_with_overflow:
1043 case Intrinsic::uadd_with_overflow:
1044 Opcode = Instruction::Add;
1045 break;
1046 case Intrinsic::ssub_with_overflow:
1047 case Intrinsic::usub_with_overflow:
1048 Opcode = Instruction::Sub;
1049 break;
1050 case Intrinsic::smul_with_overflow:
1051 case Intrinsic::umul_with_overflow:
1052 Opcode = Instruction::Mul;
1053 break;
1054 default:
1055 break;
1056 }
1057
1058 if (Opcode != 0) {
1059 // Intrinsic recognized. Grab its args to finish building the
1060 // expression.
1061 assert(II->getNumArgOperands() == 2 &&
1062 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001063 return createBinaryExpression(
1064 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001065 }
1066 }
1067 }
1068
Daniel Berlin97718e62017-01-31 22:32:03 +00001069 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001070}
Daniel Berlin97718e62017-01-31 22:32:03 +00001071const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001072 auto *CI = dyn_cast<CmpInst>(I);
1073 // See if our operands are equal to those of a previous predicate, and if so,
1074 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001075 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1076 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001077 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001078 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001079 std::swap(Op0, Op1);
1080 OurPredicate = CI->getSwappedPredicate();
1081 }
1082
1083 // Avoid processing the same info twice
1084 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001085 // See if we know something about the comparison itself, like it is the target
1086 // of an assume.
1087 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1088 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1089 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1090
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001091 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001092 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001093 if (CI->isTrueWhenEqual())
1094 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1095 else if (CI->isFalseWhenEqual())
1096 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1097 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001098
1099 // NOTE: Because we are comparing both operands here and below, and using
1100 // previous comparisons, we rely on fact that predicateinfo knows to mark
1101 // comparisons that use renamed operands as users of the earlier comparisons.
1102 // It is *not* enough to just mark predicateinfo renamed operands as users of
1103 // the earlier comparisons, because the *other* operand may have changed in a
1104 // previous iteration.
1105 // Example:
1106 // icmp slt %a, %b
1107 // %b.0 = ssa.copy(%b)
1108 // false branch:
1109 // icmp slt %c, %b.0
1110
1111 // %c and %a may start out equal, and thus, the code below will say the second
1112 // %icmp is false. c may become equal to something else, and in that case the
1113 // %second icmp *must* be reexamined, but would not if only the renamed
1114 // %operands are considered users of the icmp.
1115
1116 // *Currently* we only check one level of comparisons back, and only mark one
1117 // level back as touched when changes appen . If you modify this code to look
1118 // back farther through comparisons, you *must* mark the appropriate
1119 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1120 // we know something just from the operands themselves
1121
1122 // See if our operands have predicate info, so that we may be able to derive
1123 // something from a previous comparison.
1124 for (const auto &Op : CI->operands()) {
1125 auto *PI = PredInfo->getPredicateInfoFor(Op);
1126 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1127 if (PI == LastPredInfo)
1128 continue;
1129 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001130
Daniel Berlinf7d95802017-02-18 23:06:50 +00001131 // TODO: Along the false edge, we may know more things too, like icmp of
1132 // same operands is false.
1133 // TODO: We only handle actual comparison conditions below, not and/or.
1134 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1135 if (!BranchCond)
1136 continue;
1137 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1138 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1139 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001140 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001141 std::swap(BranchOp0, BranchOp1);
1142 BranchPredicate = BranchCond->getSwappedPredicate();
1143 }
1144 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1145 if (PBranch->TrueEdge) {
1146 // If we know the previous predicate is true and we are in the true
1147 // edge then we may be implied true or false.
1148 if (CmpInst::isImpliedTrueByMatchingCmp(OurPredicate,
1149 BranchPredicate)) {
1150 addPredicateUsers(PI, I);
1151 return createConstantExpression(
1152 ConstantInt::getTrue(CI->getType()));
1153 }
1154
1155 if (CmpInst::isImpliedFalseByMatchingCmp(OurPredicate,
1156 BranchPredicate)) {
1157 addPredicateUsers(PI, I);
1158 return createConstantExpression(
1159 ConstantInt::getFalse(CI->getType()));
1160 }
1161
1162 } else {
1163 // Just handle the ne and eq cases, where if we have the same
1164 // operands, we may know something.
1165 if (BranchPredicate == OurPredicate) {
1166 addPredicateUsers(PI, I);
1167 // Same predicate, same ops,we know it was false, so this is false.
1168 return createConstantExpression(
1169 ConstantInt::getFalse(CI->getType()));
1170 } else if (BranchPredicate ==
1171 CmpInst::getInversePredicate(OurPredicate)) {
1172 addPredicateUsers(PI, I);
1173 // Inverse predicate, we know the other was false, so this is true.
1174 // FIXME: Double check this
1175 return createConstantExpression(
1176 ConstantInt::getTrue(CI->getType()));
1177 }
1178 }
1179 }
1180 }
1181 }
1182 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001183 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001184}
Davide Italiano7e274e02016-12-22 16:03:48 +00001185
1186// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +00001187const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001188 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001189 if (auto *C = dyn_cast<Constant>(V))
1190 E = createConstantExpression(C);
1191 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1192 E = createVariableExpression(V);
1193 } else {
1194 // TODO: memory intrinsics.
1195 // TODO: Some day, we should do the forward propagation and reassociation
1196 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001197 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001198 switch (I->getOpcode()) {
1199 case Instruction::ExtractValue:
1200 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001201 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001202 break;
1203 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001204 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001205 break;
1206 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001207 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001208 break;
1209 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001210 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001211 break;
1212 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001213 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001214 break;
1215 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001216 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001217 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001218 case Instruction::ICmp:
1219 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001220 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001221 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001222 case Instruction::Add:
1223 case Instruction::FAdd:
1224 case Instruction::Sub:
1225 case Instruction::FSub:
1226 case Instruction::Mul:
1227 case Instruction::FMul:
1228 case Instruction::UDiv:
1229 case Instruction::SDiv:
1230 case Instruction::FDiv:
1231 case Instruction::URem:
1232 case Instruction::SRem:
1233 case Instruction::FRem:
1234 case Instruction::Shl:
1235 case Instruction::LShr:
1236 case Instruction::AShr:
1237 case Instruction::And:
1238 case Instruction::Or:
1239 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001240 case Instruction::Trunc:
1241 case Instruction::ZExt:
1242 case Instruction::SExt:
1243 case Instruction::FPToUI:
1244 case Instruction::FPToSI:
1245 case Instruction::UIToFP:
1246 case Instruction::SIToFP:
1247 case Instruction::FPTrunc:
1248 case Instruction::FPExt:
1249 case Instruction::PtrToInt:
1250 case Instruction::IntToPtr:
1251 case Instruction::Select:
1252 case Instruction::ExtractElement:
1253 case Instruction::InsertElement:
1254 case Instruction::ShuffleVector:
1255 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001256 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001257 break;
1258 default:
1259 return nullptr;
1260 }
1261 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001262 return E;
1263}
1264
Davide Italiano7e274e02016-12-22 16:03:48 +00001265void NewGVN::markUsersTouched(Value *V) {
1266 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001267 for (auto *User : V->users()) {
1268 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001269 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001270 }
1271}
1272
1273void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1274 for (auto U : MA->users()) {
1275 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001276 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001277 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001278 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001279 }
1280}
1281
Daniel Berlinf7d95802017-02-18 23:06:50 +00001282// Add I to the set of users of a given predicate.
1283void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1284 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1285 PredicateToUsers[PBranch->Condition].insert(I);
1286 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1287 PredicateToUsers[PAssume->Condition].insert(I);
1288}
1289
1290// Touch all the predicates that depend on this instruction.
1291void NewGVN::markPredicateUsersTouched(Instruction *I) {
1292 const auto Result = PredicateToUsers.find(I);
1293 if (Result != PredicateToUsers.end())
1294 for (auto *User : Result->second)
1295 TouchedInstructions.set(InstrDFS.lookup(User));
1296}
1297
Daniel Berlin32f8d562017-01-07 16:55:14 +00001298// Touch the instructions that need to be updated after a congruence class has a
1299// leader change, and mark changed values.
1300void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1301 for (auto M : CC->Members) {
1302 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001303 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001304 LeaderChanges.insert(M);
1305 }
1306}
1307
1308// Move a value, currently in OldClass, to be part of NewClass
1309// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001310void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1311 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001312 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001313 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001314 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001315
1316 if (I == OldClass->NextLeader.first)
1317 OldClass->NextLeader = {nullptr, ~0U};
1318
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001319 // It's possible, though unlikely, for us to discover equivalences such
1320 // that the current leader does not dominate the old one.
1321 // This statistic tracks how often this happens.
1322 // We assert on phi nodes when this happens, currently, for debugging, because
1323 // we want to make sure we name phi node cycles properly.
1324 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1325 I != NewClass->RepLeader &&
1326 DT->properlyDominates(
1327 I->getParent(),
1328 cast<Instruction>(NewClass->RepLeader)->getParent())) {
1329 ++NumGVNNotMostDominatingLeader;
1330 assert(!isa<PHINode>(I) &&
1331 "New class for instruction should not be dominated by instruction");
1332 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001333
1334 if (NewClass->RepLeader != I) {
1335 auto DFSNum = InstrDFS.lookup(I);
1336 if (DFSNum < NewClass->NextLeader.second)
1337 NewClass->NextLeader = {I, DFSNum};
1338 }
1339
1340 OldClass->Members.erase(I);
1341 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001342 MemoryAccess *StoreAccess = nullptr;
1343 if (auto *SI = dyn_cast<StoreInst>(I)) {
1344 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001345 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001346 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001347 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001348 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001349 if (!NewClass->RepMemoryAccess) {
1350 // If we don't have a representative memory access, it better be the only
1351 // store in there.
1352 assert(NewClass->StoreCount == 1);
1353 NewClass->RepMemoryAccess = StoreAccess;
1354 }
1355 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001356 }
1357
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001358 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001359 // See if we destroyed the class or need to swap leaders.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001360 if (OldClass->Members.empty() && OldClass != TOPClass) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001361 if (OldClass->DefiningExpr) {
1362 OldClass->Dead = true;
1363 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1364 << " from table\n");
1365 ExpressionToClass.erase(OldClass->DefiningExpr);
1366 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001367 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001368 // When the leader changes, the value numbering of
1369 // everything may change due to symbolization changes, so we need to
1370 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001371 DEBUG(dbgs() << "Leader change!\n");
1372 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001373 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001374 if (OldClass->StoreCount == 0) {
1375 if (OldClass->RepStoredValue != nullptr)
1376 OldClass->RepStoredValue = nullptr;
1377 if (OldClass->RepMemoryAccess != nullptr)
1378 OldClass->RepMemoryAccess = nullptr;
1379 }
1380
1381 // If we destroy the old access leader, we have to effectively destroy the
1382 // congruence class. When it comes to scalars, anything with the same value
1383 // is as good as any other. That means that one leader is as good as
1384 // another, and as long as you have some leader for the value, you are
1385 // good.. When it comes to *memory states*, only one particular thing really
1386 // represents the definition of a given memory state. Once it goes away, we
1387 // need to re-evaluate which pieces of memory are really still
1388 // equivalent. The best way to do this is to re-value number things. The
1389 // only way to really make that happen is to destroy the rest of the class.
1390 // In order to effectively destroy the class, we reset ExpressionToClass for
1391 // each by using the ValueToExpression mapping. The members later get
1392 // marked as touched due to the leader change. We will create new
1393 // congruence classes, and the pieces that are still equivalent will end
1394 // back together in a new class. If this becomes too expensive, it is
1395 // possible to use a versioning scheme for the congruence classes to avoid
1396 // the expressions finding this old class.
1397 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1398 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1399 << " because memory access leader changed");
1400 for (auto Member : OldClass->Members)
1401 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1402 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001403
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001404 // 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 +00001405 // sorting the TOP class because everything either gets out of it or is
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001406 // unreachable.
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001407 if (OldClass->Members.size() == 1 || OldClass == TOPClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001408 OldClass->RepLeader = *(OldClass->Members.begin());
1409 } else if (OldClass->NextLeader.first) {
1410 ++NumGVNAvoidedSortedLeaderChanges;
1411 OldClass->RepLeader = OldClass->NextLeader.first;
1412 OldClass->NextLeader = {nullptr, ~0U};
1413 } else {
1414 ++NumGVNSortedLeaderChanges;
1415 // TODO: If this ends up to slow, we can maintain a dual structure for
1416 // member testing/insertion, or keep things mostly sorted, and sort only
1417 // here, or ....
1418 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1419 for (const auto X : OldClass->Members) {
1420 auto DFSNum = InstrDFS.lookup(X);
1421 if (DFSNum < MinDFS.second)
1422 MinDFS = {X, DFSNum};
1423 }
1424 OldClass->RepLeader = MinDFS.first;
1425 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001426 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001427 }
1428}
1429
Davide Italiano7e274e02016-12-22 16:03:48 +00001430// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001431void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1432 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001433 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00001434 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001435
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001436 CongruenceClass *IClass = ValueToClass[I];
1437 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001438 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001439 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001440
1441 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001442 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001443 EClass = ValueToClass[VE->getVariableValue()];
1444 } else {
1445 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1446
1447 // If it's not in the value table, create a new congruence class.
1448 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001449 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001450 auto place = lookupResult.first;
1451 place->second = NewClass;
1452
1453 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001454 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001455 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001456 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1457 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001458 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001459 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001460 // The RepMemoryAccess field will be filled in properly by the
1461 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001462 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001463 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001464 }
1465 assert(!isa<VariableExpression>(E) &&
1466 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001467
1468 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001469 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001470 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001471 << " and leader " << *(NewClass->RepLeader));
1472 if (NewClass->RepStoredValue)
1473 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1474 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001475 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1476 } else {
1477 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001478 if (isa<ConstantExpression>(E))
1479 assert(isa<Constant>(EClass->RepLeader) &&
1480 "Any class with a constant expression should have a "
1481 "constant leader");
1482
Davide Italiano7e274e02016-12-22 16:03:48 +00001483 assert(EClass && "Somehow don't have an eclass");
1484
1485 assert(!EClass->Dead && "We accidentally looked up a dead class");
1486 }
1487 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001488 bool ClassChanged = IClass != EClass;
1489 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001490 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001491 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1492 << "\n");
1493
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001494 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001495 moveValueToNewCongruenceClass(I, IClass, EClass);
1496 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001497 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001498 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001499 if (auto *CI = dyn_cast<CmpInst>(I))
1500 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00001501 }
1502}
1503
1504// Process the fact that Edge (from, to) is reachable, including marking
1505// any newly reachable blocks and instructions for processing.
1506void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1507 // Check if the Edge was reachable before.
1508 if (ReachableEdges.insert({From, To}).second) {
1509 // If this block wasn't reachable before, all instructions are touched.
1510 if (ReachableBlocks.insert(To).second) {
1511 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1512 const auto &InstRange = BlockInstRange.lookup(To);
1513 TouchedInstructions.set(InstRange.first, InstRange.second);
1514 } else {
1515 DEBUG(dbgs() << "Block " << getBlockName(To)
1516 << " was reachable, but new edge {" << getBlockName(From)
1517 << "," << getBlockName(To) << "} to it found\n");
1518
1519 // We've made an edge reachable to an existing block, which may
1520 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1521 // they are the only thing that depend on new edges. Anything using their
1522 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001523 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001524 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001525
Davide Italiano7e274e02016-12-22 16:03:48 +00001526 auto BI = To->begin();
1527 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001528 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001529 ++BI;
1530 }
1531 }
1532 }
1533}
1534
1535// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1536// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001537Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001538 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001539 if (isa<Constant>(Result))
1540 return Result;
1541 return nullptr;
1542}
1543
1544// Process the outgoing edges of a block for reachability.
1545void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1546 // Evaluate reachability of terminator instruction.
1547 BranchInst *BR;
1548 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1549 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001550 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001551 if (!CondEvaluated) {
1552 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001553 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001554 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1555 CondEvaluated = CE->getConstantValue();
1556 }
1557 } else if (isa<ConstantInt>(Cond)) {
1558 CondEvaluated = Cond;
1559 }
1560 }
1561 ConstantInt *CI;
1562 BasicBlock *TrueSucc = BR->getSuccessor(0);
1563 BasicBlock *FalseSucc = BR->getSuccessor(1);
1564 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1565 if (CI->isOne()) {
1566 DEBUG(dbgs() << "Condition for Terminator " << *TI
1567 << " evaluated to true\n");
1568 updateReachableEdge(B, TrueSucc);
1569 } else if (CI->isZero()) {
1570 DEBUG(dbgs() << "Condition for Terminator " << *TI
1571 << " evaluated to false\n");
1572 updateReachableEdge(B, FalseSucc);
1573 }
1574 } else {
1575 updateReachableEdge(B, TrueSucc);
1576 updateReachableEdge(B, FalseSucc);
1577 }
1578 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1579 // For switches, propagate the case values into the case
1580 // destinations.
1581
1582 // Remember how many outgoing edges there are to every successor.
1583 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1584
Davide Italiano7e274e02016-12-22 16:03:48 +00001585 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001586 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001587 // See if we were able to turn this switch statement into a constant.
1588 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001589 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001590 // We should be able to get case value for this.
1591 auto CaseVal = SI->findCaseValue(CondVal);
1592 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1593 // We proved the value is outside of the range of the case.
1594 // We can't do anything other than mark the default dest as reachable,
1595 // and go home.
1596 updateReachableEdge(B, SI->getDefaultDest());
1597 return;
1598 }
1599 // Now get where it goes and mark it reachable.
1600 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1601 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001602 } else {
1603 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1604 BasicBlock *TargetBlock = SI->getSuccessor(i);
1605 ++SwitchEdges[TargetBlock];
1606 updateReachableEdge(B, TargetBlock);
1607 }
1608 }
1609 } else {
1610 // Otherwise this is either unconditional, or a type we have no
1611 // idea about. Just mark successors as reachable.
1612 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1613 BasicBlock *TargetBlock = TI->getSuccessor(i);
1614 updateReachableEdge(B, TargetBlock);
1615 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001616
1617 // This also may be a memory defining terminator, in which case, set it
1618 // equivalent to nothing.
1619 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1620 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001621 }
1622}
1623
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001624// The algorithm initially places the values of the routine in the TOP
1625// congruence class. The leader of TOP is the undetermined value `undef`.
1626// When the algorithm has finished, values still in TOP are unreachable.
Davide Italiano7e274e02016-12-22 16:03:48 +00001627void NewGVN::initializeCongruenceClasses(Function &F) {
1628 // FIXME now i can't remember why this is 2
1629 NextCongruenceNum = 2;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001630 // Initialize all other instructions to be in TOP class.
Davide Italiano7e274e02016-12-22 16:03:48 +00001631 CongruenceClass::MemberSet InitialValues;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001632 TOPClass = createCongruenceClass(nullptr, nullptr);
1633 TOPClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001634 for (auto &B : F) {
1635 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001636 MemoryAccessToClass[MP] = TOPClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001637
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001638 for (auto &I : B) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00001639 // Don't insert void terminators into the class. We don't value number
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001640 // them, and they just end up sitting in TOP.
Daniel Berlin22a4a012017-02-11 15:20:15 +00001641 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
1642 continue;
1643 InitialValues.insert(&I);
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001644 ValueToClass[&I] = TOPClass;
Daniel Berlin22a4a012017-02-11 15:20:15 +00001645
Daniel Berlin589cecc2017-01-02 18:00:46 +00001646 // All memory accesses are equivalent to live on entry to start. They must
1647 // be initialized to something so that initial changes are noticed. For
1648 // the maximal answer, we initialize them all to be the same as
1649 // liveOnEntry. Note that to save time, we only initialize the
1650 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1651 // other expression can generate a memory equivalence. If we start
1652 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001653 if (isa<StoreInst>(&I)) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001654 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = TOPClass;
1655 ++TOPClass->StoreCount;
1656 assert(TOPClass->StoreCount > 0);
Davide Italianoeac05f62017-01-11 23:41:24 +00001657 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001658 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001659 }
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001660 TOPClass->Members.swap(InitialValues);
Davide Italiano7e274e02016-12-22 16:03:48 +00001661
1662 // Initialize arguments to be in their own unique congruence classes
1663 for (auto &FA : F.args())
1664 createSingletonCongruenceClass(&FA);
1665}
1666
1667void NewGVN::cleanupTables() {
1668 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1669 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1670 << CongruenceClasses[i]->Members.size() << " members\n");
1671 // Make sure we delete the congruence class (probably worth switching to
1672 // a unique_ptr at some point.
1673 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001674 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001675 }
1676
1677 ValueToClass.clear();
1678 ArgRecycler.clear(ExpressionAllocator);
1679 ExpressionAllocator.Reset();
1680 CongruenceClasses.clear();
1681 ExpressionToClass.clear();
1682 ValueToExpression.clear();
1683 ReachableBlocks.clear();
1684 ReachableEdges.clear();
1685#ifndef NDEBUG
1686 ProcessedCount.clear();
1687#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001688 InstrDFS.clear();
1689 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001690 DFSToInstr.clear();
1691 BlockInstRange.clear();
1692 TouchedInstructions.clear();
1693 DominatedInstRange.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001694 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00001695 PredicateToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001696}
1697
1698std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1699 unsigned Start) {
1700 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001701 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1702 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001703 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001704 }
1705
Davide Italiano7e274e02016-12-22 16:03:48 +00001706 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00001707 // There's no need to call isInstructionTriviallyDead more than once on
1708 // an instruction. Therefore, once we know that an instruction is dead
1709 // we change its DFS number so that it doesn't get value numbered.
1710 if (isInstructionTriviallyDead(&I, TLI)) {
1711 InstrDFS[&I] = 0;
1712 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
1713 markInstructionForDeletion(&I);
1714 continue;
1715 }
1716
Davide Italiano7e274e02016-12-22 16:03:48 +00001717 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001718 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001719 }
1720
1721 // All of the range functions taken half-open ranges (open on the end side).
1722 // So we do not subtract one from count, because at this point it is one
1723 // greater than the last instruction.
1724 return std::make_pair(Start, End);
1725}
1726
1727void NewGVN::updateProcessedCount(Value *V) {
1728#ifndef NDEBUG
1729 if (ProcessedCount.count(V) == 0) {
1730 ProcessedCount.insert({V, 1});
1731 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001732 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001733 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001734 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001735 }
1736#endif
1737}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001738// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1739void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1740 // If all the arguments are the same, the MemoryPhi has the same value as the
1741 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001742 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlin41b39162017-03-18 15:41:36 +00001743 const BasicBlock *PHIBlock = MP->getBlock();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001744 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001745 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1746 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
Daniel Berlin41b39162017-03-18 15:41:36 +00001747 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001748 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001749 // If all that is left is nothing, our memoryphi is undef. We keep it as
1750 // InitialClass. Note: The only case this should happen is if we have at
1751 // least one self-argument.
1752 if (Filtered.begin() == Filtered.end()) {
Daniel Berlin5c338ff2017-03-10 19:05:04 +00001753 if (setMemoryAccessEquivTo(MP, TOPClass))
Daniel Berlinc4796862017-01-27 02:37:11 +00001754 markMemoryUsersTouched(MP);
1755 return;
1756 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001757
1758 // Transform the remaining operands into operand leaders.
1759 // FIXME: mapped_iterator should have a range version.
1760 auto LookupFunc = [&](const Use &U) {
1761 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1762 };
1763 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1764 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1765
1766 // and now check if all the elements are equal.
1767 // Sadly, we can't use std::equals since these are random access iterators.
1768 MemoryAccess *AllSameValue = *MappedBegin;
1769 ++MappedBegin;
1770 bool AllEqual = std::all_of(
1771 MappedBegin, MappedEnd,
1772 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1773
1774 if (AllEqual)
1775 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1776 else
1777 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1778
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001779 if (setMemoryAccessEquivTo(
1780 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001781 markMemoryUsersTouched(MP);
1782}
1783
1784// Value number a single instruction, symbolically evaluating, performing
1785// congruence finding, and updating mappings.
1786void NewGVN::valueNumberInstruction(Instruction *I) {
1787 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001788 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00001789 const Expression *Symbolized = nullptr;
1790 if (DebugCounter::shouldExecute(VNCounter)) {
1791 Symbolized = performSymbolicEvaluation(I);
1792 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00001793 // Mark the instruction as unused so we don't value number it again.
1794 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00001795 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00001796 // If we couldn't come up with a symbolic expression, use the unknown
1797 // expression
1798 if (Symbolized == nullptr)
1799 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001800 performCongruenceFinding(I, Symbolized);
1801 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001802 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00001803 // don't currently understand. We don't place non-value producing
1804 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001805 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001806 auto *Symbolized = createUnknownExpression(I);
1807 performCongruenceFinding(I, Symbolized);
1808 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001809 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1810 }
1811}
Davide Italiano7e274e02016-12-22 16:03:48 +00001812
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001813// Check if there is a path, using single or equal argument phi nodes, from
1814// First to Second.
1815bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1816 const MemoryAccess *Second) const {
1817 if (First == Second)
1818 return true;
1819
1820 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1821 auto *DefAccess = FirstDef->getDefiningAccess();
1822 return singleReachablePHIPath(DefAccess, Second);
1823 } else {
1824 auto *MP = cast<MemoryPhi>(First);
1825 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00001826 return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001827 };
1828 auto FilteredPhiArgs =
1829 make_filter_range(MP->operands(), ReachableOperandPred);
1830 SmallVector<const Value *, 32> OperandList;
1831 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1832 std::back_inserter(OperandList));
1833 bool Okay = OperandList.size() == 1;
1834 if (!Okay)
1835 Okay = std::equal(OperandList.begin(), OperandList.end(),
1836 OperandList.begin());
1837 if (Okay)
1838 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1839 return false;
1840 }
1841}
1842
Daniel Berlin589cecc2017-01-02 18:00:46 +00001843// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001844// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001845// subject to very rare false negatives. It is only useful for
1846// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001847void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001848 // Anything equivalent in the memory access table should be in the same
1849 // congruence class.
1850
1851 // Filter out the unreachable and trivially dead entries, because they may
1852 // never have been updated if the instructions were not processed.
1853 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001854 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001855 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1856 if (!Result)
1857 return false;
1858 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1859 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1860 return true;
1861 };
1862
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001863 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001864 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001865 // Unreachable instructions may not have changed because we never process
1866 // them.
1867 if (!ReachableBlocks.count(KV.first->getBlock()))
1868 continue;
1869 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001870 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001871 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001872 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001873 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1874 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1875 "The instructions for these memory operations should have "
1876 "been in the same congruence class or reachable through"
1877 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001878 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1879
1880 // We can only sanely verify that MemoryDefs in the operand list all have
1881 // the same class.
1882 auto ReachableOperandPred = [&](const Use &U) {
Daniel Berlin41b39162017-03-18 15:41:36 +00001883 return ReachableEdges.count(
1884 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00001885 isa<MemoryDef>(U);
1886
1887 };
1888 // All arguments should in the same class, ignoring unreachable arguments
1889 auto FilteredPhiArgs =
1890 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1891 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1892 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1893 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1894 const MemoryDef *MD = cast<MemoryDef>(U);
1895 return ValueToClass.lookup(MD->getMemoryInst());
1896 });
1897 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1898 PhiOpClasses.begin()) &&
1899 "All MemoryPhi arguments should be in the same class");
1900 }
1901 }
1902}
1903
Daniel Berlinf7d95802017-02-18 23:06:50 +00001904// Re-evaluate all the comparisons after value numbering and ensure they don't
1905// change. If they changed, we didn't mark them touched properly.
1906void NewGVN::verifyComparisons(Function &F) {
1907#ifndef NDEBUG
1908 for (auto &BB : F) {
1909 if (!ReachableBlocks.count(&BB))
1910 continue;
1911 for (auto &I : BB) {
Daniel Berlin343576a2017-03-06 18:42:39 +00001912 if (InstrDFS.lookup(&I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001913 continue;
1914 if (isa<CmpInst>(&I)) {
1915 auto *CurrentVal = ValueToClass.lookup(&I);
1916 valueNumberInstruction(&I);
1917 assert(CurrentVal == ValueToClass.lookup(&I) &&
1918 "Re-evaluating comparison changed value");
1919 }
1920 }
1921 }
1922#endif
1923}
1924
Daniel Berlin85f91b02016-12-26 20:06:58 +00001925// This is the main transformation entry point.
Daniel Berlin64e68992017-03-12 04:46:45 +00001926bool NewGVN::runGVN() {
Davide Italiano7e274e02016-12-22 16:03:48 +00001927 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00001928 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00001929 MSSAWalker = MSSA->getWalker();
1930
1931 // Count number of instructions for sizing of hash tables, and come
1932 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001933 unsigned ICount = 1;
1934 // Add an empty instruction to account for the fact that we start at 1
1935 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001936 // Note: We want ideal RPO traversal of the blocks, which is not quite the
1937 // same as dominator tree order, particularly with regard whether backedges
1938 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00001939 // If we visit in the wrong order, we will end up performing N times as many
1940 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001941 // The dominator tree does guarantee that, for a given dom tree node, it's
1942 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1943 // the siblings.
1944 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001945 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001946 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001947 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001948 auto *Node = DT->getNode(B);
1949 assert(Node && "RPO and Dominator tree should have same reachability");
1950 RPOOrdering[Node] = ++Counter;
1951 }
1952 // Sort dominator tree children arrays into RPO.
1953 for (auto &B : RPOT) {
1954 auto *Node = DT->getNode(B);
1955 if (Node->getChildren().size() > 1)
1956 std::sort(Node->begin(), Node->end(),
1957 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1958 return RPOOrdering[A] < RPOOrdering[B];
1959 });
1960 }
1961
1962 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1963 auto DFI = df_begin(DT->getRootNode());
1964 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1965 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001966 const auto &BlockRange = assignDFSNumbers(B, ICount);
1967 BlockInstRange.insert({B, BlockRange});
1968 ICount += BlockRange.second - BlockRange.first;
1969 }
1970
1971 // Handle forward unreachable blocks and figure out which blocks
1972 // have single preds.
1973 for (auto &B : F) {
1974 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001975 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001976 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1977 BlockInstRange.insert({&B, BlockRange});
1978 ICount += BlockRange.second - BlockRange.first;
1979 }
1980 }
1981
Daniel Berline0bd37e2016-12-29 22:15:12 +00001982 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001983 DominatedInstRange.reserve(F.size());
1984 // Ensure we don't end up resizing the expressionToClass map, as
1985 // that can be quite expensive. At most, we have one expression per
1986 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001987 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001988
1989 // Initialize the touched instructions to include the entry block.
1990 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1991 TouchedInstructions.set(InstRange.first, InstRange.second);
1992 ReachableBlocks.insert(&F.getEntryBlock());
1993
1994 initializeCongruenceClasses(F);
1995
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001996 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001997 // We start out in the entry block.
1998 BasicBlock *LastBlock = &F.getEntryBlock();
1999 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00002000 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00002001 // Walk through all the instructions in all the blocks in RPO.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002002 // TODO: As we hit a new block, we should push and pop equalities into a
2003 // table lookupOperandLeader can use, to catch things PredicateInfo
2004 // might miss, like edge-only equivalences.
Davide Italiano7e274e02016-12-22 16:03:48 +00002005 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2006 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Davide Italiano71f2d9c2017-01-20 23:29:28 +00002007
2008 // This instruction was found to be dead. We don't bother looking
2009 // at it again.
2010 if (InstrNum == 0) {
2011 TouchedInstructions.reset(InstrNum);
2012 continue;
2013 }
2014
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002015 Value *V = DFSToInstr[InstrNum];
2016 BasicBlock *CurrBlock = nullptr;
2017
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002018 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002019 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002020 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002021 CurrBlock = MP->getBlock();
2022 else
2023 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00002024
2025 // If we hit a new block, do reachability processing.
2026 if (CurrBlock != LastBlock) {
2027 LastBlock = CurrBlock;
2028 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2029 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2030
2031 // If it's not reachable, erase any touched instructions and move on.
2032 if (!BlockReachable) {
2033 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2034 DEBUG(dbgs() << "Skipping instructions in block "
2035 << getBlockName(CurrBlock)
2036 << " because it is unreachable\n");
2037 continue;
2038 }
2039 updateProcessedCount(CurrBlock);
2040 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002041
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002042 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002043 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2044 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002045 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002046 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002047 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002048 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00002049 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002050 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002051 // Reset after processing (because we may mark ourselves as touched when
2052 // we propagate equalities).
2053 TouchedInstructions.reset(InstrNum);
2054 }
2055 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00002056 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002057#ifndef NDEBUG
2058 verifyMemoryCongruency();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002059 verifyComparisons(F);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002060#endif
Daniel Berlinf7d95802017-02-18 23:06:50 +00002061
Davide Italiano7e274e02016-12-22 16:03:48 +00002062 Changed |= eliminateInstructions(F);
2063
2064 // Delete all instructions marked for deletion.
2065 for (Instruction *ToErase : InstructionsToErase) {
2066 if (!ToErase->use_empty())
2067 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2068
2069 ToErase->eraseFromParent();
2070 }
2071
2072 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002073 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2074 return !ReachableBlocks.count(&BB);
2075 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002076
2077 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2078 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002079 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002080 deleteInstructionsInBlock(&BB);
2081 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002082 }
2083
2084 cleanupTables();
2085 return Changed;
2086}
2087
Davide Italiano7e274e02016-12-22 16:03:48 +00002088// Return true if V is a value that will always be available (IE can
2089// be placed anywhere) in the function. We don't do globals here
2090// because they are often worse to put in place.
2091// TODO: Separate cost from availability
2092static bool alwaysAvailable(Value *V) {
2093 return isa<Constant>(V) || isa<Argument>(V);
2094}
2095
2096// Get the basic block from an instruction/value.
2097static BasicBlock *getBlockForValue(Value *V) {
2098 if (auto *I = dyn_cast<Instruction>(V))
2099 return I->getParent();
2100 return nullptr;
2101}
2102
2103struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002104 int DFSIn = 0;
2105 int DFSOut = 0;
2106 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002107 // Only one of Def and U will be set.
2108 Value *Def = nullptr;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002109 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002110 bool operator<(const ValueDFS &Other) const {
2111 // It's not enough that any given field be less than - we have sets
2112 // of fields that need to be evaluated together to give a proper ordering.
2113 // For example, if you have;
2114 // DFS (1, 3)
2115 // Val 0
2116 // DFS (1, 2)
2117 // Val 50
2118 // We want the second to be less than the first, but if we just go field
2119 // by field, we will get to Val 0 < Val 50 and say the first is less than
2120 // the second. We only want it to be less than if the DFS orders are equal.
2121 //
2122 // Each LLVM instruction only produces one value, and thus the lowest-level
2123 // differentiator that really matters for the stack (and what we use as as a
2124 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002125 // Everything else in the structure is instruction level, and only affects
2126 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002127 //
2128 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2129 // the order of replacement of uses does not matter.
2130 // IE given,
2131 // a = 5
2132 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002133 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2134 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002135 // The .val will be the same as well.
2136 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002137 // You will replace both, and it does not matter what order you replace them
2138 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2139 // operand 2).
2140 // Similarly for the case of same dfsin, dfsout, localnum, but different
2141 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002142 // a = 5
2143 // b = 6
2144 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002145 // in c, we will a valuedfs for a, and one for b,with everything the same
2146 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002147 // It does not matter what order we replace these operands in.
2148 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002149 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2150 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00002151 Other.U);
2152 }
2153};
2154
Daniel Berlinc4796862017-01-27 02:37:11 +00002155// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002156// to sets of defs and uses with associated DFS info. The total number of
Daniel Berline3e69e12017-03-10 00:32:33 +00002157// reachable uses for each value is stored in UseCount, and instructions that
2158// seem
2159// dead (have no non-dead uses) are stored in ProbablyDead.
2160void NewGVN::convertClassToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00002161 const CongruenceClass::MemberSet &Dense,
Daniel Berline3e69e12017-03-10 00:32:33 +00002162 SmallVectorImpl<ValueDFS> &DFSOrderedSet,
2163 DenseMap<const Value *, unsigned int> &UseCounts,
2164 SmallPtrSetImpl<Instruction *> &ProbablyDead) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002165 for (auto D : Dense) {
2166 // First add the value.
2167 BasicBlock *BB = getBlockForValue(D);
2168 // Constants are handled prior to ever calling this function, so
2169 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002170 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002171 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002172 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002173 VDDef.DFSIn = DomNode->getDFSNumIn();
2174 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00002175 // If it's a store, use the leader of the value operand.
2176 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002177 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002178 VDDef.Def = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
Daniel Berlin26addef2017-01-20 21:04:30 +00002179 } else {
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002180 VDDef.Def = D;
Daniel Berlin26addef2017-01-20 21:04:30 +00002181 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002182 assert(isa<Instruction>(D) &&
2183 "The dense set member should always be an instruction");
2184 VDDef.LocalNum = InstrDFS.lookup(D);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002185 DFSOrderedSet.emplace_back(VDDef);
Daniel Berline3e69e12017-03-10 00:32:33 +00002186 Instruction *Def = cast<Instruction>(D);
2187 unsigned int UseCount = 0;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002188 // Now add the uses.
Daniel Berline3e69e12017-03-10 00:32:33 +00002189 for (auto &U : Def->uses()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002190 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002191 // Don't try to replace into dead uses
2192 if (InstructionsToErase.count(I))
2193 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002194 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00002195 // Put the phi node uses in the incoming block.
2196 BasicBlock *IBlock;
2197 if (auto *P = dyn_cast<PHINode>(I)) {
2198 IBlock = P->getIncomingBlock(U);
2199 // Make phi node users appear last in the incoming block
2200 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002201 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00002202 } else {
2203 IBlock = I->getParent();
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002204 VDUse.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002205 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002206
2207 // Skip uses in unreachable blocks, as we're going
2208 // to delete them.
2209 if (ReachableBlocks.count(IBlock) == 0)
2210 continue;
2211
Daniel Berlinb66164c2017-01-14 00:24:23 +00002212 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002213 VDUse.DFSIn = DomNode->getDFSNumIn();
2214 VDUse.DFSOut = DomNode->getDFSNumOut();
2215 VDUse.U = &U;
Daniel Berline3e69e12017-03-10 00:32:33 +00002216 ++UseCount;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002217 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00002218 }
2219 }
Daniel Berline3e69e12017-03-10 00:32:33 +00002220
2221 // If there are no uses, it's probably dead (but it may have side-effects,
2222 // so not definitely dead. Otherwise, store the number of uses so we can
2223 // track if it becomes dead later).
2224 if (UseCount == 0)
2225 ProbablyDead.insert(Def);
2226 else
2227 UseCounts[Def] = UseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002228 }
2229}
2230
Daniel Berlinc4796862017-01-27 02:37:11 +00002231// This function converts the set of members for a congruence class from values,
2232// to the set of defs for loads and stores, with associated DFS info.
Daniel Berline3e69e12017-03-10 00:32:33 +00002233void NewGVN::convertClassToLoadsAndStores(
Daniel Berlinc4796862017-01-27 02:37:11 +00002234 const CongruenceClass::MemberSet &Dense,
2235 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2236 for (auto D : Dense) {
2237 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2238 continue;
2239
2240 BasicBlock *BB = getBlockForValue(D);
2241 ValueDFS VD;
2242 DomTreeNode *DomNode = DT->getNode(BB);
2243 VD.DFSIn = DomNode->getDFSNumIn();
2244 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002245 VD.Def = D;
Daniel Berlinc4796862017-01-27 02:37:11 +00002246
2247 // If it's an instruction, use the real local dfs number.
2248 if (auto *I = dyn_cast<Instruction>(D))
2249 VD.LocalNum = InstrDFS.lookup(I);
2250 else
2251 llvm_unreachable("Should have been an instruction");
2252
2253 LoadsAndStores.emplace_back(VD);
2254 }
2255}
2256
Davide Italiano7e274e02016-12-22 16:03:48 +00002257static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00002258 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00002259 if (!ReplInst)
2260 return;
2261
Davide Italiano7e274e02016-12-22 16:03:48 +00002262 // Patch the replacement so that it is not more restrictive than the value
2263 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00002264 // Note that if 'I' is a load being replaced by some operation,
2265 // for example, by an arithmetic operation, then andIRFlags()
2266 // would just erase all math flags from the original arithmetic
2267 // operation, which is clearly not wanted and not needed.
2268 if (!isa<LoadInst>(I))
2269 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002270
Daniel Berlin86eab152017-02-12 22:25:20 +00002271 // FIXME: If both the original and replacement value are part of the
2272 // same control-flow region (meaning that the execution of one
2273 // guarantees the execution of the other), then we can combine the
2274 // noalias scopes here and do better than the general conservative
2275 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00002276
Daniel Berlin86eab152017-02-12 22:25:20 +00002277 // In general, GVN unifies expressions over different control-flow
2278 // regions, and so we need a conservative combination of the noalias
2279 // scopes.
2280 static const unsigned KnownIDs[] = {
2281 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2282 LLVMContext::MD_noalias, LLVMContext::MD_range,
2283 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2284 LLVMContext::MD_invariant_group};
2285 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00002286}
2287
2288static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2289 patchReplacementInstruction(I, Repl);
2290 I->replaceAllUsesWith(Repl);
2291}
2292
2293void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2294 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2295 ++NumGVNBlocksDeleted;
2296
Daniel Berline19f0e02017-01-30 17:06:55 +00002297 // Delete the instructions backwards, as it has a reduced likelihood of having
2298 // to update as many def-use and use-def chains. Start after the terminator.
2299 auto StartPoint = BB->rbegin();
2300 ++StartPoint;
2301 // Note that we explicitly recalculate BB->rend() on each iteration,
2302 // as it may change when we remove the first instruction.
2303 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2304 Instruction &Inst = *I++;
2305 if (!Inst.use_empty())
2306 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2307 if (isa<LandingPadInst>(Inst))
2308 continue;
2309
2310 Inst.eraseFromParent();
2311 ++NumGVNInstrDeleted;
2312 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002313 // Now insert something that simplifycfg will turn into an unreachable.
2314 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2315 new StoreInst(UndefValue::get(Int8Ty),
2316 Constant::getNullValue(Int8Ty->getPointerTo()),
2317 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002318}
2319
2320void NewGVN::markInstructionForDeletion(Instruction *I) {
2321 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2322 InstructionsToErase.insert(I);
2323}
2324
2325void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2326
2327 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2328 patchAndReplaceAllUsesWith(I, V);
2329 // We save the actual erasing to avoid invalidating memory
2330 // dependencies until we are done with everything.
2331 markInstructionForDeletion(I);
2332}
2333
2334namespace {
2335
2336// This is a stack that contains both the value and dfs info of where
2337// that value is valid.
2338class ValueDFSStack {
2339public:
2340 Value *back() const { return ValueStack.back(); }
2341 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2342
2343 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002344 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002345 DFSStack.emplace_back(DFSIn, DFSOut);
2346 }
2347 bool empty() const { return DFSStack.empty(); }
2348 bool isInScope(int DFSIn, int DFSOut) const {
2349 if (empty())
2350 return false;
2351 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2352 }
2353
2354 void popUntilDFSScope(int DFSIn, int DFSOut) {
2355
2356 // These two should always be in sync at this point.
2357 assert(ValueStack.size() == DFSStack.size() &&
2358 "Mismatch between ValueStack and DFSStack");
2359 while (
2360 !DFSStack.empty() &&
2361 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2362 DFSStack.pop_back();
2363 ValueStack.pop_back();
2364 }
2365 }
2366
2367private:
2368 SmallVector<Value *, 8> ValueStack;
2369 SmallVector<std::pair<int, int>, 8> DFSStack;
2370};
2371}
Daniel Berlin04443432017-01-07 03:23:47 +00002372
Davide Italiano7e274e02016-12-22 16:03:48 +00002373bool NewGVN::eliminateInstructions(Function &F) {
2374 // This is a non-standard eliminator. The normal way to eliminate is
2375 // to walk the dominator tree in order, keeping track of available
2376 // values, and eliminating them. However, this is mildly
2377 // pointless. It requires doing lookups on every instruction,
2378 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002379 // instructions part of most singleton congruence classes, we know we
2380 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002381
2382 // Instead, this eliminator looks at the congruence classes directly, sorts
2383 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002384 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002385 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002386 // last member. This is worst case O(E log E) where E = number of
2387 // instructions in a single congruence class. In theory, this is all
2388 // instructions. In practice, it is much faster, as most instructions are
2389 // either in singleton congruence classes or can't possibly be eliminated
2390 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002391 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002392 // for elimination purposes.
2393 // TODO: If we wanted to be faster, We could remove any members with no
2394 // overlapping ranges while sorting, as we will never eliminate anything
2395 // with those members, as they don't dominate anything else in our set.
2396
Davide Italiano7e274e02016-12-22 16:03:48 +00002397 bool AnythingReplaced = false;
2398
2399 // Since we are going to walk the domtree anyway, and we can't guarantee the
2400 // DFS numbers are updated, we compute some ourselves.
2401 DT->updateDFSNumbers();
2402
2403 for (auto &B : F) {
2404 if (!ReachableBlocks.count(&B)) {
2405 for (const auto S : successors(&B)) {
2406 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002407 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002408 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2409 << getBlockName(&B)
2410 << " with undef due to it being unreachable\n");
2411 for (auto &Operand : Phi.incoming_values())
2412 if (Phi.getIncomingBlock(Operand) == &B)
2413 Operand.set(UndefValue::get(Phi.getType()));
2414 }
2415 }
2416 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002417 }
2418
Daniel Berline3e69e12017-03-10 00:32:33 +00002419 // Map to store the use counts
2420 DenseMap<const Value *, unsigned int> UseCounts;
Daniel Berlin4d547962017-02-12 23:24:45 +00002421 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002422 // Track the equivalent store info so we can decide whether to try
2423 // dead store elimination.
2424 SmallVector<ValueDFS, 8> PossibleDeadStores;
Daniel Berline3e69e12017-03-10 00:32:33 +00002425 SmallPtrSet<Instruction *, 8> ProbablyDead;
Daniel Berlinb79f5362017-02-11 12:48:50 +00002426 if (CC->Dead)
Davide Italiano7e274e02016-12-22 16:03:48 +00002427 continue;
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002428 // Everything still in the TOP class is unreachable or dead.
2429 if (CC == TOPClass) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00002430#ifndef NDEBUG
2431 for (auto M : CC->Members)
2432 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2433 InstructionsToErase.count(cast<Instruction>(M))) &&
Daniel Berlin5c338ff2017-03-10 19:05:04 +00002434 "Everything in TOP should be unreachable or dead at this "
Daniel Berlinb79f5362017-02-11 12:48:50 +00002435 "point");
2436#endif
2437 continue;
2438 }
2439
Davide Italiano7e274e02016-12-22 16:03:48 +00002440 assert(CC->RepLeader && "We should have had a leader");
2441
2442 // If this is a leader that is always available, and it's a
2443 // constant or has no equivalences, just replace everything with
2444 // it. We then update the congruence class with whatever members
2445 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002446 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2447 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002448 SmallPtrSet<Value *, 4> MembersLeft;
2449 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002450 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002451 // Void things have no uses we can replace.
Daniel Berline3e69e12017-03-10 00:32:33 +00002452 if (Member == Leader || Member->getType()->isVoidTy()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002453 MembersLeft.insert(Member);
2454 continue;
2455 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002456 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2457 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002458 // Due to equality propagation, these may not always be
2459 // instructions, they may be real values. We don't really
2460 // care about trying to replace the non-instructions.
2461 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002462 assert(Leader != I && "About to accidentally remove our leader");
2463 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002464 AnythingReplaced = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002465 continue;
2466 } else {
2467 MembersLeft.insert(I);
2468 }
2469 }
2470 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002471 } else {
2472 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2473 // If this is a singleton, we can skip it.
2474 if (CC->Members.size() != 1) {
2475
2476 // This is a stack because equality replacement/etc may place
2477 // constants in the middle of the member list, and we want to use
2478 // those constant values in preference to the current leader, over
2479 // the scope of those constants.
2480 ValueDFSStack EliminationStack;
2481
2482 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002483 SmallVector<ValueDFS, 8> DFSOrderedSet;
Daniel Berline3e69e12017-03-10 00:32:33 +00002484 convertClassToDFSOrdered(CC->Members, DFSOrderedSet, UseCounts,
2485 ProbablyDead);
Davide Italiano7e274e02016-12-22 16:03:48 +00002486
2487 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002488 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002489 for (auto &VD : DFSOrderedSet) {
2490 int MemberDFSIn = VD.DFSIn;
2491 int MemberDFSOut = VD.DFSOut;
Daniel Berline3e69e12017-03-10 00:32:33 +00002492 Value *Def = VD.Def;
2493 Use *U = VD.U;
Daniel Berlinc4796862017-01-27 02:37:11 +00002494 // We ignore void things because we can't get a value from them.
Daniel Berline3e69e12017-03-10 00:32:33 +00002495 if (Def && Def->getType()->isVoidTy())
Daniel Berlinc4796862017-01-27 02:37:11 +00002496 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002497
2498 if (EliminationStack.empty()) {
2499 DEBUG(dbgs() << "Elimination Stack is empty\n");
2500 } else {
2501 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2502 << EliminationStack.dfs_back().first << ","
2503 << EliminationStack.dfs_back().second << ")\n");
2504 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002505
2506 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2507 << MemberDFSOut << ")\n");
2508 // First, we see if we are out of scope or empty. If so,
2509 // and there equivalences, we try to replace the top of
2510 // stack with equivalences (if it's on the stack, it must
2511 // not have been eliminated yet).
2512 // Then we synchronize to our current scope, by
2513 // popping until we are back within a DFS scope that
2514 // dominates the current member.
2515 // Then, what happens depends on a few factors
2516 // If the stack is now empty, we need to push
2517 // If we have a constant or a local equivalence we want to
2518 // start using, we also push.
2519 // Otherwise, we walk along, processing members who are
2520 // dominated by this scope, and eliminate them.
Daniel Berline3e69e12017-03-10 00:32:33 +00002521 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002522 bool OutOfScope =
2523 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2524
2525 if (OutOfScope || ShouldPush) {
2526 // Sync to our current scope.
2527 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berline3e69e12017-03-10 00:32:33 +00002528 bool ShouldPush = Def && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002529 if (ShouldPush) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002530 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
Davide Italiano7e274e02016-12-22 16:03:48 +00002531 }
2532 }
2533
Daniel Berline3e69e12017-03-10 00:32:33 +00002534 // Skip the Def's, we only want to eliminate on their uses. But mark
2535 // dominated defs as dead.
2536 if (Def) {
2537 // For anything in this case, what and how we value number
2538 // guarantees that any side-effets that would have occurred (ie
2539 // throwing, etc) can be proven to either still occur (because it's
2540 // dominated by something that has the same side-effects), or never
2541 // occur. Otherwise, we would not have been able to prove it value
2542 // equivalent to something else. For these things, we can just mark
2543 // it all dead. Note that this is different from the "ProbablyDead"
2544 // set, which may not be dominated by anything, and thus, are only
2545 // easy to prove dead if they are also side-effect free.
2546 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
2547 isa<Instruction>(Def))
2548 markInstructionForDeletion(cast<Instruction>(Def));
2549 continue;
2550 }
2551 // At this point, we know it is a Use we are trying to possibly
2552 // replace.
2553
2554 assert(isa<Instruction>(U->get()) &&
2555 "Current def should have been an instruction");
2556 assert(isa<Instruction>(U->getUser()) &&
2557 "Current user should have been an instruction");
2558
2559 // If the thing we are replacing into is already marked to be dead,
2560 // this use is dead. Note that this is true regardless of whether
2561 // we have anything dominating the use or not. We do this here
2562 // because we are already walking all the uses anyway.
2563 Instruction *InstUse = cast<Instruction>(U->getUser());
2564 if (InstructionsToErase.count(InstUse)) {
2565 auto &UseCount = UseCounts[U->get()];
2566 if (--UseCount == 0) {
2567 ProbablyDead.insert(cast<Instruction>(U->get()));
2568 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002569 }
2570
Davide Italiano7e274e02016-12-22 16:03:48 +00002571 // If we get to this point, and the stack is empty we must have a use
Daniel Berline3e69e12017-03-10 00:32:33 +00002572 // with nothing we can use to eliminate this use, so just skip it.
Davide Italiano7e274e02016-12-22 16:03:48 +00002573 if (EliminationStack.empty())
2574 continue;
2575
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002576 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00002577
Daniel Berlind92e7f92017-01-07 00:01:42 +00002578 // Don't replace our existing users with ourselves.
Daniel Berline3e69e12017-03-10 00:32:33 +00002579 if (U->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00002580 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002581 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Daniel Berline3e69e12017-03-10 00:32:33 +00002582 << *U->get() << " in " << *(U->getUser()) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002583
2584 // If we replaced something in an instruction, handle the patching of
Daniel Berline3e69e12017-03-10 00:32:33 +00002585 // metadata. Skip this if we are replacing predicateinfo with its
2586 // original operand, as we already know we can just drop it.
2587 auto *ReplacedInst = cast<Instruction>(U->get());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002588 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
2589 if (!PI || DominatingLeader != PI->OriginalOp)
2590 patchReplacementInstruction(ReplacedInst, DominatingLeader);
Daniel Berline3e69e12017-03-10 00:32:33 +00002591 U->set(DominatingLeader);
2592 // This is now a use of the dominating leader, which means if the
2593 // dominating leader was dead, it's now live!
2594 auto &LeaderUseCount = UseCounts[DominatingLeader];
2595 // It's about to be alive again.
2596 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
2597 ProbablyDead.erase(cast<Instruction>(DominatingLeader));
2598 ++LeaderUseCount;
Davide Italiano7e274e02016-12-22 16:03:48 +00002599 AnythingReplaced = true;
2600 }
2601 }
2602 }
2603
Daniel Berline3e69e12017-03-10 00:32:33 +00002604 // At this point, anything still in the ProbablyDead set is actually dead if
2605 // would be trivially dead.
2606 for (auto *I : ProbablyDead)
2607 if (wouldInstructionBeTriviallyDead(I))
2608 markInstructionForDeletion(I);
2609
Davide Italiano7e274e02016-12-22 16:03:48 +00002610 // Cleanup the congruence class.
2611 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002612 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002613 if (Member->getType()->isVoidTy()) {
2614 MembersLeft.insert(Member);
2615 continue;
2616 }
2617
Davide Italiano7e274e02016-12-22 16:03:48 +00002618 MembersLeft.insert(Member);
2619 }
2620 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002621
2622 // If we have possible dead stores to look at, try to eliminate them.
2623 if (CC->StoreCount > 0) {
Daniel Berline3e69e12017-03-10 00:32:33 +00002624 convertClassToLoadsAndStores(CC->Members, PossibleDeadStores);
Daniel Berlinc4796862017-01-27 02:37:11 +00002625 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2626 ValueDFSStack EliminationStack;
2627 for (auto &VD : PossibleDeadStores) {
2628 int MemberDFSIn = VD.DFSIn;
2629 int MemberDFSOut = VD.DFSOut;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002630 Instruction *Member = cast<Instruction>(VD.Def);
Daniel Berlinc4796862017-01-27 02:37:11 +00002631 if (EliminationStack.empty() ||
2632 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2633 // Sync to our current scope.
2634 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2635 if (EliminationStack.empty()) {
2636 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2637 continue;
2638 }
2639 }
2640 // We already did load elimination, so nothing to do here.
2641 if (isa<LoadInst>(Member))
2642 continue;
2643 assert(!EliminationStack.empty());
2644 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002645 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002646 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2647 // Member is dominater by Leader, and thus dead
2648 DEBUG(dbgs() << "Marking dead store " << *Member
2649 << " that is dominated by " << *Leader << "\n");
2650 markInstructionForDeletion(Member);
2651 CC->Members.erase(Member);
2652 ++NumGVNDeadStores;
2653 }
2654 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002655 }
2656
2657 return AnythingReplaced;
2658}
Daniel Berlin1c087672017-02-11 15:07:01 +00002659
2660// This function provides global ranking of operations so that we can place them
2661// in a canonical order. Note that rank alone is not necessarily enough for a
2662// complete ordering, as constants all have the same rank. However, generally,
2663// we will simplify an operation with all constants so that it doesn't matter
2664// what order they appear in.
2665unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002666 // Prefer undef to anything else
2667 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00002668 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002669 if (isa<Constant>(V))
2670 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00002671 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002672 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00002673
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002674 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00002675 // the constant and argument ranking above.
2676 unsigned Result = InstrDFS.lookup(V);
2677 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002678 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00002679 // Unreachable or something else, just return a really large number.
2680 return ~0;
2681}
2682
2683// This is a function that says whether two commutative operations should
2684// have their order swapped when canonicalizing.
2685bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
2686 // Because we only care about a total ordering, and don't rewrite expressions
2687 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002688 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002689 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00002690}
Daniel Berlin64e68992017-03-12 04:46:45 +00002691
2692class NewGVNLegacyPass : public FunctionPass {
2693public:
2694 static char ID; // Pass identification, replacement for typeid.
2695 NewGVNLegacyPass() : FunctionPass(ID) {
2696 initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
2697 }
2698 bool runOnFunction(Function &F) override;
2699
2700private:
2701 void getAnalysisUsage(AnalysisUsage &AU) const override {
2702 AU.addRequired<AssumptionCacheTracker>();
2703 AU.addRequired<DominatorTreeWrapperPass>();
2704 AU.addRequired<TargetLibraryInfoWrapperPass>();
2705 AU.addRequired<MemorySSAWrapperPass>();
2706 AU.addRequired<AAResultsWrapperPass>();
2707 AU.addPreserved<DominatorTreeWrapperPass>();
2708 AU.addPreserved<GlobalsAAWrapperPass>();
2709 }
2710};
2711
2712bool NewGVNLegacyPass::runOnFunction(Function &F) {
2713 if (skipFunction(F))
2714 return false;
2715 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2716 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2717 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2718 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
2719 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
2720 F.getParent()->getDataLayout())
2721 .runGVN();
2722}
2723
2724INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
2725 false, false)
2726INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2727INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2728INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2729INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2730INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2731INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2732INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
2733 false)
2734
2735char NewGVNLegacyPass::ID = 0;
2736
2737// createGVNPass - The public interface to this file.
2738FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
2739
2740PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
2741 // Apparently the order in which we get these results matter for
2742 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
2743 // the same order here, just in case.
2744 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2745 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2746 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2747 auto &AA = AM.getResult<AAManager>(F);
2748 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2749 bool Changed =
2750 NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
2751 .runGVN();
2752 if (!Changed)
2753 return PreservedAnalyses::all();
2754 PreservedAnalyses PA;
2755 PA.preserve<DominatorTreeAnalysis>();
2756 PA.preserve<GlobalsAA>();
2757 return PA;
2758}