blob: 259a4eade0dbe06def558ee423ab16046ae0fe50 [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"
64#include "llvm/Analysis/Loads.h"
65#include "llvm/Analysis/MemoryBuiltins.h"
66#include "llvm/Analysis/MemoryDependenceAnalysis.h"
67#include "llvm/Analysis/MemoryLocation.h"
68#include "llvm/Analysis/PHITransAddr.h"
69#include "llvm/Analysis/TargetLibraryInfo.h"
70#include "llvm/Analysis/ValueTracking.h"
71#include "llvm/IR/DataLayout.h"
72#include "llvm/IR/Dominators.h"
73#include "llvm/IR/GlobalVariable.h"
74#include "llvm/IR/IRBuilder.h"
75#include "llvm/IR/IntrinsicInst.h"
76#include "llvm/IR/LLVMContext.h"
77#include "llvm/IR/Metadata.h"
78#include "llvm/IR/PatternMatch.h"
79#include "llvm/IR/PredIteratorCache.h"
80#include "llvm/IR/Type.h"
81#include "llvm/Support/Allocator.h"
82#include "llvm/Support/CommandLine.h"
83#include "llvm/Support/Debug.h"
84#include "llvm/Transforms/Scalar.h"
85#include "llvm/Transforms/Scalar/GVNExpression.h"
86#include "llvm/Transforms/Utils/BasicBlockUtils.h"
87#include "llvm/Transforms/Utils/Local.h"
88#include "llvm/Transforms/Utils/MemorySSA.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000089#include <unordered_map>
90#include <utility>
91#include <vector>
92using namespace llvm;
93using namespace PatternMatch;
94using namespace llvm::GVNExpression;
95
96#define DEBUG_TYPE "newgvn"
97
98STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
99STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
100STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
101STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +0000102STATISTIC(NumGVNMaxIterations,
103 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000104STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
105STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
106STATISTIC(NumGVNAvoidedSortedLeaderChanges,
107 "Number of avoided sorted leader changes");
Daniel Berlin89fea6f2017-01-20 06:38:41 +0000108STATISTIC(NumGVNNotMostDominatingLeader,
109 "Number of times a member dominated it's new classes' leader");
Daniel Berlinc4796862017-01-27 02:37:11 +0000110STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Davide Italiano7e274e02016-12-22 16:03:48 +0000111
112//===----------------------------------------------------------------------===//
113// GVN Pass
114//===----------------------------------------------------------------------===//
115
116// Anchor methods.
117namespace llvm {
118namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000119Expression::~Expression() = default;
120BasicExpression::~BasicExpression() = default;
121CallExpression::~CallExpression() = default;
122LoadExpression::~LoadExpression() = default;
123StoreExpression::~StoreExpression() = default;
124AggregateValueExpression::~AggregateValueExpression() = default;
125PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000126}
127}
128
129// Congruence classes represent the set of expressions/instructions
130// that are all the same *during some scope in the function*.
131// That is, because of the way we perform equality propagation, and
132// because of memory value numbering, it is not correct to assume
133// you can willy-nilly replace any member with any other at any
134// point in the function.
135//
136// For any Value in the Member set, it is valid to replace any dominated member
137// with that Value.
138//
139// Every congruence class has a leader, and the leader is used to
140// symbolize instructions in a canonical way (IE every operand of an
141// instruction that is a member of the same congruence class will
142// always be replaced with leader during symbolization).
143// To simplify symbolization, we keep the leader as a constant if class can be
144// proved to be a constant value.
145// Otherwise, the leader is a randomly chosen member of the value set, it does
146// not matter which one is chosen.
147// Each congruence class also has a defining expression,
148// though the expression may be null. If it exists, it can be used for forward
149// propagation and reassociation of values.
150//
151struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000152 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000153 unsigned ID;
154 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000155 Value *RepLeader = nullptr;
Daniel Berlin26addef2017-01-20 21:04:30 +0000156 // If this is represented by a store, the value.
157 Value *RepStoredValue = nullptr;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000158 // If this class contains MemoryDefs, what is the represented memory state.
159 MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000160 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000161 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000162 // Actual members of this class.
163 MemberSet Members;
164
165 // True if this class has no members left. This is mainly used for assertion
166 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000167 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000168
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000169 // Number of stores in this congruence class.
170 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000171 int StoreCount = 0;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000172
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000173 // The most dominating leader after our current leader, because the member set
174 // is not sorted and is expensive to keep sorted all the time.
175 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
176
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000177 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000178 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000179 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000180};
181
182namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000183template <> struct DenseMapInfo<const Expression *> {
184 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000185 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000186 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
187 return reinterpret_cast<const Expression *>(Val);
188 }
189 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000190 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000191 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
192 return reinterpret_cast<const Expression *>(Val);
193 }
194 static unsigned getHashValue(const Expression *V) {
195 return static_cast<unsigned>(V->getHashValue());
196 }
197 static bool isEqual(const Expression *LHS, const Expression *RHS) {
198 if (LHS == RHS)
199 return true;
200 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
201 LHS == getEmptyKey() || RHS == getEmptyKey())
202 return false;
203 return *LHS == *RHS;
204 }
205};
Davide Italiano7e274e02016-12-22 16:03:48 +0000206} // end namespace llvm
207
208class NewGVN : public FunctionPass {
209 DominatorTree *DT;
210 const DataLayout *DL;
211 const TargetLibraryInfo *TLI;
212 AssumptionCache *AC;
213 AliasAnalysis *AA;
214 MemorySSA *MSSA;
215 MemorySSAWalker *MSSAWalker;
216 BumpPtrAllocator ExpressionAllocator;
217 ArrayRecycler<Value *> ArgRecycler;
218
219 // Congruence class info.
220 CongruenceClass *InitialClass;
221 std::vector<CongruenceClass *> CongruenceClasses;
222 unsigned NextCongruenceNum;
223
224 // Value Mappings.
225 DenseMap<Value *, CongruenceClass *> ValueToClass;
226 DenseMap<Value *, const Expression *> ValueToExpression;
227
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000228 // A table storing which memorydefs/phis represent a memory state provably
229 // equivalent to another memory state.
230 // We could use the congruence class machinery, but the MemoryAccess's are
231 // abstract memory states, so they can only ever be equivalent to each other,
232 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000233 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000234
Davide Italiano7e274e02016-12-22 16:03:48 +0000235 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000236 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000237 ExpressionClassMap ExpressionToClass;
238
239 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000240 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000241
242 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000243 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000244 DenseSet<BlockEdge> ReachableEdges;
245 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
246
247 // This is a bitvector because, on larger functions, we may have
248 // thousands of touched instructions at once (entire blocks,
249 // instructions with hundreds of uses, etc). Even with optimization
250 // for when we mark whole blocks as touched, when this was a
251 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
252 // the time in GVN just managing this list. The bitvector, on the
253 // other hand, efficiently supports test/set/clear of both
254 // individual and ranges, as well as "find next element" This
255 // enables us to use it as a worklist with essentially 0 cost.
256 BitVector TouchedInstructions;
257
258 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
259 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
260 DominatedInstRange;
261
262#ifndef NDEBUG
263 // Debugging for how many times each block and instruction got processed.
264 DenseMap<const Value *, unsigned> ProcessedCount;
265#endif
266
267 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000268 // This contains a mapping from Instructions to DFS numbers.
269 // The numbering starts at 1. An instruction with DFS number zero
270 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000271 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000272
273 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000274 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000275
276 // Deletion info.
277 SmallPtrSet<Instruction *, 8> InstructionsToErase;
278
279public:
280 static char ID; // Pass identification, replacement for typeid.
281 NewGVN() : FunctionPass(ID) {
282 initializeNewGVNPass(*PassRegistry::getPassRegistry());
283 }
284
285 bool runOnFunction(Function &F) override;
286 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000287 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000288
289private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000290 void getAnalysisUsage(AnalysisUsage &AU) const override {
291 AU.addRequired<AssumptionCacheTracker>();
292 AU.addRequired<DominatorTreeWrapperPass>();
293 AU.addRequired<TargetLibraryInfoWrapperPass>();
294 AU.addRequired<MemorySSAWrapperPass>();
295 AU.addRequired<AAResultsWrapperPass>();
296
297 AU.addPreserved<DominatorTreeWrapperPass>();
298 AU.addPreserved<GlobalsAAWrapperPass>();
299 }
300
301 // Expression handling.
302 const Expression *createExpression(Instruction *, const BasicBlock *);
303 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
304 const BasicBlock *);
305 PHIExpression *createPHIExpression(Instruction *);
306 const VariableExpression *createVariableExpression(Value *);
307 const ConstantExpression *createConstantExpression(Constant *);
308 const Expression *createVariableOrConstant(Value *V, const BasicBlock *B);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000309 const UnknownExpression *createUnknownExpression(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000310 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
311 const BasicBlock *);
312 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
313 MemoryAccess *, const BasicBlock *);
314
315 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
316 const BasicBlock *);
317 const AggregateValueExpression *
318 createAggregateValueExpression(Instruction *, const BasicBlock *);
319 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
320 const BasicBlock *);
321
322 // Congruence class handling.
323 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000324 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000325 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000326 return result;
327 }
328
329 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000330 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000331 CClass->Members.insert(Member);
332 ValueToClass[Member] = CClass;
333 return CClass;
334 }
335 void initializeCongruenceClasses(Function &F);
336
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000337 // Value number an Instruction or MemoryPhi.
338 void valueNumberMemoryPhi(MemoryPhi *);
339 void valueNumberInstruction(Instruction *);
340
Davide Italiano7e274e02016-12-22 16:03:48 +0000341 // Symbolic evaluation.
342 const Expression *checkSimplificationResults(Expression *, Instruction *,
343 Value *);
344 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
345 const Expression *performSymbolicLoadEvaluation(Instruction *,
346 const BasicBlock *);
347 const Expression *performSymbolicStoreEvaluation(Instruction *,
348 const BasicBlock *);
349 const Expression *performSymbolicCallEvaluation(Instruction *,
350 const BasicBlock *);
351 const Expression *performSymbolicPHIEvaluation(Instruction *,
352 const BasicBlock *);
353 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
354 const BasicBlock *);
355
356 // Congruence finding.
357 // Templated to allow them to work both on BB's and BB-edges.
358 template <class T>
359 Value *lookupOperandLeader(Value *, const User *, const T &) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000360 void performCongruenceFinding(Instruction *, const Expression *);
361 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000362 CongruenceClass *);
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000363 bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
364 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000365 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000366
Davide Italiano7e274e02016-12-22 16:03:48 +0000367 // Reachability handling.
368 void updateReachableEdge(BasicBlock *, BasicBlock *);
369 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000370 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000371 Value *findConditionEquivalence(Value *, BasicBlock *) const;
372
373 // Elimination.
374 struct ValueDFS;
Daniel Berlinc4796862017-01-27 02:37:11 +0000375 void convertDenseToDFSOrdered(const CongruenceClass::MemberSet &,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +0000376 SmallVectorImpl<ValueDFS> &);
Daniel Berlinc4796862017-01-27 02:37:11 +0000377 void convertDenseToLoadsAndStores(const CongruenceClass::MemberSet &,
378 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000379
380 bool eliminateInstructions(Function &);
381 void replaceInstruction(Instruction *, Value *);
382 void markInstructionForDeletion(Instruction *);
383 void deleteInstructionsInBlock(BasicBlock *);
384
385 // New instruction creation.
386 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000387
388 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000389 void markUsersTouched(Value *);
390 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000391 void markLeaderChangeTouched(CongruenceClass *CC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000392
393 // Utilities.
394 void cleanupTables();
395 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
396 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000397 void verifyMemoryCongruency() const;
398 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000399};
400
401char NewGVN::ID = 0;
402
403// createGVNPass - The public interface to this file.
404FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
405
Davide Italianob1114092016-12-28 13:37:17 +0000406template <typename T>
407static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
408 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000409 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000410 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000411 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000412 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000413 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000414 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000415 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000416 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000417 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000418 return true;
419}
420
Davide Italianob1114092016-12-28 13:37:17 +0000421bool LoadExpression::equals(const Expression &Other) const {
422 return equalsLoadStoreHelper(*this, Other);
423}
Davide Italiano7e274e02016-12-22 16:03:48 +0000424
Davide Italianob1114092016-12-28 13:37:17 +0000425bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000426 bool Result = equalsLoadStoreHelper(*this, Other);
427 // Make sure that store vs store includes the value operand.
428 if (Result)
429 if (const auto *S = dyn_cast<StoreExpression>(&Other))
430 if (getStoredValue() != S->getStoredValue())
431 return false;
432 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000433}
434
435#ifndef NDEBUG
436static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000437 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000438}
439#endif
440
441INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
442INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
443INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
444INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
445INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
446INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
447INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
448INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
449
450PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000451 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000452 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000453 auto *E =
454 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000455
456 E->allocateOperands(ArgRecycler, ExpressionAllocator);
457 E->setType(I->getType());
458 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000459
Davide Italianob3886dd2017-01-25 23:37:49 +0000460 // Filter out unreachable phi operands.
461 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000462 return ReachableBlocks.count(PN->getIncomingBlock(U));
Davide Italianob3886dd2017-01-25 23:37:49 +0000463 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000464
465 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
466 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000467 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000468 if (U == PN)
469 return PN;
Daniel Berlind92e7f92017-01-07 00:01:42 +0000470 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PHIBlock);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000471 return lookupOperandLeader(U, I, BBE);
472 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000473 return E;
474}
475
476// Set basic expression info (Arguments, type, opcode) for Expression
477// E from Instruction I in block B.
478bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
479 const BasicBlock *B) {
480 bool AllConstant = true;
481 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
482 E->setType(GEP->getSourceElementType());
483 else
484 E->setType(I->getType());
485 E->setOpcode(I->getOpcode());
486 E->allocateOperands(ArgRecycler, ExpressionAllocator);
487
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000488 // Transform the operand array into an operand leader array, and keep track of
489 // whether all members are constant.
490 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000491 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000492 AllConstant &= isa<Constant>(Operand);
493 return Operand;
494 });
495
Davide Italiano7e274e02016-12-22 16:03:48 +0000496 return AllConstant;
497}
498
499const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
500 Value *Arg1, Value *Arg2,
501 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000502 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000503
504 E->setType(T);
505 E->setOpcode(Opcode);
506 E->allocateOperands(ArgRecycler, ExpressionAllocator);
507 if (Instruction::isCommutative(Opcode)) {
508 // Ensure that commutative instructions that only differ by a permutation
509 // of their operands get the same value number by sorting the operand value
510 // numbers. Since all commutative instructions have two operands it is more
511 // efficient to sort by hand rather than using, say, std::sort.
512 if (Arg1 > Arg2)
513 std::swap(Arg1, Arg2);
514 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000515 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
516 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000517
518 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
519 DT, AC);
520 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
521 return SimplifiedE;
522 return E;
523}
524
525// Take a Value returned by simplification of Expression E/Instruction
526// I, and see if it resulted in a simpler expression. If so, return
527// that expression.
528// TODO: Once finished, this should not take an Instruction, we only
529// use it for printing.
530const Expression *NewGVN::checkSimplificationResults(Expression *E,
531 Instruction *I, Value *V) {
532 if (!V)
533 return nullptr;
534 if (auto *C = dyn_cast<Constant>(V)) {
535 if (I)
536 DEBUG(dbgs() << "Simplified " << *I << " to "
537 << " constant " << *C << "\n");
538 NumGVNOpsSimplified++;
539 assert(isa<BasicExpression>(E) &&
540 "We should always have had a basic expression here");
541
542 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
543 ExpressionAllocator.Deallocate(E);
544 return createConstantExpression(C);
545 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
546 if (I)
547 DEBUG(dbgs() << "Simplified " << *I << " to "
548 << " variable " << *V << "\n");
549 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
550 ExpressionAllocator.Deallocate(E);
551 return createVariableExpression(V);
552 }
553
554 CongruenceClass *CC = ValueToClass.lookup(V);
555 if (CC && CC->DefiningExpr) {
556 if (I)
557 DEBUG(dbgs() << "Simplified " << *I << " to "
558 << " expression " << *V << "\n");
559 NumGVNOpsSimplified++;
560 assert(isa<BasicExpression>(E) &&
561 "We should always have had a basic expression here");
562 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
563 ExpressionAllocator.Deallocate(E);
564 return CC->DefiningExpr;
565 }
566 return nullptr;
567}
568
569const Expression *NewGVN::createExpression(Instruction *I,
570 const BasicBlock *B) {
571
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000572 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000573
574 bool AllConstant = setBasicExpressionInfo(I, E, B);
575
576 if (I->isCommutative()) {
577 // Ensure that commutative instructions that only differ by a permutation
578 // of their operands get the same value number by sorting the operand value
579 // numbers. Since all commutative instructions have two operands it is more
580 // efficient to sort by hand rather than using, say, std::sort.
581 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
582 if (E->getOperand(0) > E->getOperand(1))
583 E->swapOperands(0, 1);
584 }
585
586 // Perform simplificaiton
587 // TODO: Right now we only check to see if we get a constant result.
588 // We may get a less than constant, but still better, result for
589 // some operations.
590 // IE
591 // add 0, x -> x
592 // and x, x -> x
593 // We should handle this by simply rewriting the expression.
594 if (auto *CI = dyn_cast<CmpInst>(I)) {
595 // Sort the operand value numbers so x<y and y>x get the same value
596 // number.
597 CmpInst::Predicate Predicate = CI->getPredicate();
598 if (E->getOperand(0) > E->getOperand(1)) {
599 E->swapOperands(0, 1);
600 Predicate = CmpInst::getSwappedPredicate(Predicate);
601 }
602 E->setOpcode((CI->getOpcode() << 8) | Predicate);
603 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
604 // TODO: Since we noop bitcasts, we may need to check types before
605 // simplifying, so that we don't end up simplifying based on a wrong
606 // type assumption. We should clean this up so we can use constants of the
607 // wrong type
608
609 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
610 "Wrong types on cmp instruction");
611 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
612 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
613 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
614 *DL, TLI, DT, AC);
615 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
616 return SimplifiedE;
617 }
618 } else if (isa<SelectInst>(I)) {
619 if (isa<Constant>(E->getOperand(0)) ||
620 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
621 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
622 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
623 E->getOperand(2), *DL, TLI, DT, AC);
624 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
625 return SimplifiedE;
626 }
627 } else if (I->isBinaryOp()) {
628 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
629 *DL, TLI, DT, AC);
630 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
631 return SimplifiedE;
632 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
633 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
634 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
635 return SimplifiedE;
636 } else if (isa<GetElementPtrInst>(I)) {
637 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000638 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000639 *DL, TLI, DT, AC);
640 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
641 return SimplifiedE;
642 } else if (AllConstant) {
643 // We don't bother trying to simplify unless all of the operands
644 // were constant.
645 // TODO: There are a lot of Simplify*'s we could call here, if we
646 // wanted to. The original motivating case for this code was a
647 // zext i1 false to i8, which we don't have an interface to
648 // simplify (IE there is no SimplifyZExt).
649
650 SmallVector<Constant *, 8> C;
651 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000652 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000653
654 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
655 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
656 return SimplifiedE;
657 }
658 return E;
659}
660
661const AggregateValueExpression *
662NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
663 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000664 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000665 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
666 setBasicExpressionInfo(I, E, B);
667 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000668 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000669 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000670 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000671 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000672 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
673 setBasicExpressionInfo(EI, E, B);
674 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000675 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000676 return E;
677 }
678 llvm_unreachable("Unhandled type of aggregate value operation");
679}
680
Daniel Berlin85f91b02016-12-26 20:06:58 +0000681const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000682 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000683 E->setOpcode(V->getValueID());
684 return E;
685}
686
687const Expression *NewGVN::createVariableOrConstant(Value *V,
688 const BasicBlock *B) {
689 auto Leader = lookupOperandLeader(V, nullptr, B);
690 if (auto *C = dyn_cast<Constant>(Leader))
691 return createConstantExpression(C);
692 return createVariableExpression(Leader);
693}
694
Daniel Berlin85f91b02016-12-26 20:06:58 +0000695const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000696 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000697 E->setOpcode(C->getValueID());
698 return E;
699}
700
Daniel Berlin02c6b172017-01-02 18:00:53 +0000701const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
702 auto *E = new (ExpressionAllocator) UnknownExpression(I);
703 E->setOpcode(I->getOpcode());
704 return E;
705}
706
Davide Italiano7e274e02016-12-22 16:03:48 +0000707const CallExpression *NewGVN::createCallExpression(CallInst *CI,
708 MemoryAccess *HV,
709 const BasicBlock *B) {
710 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000711 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000712 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
713 setBasicExpressionInfo(CI, E, B);
714 return E;
715}
716
717// See if we have a congruence class and leader for this operand, and if so,
718// return it. Otherwise, return the operand itself.
719template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000720Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000721 CongruenceClass *CC = ValueToClass.lookup(V);
722 if (CC && (CC != InitialClass))
Daniel Berlin26addef2017-01-20 21:04:30 +0000723 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Davide Italiano7e274e02016-12-22 16:03:48 +0000724 return V;
725}
726
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000727MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000728 auto *CC = MemoryAccessToClass.lookup(MA);
729 if (CC && CC->RepMemoryAccess)
730 return CC->RepMemoryAccess;
731 // FIXME: We need to audit all the places that current set a nullptr To, and
732 // fix them. There should always be *some* congruence class, even if it is
733 // singular. Right now, we don't bother setting congruence classes for
734 // anything but stores, which means we have to return the original access
735 // here. Otherwise, this should be unreachable.
736 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000737}
738
Daniel Berlinc4796862017-01-27 02:37:11 +0000739// Return true if the MemoryAccess is really equivalent to everything. This is
740// equivalent to the lattice value "TOP" in most lattices. This is the initial
741// state of all memory accesses.
742bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
743 return MemoryAccessToClass.lookup(MA) == InitialClass;
744}
745
Davide Italiano7e274e02016-12-22 16:03:48 +0000746LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
747 LoadInst *LI, MemoryAccess *DA,
748 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000749 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000750 E->allocateOperands(ArgRecycler, ExpressionAllocator);
751 E->setType(LoadType);
752
753 // Give store and loads same opcode so they value number together.
754 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000755 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000756 if (LI)
757 E->setAlignment(LI->getAlignment());
758
759 // TODO: Value number heap versions. We may be able to discover
760 // things alias analysis can't on it's own (IE that a store and a
761 // load have the same value, and thus, it isn't clobbering the load).
762 return E;
763}
764
765const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
766 MemoryAccess *DA,
767 const BasicBlock *B) {
Daniel Berlin26addef2017-01-20 21:04:30 +0000768 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand(), SI, B);
769 auto *E = new (ExpressionAllocator)
770 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000771 E->allocateOperands(ArgRecycler, ExpressionAllocator);
772 E->setType(SI->getValueOperand()->getType());
773
774 // Give store and loads same opcode so they value number together.
775 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000776 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000777
778 // TODO: Value number heap versions. We may be able to discover
779 // things alias analysis can't on it's own (IE that a store and a
780 // load have the same value, and thus, it isn't clobbering the load).
781 return E;
782}
783
Daniel Berlinb755aea2017-01-09 05:34:29 +0000784// Utility function to check whether the congruence class has a member other
785// than the given instruction.
786bool hasMemberOtherThanUs(const CongruenceClass *CC, Instruction *I) {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000787 // Either it has more than one store, in which case it must contain something
788 // other than us (because it's indexed by value), or if it only has one store
Daniel Berlinb755aea2017-01-09 05:34:29 +0000789 // right now, that member should not be us.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000790 return CC->StoreCount > 1 || CC->Members.count(I) == 0;
Daniel Berlinb755aea2017-01-09 05:34:29 +0000791}
792
Davide Italiano7e274e02016-12-22 16:03:48 +0000793const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
794 const BasicBlock *B) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000795 // Unlike loads, we never try to eliminate stores, so we do not check if they
796 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000797 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000798 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000799 // Get the expression, if any, for the RHS of the MemoryDef.
800 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
801 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
802 // If we are defined by ourselves, use the live on entry def.
803 if (StoreRHS == StoreAccess)
804 StoreRHS = MSSA->getLiveOnEntryDef();
805
Daniel Berlin589cecc2017-01-02 18:00:46 +0000806 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000807 // See if we are defined by a previous store expression, it already has a
808 // value, and it's the same value as our current store. FIXME: Right now, we
809 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlinde43ef92017-01-02 19:49:17 +0000810 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000811 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000812 // Basically, check if the congruence class the store is in is defined by a
813 // store that isn't us, and has the same value. MemorySSA takes care of
814 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000815 // The RepStoredValue gets nulled if all the stores disappear in a class, so
816 // we don't need to check if the class contains a store besides us.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000817 if (CC &&
Daniel Berlin26addef2017-01-20 21:04:30 +0000818 CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand(), SI, B))
Daniel Berlin589cecc2017-01-02 18:00:46 +0000819 return createStoreExpression(SI, StoreRHS, B);
Daniel Berlinc4796862017-01-27 02:37:11 +0000820 // Also check if our value operand is defined by a load of the same memory
821 // location, and the memory state is the same as it was then
822 // (otherwise, it could have been overwritten later. See test32 in
823 // transforms/DeadStoreElimination/simple.ll)
824 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
825 if ((lookupOperandLeader(LI->getPointerOperand(), LI, LI->getParent()) ==
826 lookupOperandLeader(SI->getPointerOperand(), SI, B)) &&
827 (lookupMemoryAccessEquiv(
828 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
829 return createVariableExpression(LI);
830 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000831 }
832 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000833}
834
835const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
836 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000837 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000838
839 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000840 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000841 if (!LI->isSimple())
842 return nullptr;
843
Daniel Berlin85f91b02016-12-26 20:06:58 +0000844 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000845 // Load of undef is undef.
846 if (isa<UndefValue>(LoadAddressLeader))
847 return createConstantExpression(UndefValue::get(LI->getType()));
848
849 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
850
851 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
852 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
853 Instruction *DefiningInst = MD->getMemoryInst();
854 // If the defining instruction is not reachable, replace with undef.
855 if (!ReachableBlocks.count(DefiningInst->getParent()))
856 return createConstantExpression(UndefValue::get(LI->getType()));
857 }
858 }
859
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000860 const Expression *E =
861 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
862 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000863 return E;
864}
865
866// Evaluate read only and pure calls, and create an expression result.
867const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
868 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000869 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000870 if (AA->doesNotAccessMemory(CI))
871 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000872 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000873 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000874 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000875 }
876 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000877}
878
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000879// Update the memory access equivalence table to say that From is equal to To,
880// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000881// FIXME: We need to audit all the places that current set a nullptr To, and fix
882// them. There should always be *some* congruence class, even if it is singular.
883bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
884 DEBUG(dbgs() << "Setting " << *From);
885 if (To) {
886 DEBUG(dbgs() << " equivalent to congruence class ");
887 DEBUG(dbgs() << To->ID << " with current memory access leader ");
888 DEBUG(dbgs() << *To->RepMemoryAccess);
889 } else {
890 DEBUG(dbgs() << " equivalent to itself");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000891 }
Daniel Berlin9f376b72017-01-29 10:26:03 +0000892 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000893
894 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000895 bool Changed = false;
896 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000897 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000898 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000899 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000900 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000901 Changed = true;
902 } else if (!To) {
903 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000904 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000905 Changed = true;
906 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000907 } else {
908 assert(!To &&
909 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000910 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000911
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000912 return Changed;
913}
Davide Italiano7e274e02016-12-22 16:03:48 +0000914// Evaluate PHI nodes symbolically, and create an expression result.
915const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
916 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000917 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +0000918 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
919
920 // See if all arguaments are the same.
921 // We track if any were undef because they need special handling.
922 bool HasUndef = false;
923 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
924 if (Arg == I)
925 return false;
926 if (isa<UndefValue>(Arg)) {
927 HasUndef = true;
928 return false;
929 }
930 return true;
931 });
932 // If we are left with no operands, it's undef
933 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000934 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
935 << "\n");
936 E->deallocateOperands(ArgRecycler);
937 ExpressionAllocator.Deallocate(E);
938 return createConstantExpression(UndefValue::get(I->getType()));
939 }
Daniel Berlind92e7f92017-01-07 00:01:42 +0000940 Value *AllSameValue = *(Filtered.begin());
941 ++Filtered.begin();
942 // Can't use std::equal here, sadly, because filter.begin moves.
943 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
944 return V == AllSameValue;
945 })) {
946 // In LLVM's non-standard representation of phi nodes, it's possible to have
947 // phi nodes with cycles (IE dependent on other phis that are .... dependent
948 // on the original phi node), especially in weird CFG's where some arguments
949 // are unreachable, or uninitialized along certain paths. This can cause
950 // infinite loops during evaluation. We work around this by not trying to
951 // really evaluate them independently, but instead using a variable
952 // expression to say if one is equivalent to the other.
953 // We also special case undef, so that if we have an undef, we can't use the
954 // common value unless it dominates the phi block.
955 if (HasUndef) {
956 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +0000957 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +0000958 if (!DT->dominates(AllSameInst, I))
959 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000960 }
961
Davide Italiano7e274e02016-12-22 16:03:48 +0000962 NumGVNPhisAllSame++;
963 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
964 << "\n");
965 E->deallocateOperands(ArgRecycler);
966 ExpressionAllocator.Deallocate(E);
967 if (auto *C = dyn_cast<Constant>(AllSameValue))
968 return createConstantExpression(C);
969 return createVariableExpression(AllSameValue);
970 }
971 return E;
972}
973
974const Expression *
975NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
976 const BasicBlock *B) {
977 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
978 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
979 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
980 unsigned Opcode = 0;
981 // EI might be an extract from one of our recognised intrinsics. If it
982 // is we'll synthesize a semantically equivalent expression instead on
983 // an extract value expression.
984 switch (II->getIntrinsicID()) {
985 case Intrinsic::sadd_with_overflow:
986 case Intrinsic::uadd_with_overflow:
987 Opcode = Instruction::Add;
988 break;
989 case Intrinsic::ssub_with_overflow:
990 case Intrinsic::usub_with_overflow:
991 Opcode = Instruction::Sub;
992 break;
993 case Intrinsic::smul_with_overflow:
994 case Intrinsic::umul_with_overflow:
995 Opcode = Instruction::Mul;
996 break;
997 default:
998 break;
999 }
1000
1001 if (Opcode != 0) {
1002 // Intrinsic recognized. Grab its args to finish building the
1003 // expression.
1004 assert(II->getNumArgOperands() == 2 &&
1005 "Expect two args for recognised intrinsics.");
1006 return createBinaryExpression(Opcode, EI->getType(),
1007 II->getArgOperand(0),
1008 II->getArgOperand(1), B);
1009 }
1010 }
1011 }
1012
1013 return createAggregateValueExpression(I, B);
1014}
1015
1016// Substitute and symbolize the value before value numbering.
1017const Expression *NewGVN::performSymbolicEvaluation(Value *V,
1018 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +00001019 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001020 if (auto *C = dyn_cast<Constant>(V))
1021 E = createConstantExpression(C);
1022 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1023 E = createVariableExpression(V);
1024 } else {
1025 // TODO: memory intrinsics.
1026 // TODO: Some day, we should do the forward propagation and reassociation
1027 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001028 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001029 switch (I->getOpcode()) {
1030 case Instruction::ExtractValue:
1031 case Instruction::InsertValue:
1032 E = performSymbolicAggrValueEvaluation(I, B);
1033 break;
1034 case Instruction::PHI:
1035 E = performSymbolicPHIEvaluation(I, B);
1036 break;
1037 case Instruction::Call:
1038 E = performSymbolicCallEvaluation(I, B);
1039 break;
1040 case Instruction::Store:
1041 E = performSymbolicStoreEvaluation(I, B);
1042 break;
1043 case Instruction::Load:
1044 E = performSymbolicLoadEvaluation(I, B);
1045 break;
1046 case Instruction::BitCast: {
1047 E = createExpression(I, B);
1048 } break;
1049
1050 case Instruction::Add:
1051 case Instruction::FAdd:
1052 case Instruction::Sub:
1053 case Instruction::FSub:
1054 case Instruction::Mul:
1055 case Instruction::FMul:
1056 case Instruction::UDiv:
1057 case Instruction::SDiv:
1058 case Instruction::FDiv:
1059 case Instruction::URem:
1060 case Instruction::SRem:
1061 case Instruction::FRem:
1062 case Instruction::Shl:
1063 case Instruction::LShr:
1064 case Instruction::AShr:
1065 case Instruction::And:
1066 case Instruction::Or:
1067 case Instruction::Xor:
1068 case Instruction::ICmp:
1069 case Instruction::FCmp:
1070 case Instruction::Trunc:
1071 case Instruction::ZExt:
1072 case Instruction::SExt:
1073 case Instruction::FPToUI:
1074 case Instruction::FPToSI:
1075 case Instruction::UIToFP:
1076 case Instruction::SIToFP:
1077 case Instruction::FPTrunc:
1078 case Instruction::FPExt:
1079 case Instruction::PtrToInt:
1080 case Instruction::IntToPtr:
1081 case Instruction::Select:
1082 case Instruction::ExtractElement:
1083 case Instruction::InsertElement:
1084 case Instruction::ShuffleVector:
1085 case Instruction::GetElementPtr:
1086 E = createExpression(I, B);
1087 break;
1088 default:
1089 return nullptr;
1090 }
1091 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001092 return E;
1093}
1094
1095// There is an edge from 'Src' to 'Dst'. Return true if every path from
1096// the entry block to 'Dst' passes via this edge. In particular 'Dst'
1097// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +00001098bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001099
1100 // While in theory it is interesting to consider the case in which Dst has
1101 // more than one predecessor, because Dst might be part of a loop which is
1102 // only reachable from Src, in practice it is pointless since at the time
1103 // GVN runs all such loops have preheaders, which means that Dst will have
1104 // been changed to have only one predecessor, namely Src.
1105 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1106 const BasicBlock *Src = E.getStart();
1107 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
1108 (void)Src;
1109 return Pred != nullptr;
1110}
1111
1112void NewGVN::markUsersTouched(Value *V) {
1113 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001114 for (auto *User : V->users()) {
1115 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001116 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001117 }
1118}
1119
1120void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1121 for (auto U : MA->users()) {
1122 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001123 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001124 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001125 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001126 }
1127}
1128
Daniel Berlin32f8d562017-01-07 16:55:14 +00001129// Touch the instructions that need to be updated after a congruence class has a
1130// leader change, and mark changed values.
1131void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1132 for (auto M : CC->Members) {
1133 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001134 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001135 LeaderChanges.insert(M);
1136 }
1137}
1138
1139// Move a value, currently in OldClass, to be part of NewClass
1140// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001141void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1142 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001143 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001144 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001145 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001146
1147 if (I == OldClass->NextLeader.first)
1148 OldClass->NextLeader = {nullptr, ~0U};
1149
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001150 // It's possible, though unlikely, for us to discover equivalences such
1151 // that the current leader does not dominate the old one.
1152 // This statistic tracks how often this happens.
1153 // We assert on phi nodes when this happens, currently, for debugging, because
1154 // we want to make sure we name phi node cycles properly.
1155 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1156 I != NewClass->RepLeader &&
1157 DT->properlyDominates(
1158 I->getParent(),
1159 cast<Instruction>(NewClass->RepLeader)->getParent())) {
1160 ++NumGVNNotMostDominatingLeader;
1161 assert(!isa<PHINode>(I) &&
1162 "New class for instruction should not be dominated by instruction");
1163 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001164
1165 if (NewClass->RepLeader != I) {
1166 auto DFSNum = InstrDFS.lookup(I);
1167 if (DFSNum < NewClass->NextLeader.second)
1168 NewClass->NextLeader = {I, DFSNum};
1169 }
1170
1171 OldClass->Members.erase(I);
1172 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001173 MemoryAccess *StoreAccess = nullptr;
1174 if (auto *SI = dyn_cast<StoreInst>(I)) {
1175 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001176 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001177 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001178 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001179 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001180 if (!NewClass->RepMemoryAccess) {
1181 // If we don't have a representative memory access, it better be the only
1182 // store in there.
1183 assert(NewClass->StoreCount == 1);
1184 NewClass->RepMemoryAccess = StoreAccess;
1185 }
1186 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001187 }
1188
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001189 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001190 // See if we destroyed the class or need to swap leaders.
1191 if (OldClass->Members.empty() && OldClass != InitialClass) {
1192 if (OldClass->DefiningExpr) {
1193 OldClass->Dead = true;
1194 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1195 << " from table\n");
1196 ExpressionToClass.erase(OldClass->DefiningExpr);
1197 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001198 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001199 // When the leader changes, the value numbering of
1200 // everything may change due to symbolization changes, so we need to
1201 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001202 DEBUG(dbgs() << "Leader change!\n");
1203 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001204 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001205 if (OldClass->StoreCount == 0) {
1206 if (OldClass->RepStoredValue != nullptr)
1207 OldClass->RepStoredValue = nullptr;
1208 if (OldClass->RepMemoryAccess != nullptr)
1209 OldClass->RepMemoryAccess = nullptr;
1210 }
1211
1212 // If we destroy the old access leader, we have to effectively destroy the
1213 // congruence class. When it comes to scalars, anything with the same value
1214 // is as good as any other. That means that one leader is as good as
1215 // another, and as long as you have some leader for the value, you are
1216 // good.. When it comes to *memory states*, only one particular thing really
1217 // represents the definition of a given memory state. Once it goes away, we
1218 // need to re-evaluate which pieces of memory are really still
1219 // equivalent. The best way to do this is to re-value number things. The
1220 // only way to really make that happen is to destroy the rest of the class.
1221 // In order to effectively destroy the class, we reset ExpressionToClass for
1222 // each by using the ValueToExpression mapping. The members later get
1223 // marked as touched due to the leader change. We will create new
1224 // congruence classes, and the pieces that are still equivalent will end
1225 // back together in a new class. If this becomes too expensive, it is
1226 // possible to use a versioning scheme for the congruence classes to avoid
1227 // the expressions finding this old class.
1228 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1229 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1230 << " because memory access leader changed");
1231 for (auto Member : OldClass->Members)
1232 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1233 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001234
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001235 // We don't need to sort members if there is only 1, and we don't care about
1236 // sorting the initial class because everything either gets out of it or is
1237 // unreachable.
1238 if (OldClass->Members.size() == 1 || OldClass == InitialClass) {
1239 OldClass->RepLeader = *(OldClass->Members.begin());
1240 } else if (OldClass->NextLeader.first) {
1241 ++NumGVNAvoidedSortedLeaderChanges;
1242 OldClass->RepLeader = OldClass->NextLeader.first;
1243 OldClass->NextLeader = {nullptr, ~0U};
1244 } else {
1245 ++NumGVNSortedLeaderChanges;
1246 // TODO: If this ends up to slow, we can maintain a dual structure for
1247 // member testing/insertion, or keep things mostly sorted, and sort only
1248 // here, or ....
1249 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1250 for (const auto X : OldClass->Members) {
1251 auto DFSNum = InstrDFS.lookup(X);
1252 if (DFSNum < MinDFS.second)
1253 MinDFS = {X, DFSNum};
1254 }
1255 OldClass->RepLeader = MinDFS.first;
1256 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001257 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001258 }
1259}
1260
Davide Italiano7e274e02016-12-22 16:03:48 +00001261// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001262void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1263 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001264 // This is guaranteed to return something, since it will at least find
1265 // INITIAL.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001266
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001267 CongruenceClass *IClass = ValueToClass[I];
1268 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001269 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001270 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001271
1272 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001273 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001274 EClass = ValueToClass[VE->getVariableValue()];
1275 } else {
1276 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1277
1278 // If it's not in the value table, create a new congruence class.
1279 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001280 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001281 auto place = lookupResult.first;
1282 place->second = NewClass;
1283
1284 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001285 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001286 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001287 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1288 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001289 NewClass->RepLeader = SI;
1290 NewClass->RepStoredValue =
Daniel Berlin32f8d562017-01-07 16:55:14 +00001291 lookupOperandLeader(SI->getValueOperand(), SI, SI->getParent());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001292 // The RepMemoryAccess field will be filled in properly by the
1293 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001294 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001295 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001296 }
1297 assert(!isa<VariableExpression>(E) &&
1298 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001299
1300 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001301 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001302 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001303 << " and leader " << *(NewClass->RepLeader));
1304 if (NewClass->RepStoredValue)
1305 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1306 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001307 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1308 } else {
1309 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001310 if (isa<ConstantExpression>(E))
1311 assert(isa<Constant>(EClass->RepLeader) &&
1312 "Any class with a constant expression should have a "
1313 "constant leader");
1314
Davide Italiano7e274e02016-12-22 16:03:48 +00001315 assert(EClass && "Somehow don't have an eclass");
1316
1317 assert(!EClass->Dead && "We accidentally looked up a dead class");
1318 }
1319 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001320 bool ClassChanged = IClass != EClass;
1321 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001322 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001323 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1324 << "\n");
1325
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001326 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001327 moveValueToNewCongruenceClass(I, IClass, EClass);
1328 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001329 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001330 markMemoryUsersTouched(MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001331 }
1332}
1333
1334// Process the fact that Edge (from, to) is reachable, including marking
1335// any newly reachable blocks and instructions for processing.
1336void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1337 // Check if the Edge was reachable before.
1338 if (ReachableEdges.insert({From, To}).second) {
1339 // If this block wasn't reachable before, all instructions are touched.
1340 if (ReachableBlocks.insert(To).second) {
1341 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1342 const auto &InstRange = BlockInstRange.lookup(To);
1343 TouchedInstructions.set(InstRange.first, InstRange.second);
1344 } else {
1345 DEBUG(dbgs() << "Block " << getBlockName(To)
1346 << " was reachable, but new edge {" << getBlockName(From)
1347 << "," << getBlockName(To) << "} to it found\n");
1348
1349 // We've made an edge reachable to an existing block, which may
1350 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1351 // they are the only thing that depend on new edges. Anything using their
1352 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001353 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001354 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001355
Davide Italiano7e274e02016-12-22 16:03:48 +00001356 auto BI = To->begin();
1357 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001358 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001359 ++BI;
1360 }
1361 }
1362 }
1363}
1364
1365// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1366// see if we know some constant value for it already.
1367Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1368 auto Result = lookupOperandLeader(Cond, nullptr, B);
1369 if (isa<Constant>(Result))
1370 return Result;
1371 return nullptr;
1372}
1373
1374// Process the outgoing edges of a block for reachability.
1375void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1376 // Evaluate reachability of terminator instruction.
1377 BranchInst *BR;
1378 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1379 Value *Cond = BR->getCondition();
1380 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1381 if (!CondEvaluated) {
1382 if (auto *I = dyn_cast<Instruction>(Cond)) {
1383 const Expression *E = createExpression(I, B);
1384 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1385 CondEvaluated = CE->getConstantValue();
1386 }
1387 } else if (isa<ConstantInt>(Cond)) {
1388 CondEvaluated = Cond;
1389 }
1390 }
1391 ConstantInt *CI;
1392 BasicBlock *TrueSucc = BR->getSuccessor(0);
1393 BasicBlock *FalseSucc = BR->getSuccessor(1);
1394 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1395 if (CI->isOne()) {
1396 DEBUG(dbgs() << "Condition for Terminator " << *TI
1397 << " evaluated to true\n");
1398 updateReachableEdge(B, TrueSucc);
1399 } else if (CI->isZero()) {
1400 DEBUG(dbgs() << "Condition for Terminator " << *TI
1401 << " evaluated to false\n");
1402 updateReachableEdge(B, FalseSucc);
1403 }
1404 } else {
1405 updateReachableEdge(B, TrueSucc);
1406 updateReachableEdge(B, FalseSucc);
1407 }
1408 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1409 // For switches, propagate the case values into the case
1410 // destinations.
1411
1412 // Remember how many outgoing edges there are to every successor.
1413 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1414
Davide Italiano7e274e02016-12-22 16:03:48 +00001415 Value *SwitchCond = SI->getCondition();
1416 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1417 // See if we were able to turn this switch statement into a constant.
1418 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001419 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001420 // We should be able to get case value for this.
1421 auto CaseVal = SI->findCaseValue(CondVal);
1422 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1423 // We proved the value is outside of the range of the case.
1424 // We can't do anything other than mark the default dest as reachable,
1425 // and go home.
1426 updateReachableEdge(B, SI->getDefaultDest());
1427 return;
1428 }
1429 // Now get where it goes and mark it reachable.
1430 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1431 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001432 } else {
1433 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1434 BasicBlock *TargetBlock = SI->getSuccessor(i);
1435 ++SwitchEdges[TargetBlock];
1436 updateReachableEdge(B, TargetBlock);
1437 }
1438 }
1439 } else {
1440 // Otherwise this is either unconditional, or a type we have no
1441 // idea about. Just mark successors as reachable.
1442 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1443 BasicBlock *TargetBlock = TI->getSuccessor(i);
1444 updateReachableEdge(B, TargetBlock);
1445 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001446
1447 // This also may be a memory defining terminator, in which case, set it
1448 // equivalent to nothing.
1449 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1450 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001451 }
1452}
1453
Daniel Berlin85f91b02016-12-26 20:06:58 +00001454// The algorithm initially places the values of the routine in the INITIAL
1455// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001456// class. The leader of INITIAL is the undetermined value `TOP`.
1457// When the algorithm has finished, values still in INITIAL are unreachable.
1458void NewGVN::initializeCongruenceClasses(Function &F) {
1459 // FIXME now i can't remember why this is 2
1460 NextCongruenceNum = 2;
1461 // Initialize all other instructions to be in INITIAL class.
1462 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001463 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001464 InitialClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001465 for (auto &B : F) {
1466 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001467 MemoryAccessToClass[MP] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001468
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001469 for (auto &I : B) {
1470 InitialValues.insert(&I);
1471 ValueToClass[&I] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001472 // All memory accesses are equivalent to live on entry to start. They must
1473 // be initialized to something so that initial changes are noticed. For
1474 // the maximal answer, we initialize them all to be the same as
1475 // liveOnEntry. Note that to save time, we only initialize the
1476 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1477 // other expression can generate a memory equivalence. If we start
1478 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001479 if (isa<StoreInst>(&I)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001480 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = InitialClass;
Davide Italianoeac05f62017-01-11 23:41:24 +00001481 ++InitialClass->StoreCount;
1482 assert(InitialClass->StoreCount > 0);
1483 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001484 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001485 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001486 InitialClass->Members.swap(InitialValues);
1487
1488 // Initialize arguments to be in their own unique congruence classes
1489 for (auto &FA : F.args())
1490 createSingletonCongruenceClass(&FA);
1491}
1492
1493void NewGVN::cleanupTables() {
1494 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1495 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1496 << CongruenceClasses[i]->Members.size() << " members\n");
1497 // Make sure we delete the congruence class (probably worth switching to
1498 // a unique_ptr at some point.
1499 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001500 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001501 }
1502
1503 ValueToClass.clear();
1504 ArgRecycler.clear(ExpressionAllocator);
1505 ExpressionAllocator.Reset();
1506 CongruenceClasses.clear();
1507 ExpressionToClass.clear();
1508 ValueToExpression.clear();
1509 ReachableBlocks.clear();
1510 ReachableEdges.clear();
1511#ifndef NDEBUG
1512 ProcessedCount.clear();
1513#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001514 InstrDFS.clear();
1515 InstructionsToErase.clear();
1516
1517 DFSToInstr.clear();
1518 BlockInstRange.clear();
1519 TouchedInstructions.clear();
1520 DominatedInstRange.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001521 MemoryAccessToClass.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001522}
1523
1524std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1525 unsigned Start) {
1526 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001527 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1528 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001529 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001530 }
1531
Davide Italiano7e274e02016-12-22 16:03:48 +00001532 for (auto &I : *B) {
1533 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001534 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001535 }
1536
1537 // All of the range functions taken half-open ranges (open on the end side).
1538 // So we do not subtract one from count, because at this point it is one
1539 // greater than the last instruction.
1540 return std::make_pair(Start, End);
1541}
1542
1543void NewGVN::updateProcessedCount(Value *V) {
1544#ifndef NDEBUG
1545 if (ProcessedCount.count(V) == 0) {
1546 ProcessedCount.insert({V, 1});
1547 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001548 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001549 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001550 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001551 }
1552#endif
1553}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001554// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1555void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1556 // If all the arguments are the same, the MemoryPhi has the same value as the
1557 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001558 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001559 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001560 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1561 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
1562 ReachableBlocks.count(MP->getIncomingBlock(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001563 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001564 // If all that is left is nothing, our memoryphi is undef. We keep it as
1565 // InitialClass. Note: The only case this should happen is if we have at
1566 // least one self-argument.
1567 if (Filtered.begin() == Filtered.end()) {
1568 if (setMemoryAccessEquivTo(MP, InitialClass))
1569 markMemoryUsersTouched(MP);
1570 return;
1571 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001572
1573 // Transform the remaining operands into operand leaders.
1574 // FIXME: mapped_iterator should have a range version.
1575 auto LookupFunc = [&](const Use &U) {
1576 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1577 };
1578 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1579 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1580
1581 // and now check if all the elements are equal.
1582 // Sadly, we can't use std::equals since these are random access iterators.
1583 MemoryAccess *AllSameValue = *MappedBegin;
1584 ++MappedBegin;
1585 bool AllEqual = std::all_of(
1586 MappedBegin, MappedEnd,
1587 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1588
1589 if (AllEqual)
1590 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1591 else
1592 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1593
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001594 if (setMemoryAccessEquivTo(
1595 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001596 markMemoryUsersTouched(MP);
1597}
1598
1599// Value number a single instruction, symbolically evaluating, performing
1600// congruence finding, and updating mappings.
1601void NewGVN::valueNumberInstruction(Instruction *I) {
1602 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001603
1604 // There's no need to call isInstructionTriviallyDead more than once on
1605 // an instruction. Therefore, once we know that an instruction is dead
1606 // we change its DFS number so that it doesn't get numbered again.
1607 if (InstrDFS[I] != 0 && isInstructionTriviallyDead(I, TLI)) {
1608 InstrDFS[I] = 0;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001609 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001610 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001611 return;
1612 }
1613 if (!I->isTerminator()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001614 const auto *Symbolized = performSymbolicEvaluation(I, I->getParent());
1615 // If we couldn't come up with a symbolic expression, use the unknown
1616 // expression
1617 if (Symbolized == nullptr)
1618 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001619 performCongruenceFinding(I, Symbolized);
1620 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001621 // Handle terminators that return values. All of them produce values we
1622 // don't currently understand.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001623 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001624 auto *Symbolized = createUnknownExpression(I);
1625 performCongruenceFinding(I, Symbolized);
1626 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001627 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1628 }
1629}
Davide Italiano7e274e02016-12-22 16:03:48 +00001630
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001631// Check if there is a path, using single or equal argument phi nodes, from
1632// First to Second.
1633bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1634 const MemoryAccess *Second) const {
1635 if (First == Second)
1636 return true;
1637
1638 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1639 auto *DefAccess = FirstDef->getDefiningAccess();
1640 return singleReachablePHIPath(DefAccess, Second);
1641 } else {
1642 auto *MP = cast<MemoryPhi>(First);
1643 auto ReachableOperandPred = [&](const Use &U) {
1644 return ReachableBlocks.count(MP->getIncomingBlock(U));
1645 };
1646 auto FilteredPhiArgs =
1647 make_filter_range(MP->operands(), ReachableOperandPred);
1648 SmallVector<const Value *, 32> OperandList;
1649 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1650 std::back_inserter(OperandList));
1651 bool Okay = OperandList.size() == 1;
1652 if (!Okay)
1653 Okay = std::equal(OperandList.begin(), OperandList.end(),
1654 OperandList.begin());
1655 if (Okay)
1656 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1657 return false;
1658 }
1659}
1660
Daniel Berlin589cecc2017-01-02 18:00:46 +00001661// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001662// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001663// subject to very rare false negatives. It is only useful for
1664// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001665void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001666 // Anything equivalent in the memory access table should be in the same
1667 // congruence class.
1668
1669 // Filter out the unreachable and trivially dead entries, because they may
1670 // never have been updated if the instructions were not processed.
1671 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001672 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001673 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1674 if (!Result)
1675 return false;
1676 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1677 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1678 return true;
1679 };
1680
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001681 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001682 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001683 // Unreachable instructions may not have changed because we never process
1684 // them.
1685 if (!ReachableBlocks.count(KV.first->getBlock()))
1686 continue;
1687 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001688 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001689 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001690 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001691 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1692 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1693 "The instructions for these memory operations should have "
1694 "been in the same congruence class or reachable through"
1695 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001696 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1697
1698 // We can only sanely verify that MemoryDefs in the operand list all have
1699 // the same class.
1700 auto ReachableOperandPred = [&](const Use &U) {
1701 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1702 isa<MemoryDef>(U);
1703
1704 };
1705 // All arguments should in the same class, ignoring unreachable arguments
1706 auto FilteredPhiArgs =
1707 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1708 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1709 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1710 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1711 const MemoryDef *MD = cast<MemoryDef>(U);
1712 return ValueToClass.lookup(MD->getMemoryInst());
1713 });
1714 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1715 PhiOpClasses.begin()) &&
1716 "All MemoryPhi arguments should be in the same class");
1717 }
1718 }
1719}
1720
Daniel Berlin85f91b02016-12-26 20:06:58 +00001721// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001722bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001723 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1724 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001725 bool Changed = false;
1726 DT = _DT;
1727 AC = _AC;
1728 TLI = _TLI;
1729 AA = _AA;
1730 MSSA = _MSSA;
1731 DL = &F.getParent()->getDataLayout();
1732 MSSAWalker = MSSA->getWalker();
1733
1734 // Count number of instructions for sizing of hash tables, and come
1735 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001736 unsigned ICount = 1;
1737 // Add an empty instruction to account for the fact that we start at 1
1738 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001739 // Note: We want RPO traversal of the blocks, which is not quite the same as
1740 // dominator tree order, particularly with regard whether backedges get
1741 // visited first or second, given a block with multiple successors.
1742 // If we visit in the wrong order, we will end up performing N times as many
1743 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001744 // The dominator tree does guarantee that, for a given dom tree node, it's
1745 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1746 // the siblings.
1747 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001748 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001749 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001750 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001751 auto *Node = DT->getNode(B);
1752 assert(Node && "RPO and Dominator tree should have same reachability");
1753 RPOOrdering[Node] = ++Counter;
1754 }
1755 // Sort dominator tree children arrays into RPO.
1756 for (auto &B : RPOT) {
1757 auto *Node = DT->getNode(B);
1758 if (Node->getChildren().size() > 1)
1759 std::sort(Node->begin(), Node->end(),
1760 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1761 return RPOOrdering[A] < RPOOrdering[B];
1762 });
1763 }
1764
1765 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1766 auto DFI = df_begin(DT->getRootNode());
1767 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1768 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001769 const auto &BlockRange = assignDFSNumbers(B, ICount);
1770 BlockInstRange.insert({B, BlockRange});
1771 ICount += BlockRange.second - BlockRange.first;
1772 }
1773
1774 // Handle forward unreachable blocks and figure out which blocks
1775 // have single preds.
1776 for (auto &B : F) {
1777 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001778 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001779 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1780 BlockInstRange.insert({&B, BlockRange});
1781 ICount += BlockRange.second - BlockRange.first;
1782 }
1783 }
1784
Daniel Berline0bd37e2016-12-29 22:15:12 +00001785 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001786 DominatedInstRange.reserve(F.size());
1787 // Ensure we don't end up resizing the expressionToClass map, as
1788 // that can be quite expensive. At most, we have one expression per
1789 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001790 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001791
1792 // Initialize the touched instructions to include the entry block.
1793 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1794 TouchedInstructions.set(InstRange.first, InstRange.second);
1795 ReachableBlocks.insert(&F.getEntryBlock());
1796
1797 initializeCongruenceClasses(F);
1798
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001799 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001800 // We start out in the entry block.
1801 BasicBlock *LastBlock = &F.getEntryBlock();
1802 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001803 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00001804 // Walk through all the instructions in all the blocks in RPO.
1805 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1806 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001807
1808 // This instruction was found to be dead. We don't bother looking
1809 // at it again.
1810 if (InstrNum == 0) {
1811 TouchedInstructions.reset(InstrNum);
1812 continue;
1813 }
1814
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001815 Value *V = DFSToInstr[InstrNum];
1816 BasicBlock *CurrBlock = nullptr;
1817
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001818 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001819 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001820 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001821 CurrBlock = MP->getBlock();
1822 else
1823 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001824
1825 // If we hit a new block, do reachability processing.
1826 if (CurrBlock != LastBlock) {
1827 LastBlock = CurrBlock;
1828 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1829 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1830
1831 // If it's not reachable, erase any touched instructions and move on.
1832 if (!BlockReachable) {
1833 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1834 DEBUG(dbgs() << "Skipping instructions in block "
1835 << getBlockName(CurrBlock)
1836 << " because it is unreachable\n");
1837 continue;
1838 }
1839 updateProcessedCount(CurrBlock);
1840 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001841
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001842 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001843 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1844 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001845 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001846 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001847 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001848 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001849 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001850 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001851 // Reset after processing (because we may mark ourselves as touched when
1852 // we propagate equalities).
1853 TouchedInstructions.reset(InstrNum);
1854 }
1855 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001856 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001857#ifndef NDEBUG
1858 verifyMemoryCongruency();
1859#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001860 Changed |= eliminateInstructions(F);
1861
1862 // Delete all instructions marked for deletion.
1863 for (Instruction *ToErase : InstructionsToErase) {
1864 if (!ToErase->use_empty())
1865 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1866
1867 ToErase->eraseFromParent();
1868 }
1869
1870 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001871 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1872 return !ReachableBlocks.count(&BB);
1873 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001874
1875 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1876 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001877 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001878 deleteInstructionsInBlock(&BB);
1879 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001880 }
1881
1882 cleanupTables();
1883 return Changed;
1884}
1885
1886bool NewGVN::runOnFunction(Function &F) {
1887 if (skipFunction(F))
1888 return false;
1889 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1890 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1891 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1892 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1893 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1894}
1895
Daniel Berlin85f91b02016-12-26 20:06:58 +00001896PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001897 NewGVN Impl;
1898
1899 // Apparently the order in which we get these results matter for
1900 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1901 // the same order here, just in case.
1902 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1903 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1904 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1905 auto &AA = AM.getResult<AAManager>(F);
1906 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1907 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1908 if (!Changed)
1909 return PreservedAnalyses::all();
1910 PreservedAnalyses PA;
1911 PA.preserve<DominatorTreeAnalysis>();
1912 PA.preserve<GlobalsAA>();
1913 return PA;
1914}
1915
1916// Return true if V is a value that will always be available (IE can
1917// be placed anywhere) in the function. We don't do globals here
1918// because they are often worse to put in place.
1919// TODO: Separate cost from availability
1920static bool alwaysAvailable(Value *V) {
1921 return isa<Constant>(V) || isa<Argument>(V);
1922}
1923
1924// Get the basic block from an instruction/value.
1925static BasicBlock *getBlockForValue(Value *V) {
1926 if (auto *I = dyn_cast<Instruction>(V))
1927 return I->getParent();
1928 return nullptr;
1929}
1930
1931struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001932 int DFSIn = 0;
1933 int DFSOut = 0;
1934 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001935 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001936 Value *Val = nullptr;
1937 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001938
1939 bool operator<(const ValueDFS &Other) const {
1940 // It's not enough that any given field be less than - we have sets
1941 // of fields that need to be evaluated together to give a proper ordering.
1942 // For example, if you have;
1943 // DFS (1, 3)
1944 // Val 0
1945 // DFS (1, 2)
1946 // Val 50
1947 // We want the second to be less than the first, but if we just go field
1948 // by field, we will get to Val 0 < Val 50 and say the first is less than
1949 // the second. We only want it to be less than if the DFS orders are equal.
1950 //
1951 // Each LLVM instruction only produces one value, and thus the lowest-level
1952 // differentiator that really matters for the stack (and what we use as as a
1953 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001954 // Everything else in the structure is instruction level, and only affects
1955 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001956 //
1957 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1958 // the order of replacement of uses does not matter.
1959 // IE given,
1960 // a = 5
1961 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001962 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1963 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001964 // The .val will be the same as well.
1965 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001966 // You will replace both, and it does not matter what order you replace them
1967 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1968 // operand 2).
1969 // Similarly for the case of same dfsin, dfsout, localnum, but different
1970 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001971 // a = 5
1972 // b = 6
1973 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001974 // in c, we will a valuedfs for a, and one for b,with everything the same
1975 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001976 // It does not matter what order we replace these operands in.
1977 // You will always end up with the same IR, and this is guaranteed.
1978 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1979 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1980 Other.U);
1981 }
1982};
1983
Daniel Berlinc4796862017-01-27 02:37:11 +00001984// This function converts the set of members for a congruence class from values,
1985// to sets of defs and uses with associated DFS info.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001986void NewGVN::convertDenseToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00001987 const CongruenceClass::MemberSet &Dense,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001988 SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001989 for (auto D : Dense) {
1990 // First add the value.
1991 BasicBlock *BB = getBlockForValue(D);
1992 // Constants are handled prior to ever calling this function, so
1993 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001994 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001995 ValueDFS VD;
Daniel Berlinb66164c2017-01-14 00:24:23 +00001996 DomTreeNode *DomNode = DT->getNode(BB);
1997 VD.DFSIn = DomNode->getDFSNumIn();
1998 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00001999 // If it's a store, use the leader of the value operand.
2000 if (auto *SI = dyn_cast<StoreInst>(D)) {
2001 auto Leader =
2002 lookupOperandLeader(SI->getValueOperand(), SI, SI->getParent());
2003 VD.Val = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
2004 } else {
2005 VD.Val = D;
2006 }
2007
Davide Italiano7e274e02016-12-22 16:03:48 +00002008 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlinaac56842017-01-15 09:18:41 +00002009 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002010 else
2011 llvm_unreachable("Should have been an instruction");
2012
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002013 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00002014
Daniel Berlinb66164c2017-01-14 00:24:23 +00002015 // Now add the uses.
Davide Italiano7e274e02016-12-22 16:03:48 +00002016 for (auto &U : D->uses()) {
2017 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
2018 ValueDFS VD;
2019 // Put the phi node uses in the incoming block.
2020 BasicBlock *IBlock;
2021 if (auto *P = dyn_cast<PHINode>(I)) {
2022 IBlock = P->getIncomingBlock(U);
2023 // Make phi node users appear last in the incoming block
2024 // they are from.
2025 VD.LocalNum = InstrDFS.size() + 1;
2026 } else {
2027 IBlock = I->getParent();
Daniel Berlinaac56842017-01-15 09:18:41 +00002028 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002029 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002030
2031 // Skip uses in unreachable blocks, as we're going
2032 // to delete them.
2033 if (ReachableBlocks.count(IBlock) == 0)
2034 continue;
2035
Daniel Berlinb66164c2017-01-14 00:24:23 +00002036 DomTreeNode *DomNode = DT->getNode(IBlock);
2037 VD.DFSIn = DomNode->getDFSNumIn();
2038 VD.DFSOut = DomNode->getDFSNumOut();
Davide Italiano7e274e02016-12-22 16:03:48 +00002039 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002040 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00002041 }
2042 }
2043 }
2044}
2045
Daniel Berlinc4796862017-01-27 02:37:11 +00002046// This function converts the set of members for a congruence class from values,
2047// to the set of defs for loads and stores, with associated DFS info.
2048void NewGVN::convertDenseToLoadsAndStores(
2049 const CongruenceClass::MemberSet &Dense,
2050 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2051 for (auto D : Dense) {
2052 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2053 continue;
2054
2055 BasicBlock *BB = getBlockForValue(D);
2056 ValueDFS VD;
2057 DomTreeNode *DomNode = DT->getNode(BB);
2058 VD.DFSIn = DomNode->getDFSNumIn();
2059 VD.DFSOut = DomNode->getDFSNumOut();
2060 VD.Val = D;
2061
2062 // If it's an instruction, use the real local dfs number.
2063 if (auto *I = dyn_cast<Instruction>(D))
2064 VD.LocalNum = InstrDFS.lookup(I);
2065 else
2066 llvm_unreachable("Should have been an instruction");
2067
2068 LoadsAndStores.emplace_back(VD);
2069 }
2070}
2071
Davide Italiano7e274e02016-12-22 16:03:48 +00002072static void patchReplacementInstruction(Instruction *I, Value *Repl) {
2073 // Patch the replacement so that it is not more restrictive than the value
2074 // being replaced.
2075 auto *Op = dyn_cast<BinaryOperator>(I);
2076 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
2077
2078 if (Op && ReplOp)
2079 ReplOp->andIRFlags(Op);
2080
2081 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
2082 // FIXME: If both the original and replacement value are part of the
2083 // same control-flow region (meaning that the execution of one
2084 // guarentees the executation of the other), then we can combine the
2085 // noalias scopes here and do better than the general conservative
2086 // answer used in combineMetadata().
2087
2088 // In general, GVN unifies expressions over different control-flow
2089 // regions, and so we need a conservative combination of the noalias
2090 // scopes.
2091 unsigned KnownIDs[] = {
2092 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2093 LLVMContext::MD_noalias, LLVMContext::MD_range,
2094 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2095 LLVMContext::MD_invariant_group};
2096 combineMetadata(ReplInst, I, KnownIDs);
2097 }
2098}
2099
2100static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2101 patchReplacementInstruction(I, Repl);
2102 I->replaceAllUsesWith(Repl);
2103}
2104
2105void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2106 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2107 ++NumGVNBlocksDeleted;
2108
Daniel Berline19f0e02017-01-30 17:06:55 +00002109 // Check to see if there are non-terminating instructions to delete.
2110 if (isa<TerminatorInst>(BB->begin()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002111 return;
Daniel Berlin2b834922017-01-26 18:30:29 +00002112
Daniel Berline19f0e02017-01-30 17:06:55 +00002113 // Delete the instructions backwards, as it has a reduced likelihood of having
2114 // to update as many def-use and use-def chains. Start after the terminator.
2115 auto StartPoint = BB->rbegin();
2116 ++StartPoint;
2117 // Note that we explicitly recalculate BB->rend() on each iteration,
2118 // as it may change when we remove the first instruction.
2119 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2120 Instruction &Inst = *I++;
2121 if (!Inst.use_empty())
2122 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2123 if (isa<LandingPadInst>(Inst))
2124 continue;
2125
2126 Inst.eraseFromParent();
2127 ++NumGVNInstrDeleted;
2128 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002129}
2130
2131void NewGVN::markInstructionForDeletion(Instruction *I) {
2132 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2133 InstructionsToErase.insert(I);
2134}
2135
2136void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2137
2138 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2139 patchAndReplaceAllUsesWith(I, V);
2140 // We save the actual erasing to avoid invalidating memory
2141 // dependencies until we are done with everything.
2142 markInstructionForDeletion(I);
2143}
2144
2145namespace {
2146
2147// This is a stack that contains both the value and dfs info of where
2148// that value is valid.
2149class ValueDFSStack {
2150public:
2151 Value *back() const { return ValueStack.back(); }
2152 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2153
2154 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002155 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002156 DFSStack.emplace_back(DFSIn, DFSOut);
2157 }
2158 bool empty() const { return DFSStack.empty(); }
2159 bool isInScope(int DFSIn, int DFSOut) const {
2160 if (empty())
2161 return false;
2162 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2163 }
2164
2165 void popUntilDFSScope(int DFSIn, int DFSOut) {
2166
2167 // These two should always be in sync at this point.
2168 assert(ValueStack.size() == DFSStack.size() &&
2169 "Mismatch between ValueStack and DFSStack");
2170 while (
2171 !DFSStack.empty() &&
2172 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2173 DFSStack.pop_back();
2174 ValueStack.pop_back();
2175 }
2176 }
2177
2178private:
2179 SmallVector<Value *, 8> ValueStack;
2180 SmallVector<std::pair<int, int>, 8> DFSStack;
2181};
2182}
Daniel Berlin04443432017-01-07 03:23:47 +00002183
Davide Italiano7e274e02016-12-22 16:03:48 +00002184bool NewGVN::eliminateInstructions(Function &F) {
2185 // This is a non-standard eliminator. The normal way to eliminate is
2186 // to walk the dominator tree in order, keeping track of available
2187 // values, and eliminating them. However, this is mildly
2188 // pointless. It requires doing lookups on every instruction,
2189 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002190 // instructions part of most singleton congruence classes, we know we
2191 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002192
2193 // Instead, this eliminator looks at the congruence classes directly, sorts
2194 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002195 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002196 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002197 // last member. This is worst case O(E log E) where E = number of
2198 // instructions in a single congruence class. In theory, this is all
2199 // instructions. In practice, it is much faster, as most instructions are
2200 // either in singleton congruence classes or can't possibly be eliminated
2201 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002202 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002203 // for elimination purposes.
2204 // TODO: If we wanted to be faster, We could remove any members with no
2205 // overlapping ranges while sorting, as we will never eliminate anything
2206 // with those members, as they don't dominate anything else in our set.
2207
Davide Italiano7e274e02016-12-22 16:03:48 +00002208 bool AnythingReplaced = false;
2209
2210 // Since we are going to walk the domtree anyway, and we can't guarantee the
2211 // DFS numbers are updated, we compute some ourselves.
2212 DT->updateDFSNumbers();
2213
2214 for (auto &B : F) {
2215 if (!ReachableBlocks.count(&B)) {
2216 for (const auto S : successors(&B)) {
2217 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002218 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002219 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2220 << getBlockName(&B)
2221 << " with undef due to it being unreachable\n");
2222 for (auto &Operand : Phi.incoming_values())
2223 if (Phi.getIncomingBlock(Operand) == &B)
2224 Operand.set(UndefValue::get(Phi.getType()));
2225 }
2226 }
2227 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002228 }
2229
2230 for (CongruenceClass *CC : CongruenceClasses) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002231 // Track the equivalent store info so we can decide whether to try
2232 // dead store elimination.
2233 SmallVector<ValueDFS, 8> PossibleDeadStores;
2234
Davide Italiano7e274e02016-12-22 16:03:48 +00002235 // FIXME: We should eventually be able to replace everything still
2236 // in the initial class with undef, as they should be unreachable.
2237 // Right now, initial still contains some things we skip value
2238 // numbering of (UNREACHABLE's, for example).
2239 if (CC == InitialClass || CC->Dead)
2240 continue;
2241 assert(CC->RepLeader && "We should have had a leader");
2242
2243 // If this is a leader that is always available, and it's a
2244 // constant or has no equivalences, just replace everything with
2245 // it. We then update the congruence class with whatever members
2246 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002247 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2248 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002249 SmallPtrSet<Value *, 4> MembersLeft;
2250 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002251 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002252 // Void things have no uses we can replace.
2253 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2254 MembersLeft.insert(Member);
2255 continue;
2256 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002257 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2258 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002259 // Due to equality propagation, these may not always be
2260 // instructions, they may be real values. We don't really
2261 // care about trying to replace the non-instructions.
2262 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002263 assert(Leader != I && "About to accidentally remove our leader");
2264 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002265 AnythingReplaced = true;
2266
2267 continue;
2268 } else {
2269 MembersLeft.insert(I);
2270 }
2271 }
2272 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002273 } else {
2274 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2275 // If this is a singleton, we can skip it.
2276 if (CC->Members.size() != 1) {
2277
2278 // This is a stack because equality replacement/etc may place
2279 // constants in the middle of the member list, and we want to use
2280 // those constant values in preference to the current leader, over
2281 // the scope of those constants.
2282 ValueDFSStack EliminationStack;
2283
2284 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002285 SmallVector<ValueDFS, 8> DFSOrderedSet;
Davide Italiano7e274e02016-12-22 16:03:48 +00002286 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2287
2288 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002289 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002290 for (auto &VD : DFSOrderedSet) {
2291 int MemberDFSIn = VD.DFSIn;
2292 int MemberDFSOut = VD.DFSOut;
2293 Value *Member = VD.Val;
2294 Use *MemberUse = VD.U;
Davide Italiano7e274e02016-12-22 16:03:48 +00002295
Daniel Berlinc4796862017-01-27 02:37:11 +00002296 // We ignore void things because we can't get a value from them.
2297 if (Member && Member->getType()->isVoidTy())
2298 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002299
2300 if (EliminationStack.empty()) {
2301 DEBUG(dbgs() << "Elimination Stack is empty\n");
2302 } else {
2303 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2304 << EliminationStack.dfs_back().first << ","
2305 << EliminationStack.dfs_back().second << ")\n");
2306 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002307
2308 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2309 << MemberDFSOut << ")\n");
2310 // First, we see if we are out of scope or empty. If so,
2311 // and there equivalences, we try to replace the top of
2312 // stack with equivalences (if it's on the stack, it must
2313 // not have been eliminated yet).
2314 // Then we synchronize to our current scope, by
2315 // popping until we are back within a DFS scope that
2316 // dominates the current member.
2317 // Then, what happens depends on a few factors
2318 // If the stack is now empty, we need to push
2319 // If we have a constant or a local equivalence we want to
2320 // start using, we also push.
2321 // Otherwise, we walk along, processing members who are
2322 // dominated by this scope, and eliminate them.
2323 bool ShouldPush =
2324 Member && (EliminationStack.empty() || isa<Constant>(Member));
2325 bool OutOfScope =
2326 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2327
2328 if (OutOfScope || ShouldPush) {
2329 // Sync to our current scope.
2330 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2331 ShouldPush |= Member && EliminationStack.empty();
2332 if (ShouldPush) {
2333 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2334 }
2335 }
2336
2337 // If we get to this point, and the stack is empty we must have a use
2338 // with nothing we can use to eliminate it, just skip it.
2339 if (EliminationStack.empty())
2340 continue;
2341
2342 // Skip the Value's, we only want to eliminate on their uses.
2343 if (Member)
2344 continue;
2345 Value *Result = EliminationStack.back();
2346
Daniel Berlind92e7f92017-01-07 00:01:42 +00002347 // Don't replace our existing users with ourselves.
2348 if (MemberUse->get() == Result)
Davide Italiano7e274e02016-12-22 16:03:48 +00002349 continue;
2350
2351 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2352 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2353 << "\n");
2354
2355 // If we replaced something in an instruction, handle the patching of
2356 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002357 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002358 patchReplacementInstruction(ReplacedInst, Result);
2359
2360 assert(isa<Instruction>(MemberUse->getUser()));
2361 MemberUse->set(Result);
2362 AnythingReplaced = true;
2363 }
2364 }
2365 }
2366
2367 // Cleanup the congruence class.
2368 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002369 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002370 if (Member->getType()->isVoidTy()) {
2371 MembersLeft.insert(Member);
2372 continue;
2373 }
2374
2375 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2376 if (isInstructionTriviallyDead(MemberInst)) {
2377 // TODO: Don't mark loads of undefs.
2378 markInstructionForDeletion(MemberInst);
2379 continue;
2380 }
2381 }
2382 MembersLeft.insert(Member);
2383 }
2384 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002385
2386 // If we have possible dead stores to look at, try to eliminate them.
2387 if (CC->StoreCount > 0) {
2388 convertDenseToLoadsAndStores(CC->Members, PossibleDeadStores);
2389 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2390 ValueDFSStack EliminationStack;
2391 for (auto &VD : PossibleDeadStores) {
2392 int MemberDFSIn = VD.DFSIn;
2393 int MemberDFSOut = VD.DFSOut;
2394 Instruction *Member = cast<Instruction>(VD.Val);
2395 if (EliminationStack.empty() ||
2396 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2397 // Sync to our current scope.
2398 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2399 if (EliminationStack.empty()) {
2400 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2401 continue;
2402 }
2403 }
2404 // We already did load elimination, so nothing to do here.
2405 if (isa<LoadInst>(Member))
2406 continue;
2407 assert(!EliminationStack.empty());
2408 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002409 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002410 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2411 // Member is dominater by Leader, and thus dead
2412 DEBUG(dbgs() << "Marking dead store " << *Member
2413 << " that is dominated by " << *Leader << "\n");
2414 markInstructionForDeletion(Member);
2415 CC->Members.erase(Member);
2416 ++NumGVNDeadStores;
2417 }
2418 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002419 }
2420
2421 return AnythingReplaced;
2422}