blob: 7b9e19bc91f0a3a8b99de7974e0d926ddd141a2d [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"
89#include "llvm/Transforms/Utils/SSAUpdater.h"
90#include <unordered_map>
91#include <utility>
92#include <vector>
93using namespace llvm;
94using namespace PatternMatch;
95using namespace llvm::GVNExpression;
96
97#define DEBUG_TYPE "newgvn"
98
99STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
100STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
101STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
102STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +0000103STATISTIC(NumGVNMaxIterations,
104 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000105STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
106STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
107STATISTIC(NumGVNAvoidedSortedLeaderChanges,
108 "Number of avoided sorted leader changes");
Daniel Berlin89fea6f2017-01-20 06:38:41 +0000109STATISTIC(NumGVNNotMostDominatingLeader,
110 "Number of times a member dominated it's new classes' leader");
Daniel Berlinc4796862017-01-27 02:37:11 +0000111STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Davide Italiano7e274e02016-12-22 16:03:48 +0000112
113//===----------------------------------------------------------------------===//
114// GVN Pass
115//===----------------------------------------------------------------------===//
116
117// Anchor methods.
118namespace llvm {
119namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000120Expression::~Expression() = default;
121BasicExpression::~BasicExpression() = default;
122CallExpression::~CallExpression() = default;
123LoadExpression::~LoadExpression() = default;
124StoreExpression::~StoreExpression() = default;
125AggregateValueExpression::~AggregateValueExpression() = default;
126PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000127}
128}
129
130// Congruence classes represent the set of expressions/instructions
131// that are all the same *during some scope in the function*.
132// That is, because of the way we perform equality propagation, and
133// because of memory value numbering, it is not correct to assume
134// you can willy-nilly replace any member with any other at any
135// point in the function.
136//
137// For any Value in the Member set, it is valid to replace any dominated member
138// with that Value.
139//
140// Every congruence class has a leader, and the leader is used to
141// symbolize instructions in a canonical way (IE every operand of an
142// instruction that is a member of the same congruence class will
143// always be replaced with leader during symbolization).
144// To simplify symbolization, we keep the leader as a constant if class can be
145// proved to be a constant value.
146// Otherwise, the leader is a randomly chosen member of the value set, it does
147// not matter which one is chosen.
148// Each congruence class also has a defining expression,
149// though the expression may be null. If it exists, it can be used for forward
150// propagation and reassociation of values.
151//
152struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000153 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000154 unsigned ID;
155 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000156 Value *RepLeader = nullptr;
Daniel Berlin26addef2017-01-20 21:04:30 +0000157 // If this is represented by a store, the value.
158 Value *RepStoredValue = nullptr;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000159 // If this class contains MemoryDefs, what is the represented memory state.
160 MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000161 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000162 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000163 // Actual members of this class.
164 MemberSet Members;
165
166 // True if this class has no members left. This is mainly used for assertion
167 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000168 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000169
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000170 // Number of stores in this congruence class.
171 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000172 int StoreCount = 0;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000173
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000174 // The most dominating leader after our current leader, because the member set
175 // is not sorted and is expensive to keep sorted all the time.
176 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
177
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000178 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000179 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000180 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000181};
182
183namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000184template <> struct DenseMapInfo<const Expression *> {
185 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000186 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000187 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
188 return reinterpret_cast<const Expression *>(Val);
189 }
190 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000191 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000192 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
193 return reinterpret_cast<const Expression *>(Val);
194 }
195 static unsigned getHashValue(const Expression *V) {
196 return static_cast<unsigned>(V->getHashValue());
197 }
198 static bool isEqual(const Expression *LHS, const Expression *RHS) {
199 if (LHS == RHS)
200 return true;
201 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
202 LHS == getEmptyKey() || RHS == getEmptyKey())
203 return false;
204 return *LHS == *RHS;
205 }
206};
Davide Italiano7e274e02016-12-22 16:03:48 +0000207} // end namespace llvm
208
209class NewGVN : public FunctionPass {
210 DominatorTree *DT;
211 const DataLayout *DL;
212 const TargetLibraryInfo *TLI;
213 AssumptionCache *AC;
214 AliasAnalysis *AA;
215 MemorySSA *MSSA;
216 MemorySSAWalker *MSSAWalker;
217 BumpPtrAllocator ExpressionAllocator;
218 ArrayRecycler<Value *> ArgRecycler;
219
220 // Congruence class info.
221 CongruenceClass *InitialClass;
222 std::vector<CongruenceClass *> CongruenceClasses;
223 unsigned NextCongruenceNum;
224
225 // Value Mappings.
226 DenseMap<Value *, CongruenceClass *> ValueToClass;
227 DenseMap<Value *, const Expression *> ValueToExpression;
228
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000229 // A table storing which memorydefs/phis represent a memory state provably
230 // equivalent to another memory state.
231 // We could use the congruence class machinery, but the MemoryAccess's are
232 // abstract memory states, so they can only ever be equivalent to each other,
233 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000234 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000235
Davide Italiano7e274e02016-12-22 16:03:48 +0000236 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000237 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000238 ExpressionClassMap ExpressionToClass;
239
240 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000241 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000242
243 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000244 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000245 DenseSet<BlockEdge> ReachableEdges;
246 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
247
248 // This is a bitvector because, on larger functions, we may have
249 // thousands of touched instructions at once (entire blocks,
250 // instructions with hundreds of uses, etc). Even with optimization
251 // for when we mark whole blocks as touched, when this was a
252 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
253 // the time in GVN just managing this list. The bitvector, on the
254 // other hand, efficiently supports test/set/clear of both
255 // individual and ranges, as well as "find next element" This
256 // enables us to use it as a worklist with essentially 0 cost.
257 BitVector TouchedInstructions;
258
259 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
260 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
261 DominatedInstRange;
262
263#ifndef NDEBUG
264 // Debugging for how many times each block and instruction got processed.
265 DenseMap<const Value *, unsigned> ProcessedCount;
266#endif
267
268 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000269 // This contains a mapping from Instructions to DFS numbers.
270 // The numbering starts at 1. An instruction with DFS number zero
271 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000272 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000273
274 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000275 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000276
277 // Deletion info.
278 SmallPtrSet<Instruction *, 8> InstructionsToErase;
279
280public:
281 static char ID; // Pass identification, replacement for typeid.
282 NewGVN() : FunctionPass(ID) {
283 initializeNewGVNPass(*PassRegistry::getPassRegistry());
284 }
285
286 bool runOnFunction(Function &F) override;
287 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000288 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000289
290private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000291 void getAnalysisUsage(AnalysisUsage &AU) const override {
292 AU.addRequired<AssumptionCacheTracker>();
293 AU.addRequired<DominatorTreeWrapperPass>();
294 AU.addRequired<TargetLibraryInfoWrapperPass>();
295 AU.addRequired<MemorySSAWrapperPass>();
296 AU.addRequired<AAResultsWrapperPass>();
297
298 AU.addPreserved<DominatorTreeWrapperPass>();
299 AU.addPreserved<GlobalsAAWrapperPass>();
300 }
301
302 // Expression handling.
303 const Expression *createExpression(Instruction *, const BasicBlock *);
304 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
305 const BasicBlock *);
306 PHIExpression *createPHIExpression(Instruction *);
307 const VariableExpression *createVariableExpression(Value *);
308 const ConstantExpression *createConstantExpression(Constant *);
309 const Expression *createVariableOrConstant(Value *V, const BasicBlock *B);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000310 const UnknownExpression *createUnknownExpression(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000311 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
312 const BasicBlock *);
313 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
314 MemoryAccess *, const BasicBlock *);
315
316 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
317 const BasicBlock *);
318 const AggregateValueExpression *
319 createAggregateValueExpression(Instruction *, const BasicBlock *);
320 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
321 const BasicBlock *);
322
323 // Congruence class handling.
324 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000325 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000326 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000327 return result;
328 }
329
330 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000331 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000332 CClass->Members.insert(Member);
333 ValueToClass[Member] = CClass;
334 return CClass;
335 }
336 void initializeCongruenceClasses(Function &F);
337
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000338 // Value number an Instruction or MemoryPhi.
339 void valueNumberMemoryPhi(MemoryPhi *);
340 void valueNumberInstruction(Instruction *);
341
Davide Italiano7e274e02016-12-22 16:03:48 +0000342 // Symbolic evaluation.
343 const Expression *checkSimplificationResults(Expression *, Instruction *,
344 Value *);
345 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
346 const Expression *performSymbolicLoadEvaluation(Instruction *,
347 const BasicBlock *);
348 const Expression *performSymbolicStoreEvaluation(Instruction *,
349 const BasicBlock *);
350 const Expression *performSymbolicCallEvaluation(Instruction *,
351 const BasicBlock *);
352 const Expression *performSymbolicPHIEvaluation(Instruction *,
353 const BasicBlock *);
354 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
355 const BasicBlock *);
356
357 // Congruence finding.
358 // Templated to allow them to work both on BB's and BB-edges.
359 template <class T>
360 Value *lookupOperandLeader(Value *, const User *, const T &) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000361 void performCongruenceFinding(Instruction *, const Expression *);
362 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000363 CongruenceClass *);
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000364 bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
365 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000366 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000367
Davide Italiano7e274e02016-12-22 16:03:48 +0000368 // Reachability handling.
369 void updateReachableEdge(BasicBlock *, BasicBlock *);
370 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000371 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000372 Value *findConditionEquivalence(Value *, BasicBlock *) const;
373
374 // Elimination.
375 struct ValueDFS;
Daniel Berlinc4796862017-01-27 02:37:11 +0000376 void convertDenseToDFSOrdered(const CongruenceClass::MemberSet &,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +0000377 SmallVectorImpl<ValueDFS> &);
Daniel Berlinc4796862017-01-27 02:37:11 +0000378 void convertDenseToLoadsAndStores(const CongruenceClass::MemberSet &,
379 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000380
381 bool eliminateInstructions(Function &);
382 void replaceInstruction(Instruction *, Value *);
383 void markInstructionForDeletion(Instruction *);
384 void deleteInstructionsInBlock(BasicBlock *);
385
386 // New instruction creation.
387 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000388
389 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000390 void markUsersTouched(Value *);
391 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000392 void markLeaderChangeTouched(CongruenceClass *CC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000393
394 // Utilities.
395 void cleanupTables();
396 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
397 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000398 void verifyMemoryCongruency() const;
399 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000400};
401
402char NewGVN::ID = 0;
403
404// createGVNPass - The public interface to this file.
405FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
406
Davide Italianob1114092016-12-28 13:37:17 +0000407template <typename T>
408static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
409 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000410 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000411 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000412 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000413 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000414 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000415 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000416 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000417 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000418 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000419 return true;
420}
421
Davide Italianob1114092016-12-28 13:37:17 +0000422bool LoadExpression::equals(const Expression &Other) const {
423 return equalsLoadStoreHelper(*this, Other);
424}
Davide Italiano7e274e02016-12-22 16:03:48 +0000425
Davide Italianob1114092016-12-28 13:37:17 +0000426bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000427 bool Result = equalsLoadStoreHelper(*this, Other);
428 // Make sure that store vs store includes the value operand.
429 if (Result)
430 if (const auto *S = dyn_cast<StoreExpression>(&Other))
431 if (getStoredValue() != S->getStoredValue())
432 return false;
433 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000434}
435
436#ifndef NDEBUG
437static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000438 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000439}
440#endif
441
442INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
443INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
444INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
445INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
446INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
447INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
448INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
449INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
450
451PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000452 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000453 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000454 auto *E =
455 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000456
457 E->allocateOperands(ArgRecycler, ExpressionAllocator);
458 E->setType(I->getType());
459 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000460
Davide Italianob3886dd2017-01-25 23:37:49 +0000461 // Filter out unreachable phi operands.
462 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000463 return ReachableBlocks.count(PN->getIncomingBlock(U));
Davide Italianob3886dd2017-01-25 23:37:49 +0000464 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000465
466 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
467 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000468 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000469 if (U == PN)
470 return PN;
Daniel Berlind92e7f92017-01-07 00:01:42 +0000471 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PHIBlock);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000472 return lookupOperandLeader(U, I, BBE);
473 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000474 return E;
475}
476
477// Set basic expression info (Arguments, type, opcode) for Expression
478// E from Instruction I in block B.
479bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
480 const BasicBlock *B) {
481 bool AllConstant = true;
482 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
483 E->setType(GEP->getSourceElementType());
484 else
485 E->setType(I->getType());
486 E->setOpcode(I->getOpcode());
487 E->allocateOperands(ArgRecycler, ExpressionAllocator);
488
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000489 // Transform the operand array into an operand leader array, and keep track of
490 // whether all members are constant.
491 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000492 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000493 AllConstant &= isa<Constant>(Operand);
494 return Operand;
495 });
496
Davide Italiano7e274e02016-12-22 16:03:48 +0000497 return AllConstant;
498}
499
500const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
501 Value *Arg1, Value *Arg2,
502 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000503 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000504
505 E->setType(T);
506 E->setOpcode(Opcode);
507 E->allocateOperands(ArgRecycler, ExpressionAllocator);
508 if (Instruction::isCommutative(Opcode)) {
509 // Ensure that commutative instructions that only differ by a permutation
510 // of their operands get the same value number by sorting the operand value
511 // numbers. Since all commutative instructions have two operands it is more
512 // efficient to sort by hand rather than using, say, std::sort.
513 if (Arg1 > Arg2)
514 std::swap(Arg1, Arg2);
515 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000516 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
517 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000518
519 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
520 DT, AC);
521 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
522 return SimplifiedE;
523 return E;
524}
525
526// Take a Value returned by simplification of Expression E/Instruction
527// I, and see if it resulted in a simpler expression. If so, return
528// that expression.
529// TODO: Once finished, this should not take an Instruction, we only
530// use it for printing.
531const Expression *NewGVN::checkSimplificationResults(Expression *E,
532 Instruction *I, Value *V) {
533 if (!V)
534 return nullptr;
535 if (auto *C = dyn_cast<Constant>(V)) {
536 if (I)
537 DEBUG(dbgs() << "Simplified " << *I << " to "
538 << " constant " << *C << "\n");
539 NumGVNOpsSimplified++;
540 assert(isa<BasicExpression>(E) &&
541 "We should always have had a basic expression here");
542
543 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
544 ExpressionAllocator.Deallocate(E);
545 return createConstantExpression(C);
546 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
547 if (I)
548 DEBUG(dbgs() << "Simplified " << *I << " to "
549 << " variable " << *V << "\n");
550 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
551 ExpressionAllocator.Deallocate(E);
552 return createVariableExpression(V);
553 }
554
555 CongruenceClass *CC = ValueToClass.lookup(V);
556 if (CC && CC->DefiningExpr) {
557 if (I)
558 DEBUG(dbgs() << "Simplified " << *I << " to "
559 << " expression " << *V << "\n");
560 NumGVNOpsSimplified++;
561 assert(isa<BasicExpression>(E) &&
562 "We should always have had a basic expression here");
563 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
564 ExpressionAllocator.Deallocate(E);
565 return CC->DefiningExpr;
566 }
567 return nullptr;
568}
569
570const Expression *NewGVN::createExpression(Instruction *I,
571 const BasicBlock *B) {
572
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000573 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000574
575 bool AllConstant = setBasicExpressionInfo(I, E, B);
576
577 if (I->isCommutative()) {
578 // Ensure that commutative instructions that only differ by a permutation
579 // of their operands get the same value number by sorting the operand value
580 // numbers. Since all commutative instructions have two operands it is more
581 // efficient to sort by hand rather than using, say, std::sort.
582 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
583 if (E->getOperand(0) > E->getOperand(1))
584 E->swapOperands(0, 1);
585 }
586
587 // Perform simplificaiton
588 // TODO: Right now we only check to see if we get a constant result.
589 // We may get a less than constant, but still better, result for
590 // some operations.
591 // IE
592 // add 0, x -> x
593 // and x, x -> x
594 // We should handle this by simply rewriting the expression.
595 if (auto *CI = dyn_cast<CmpInst>(I)) {
596 // Sort the operand value numbers so x<y and y>x get the same value
597 // number.
598 CmpInst::Predicate Predicate = CI->getPredicate();
599 if (E->getOperand(0) > E->getOperand(1)) {
600 E->swapOperands(0, 1);
601 Predicate = CmpInst::getSwappedPredicate(Predicate);
602 }
603 E->setOpcode((CI->getOpcode() << 8) | Predicate);
604 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
605 // TODO: Since we noop bitcasts, we may need to check types before
606 // simplifying, so that we don't end up simplifying based on a wrong
607 // type assumption. We should clean this up so we can use constants of the
608 // wrong type
609
610 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
611 "Wrong types on cmp instruction");
612 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
613 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
614 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
615 *DL, TLI, DT, AC);
616 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
617 return SimplifiedE;
618 }
619 } else if (isa<SelectInst>(I)) {
620 if (isa<Constant>(E->getOperand(0)) ||
621 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
622 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
623 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
624 E->getOperand(2), *DL, TLI, DT, AC);
625 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
626 return SimplifiedE;
627 }
628 } else if (I->isBinaryOp()) {
629 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
630 *DL, TLI, DT, AC);
631 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
632 return SimplifiedE;
633 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
634 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
635 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
636 return SimplifiedE;
637 } else if (isa<GetElementPtrInst>(I)) {
638 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000639 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000640 *DL, TLI, DT, AC);
641 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
642 return SimplifiedE;
643 } else if (AllConstant) {
644 // We don't bother trying to simplify unless all of the operands
645 // were constant.
646 // TODO: There are a lot of Simplify*'s we could call here, if we
647 // wanted to. The original motivating case for this code was a
648 // zext i1 false to i8, which we don't have an interface to
649 // simplify (IE there is no SimplifyZExt).
650
651 SmallVector<Constant *, 8> C;
652 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000653 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000654
655 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
656 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
657 return SimplifiedE;
658 }
659 return E;
660}
661
662const AggregateValueExpression *
663NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
664 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000665 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000666 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
667 setBasicExpressionInfo(I, E, B);
668 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000669 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000670 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000671 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000672 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000673 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
674 setBasicExpressionInfo(EI, E, B);
675 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000676 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000677 return E;
678 }
679 llvm_unreachable("Unhandled type of aggregate value operation");
680}
681
Daniel Berlin85f91b02016-12-26 20:06:58 +0000682const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000683 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000684 E->setOpcode(V->getValueID());
685 return E;
686}
687
688const Expression *NewGVN::createVariableOrConstant(Value *V,
689 const BasicBlock *B) {
690 auto Leader = lookupOperandLeader(V, nullptr, B);
691 if (auto *C = dyn_cast<Constant>(Leader))
692 return createConstantExpression(C);
693 return createVariableExpression(Leader);
694}
695
Daniel Berlin85f91b02016-12-26 20:06:58 +0000696const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000697 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000698 E->setOpcode(C->getValueID());
699 return E;
700}
701
Daniel Berlin02c6b172017-01-02 18:00:53 +0000702const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
703 auto *E = new (ExpressionAllocator) UnknownExpression(I);
704 E->setOpcode(I->getOpcode());
705 return E;
706}
707
Davide Italiano7e274e02016-12-22 16:03:48 +0000708const CallExpression *NewGVN::createCallExpression(CallInst *CI,
709 MemoryAccess *HV,
710 const BasicBlock *B) {
711 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000712 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000713 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
714 setBasicExpressionInfo(CI, E, B);
715 return E;
716}
717
718// See if we have a congruence class and leader for this operand, and if so,
719// return it. Otherwise, return the operand itself.
720template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000721Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000722 CongruenceClass *CC = ValueToClass.lookup(V);
723 if (CC && (CC != InitialClass))
Daniel Berlin26addef2017-01-20 21:04:30 +0000724 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Davide Italiano7e274e02016-12-22 16:03:48 +0000725 return V;
726}
727
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000728MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000729 auto *CC = MemoryAccessToClass.lookup(MA);
730 if (CC && CC->RepMemoryAccess)
731 return CC->RepMemoryAccess;
732 // FIXME: We need to audit all the places that current set a nullptr To, and
733 // fix them. There should always be *some* congruence class, even if it is
734 // singular. Right now, we don't bother setting congruence classes for
735 // anything but stores, which means we have to return the original access
736 // here. Otherwise, this should be unreachable.
737 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000738}
739
Daniel Berlinc4796862017-01-27 02:37:11 +0000740// Return true if the MemoryAccess is really equivalent to everything. This is
741// equivalent to the lattice value "TOP" in most lattices. This is the initial
742// state of all memory accesses.
743bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
744 return MemoryAccessToClass.lookup(MA) == InitialClass;
745}
746
Davide Italiano7e274e02016-12-22 16:03:48 +0000747LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
748 LoadInst *LI, MemoryAccess *DA,
749 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000750 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000751 E->allocateOperands(ArgRecycler, ExpressionAllocator);
752 E->setType(LoadType);
753
754 // Give store and loads same opcode so they value number together.
755 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000756 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000757 if (LI)
758 E->setAlignment(LI->getAlignment());
759
760 // TODO: Value number heap versions. We may be able to discover
761 // things alias analysis can't on it's own (IE that a store and a
762 // load have the same value, and thus, it isn't clobbering the load).
763 return E;
764}
765
766const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
767 MemoryAccess *DA,
768 const BasicBlock *B) {
Daniel Berlin26addef2017-01-20 21:04:30 +0000769 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand(), SI, B);
770 auto *E = new (ExpressionAllocator)
771 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000772 E->allocateOperands(ArgRecycler, ExpressionAllocator);
773 E->setType(SI->getValueOperand()->getType());
774
775 // Give store and loads same opcode so they value number together.
776 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000777 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000778
779 // TODO: Value number heap versions. We may be able to discover
780 // things alias analysis can't on it's own (IE that a store and a
781 // load have the same value, and thus, it isn't clobbering the load).
782 return E;
783}
784
Daniel Berlinb755aea2017-01-09 05:34:29 +0000785// Utility function to check whether the congruence class has a member other
786// than the given instruction.
787bool hasMemberOtherThanUs(const CongruenceClass *CC, Instruction *I) {
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000788 // Either it has more than one store, in which case it must contain something
789 // other than us (because it's indexed by value), or if it only has one store
Daniel Berlinb755aea2017-01-09 05:34:29 +0000790 // right now, that member should not be us.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000791 return CC->StoreCount > 1 || CC->Members.count(I) == 0;
Daniel Berlinb755aea2017-01-09 05:34:29 +0000792}
793
Davide Italiano7e274e02016-12-22 16:03:48 +0000794const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
795 const BasicBlock *B) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000796 // Unlike loads, we never try to eliminate stores, so we do not check if they
797 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000798 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000799 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000800 // Get the expression, if any, for the RHS of the MemoryDef.
801 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
802 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
803 // If we are defined by ourselves, use the live on entry def.
804 if (StoreRHS == StoreAccess)
805 StoreRHS = MSSA->getLiveOnEntryDef();
806
Daniel Berlin589cecc2017-01-02 18:00:46 +0000807 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000808 // See if we are defined by a previous store expression, it already has a
809 // value, and it's the same value as our current store. FIXME: Right now, we
810 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlinde43ef92017-01-02 19:49:17 +0000811 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000812 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000813 // Basically, check if the congruence class the store is in is defined by a
814 // store that isn't us, and has the same value. MemorySSA takes care of
815 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000816 // The RepStoredValue gets nulled if all the stores disappear in a class, so
817 // we don't need to check if the class contains a store besides us.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000818 if (CC &&
Daniel Berlin26addef2017-01-20 21:04:30 +0000819 CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand(), SI, B))
Daniel Berlin589cecc2017-01-02 18:00:46 +0000820 return createStoreExpression(SI, StoreRHS, B);
Daniel Berlinc4796862017-01-27 02:37:11 +0000821 // Also check if our value operand is defined by a load of the same memory
822 // location, and the memory state is the same as it was then
823 // (otherwise, it could have been overwritten later. See test32 in
824 // transforms/DeadStoreElimination/simple.ll)
825 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
826 if ((lookupOperandLeader(LI->getPointerOperand(), LI, LI->getParent()) ==
827 lookupOperandLeader(SI->getPointerOperand(), SI, B)) &&
828 (lookupMemoryAccessEquiv(
829 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
830 return createVariableExpression(LI);
831 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000832 }
833 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000834}
835
836const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
837 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000838 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000839
840 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000841 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000842 if (!LI->isSimple())
843 return nullptr;
844
Daniel Berlin85f91b02016-12-26 20:06:58 +0000845 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000846 // Load of undef is undef.
847 if (isa<UndefValue>(LoadAddressLeader))
848 return createConstantExpression(UndefValue::get(LI->getType()));
849
850 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
851
852 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
853 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
854 Instruction *DefiningInst = MD->getMemoryInst();
855 // If the defining instruction is not reachable, replace with undef.
856 if (!ReachableBlocks.count(DefiningInst->getParent()))
857 return createConstantExpression(UndefValue::get(LI->getType()));
858 }
859 }
860
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000861 const Expression *E =
862 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
863 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000864 return E;
865}
866
867// Evaluate read only and pure calls, and create an expression result.
868const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
869 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000870 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000871 if (AA->doesNotAccessMemory(CI))
872 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000873 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000874 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000875 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000876 }
877 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000878}
879
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000880// Update the memory access equivalence table to say that From is equal to To,
881// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000882// FIXME: We need to audit all the places that current set a nullptr To, and fix
883// them. There should always be *some* congruence class, even if it is singular.
884bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
885 DEBUG(dbgs() << "Setting " << *From);
886 if (To) {
887 DEBUG(dbgs() << " equivalent to congruence class ");
888 DEBUG(dbgs() << To->ID << " with current memory access leader ");
889 DEBUG(dbgs() << *To->RepMemoryAccess);
890 } else {
891 DEBUG(dbgs() << " equivalent to itself");
892 DEBUG(dbgs() << "\n");
893 }
894
895 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000896 bool Changed = false;
897 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000898 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000899 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000900 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000901 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000902 Changed = true;
903 } else if (!To) {
904 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000905 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000906 Changed = true;
907 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000908 } else {
909 assert(!To &&
910 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000911 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000912
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000913 return Changed;
914}
Davide Italiano7e274e02016-12-22 16:03:48 +0000915// Evaluate PHI nodes symbolically, and create an expression result.
916const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
917 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000918 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +0000919 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
920
921 // See if all arguaments are the same.
922 // We track if any were undef because they need special handling.
923 bool HasUndef = false;
924 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
925 if (Arg == I)
926 return false;
927 if (isa<UndefValue>(Arg)) {
928 HasUndef = true;
929 return false;
930 }
931 return true;
932 });
933 // If we are left with no operands, it's undef
934 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000935 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
936 << "\n");
937 E->deallocateOperands(ArgRecycler);
938 ExpressionAllocator.Deallocate(E);
939 return createConstantExpression(UndefValue::get(I->getType()));
940 }
Daniel Berlind92e7f92017-01-07 00:01:42 +0000941 Value *AllSameValue = *(Filtered.begin());
942 ++Filtered.begin();
943 // Can't use std::equal here, sadly, because filter.begin moves.
944 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
945 return V == AllSameValue;
946 })) {
947 // In LLVM's non-standard representation of phi nodes, it's possible to have
948 // phi nodes with cycles (IE dependent on other phis that are .... dependent
949 // on the original phi node), especially in weird CFG's where some arguments
950 // are unreachable, or uninitialized along certain paths. This can cause
951 // infinite loops during evaluation. We work around this by not trying to
952 // really evaluate them independently, but instead using a variable
953 // expression to say if one is equivalent to the other.
954 // We also special case undef, so that if we have an undef, we can't use the
955 // common value unless it dominates the phi block.
956 if (HasUndef) {
957 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +0000958 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +0000959 if (!DT->dominates(AllSameInst, I))
960 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000961 }
962
Davide Italiano7e274e02016-12-22 16:03:48 +0000963 NumGVNPhisAllSame++;
964 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
965 << "\n");
966 E->deallocateOperands(ArgRecycler);
967 ExpressionAllocator.Deallocate(E);
968 if (auto *C = dyn_cast<Constant>(AllSameValue))
969 return createConstantExpression(C);
970 return createVariableExpression(AllSameValue);
971 }
972 return E;
973}
974
975const Expression *
976NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
977 const BasicBlock *B) {
978 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
979 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
980 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
981 unsigned Opcode = 0;
982 // EI might be an extract from one of our recognised intrinsics. If it
983 // is we'll synthesize a semantically equivalent expression instead on
984 // an extract value expression.
985 switch (II->getIntrinsicID()) {
986 case Intrinsic::sadd_with_overflow:
987 case Intrinsic::uadd_with_overflow:
988 Opcode = Instruction::Add;
989 break;
990 case Intrinsic::ssub_with_overflow:
991 case Intrinsic::usub_with_overflow:
992 Opcode = Instruction::Sub;
993 break;
994 case Intrinsic::smul_with_overflow:
995 case Intrinsic::umul_with_overflow:
996 Opcode = Instruction::Mul;
997 break;
998 default:
999 break;
1000 }
1001
1002 if (Opcode != 0) {
1003 // Intrinsic recognized. Grab its args to finish building the
1004 // expression.
1005 assert(II->getNumArgOperands() == 2 &&
1006 "Expect two args for recognised intrinsics.");
1007 return createBinaryExpression(Opcode, EI->getType(),
1008 II->getArgOperand(0),
1009 II->getArgOperand(1), B);
1010 }
1011 }
1012 }
1013
1014 return createAggregateValueExpression(I, B);
1015}
1016
1017// Substitute and symbolize the value before value numbering.
1018const Expression *NewGVN::performSymbolicEvaluation(Value *V,
1019 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +00001020 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001021 if (auto *C = dyn_cast<Constant>(V))
1022 E = createConstantExpression(C);
1023 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1024 E = createVariableExpression(V);
1025 } else {
1026 // TODO: memory intrinsics.
1027 // TODO: Some day, we should do the forward propagation and reassociation
1028 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001029 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001030 switch (I->getOpcode()) {
1031 case Instruction::ExtractValue:
1032 case Instruction::InsertValue:
1033 E = performSymbolicAggrValueEvaluation(I, B);
1034 break;
1035 case Instruction::PHI:
1036 E = performSymbolicPHIEvaluation(I, B);
1037 break;
1038 case Instruction::Call:
1039 E = performSymbolicCallEvaluation(I, B);
1040 break;
1041 case Instruction::Store:
1042 E = performSymbolicStoreEvaluation(I, B);
1043 break;
1044 case Instruction::Load:
1045 E = performSymbolicLoadEvaluation(I, B);
1046 break;
1047 case Instruction::BitCast: {
1048 E = createExpression(I, B);
1049 } break;
1050
1051 case Instruction::Add:
1052 case Instruction::FAdd:
1053 case Instruction::Sub:
1054 case Instruction::FSub:
1055 case Instruction::Mul:
1056 case Instruction::FMul:
1057 case Instruction::UDiv:
1058 case Instruction::SDiv:
1059 case Instruction::FDiv:
1060 case Instruction::URem:
1061 case Instruction::SRem:
1062 case Instruction::FRem:
1063 case Instruction::Shl:
1064 case Instruction::LShr:
1065 case Instruction::AShr:
1066 case Instruction::And:
1067 case Instruction::Or:
1068 case Instruction::Xor:
1069 case Instruction::ICmp:
1070 case Instruction::FCmp:
1071 case Instruction::Trunc:
1072 case Instruction::ZExt:
1073 case Instruction::SExt:
1074 case Instruction::FPToUI:
1075 case Instruction::FPToSI:
1076 case Instruction::UIToFP:
1077 case Instruction::SIToFP:
1078 case Instruction::FPTrunc:
1079 case Instruction::FPExt:
1080 case Instruction::PtrToInt:
1081 case Instruction::IntToPtr:
1082 case Instruction::Select:
1083 case Instruction::ExtractElement:
1084 case Instruction::InsertElement:
1085 case Instruction::ShuffleVector:
1086 case Instruction::GetElementPtr:
1087 E = createExpression(I, B);
1088 break;
1089 default:
1090 return nullptr;
1091 }
1092 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001093 return E;
1094}
1095
1096// There is an edge from 'Src' to 'Dst'. Return true if every path from
1097// the entry block to 'Dst' passes via this edge. In particular 'Dst'
1098// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +00001099bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001100
1101 // While in theory it is interesting to consider the case in which Dst has
1102 // more than one predecessor, because Dst might be part of a loop which is
1103 // only reachable from Src, in practice it is pointless since at the time
1104 // GVN runs all such loops have preheaders, which means that Dst will have
1105 // been changed to have only one predecessor, namely Src.
1106 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1107 const BasicBlock *Src = E.getStart();
1108 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
1109 (void)Src;
1110 return Pred != nullptr;
1111}
1112
1113void NewGVN::markUsersTouched(Value *V) {
1114 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001115 for (auto *User : V->users()) {
1116 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001117 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001118 }
1119}
1120
1121void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1122 for (auto U : MA->users()) {
1123 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001124 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001125 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001126 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001127 }
1128}
1129
Daniel Berlin32f8d562017-01-07 16:55:14 +00001130// Touch the instructions that need to be updated after a congruence class has a
1131// leader change, and mark changed values.
1132void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1133 for (auto M : CC->Members) {
1134 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001135 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001136 LeaderChanges.insert(M);
1137 }
1138}
1139
1140// Move a value, currently in OldClass, to be part of NewClass
1141// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001142void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1143 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001144 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001145 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001146 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001147
1148 if (I == OldClass->NextLeader.first)
1149 OldClass->NextLeader = {nullptr, ~0U};
1150
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001151 // It's possible, though unlikely, for us to discover equivalences such
1152 // that the current leader does not dominate the old one.
1153 // This statistic tracks how often this happens.
1154 // We assert on phi nodes when this happens, currently, for debugging, because
1155 // we want to make sure we name phi node cycles properly.
1156 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1157 I != NewClass->RepLeader &&
1158 DT->properlyDominates(
1159 I->getParent(),
1160 cast<Instruction>(NewClass->RepLeader)->getParent())) {
1161 ++NumGVNNotMostDominatingLeader;
1162 assert(!isa<PHINode>(I) &&
1163 "New class for instruction should not be dominated by instruction");
1164 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001165
1166 if (NewClass->RepLeader != I) {
1167 auto DFSNum = InstrDFS.lookup(I);
1168 if (DFSNum < NewClass->NextLeader.second)
1169 NewClass->NextLeader = {I, DFSNum};
1170 }
1171
1172 OldClass->Members.erase(I);
1173 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001174 MemoryAccess *StoreAccess = nullptr;
1175 if (auto *SI = dyn_cast<StoreInst>(I)) {
1176 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001177 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001178 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001179 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001180 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001181 if (!NewClass->RepMemoryAccess) {
1182 // If we don't have a representative memory access, it better be the only
1183 // store in there.
1184 assert(NewClass->StoreCount == 1);
1185 NewClass->RepMemoryAccess = StoreAccess;
1186 }
1187 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001188 }
1189
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001190 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001191 // See if we destroyed the class or need to swap leaders.
1192 if (OldClass->Members.empty() && OldClass != InitialClass) {
1193 if (OldClass->DefiningExpr) {
1194 OldClass->Dead = true;
1195 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1196 << " from table\n");
1197 ExpressionToClass.erase(OldClass->DefiningExpr);
1198 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001199 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001200 // When the leader changes, the value numbering of
1201 // everything may change due to symbolization changes, so we need to
1202 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001203 DEBUG(dbgs() << "Leader change!\n");
1204 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001205 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001206 if (OldClass->StoreCount == 0) {
1207 if (OldClass->RepStoredValue != nullptr)
1208 OldClass->RepStoredValue = nullptr;
1209 if (OldClass->RepMemoryAccess != nullptr)
1210 OldClass->RepMemoryAccess = nullptr;
1211 }
1212
1213 // If we destroy the old access leader, we have to effectively destroy the
1214 // congruence class. When it comes to scalars, anything with the same value
1215 // is as good as any other. That means that one leader is as good as
1216 // another, and as long as you have some leader for the value, you are
1217 // good.. When it comes to *memory states*, only one particular thing really
1218 // represents the definition of a given memory state. Once it goes away, we
1219 // need to re-evaluate which pieces of memory are really still
1220 // equivalent. The best way to do this is to re-value number things. The
1221 // only way to really make that happen is to destroy the rest of the class.
1222 // In order to effectively destroy the class, we reset ExpressionToClass for
1223 // each by using the ValueToExpression mapping. The members later get
1224 // marked as touched due to the leader change. We will create new
1225 // congruence classes, and the pieces that are still equivalent will end
1226 // back together in a new class. If this becomes too expensive, it is
1227 // possible to use a versioning scheme for the congruence classes to avoid
1228 // the expressions finding this old class.
1229 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1230 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1231 << " because memory access leader changed");
1232 for (auto Member : OldClass->Members)
1233 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1234 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001235
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001236 // We don't need to sort members if there is only 1, and we don't care about
1237 // sorting the initial class because everything either gets out of it or is
1238 // unreachable.
1239 if (OldClass->Members.size() == 1 || OldClass == InitialClass) {
1240 OldClass->RepLeader = *(OldClass->Members.begin());
1241 } else if (OldClass->NextLeader.first) {
1242 ++NumGVNAvoidedSortedLeaderChanges;
1243 OldClass->RepLeader = OldClass->NextLeader.first;
1244 OldClass->NextLeader = {nullptr, ~0U};
1245 } else {
1246 ++NumGVNSortedLeaderChanges;
1247 // TODO: If this ends up to slow, we can maintain a dual structure for
1248 // member testing/insertion, or keep things mostly sorted, and sort only
1249 // here, or ....
1250 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1251 for (const auto X : OldClass->Members) {
1252 auto DFSNum = InstrDFS.lookup(X);
1253 if (DFSNum < MinDFS.second)
1254 MinDFS = {X, DFSNum};
1255 }
1256 OldClass->RepLeader = MinDFS.first;
1257 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001258 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001259 }
1260}
1261
Davide Italiano7e274e02016-12-22 16:03:48 +00001262// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001263void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1264 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001265 // This is guaranteed to return something, since it will at least find
1266 // INITIAL.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001267
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001268 CongruenceClass *IClass = ValueToClass[I];
1269 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001270 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001271 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001272
1273 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001274 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001275 EClass = ValueToClass[VE->getVariableValue()];
1276 } else {
1277 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1278
1279 // If it's not in the value table, create a new congruence class.
1280 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001281 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001282 auto place = lookupResult.first;
1283 place->second = NewClass;
1284
1285 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001286 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001287 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001288 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1289 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001290 NewClass->RepLeader = SI;
1291 NewClass->RepStoredValue =
Daniel Berlin32f8d562017-01-07 16:55:14 +00001292 lookupOperandLeader(SI->getValueOperand(), SI, SI->getParent());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001293 // The RepMemoryAccess field will be filled in properly by the
1294 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001295 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001296 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001297 }
1298 assert(!isa<VariableExpression>(E) &&
1299 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001300
1301 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001302 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001303 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001304 << " and leader " << *(NewClass->RepLeader));
1305 if (NewClass->RepStoredValue)
1306 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1307 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001308 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1309 } else {
1310 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001311 if (isa<ConstantExpression>(E))
1312 assert(isa<Constant>(EClass->RepLeader) &&
1313 "Any class with a constant expression should have a "
1314 "constant leader");
1315
Davide Italiano7e274e02016-12-22 16:03:48 +00001316 assert(EClass && "Somehow don't have an eclass");
1317
1318 assert(!EClass->Dead && "We accidentally looked up a dead class");
1319 }
1320 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001321 bool ClassChanged = IClass != EClass;
1322 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001323 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001324 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1325 << "\n");
1326
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001327 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001328 moveValueToNewCongruenceClass(I, IClass, EClass);
1329 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001330 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001331 markMemoryUsersTouched(MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001332 }
1333}
1334
1335// Process the fact that Edge (from, to) is reachable, including marking
1336// any newly reachable blocks and instructions for processing.
1337void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1338 // Check if the Edge was reachable before.
1339 if (ReachableEdges.insert({From, To}).second) {
1340 // If this block wasn't reachable before, all instructions are touched.
1341 if (ReachableBlocks.insert(To).second) {
1342 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1343 const auto &InstRange = BlockInstRange.lookup(To);
1344 TouchedInstructions.set(InstRange.first, InstRange.second);
1345 } else {
1346 DEBUG(dbgs() << "Block " << getBlockName(To)
1347 << " was reachable, but new edge {" << getBlockName(From)
1348 << "," << getBlockName(To) << "} to it found\n");
1349
1350 // We've made an edge reachable to an existing block, which may
1351 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1352 // they are the only thing that depend on new edges. Anything using their
1353 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001354 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001355 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001356
Davide Italiano7e274e02016-12-22 16:03:48 +00001357 auto BI = To->begin();
1358 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001359 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001360 ++BI;
1361 }
1362 }
1363 }
1364}
1365
1366// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1367// see if we know some constant value for it already.
1368Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1369 auto Result = lookupOperandLeader(Cond, nullptr, B);
1370 if (isa<Constant>(Result))
1371 return Result;
1372 return nullptr;
1373}
1374
1375// Process the outgoing edges of a block for reachability.
1376void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1377 // Evaluate reachability of terminator instruction.
1378 BranchInst *BR;
1379 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1380 Value *Cond = BR->getCondition();
1381 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1382 if (!CondEvaluated) {
1383 if (auto *I = dyn_cast<Instruction>(Cond)) {
1384 const Expression *E = createExpression(I, B);
1385 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1386 CondEvaluated = CE->getConstantValue();
1387 }
1388 } else if (isa<ConstantInt>(Cond)) {
1389 CondEvaluated = Cond;
1390 }
1391 }
1392 ConstantInt *CI;
1393 BasicBlock *TrueSucc = BR->getSuccessor(0);
1394 BasicBlock *FalseSucc = BR->getSuccessor(1);
1395 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1396 if (CI->isOne()) {
1397 DEBUG(dbgs() << "Condition for Terminator " << *TI
1398 << " evaluated to true\n");
1399 updateReachableEdge(B, TrueSucc);
1400 } else if (CI->isZero()) {
1401 DEBUG(dbgs() << "Condition for Terminator " << *TI
1402 << " evaluated to false\n");
1403 updateReachableEdge(B, FalseSucc);
1404 }
1405 } else {
1406 updateReachableEdge(B, TrueSucc);
1407 updateReachableEdge(B, FalseSucc);
1408 }
1409 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1410 // For switches, propagate the case values into the case
1411 // destinations.
1412
1413 // Remember how many outgoing edges there are to every successor.
1414 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1415
Davide Italiano7e274e02016-12-22 16:03:48 +00001416 Value *SwitchCond = SI->getCondition();
1417 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1418 // See if we were able to turn this switch statement into a constant.
1419 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001420 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001421 // We should be able to get case value for this.
1422 auto CaseVal = SI->findCaseValue(CondVal);
1423 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1424 // We proved the value is outside of the range of the case.
1425 // We can't do anything other than mark the default dest as reachable,
1426 // and go home.
1427 updateReachableEdge(B, SI->getDefaultDest());
1428 return;
1429 }
1430 // Now get where it goes and mark it reachable.
1431 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1432 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001433 } else {
1434 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1435 BasicBlock *TargetBlock = SI->getSuccessor(i);
1436 ++SwitchEdges[TargetBlock];
1437 updateReachableEdge(B, TargetBlock);
1438 }
1439 }
1440 } else {
1441 // Otherwise this is either unconditional, or a type we have no
1442 // idea about. Just mark successors as reachable.
1443 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1444 BasicBlock *TargetBlock = TI->getSuccessor(i);
1445 updateReachableEdge(B, TargetBlock);
1446 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001447
1448 // This also may be a memory defining terminator, in which case, set it
1449 // equivalent to nothing.
1450 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1451 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001452 }
1453}
1454
Daniel Berlin85f91b02016-12-26 20:06:58 +00001455// The algorithm initially places the values of the routine in the INITIAL
1456// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001457// class. The leader of INITIAL is the undetermined value `TOP`.
1458// When the algorithm has finished, values still in INITIAL are unreachable.
1459void NewGVN::initializeCongruenceClasses(Function &F) {
1460 // FIXME now i can't remember why this is 2
1461 NextCongruenceNum = 2;
1462 // Initialize all other instructions to be in INITIAL class.
1463 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001464 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001465 InitialClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001466 for (auto &B : F) {
1467 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001468 MemoryAccessToClass[MP] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001469
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001470 for (auto &I : B) {
1471 InitialValues.insert(&I);
1472 ValueToClass[&I] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001473 // All memory accesses are equivalent to live on entry to start. They must
1474 // be initialized to something so that initial changes are noticed. For
1475 // the maximal answer, we initialize them all to be the same as
1476 // liveOnEntry. Note that to save time, we only initialize the
1477 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1478 // other expression can generate a memory equivalence. If we start
1479 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001480 if (isa<StoreInst>(&I)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001481 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = InitialClass;
Davide Italianoeac05f62017-01-11 23:41:24 +00001482 ++InitialClass->StoreCount;
1483 assert(InitialClass->StoreCount > 0);
1484 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001485 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001486 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001487 InitialClass->Members.swap(InitialValues);
1488
1489 // Initialize arguments to be in their own unique congruence classes
1490 for (auto &FA : F.args())
1491 createSingletonCongruenceClass(&FA);
1492}
1493
1494void NewGVN::cleanupTables() {
1495 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1496 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1497 << CongruenceClasses[i]->Members.size() << " members\n");
1498 // Make sure we delete the congruence class (probably worth switching to
1499 // a unique_ptr at some point.
1500 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001501 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001502 }
1503
1504 ValueToClass.clear();
1505 ArgRecycler.clear(ExpressionAllocator);
1506 ExpressionAllocator.Reset();
1507 CongruenceClasses.clear();
1508 ExpressionToClass.clear();
1509 ValueToExpression.clear();
1510 ReachableBlocks.clear();
1511 ReachableEdges.clear();
1512#ifndef NDEBUG
1513 ProcessedCount.clear();
1514#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001515 InstrDFS.clear();
1516 InstructionsToErase.clear();
1517
1518 DFSToInstr.clear();
1519 BlockInstRange.clear();
1520 TouchedInstructions.clear();
1521 DominatedInstRange.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001522 MemoryAccessToClass.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001523}
1524
1525std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1526 unsigned Start) {
1527 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001528 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1529 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001530 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001531 }
1532
Davide Italiano7e274e02016-12-22 16:03:48 +00001533 for (auto &I : *B) {
1534 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001535 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001536 }
1537
1538 // All of the range functions taken half-open ranges (open on the end side).
1539 // So we do not subtract one from count, because at this point it is one
1540 // greater than the last instruction.
1541 return std::make_pair(Start, End);
1542}
1543
1544void NewGVN::updateProcessedCount(Value *V) {
1545#ifndef NDEBUG
1546 if (ProcessedCount.count(V) == 0) {
1547 ProcessedCount.insert({V, 1});
1548 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001549 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001550 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001551 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001552 }
1553#endif
1554}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001555// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1556void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1557 // If all the arguments are the same, the MemoryPhi has the same value as the
1558 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001559 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001560 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001561 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1562 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
1563 ReachableBlocks.count(MP->getIncomingBlock(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001564 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001565 // If all that is left is nothing, our memoryphi is undef. We keep it as
1566 // InitialClass. Note: The only case this should happen is if we have at
1567 // least one self-argument.
1568 if (Filtered.begin() == Filtered.end()) {
1569 if (setMemoryAccessEquivTo(MP, InitialClass))
1570 markMemoryUsersTouched(MP);
1571 return;
1572 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001573
1574 // Transform the remaining operands into operand leaders.
1575 // FIXME: mapped_iterator should have a range version.
1576 auto LookupFunc = [&](const Use &U) {
1577 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1578 };
1579 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1580 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1581
1582 // and now check if all the elements are equal.
1583 // Sadly, we can't use std::equals since these are random access iterators.
1584 MemoryAccess *AllSameValue = *MappedBegin;
1585 ++MappedBegin;
1586 bool AllEqual = std::all_of(
1587 MappedBegin, MappedEnd,
1588 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1589
1590 if (AllEqual)
1591 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1592 else
1593 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1594
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001595 if (setMemoryAccessEquivTo(
1596 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001597 markMemoryUsersTouched(MP);
1598}
1599
1600// Value number a single instruction, symbolically evaluating, performing
1601// congruence finding, and updating mappings.
1602void NewGVN::valueNumberInstruction(Instruction *I) {
1603 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001604
1605 // There's no need to call isInstructionTriviallyDead more than once on
1606 // an instruction. Therefore, once we know that an instruction is dead
1607 // we change its DFS number so that it doesn't get numbered again.
1608 if (InstrDFS[I] != 0 && isInstructionTriviallyDead(I, TLI)) {
1609 InstrDFS[I] = 0;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001610 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001611 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001612 return;
1613 }
1614 if (!I->isTerminator()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001615 const auto *Symbolized = performSymbolicEvaluation(I, I->getParent());
1616 // If we couldn't come up with a symbolic expression, use the unknown
1617 // expression
1618 if (Symbolized == nullptr)
1619 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001620 performCongruenceFinding(I, Symbolized);
1621 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001622 // Handle terminators that return values. All of them produce values we
1623 // don't currently understand.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001624 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001625 auto *Symbolized = createUnknownExpression(I);
1626 performCongruenceFinding(I, Symbolized);
1627 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001628 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1629 }
1630}
Davide Italiano7e274e02016-12-22 16:03:48 +00001631
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001632// Check if there is a path, using single or equal argument phi nodes, from
1633// First to Second.
1634bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1635 const MemoryAccess *Second) const {
1636 if (First == Second)
1637 return true;
1638
1639 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1640 auto *DefAccess = FirstDef->getDefiningAccess();
1641 return singleReachablePHIPath(DefAccess, Second);
1642 } else {
1643 auto *MP = cast<MemoryPhi>(First);
1644 auto ReachableOperandPred = [&](const Use &U) {
1645 return ReachableBlocks.count(MP->getIncomingBlock(U));
1646 };
1647 auto FilteredPhiArgs =
1648 make_filter_range(MP->operands(), ReachableOperandPred);
1649 SmallVector<const Value *, 32> OperandList;
1650 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1651 std::back_inserter(OperandList));
1652 bool Okay = OperandList.size() == 1;
1653 if (!Okay)
1654 Okay = std::equal(OperandList.begin(), OperandList.end(),
1655 OperandList.begin());
1656 if (Okay)
1657 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1658 return false;
1659 }
1660}
1661
Daniel Berlin589cecc2017-01-02 18:00:46 +00001662// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001663// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001664// subject to very rare false negatives. It is only useful for
1665// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001666void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001667 // Anything equivalent in the memory access table should be in the same
1668 // congruence class.
1669
1670 // Filter out the unreachable and trivially dead entries, because they may
1671 // never have been updated if the instructions were not processed.
1672 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001673 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001674 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1675 if (!Result)
1676 return false;
1677 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1678 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1679 return true;
1680 };
1681
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001682 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001683 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001684 // Unreachable instructions may not have changed because we never process
1685 // them.
1686 if (!ReachableBlocks.count(KV.first->getBlock()))
1687 continue;
1688 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001689 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001690 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001691 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001692 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1693 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1694 "The instructions for these memory operations should have "
1695 "been in the same congruence class or reachable through"
1696 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001697 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1698
1699 // We can only sanely verify that MemoryDefs in the operand list all have
1700 // the same class.
1701 auto ReachableOperandPred = [&](const Use &U) {
1702 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1703 isa<MemoryDef>(U);
1704
1705 };
1706 // All arguments should in the same class, ignoring unreachable arguments
1707 auto FilteredPhiArgs =
1708 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1709 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1710 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1711 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1712 const MemoryDef *MD = cast<MemoryDef>(U);
1713 return ValueToClass.lookup(MD->getMemoryInst());
1714 });
1715 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1716 PhiOpClasses.begin()) &&
1717 "All MemoryPhi arguments should be in the same class");
1718 }
1719 }
1720}
1721
Daniel Berlin85f91b02016-12-26 20:06:58 +00001722// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001723bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001724 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1725 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001726 bool Changed = false;
1727 DT = _DT;
1728 AC = _AC;
1729 TLI = _TLI;
1730 AA = _AA;
1731 MSSA = _MSSA;
1732 DL = &F.getParent()->getDataLayout();
1733 MSSAWalker = MSSA->getWalker();
1734
1735 // Count number of instructions for sizing of hash tables, and come
1736 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001737 unsigned ICount = 1;
1738 // Add an empty instruction to account for the fact that we start at 1
1739 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001740 // Note: We want RPO traversal of the blocks, which is not quite the same as
1741 // dominator tree order, particularly with regard whether backedges get
1742 // visited first or second, given a block with multiple successors.
1743 // If we visit in the wrong order, we will end up performing N times as many
1744 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001745 // The dominator tree does guarantee that, for a given dom tree node, it's
1746 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1747 // the siblings.
1748 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001749 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001750 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001751 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001752 auto *Node = DT->getNode(B);
1753 assert(Node && "RPO and Dominator tree should have same reachability");
1754 RPOOrdering[Node] = ++Counter;
1755 }
1756 // Sort dominator tree children arrays into RPO.
1757 for (auto &B : RPOT) {
1758 auto *Node = DT->getNode(B);
1759 if (Node->getChildren().size() > 1)
1760 std::sort(Node->begin(), Node->end(),
1761 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1762 return RPOOrdering[A] < RPOOrdering[B];
1763 });
1764 }
1765
1766 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1767 auto DFI = df_begin(DT->getRootNode());
1768 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1769 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001770 const auto &BlockRange = assignDFSNumbers(B, ICount);
1771 BlockInstRange.insert({B, BlockRange});
1772 ICount += BlockRange.second - BlockRange.first;
1773 }
1774
1775 // Handle forward unreachable blocks and figure out which blocks
1776 // have single preds.
1777 for (auto &B : F) {
1778 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001779 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001780 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1781 BlockInstRange.insert({&B, BlockRange});
1782 ICount += BlockRange.second - BlockRange.first;
1783 }
1784 }
1785
Daniel Berline0bd37e2016-12-29 22:15:12 +00001786 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001787 DominatedInstRange.reserve(F.size());
1788 // Ensure we don't end up resizing the expressionToClass map, as
1789 // that can be quite expensive. At most, we have one expression per
1790 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001791 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001792
1793 // Initialize the touched instructions to include the entry block.
1794 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1795 TouchedInstructions.set(InstRange.first, InstRange.second);
1796 ReachableBlocks.insert(&F.getEntryBlock());
1797
1798 initializeCongruenceClasses(F);
1799
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001800 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001801 // We start out in the entry block.
1802 BasicBlock *LastBlock = &F.getEntryBlock();
1803 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001804 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00001805 // Walk through all the instructions in all the blocks in RPO.
1806 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1807 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001808
1809 // This instruction was found to be dead. We don't bother looking
1810 // at it again.
1811 if (InstrNum == 0) {
1812 TouchedInstructions.reset(InstrNum);
1813 continue;
1814 }
1815
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001816 Value *V = DFSToInstr[InstrNum];
1817 BasicBlock *CurrBlock = nullptr;
1818
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001819 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001820 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001821 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001822 CurrBlock = MP->getBlock();
1823 else
1824 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001825
1826 // If we hit a new block, do reachability processing.
1827 if (CurrBlock != LastBlock) {
1828 LastBlock = CurrBlock;
1829 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1830 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1831
1832 // If it's not reachable, erase any touched instructions and move on.
1833 if (!BlockReachable) {
1834 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1835 DEBUG(dbgs() << "Skipping instructions in block "
1836 << getBlockName(CurrBlock)
1837 << " because it is unreachable\n");
1838 continue;
1839 }
1840 updateProcessedCount(CurrBlock);
1841 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001842
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001843 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001844 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1845 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001846 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001847 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001848 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001849 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001850 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001851 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001852 // Reset after processing (because we may mark ourselves as touched when
1853 // we propagate equalities).
1854 TouchedInstructions.reset(InstrNum);
1855 }
1856 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001857 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001858#ifndef NDEBUG
1859 verifyMemoryCongruency();
1860#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001861 Changed |= eliminateInstructions(F);
1862
1863 // Delete all instructions marked for deletion.
1864 for (Instruction *ToErase : InstructionsToErase) {
1865 if (!ToErase->use_empty())
1866 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1867
1868 ToErase->eraseFromParent();
1869 }
1870
1871 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001872 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1873 return !ReachableBlocks.count(&BB);
1874 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001875
1876 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1877 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001878 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001879 deleteInstructionsInBlock(&BB);
1880 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001881 }
1882
1883 cleanupTables();
1884 return Changed;
1885}
1886
1887bool NewGVN::runOnFunction(Function &F) {
1888 if (skipFunction(F))
1889 return false;
1890 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1891 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1892 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1893 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1894 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1895}
1896
Daniel Berlin85f91b02016-12-26 20:06:58 +00001897PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001898 NewGVN Impl;
1899
1900 // Apparently the order in which we get these results matter for
1901 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1902 // the same order here, just in case.
1903 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1904 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1905 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1906 auto &AA = AM.getResult<AAManager>(F);
1907 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1908 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1909 if (!Changed)
1910 return PreservedAnalyses::all();
1911 PreservedAnalyses PA;
1912 PA.preserve<DominatorTreeAnalysis>();
1913 PA.preserve<GlobalsAA>();
1914 return PA;
1915}
1916
1917// Return true if V is a value that will always be available (IE can
1918// be placed anywhere) in the function. We don't do globals here
1919// because they are often worse to put in place.
1920// TODO: Separate cost from availability
1921static bool alwaysAvailable(Value *V) {
1922 return isa<Constant>(V) || isa<Argument>(V);
1923}
1924
1925// Get the basic block from an instruction/value.
1926static BasicBlock *getBlockForValue(Value *V) {
1927 if (auto *I = dyn_cast<Instruction>(V))
1928 return I->getParent();
1929 return nullptr;
1930}
1931
1932struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001933 int DFSIn = 0;
1934 int DFSOut = 0;
1935 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001936 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001937 Value *Val = nullptr;
1938 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001939
1940 bool operator<(const ValueDFS &Other) const {
1941 // It's not enough that any given field be less than - we have sets
1942 // of fields that need to be evaluated together to give a proper ordering.
1943 // For example, if you have;
1944 // DFS (1, 3)
1945 // Val 0
1946 // DFS (1, 2)
1947 // Val 50
1948 // We want the second to be less than the first, but if we just go field
1949 // by field, we will get to Val 0 < Val 50 and say the first is less than
1950 // the second. We only want it to be less than if the DFS orders are equal.
1951 //
1952 // Each LLVM instruction only produces one value, and thus the lowest-level
1953 // differentiator that really matters for the stack (and what we use as as a
1954 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001955 // Everything else in the structure is instruction level, and only affects
1956 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001957 //
1958 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1959 // the order of replacement of uses does not matter.
1960 // IE given,
1961 // a = 5
1962 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001963 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1964 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001965 // The .val will be the same as well.
1966 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001967 // You will replace both, and it does not matter what order you replace them
1968 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1969 // operand 2).
1970 // Similarly for the case of same dfsin, dfsout, localnum, but different
1971 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001972 // a = 5
1973 // b = 6
1974 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001975 // in c, we will a valuedfs for a, and one for b,with everything the same
1976 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001977 // It does not matter what order we replace these operands in.
1978 // You will always end up with the same IR, and this is guaranteed.
1979 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1980 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1981 Other.U);
1982 }
1983};
1984
Daniel Berlinc4796862017-01-27 02:37:11 +00001985// This function converts the set of members for a congruence class from values,
1986// to sets of defs and uses with associated DFS info.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001987void NewGVN::convertDenseToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00001988 const CongruenceClass::MemberSet &Dense,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001989 SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001990 for (auto D : Dense) {
1991 // First add the value.
1992 BasicBlock *BB = getBlockForValue(D);
1993 // Constants are handled prior to ever calling this function, so
1994 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001995 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001996 ValueDFS VD;
Daniel Berlinb66164c2017-01-14 00:24:23 +00001997 DomTreeNode *DomNode = DT->getNode(BB);
1998 VD.DFSIn = DomNode->getDFSNumIn();
1999 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00002000 // If it's a store, use the leader of the value operand.
2001 if (auto *SI = dyn_cast<StoreInst>(D)) {
2002 auto Leader =
2003 lookupOperandLeader(SI->getValueOperand(), SI, SI->getParent());
2004 VD.Val = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
2005 } else {
2006 VD.Val = D;
2007 }
2008
Davide Italiano7e274e02016-12-22 16:03:48 +00002009 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlinaac56842017-01-15 09:18:41 +00002010 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002011 else
2012 llvm_unreachable("Should have been an instruction");
2013
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002014 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00002015
Daniel Berlinb66164c2017-01-14 00:24:23 +00002016 // Now add the uses.
Davide Italiano7e274e02016-12-22 16:03:48 +00002017 for (auto &U : D->uses()) {
2018 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
2019 ValueDFS VD;
2020 // Put the phi node uses in the incoming block.
2021 BasicBlock *IBlock;
2022 if (auto *P = dyn_cast<PHINode>(I)) {
2023 IBlock = P->getIncomingBlock(U);
2024 // Make phi node users appear last in the incoming block
2025 // they are from.
2026 VD.LocalNum = InstrDFS.size() + 1;
2027 } else {
2028 IBlock = I->getParent();
Daniel Berlinaac56842017-01-15 09:18:41 +00002029 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002030 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002031
2032 // Skip uses in unreachable blocks, as we're going
2033 // to delete them.
2034 if (ReachableBlocks.count(IBlock) == 0)
2035 continue;
2036
Daniel Berlinb66164c2017-01-14 00:24:23 +00002037 DomTreeNode *DomNode = DT->getNode(IBlock);
2038 VD.DFSIn = DomNode->getDFSNumIn();
2039 VD.DFSOut = DomNode->getDFSNumOut();
Davide Italiano7e274e02016-12-22 16:03:48 +00002040 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002041 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00002042 }
2043 }
2044 }
2045}
2046
Daniel Berlinc4796862017-01-27 02:37:11 +00002047// This function converts the set of members for a congruence class from values,
2048// to the set of defs for loads and stores, with associated DFS info.
2049void NewGVN::convertDenseToLoadsAndStores(
2050 const CongruenceClass::MemberSet &Dense,
2051 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2052 for (auto D : Dense) {
2053 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2054 continue;
2055
2056 BasicBlock *BB = getBlockForValue(D);
2057 ValueDFS VD;
2058 DomTreeNode *DomNode = DT->getNode(BB);
2059 VD.DFSIn = DomNode->getDFSNumIn();
2060 VD.DFSOut = DomNode->getDFSNumOut();
2061 VD.Val = D;
2062
2063 // If it's an instruction, use the real local dfs number.
2064 if (auto *I = dyn_cast<Instruction>(D))
2065 VD.LocalNum = InstrDFS.lookup(I);
2066 else
2067 llvm_unreachable("Should have been an instruction");
2068
2069 LoadsAndStores.emplace_back(VD);
2070 }
2071}
2072
Davide Italiano7e274e02016-12-22 16:03:48 +00002073static void patchReplacementInstruction(Instruction *I, Value *Repl) {
2074 // Patch the replacement so that it is not more restrictive than the value
2075 // being replaced.
2076 auto *Op = dyn_cast<BinaryOperator>(I);
2077 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
2078
2079 if (Op && ReplOp)
2080 ReplOp->andIRFlags(Op);
2081
2082 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
2083 // FIXME: If both the original and replacement value are part of the
2084 // same control-flow region (meaning that the execution of one
2085 // guarentees the executation of the other), then we can combine the
2086 // noalias scopes here and do better than the general conservative
2087 // answer used in combineMetadata().
2088
2089 // In general, GVN unifies expressions over different control-flow
2090 // regions, and so we need a conservative combination of the noalias
2091 // scopes.
2092 unsigned KnownIDs[] = {
2093 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2094 LLVMContext::MD_noalias, LLVMContext::MD_range,
2095 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2096 LLVMContext::MD_invariant_group};
2097 combineMetadata(ReplInst, I, KnownIDs);
2098 }
2099}
2100
2101static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2102 patchReplacementInstruction(I, Repl);
2103 I->replaceAllUsesWith(Repl);
2104}
2105
2106void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2107 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2108 ++NumGVNBlocksDeleted;
2109
Daniel Berlin2b834922017-01-26 18:30:29 +00002110 // Change to unreachable does not handle destroying phi nodes. We just replace
2111 // the users with undef.
2112 if (BB->empty())
Davide Italiano7e274e02016-12-22 16:03:48 +00002113 return;
Daniel Berlin2b834922017-01-26 18:30:29 +00002114 auto BBI = BB->begin();
2115 while (auto *Phi = dyn_cast<PHINode>(BBI)) {
2116 Phi->replaceAllUsesWith(UndefValue::get(Phi->getType()));
2117 ++BBI;
Davide Italiano7e274e02016-12-22 16:03:48 +00002118 }
Daniel Berlin2b834922017-01-26 18:30:29 +00002119
2120 Instruction *ToKill = &*BBI;
2121 // Nothing but phi nodes, so nothing left to remove.
2122 if (!ToKill)
2123 return;
2124 NumGVNInstrDeleted += changeToUnreachable(ToKill, false);
Davide Italiano7e274e02016-12-22 16:03:48 +00002125}
2126
2127void NewGVN::markInstructionForDeletion(Instruction *I) {
2128 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2129 InstructionsToErase.insert(I);
2130}
2131
2132void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2133
2134 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2135 patchAndReplaceAllUsesWith(I, V);
2136 // We save the actual erasing to avoid invalidating memory
2137 // dependencies until we are done with everything.
2138 markInstructionForDeletion(I);
2139}
2140
2141namespace {
2142
2143// This is a stack that contains both the value and dfs info of where
2144// that value is valid.
2145class ValueDFSStack {
2146public:
2147 Value *back() const { return ValueStack.back(); }
2148 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2149
2150 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002151 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002152 DFSStack.emplace_back(DFSIn, DFSOut);
2153 }
2154 bool empty() const { return DFSStack.empty(); }
2155 bool isInScope(int DFSIn, int DFSOut) const {
2156 if (empty())
2157 return false;
2158 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2159 }
2160
2161 void popUntilDFSScope(int DFSIn, int DFSOut) {
2162
2163 // These two should always be in sync at this point.
2164 assert(ValueStack.size() == DFSStack.size() &&
2165 "Mismatch between ValueStack and DFSStack");
2166 while (
2167 !DFSStack.empty() &&
2168 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2169 DFSStack.pop_back();
2170 ValueStack.pop_back();
2171 }
2172 }
2173
2174private:
2175 SmallVector<Value *, 8> ValueStack;
2176 SmallVector<std::pair<int, int>, 8> DFSStack;
2177};
2178}
Daniel Berlin04443432017-01-07 03:23:47 +00002179
Davide Italiano7e274e02016-12-22 16:03:48 +00002180bool NewGVN::eliminateInstructions(Function &F) {
2181 // This is a non-standard eliminator. The normal way to eliminate is
2182 // to walk the dominator tree in order, keeping track of available
2183 // values, and eliminating them. However, this is mildly
2184 // pointless. It requires doing lookups on every instruction,
2185 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002186 // instructions part of most singleton congruence classes, we know we
2187 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002188
2189 // Instead, this eliminator looks at the congruence classes directly, sorts
2190 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002191 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002192 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002193 // last member. This is worst case O(E log E) where E = number of
2194 // instructions in a single congruence class. In theory, this is all
2195 // instructions. In practice, it is much faster, as most instructions are
2196 // either in singleton congruence classes or can't possibly be eliminated
2197 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002198 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002199 // for elimination purposes.
2200 // TODO: If we wanted to be faster, We could remove any members with no
2201 // overlapping ranges while sorting, as we will never eliminate anything
2202 // with those members, as they don't dominate anything else in our set.
2203
Davide Italiano7e274e02016-12-22 16:03:48 +00002204 bool AnythingReplaced = false;
2205
2206 // Since we are going to walk the domtree anyway, and we can't guarantee the
2207 // DFS numbers are updated, we compute some ourselves.
2208 DT->updateDFSNumbers();
2209
2210 for (auto &B : F) {
2211 if (!ReachableBlocks.count(&B)) {
2212 for (const auto S : successors(&B)) {
2213 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002214 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002215 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2216 << getBlockName(&B)
2217 << " with undef due to it being unreachable\n");
2218 for (auto &Operand : Phi.incoming_values())
2219 if (Phi.getIncomingBlock(Operand) == &B)
2220 Operand.set(UndefValue::get(Phi.getType()));
2221 }
2222 }
2223 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002224 }
2225
2226 for (CongruenceClass *CC : CongruenceClasses) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002227 // Track the equivalent store info so we can decide whether to try
2228 // dead store elimination.
2229 SmallVector<ValueDFS, 8> PossibleDeadStores;
2230
Davide Italiano7e274e02016-12-22 16:03:48 +00002231 // FIXME: We should eventually be able to replace everything still
2232 // in the initial class with undef, as they should be unreachable.
2233 // Right now, initial still contains some things we skip value
2234 // numbering of (UNREACHABLE's, for example).
2235 if (CC == InitialClass || CC->Dead)
2236 continue;
2237 assert(CC->RepLeader && "We should have had a leader");
2238
2239 // If this is a leader that is always available, and it's a
2240 // constant or has no equivalences, just replace everything with
2241 // it. We then update the congruence class with whatever members
2242 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002243 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2244 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002245 SmallPtrSet<Value *, 4> MembersLeft;
2246 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002247 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002248 // Void things have no uses we can replace.
2249 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2250 MembersLeft.insert(Member);
2251 continue;
2252 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002253 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2254 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002255 // Due to equality propagation, these may not always be
2256 // instructions, they may be real values. We don't really
2257 // care about trying to replace the non-instructions.
2258 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002259 assert(Leader != I && "About to accidentally remove our leader");
2260 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002261 AnythingReplaced = true;
2262
2263 continue;
2264 } else {
2265 MembersLeft.insert(I);
2266 }
2267 }
2268 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002269 } else {
2270 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2271 // If this is a singleton, we can skip it.
2272 if (CC->Members.size() != 1) {
2273
2274 // This is a stack because equality replacement/etc may place
2275 // constants in the middle of the member list, and we want to use
2276 // those constant values in preference to the current leader, over
2277 // the scope of those constants.
2278 ValueDFSStack EliminationStack;
2279
2280 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002281 SmallVector<ValueDFS, 8> DFSOrderedSet;
Davide Italiano7e274e02016-12-22 16:03:48 +00002282 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2283
2284 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002285 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002286 for (auto &VD : DFSOrderedSet) {
2287 int MemberDFSIn = VD.DFSIn;
2288 int MemberDFSOut = VD.DFSOut;
2289 Value *Member = VD.Val;
2290 Use *MemberUse = VD.U;
Davide Italiano7e274e02016-12-22 16:03:48 +00002291
Daniel Berlinc4796862017-01-27 02:37:11 +00002292 // We ignore void things because we can't get a value from them.
2293 if (Member && Member->getType()->isVoidTy())
2294 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002295
2296 if (EliminationStack.empty()) {
2297 DEBUG(dbgs() << "Elimination Stack is empty\n");
2298 } else {
2299 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2300 << EliminationStack.dfs_back().first << ","
2301 << EliminationStack.dfs_back().second << ")\n");
2302 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002303
2304 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2305 << MemberDFSOut << ")\n");
2306 // First, we see if we are out of scope or empty. If so,
2307 // and there equivalences, we try to replace the top of
2308 // stack with equivalences (if it's on the stack, it must
2309 // not have been eliminated yet).
2310 // Then we synchronize to our current scope, by
2311 // popping until we are back within a DFS scope that
2312 // dominates the current member.
2313 // Then, what happens depends on a few factors
2314 // If the stack is now empty, we need to push
2315 // If we have a constant or a local equivalence we want to
2316 // start using, we also push.
2317 // Otherwise, we walk along, processing members who are
2318 // dominated by this scope, and eliminate them.
2319 bool ShouldPush =
2320 Member && (EliminationStack.empty() || isa<Constant>(Member));
2321 bool OutOfScope =
2322 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2323
2324 if (OutOfScope || ShouldPush) {
2325 // Sync to our current scope.
2326 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2327 ShouldPush |= Member && EliminationStack.empty();
2328 if (ShouldPush) {
2329 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2330 }
2331 }
2332
2333 // If we get to this point, and the stack is empty we must have a use
2334 // with nothing we can use to eliminate it, just skip it.
2335 if (EliminationStack.empty())
2336 continue;
2337
2338 // Skip the Value's, we only want to eliminate on their uses.
2339 if (Member)
2340 continue;
2341 Value *Result = EliminationStack.back();
2342
Daniel Berlind92e7f92017-01-07 00:01:42 +00002343 // Don't replace our existing users with ourselves.
2344 if (MemberUse->get() == Result)
Davide Italiano7e274e02016-12-22 16:03:48 +00002345 continue;
2346
2347 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2348 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2349 << "\n");
2350
2351 // If we replaced something in an instruction, handle the patching of
2352 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002353 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002354 patchReplacementInstruction(ReplacedInst, Result);
2355
2356 assert(isa<Instruction>(MemberUse->getUser()));
2357 MemberUse->set(Result);
2358 AnythingReplaced = true;
2359 }
2360 }
2361 }
2362
2363 // Cleanup the congruence class.
2364 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002365 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002366 if (Member->getType()->isVoidTy()) {
2367 MembersLeft.insert(Member);
2368 continue;
2369 }
2370
2371 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2372 if (isInstructionTriviallyDead(MemberInst)) {
2373 // TODO: Don't mark loads of undefs.
2374 markInstructionForDeletion(MemberInst);
2375 continue;
2376 }
2377 }
2378 MembersLeft.insert(Member);
2379 }
2380 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002381
2382 // If we have possible dead stores to look at, try to eliminate them.
2383 if (CC->StoreCount > 0) {
2384 convertDenseToLoadsAndStores(CC->Members, PossibleDeadStores);
2385 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2386 ValueDFSStack EliminationStack;
2387 for (auto &VD : PossibleDeadStores) {
2388 int MemberDFSIn = VD.DFSIn;
2389 int MemberDFSOut = VD.DFSOut;
2390 Instruction *Member = cast<Instruction>(VD.Val);
2391 if (EliminationStack.empty() ||
2392 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2393 // Sync to our current scope.
2394 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2395 if (EliminationStack.empty()) {
2396 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2397 continue;
2398 }
2399 }
2400 // We already did load elimination, so nothing to do here.
2401 if (isa<LoadInst>(Member))
2402 continue;
2403 assert(!EliminationStack.empty());
2404 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002405 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002406 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2407 // Member is dominater by Leader, and thus dead
2408 DEBUG(dbgs() << "Marking dead store " << *Member
2409 << " that is dominated by " << *Leader << "\n");
2410 markInstructionForDeletion(Member);
2411 CC->Members.erase(Member);
2412 ++NumGVNDeadStores;
2413 }
2414 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002415 }
2416
2417 return AnythingReplaced;
2418}