blob: e67cd1f2818c0fd63f854b79a7ad42fb825e8279 [file] [log] [blame]
Davide Italiano7e274e02016-12-22 16:03:48 +00001//===---- NewGVN.cpp - Global Value Numbering Pass --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file implements the new LLVM's Global Value Numbering pass.
11/// GVN partitions values computed by a function into congruence classes.
12/// Values ending up in the same congruence class are guaranteed to be the same
13/// for every execution of the program. In that respect, congruency is a
14/// compile-time approximation of equivalence of values at runtime.
15/// The algorithm implemented here uses a sparse formulation and it's based
16/// on the ideas described in the paper:
17/// "A Sparse Algorithm for Predicated Global Value Numbering" from
18/// Karthik Gargi.
19///
Daniel Berlindb3c7be2017-01-26 21:39:49 +000020/// A brief overview of the algorithm: The algorithm is essentially the same as
21/// the standard RPO value numbering algorithm (a good reference is the paper
22/// "SCC based value numbering" by L. Taylor Simpson) with one major difference:
23/// The RPO algorithm proceeds, on every iteration, to process every reachable
24/// block and every instruction in that block. This is because the standard RPO
25/// algorithm does not track what things have the same value number, it only
26/// tracks what the value number of a given operation is (the mapping is
27/// operation -> value number). Thus, when a value number of an operation
28/// changes, it must reprocess everything to ensure all uses of a value number
29/// get updated properly. In constrast, the sparse algorithm we use *also*
30/// tracks what operations have a given value number (IE it also tracks the
31/// reverse mapping from value number -> operations with that value number), so
32/// that it only needs to reprocess the instructions that are affected when
33/// something's value number changes. The rest of the algorithm is devoted to
34/// performing symbolic evaluation, forward propagation, and simplification of
35/// operations based on the value numbers deduced so far.
36///
37/// We also do not perform elimination by using any published algorithm. All
38/// published algorithms are O(Instructions). Instead, we use a technique that
39/// is O(number of operations with the same value number), enabling us to skip
40/// trying to eliminate things that have unique value numbers.
Davide Italiano7e274e02016-12-22 16:03:48 +000041//===----------------------------------------------------------------------===//
42
43#include "llvm/Transforms/Scalar/NewGVN.h"
44#include "llvm/ADT/BitVector.h"
45#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/DenseSet.h"
47#include "llvm/ADT/DepthFirstIterator.h"
48#include "llvm/ADT/Hashing.h"
49#include "llvm/ADT/MapVector.h"
50#include "llvm/ADT/PostOrderIterator.h"
Daniel Berlind7c12ee2016-12-25 22:23:49 +000051#include "llvm/ADT/STLExtras.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000052#include "llvm/ADT/SmallPtrSet.h"
53#include "llvm/ADT/SmallSet.h"
54#include "llvm/ADT/SparseBitVector.h"
55#include "llvm/ADT/Statistic.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include "llvm/Analysis/AliasAnalysis.h"
58#include "llvm/Analysis/AssumptionCache.h"
59#include "llvm/Analysis/CFG.h"
60#include "llvm/Analysis/CFGPrinter.h"
61#include "llvm/Analysis/ConstantFolding.h"
62#include "llvm/Analysis/GlobalsModRef.h"
63#include "llvm/Analysis/InstructionSimplify.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000064#include "llvm/Analysis/MemoryBuiltins.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000065#include "llvm/Analysis/MemoryLocation.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000066#include "llvm/Analysis/TargetLibraryInfo.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000067#include "llvm/IR/DataLayout.h"
68#include "llvm/IR/Dominators.h"
69#include "llvm/IR/GlobalVariable.h"
70#include "llvm/IR/IRBuilder.h"
71#include "llvm/IR/IntrinsicInst.h"
72#include "llvm/IR/LLVMContext.h"
73#include "llvm/IR/Metadata.h"
74#include "llvm/IR/PatternMatch.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000075#include "llvm/IR/Type.h"
76#include "llvm/Support/Allocator.h"
77#include "llvm/Support/CommandLine.h"
78#include "llvm/Support/Debug.h"
79#include "llvm/Transforms/Scalar.h"
80#include "llvm/Transforms/Scalar/GVNExpression.h"
81#include "llvm/Transforms/Utils/BasicBlockUtils.h"
82#include "llvm/Transforms/Utils/Local.h"
83#include "llvm/Transforms/Utils/MemorySSA.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000084#include <unordered_map>
85#include <utility>
86#include <vector>
87using namespace llvm;
88using namespace PatternMatch;
89using namespace llvm::GVNExpression;
90
91#define DEBUG_TYPE "newgvn"
92
93STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
94STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
95STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
96STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +000097STATISTIC(NumGVNMaxIterations,
98 "Maximum Number of iterations it took to converge GVN");
Daniel Berlinc0431fd2017-01-13 22:40:01 +000099STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
100STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
101STATISTIC(NumGVNAvoidedSortedLeaderChanges,
102 "Number of avoided sorted leader changes");
Daniel Berlin89fea6f2017-01-20 06:38:41 +0000103STATISTIC(NumGVNNotMostDominatingLeader,
104 "Number of times a member dominated it's new classes' leader");
Daniel Berlinc4796862017-01-27 02:37:11 +0000105STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
Davide Italiano7e274e02016-12-22 16:03:48 +0000106
107//===----------------------------------------------------------------------===//
108// GVN Pass
109//===----------------------------------------------------------------------===//
110
111// Anchor methods.
112namespace llvm {
113namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000114Expression::~Expression() = default;
115BasicExpression::~BasicExpression() = default;
116CallExpression::~CallExpression() = default;
117LoadExpression::~LoadExpression() = default;
118StoreExpression::~StoreExpression() = default;
119AggregateValueExpression::~AggregateValueExpression() = default;
120PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +0000121}
122}
123
124// Congruence classes represent the set of expressions/instructions
125// that are all the same *during some scope in the function*.
126// That is, because of the way we perform equality propagation, and
127// because of memory value numbering, it is not correct to assume
128// you can willy-nilly replace any member with any other at any
129// point in the function.
130//
131// For any Value in the Member set, it is valid to replace any dominated member
132// with that Value.
133//
134// Every congruence class has a leader, and the leader is used to
135// symbolize instructions in a canonical way (IE every operand of an
136// instruction that is a member of the same congruence class will
137// always be replaced with leader during symbolization).
138// To simplify symbolization, we keep the leader as a constant if class can be
139// proved to be a constant value.
140// Otherwise, the leader is a randomly chosen member of the value set, it does
141// not matter which one is chosen.
142// Each congruence class also has a defining expression,
143// though the expression may be null. If it exists, it can be used for forward
144// propagation and reassociation of values.
145//
146struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000147 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000148 unsigned ID;
149 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000150 Value *RepLeader = nullptr;
Daniel Berlin26addef2017-01-20 21:04:30 +0000151 // If this is represented by a store, the value.
152 Value *RepStoredValue = nullptr;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000153 // If this class contains MemoryDefs, what is the represented memory state.
154 MemoryAccess *RepMemoryAccess = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000155 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000156 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000157 // Actual members of this class.
158 MemberSet Members;
159
160 // True if this class has no members left. This is mainly used for assertion
161 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000162 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000163
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000164 // Number of stores in this congruence class.
165 // This is used so we can detect store equivalence changes properly.
Davide Italianoeac05f62017-01-11 23:41:24 +0000166 int StoreCount = 0;
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000167
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000168 // The most dominating leader after our current leader, because the member set
169 // is not sorted and is expensive to keep sorted all the time.
170 std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
171
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000172 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000173 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000174 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000175};
176
177namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000178template <> struct DenseMapInfo<const Expression *> {
179 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000180 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000181 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
182 return reinterpret_cast<const Expression *>(Val);
183 }
184 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000185 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000186 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
187 return reinterpret_cast<const Expression *>(Val);
188 }
189 static unsigned getHashValue(const Expression *V) {
190 return static_cast<unsigned>(V->getHashValue());
191 }
192 static bool isEqual(const Expression *LHS, const Expression *RHS) {
193 if (LHS == RHS)
194 return true;
195 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
196 LHS == getEmptyKey() || RHS == getEmptyKey())
197 return false;
198 return *LHS == *RHS;
199 }
200};
Davide Italiano7e274e02016-12-22 16:03:48 +0000201} // end namespace llvm
202
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000203namespace {
Davide Italiano7e274e02016-12-22 16:03:48 +0000204class NewGVN : public FunctionPass {
205 DominatorTree *DT;
206 const DataLayout *DL;
207 const TargetLibraryInfo *TLI;
208 AssumptionCache *AC;
209 AliasAnalysis *AA;
210 MemorySSA *MSSA;
211 MemorySSAWalker *MSSAWalker;
212 BumpPtrAllocator ExpressionAllocator;
213 ArrayRecycler<Value *> ArgRecycler;
214
215 // Congruence class info.
216 CongruenceClass *InitialClass;
217 std::vector<CongruenceClass *> CongruenceClasses;
218 unsigned NextCongruenceNum;
219
220 // Value Mappings.
221 DenseMap<Value *, CongruenceClass *> ValueToClass;
222 DenseMap<Value *, const Expression *> ValueToExpression;
223
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000224 // A table storing which memorydefs/phis represent a memory state provably
225 // equivalent to another memory state.
226 // We could use the congruence class machinery, but the MemoryAccess's are
227 // abstract memory states, so they can only ever be equivalent to each other,
228 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000229 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000230
Davide Italiano7e274e02016-12-22 16:03:48 +0000231 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000232 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000233 ExpressionClassMap ExpressionToClass;
234
235 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000236 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000237
238 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000239 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000240 DenseSet<BlockEdge> ReachableEdges;
241 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
242
243 // This is a bitvector because, on larger functions, we may have
244 // thousands of touched instructions at once (entire blocks,
245 // instructions with hundreds of uses, etc). Even with optimization
246 // for when we mark whole blocks as touched, when this was a
247 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
248 // the time in GVN just managing this list. The bitvector, on the
249 // other hand, efficiently supports test/set/clear of both
250 // individual and ranges, as well as "find next element" This
251 // enables us to use it as a worklist with essentially 0 cost.
252 BitVector TouchedInstructions;
253
254 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
255 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
256 DominatedInstRange;
257
258#ifndef NDEBUG
259 // Debugging for how many times each block and instruction got processed.
260 DenseMap<const Value *, unsigned> ProcessedCount;
261#endif
262
263 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000264 // This contains a mapping from Instructions to DFS numbers.
265 // The numbering starts at 1. An instruction with DFS number zero
266 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000267 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000268
269 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000270 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000271
272 // Deletion info.
273 SmallPtrSet<Instruction *, 8> InstructionsToErase;
274
275public:
276 static char ID; // Pass identification, replacement for typeid.
277 NewGVN() : FunctionPass(ID) {
278 initializeNewGVNPass(*PassRegistry::getPassRegistry());
279 }
280
281 bool runOnFunction(Function &F) override;
282 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000283 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000284
285private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000286 void getAnalysisUsage(AnalysisUsage &AU) const override {
287 AU.addRequired<AssumptionCacheTracker>();
288 AU.addRequired<DominatorTreeWrapperPass>();
289 AU.addRequired<TargetLibraryInfoWrapperPass>();
290 AU.addRequired<MemorySSAWrapperPass>();
291 AU.addRequired<AAResultsWrapperPass>();
292
293 AU.addPreserved<DominatorTreeWrapperPass>();
294 AU.addPreserved<GlobalsAAWrapperPass>();
295 }
296
297 // Expression handling.
Daniel Berlin97718e62017-01-31 22:32:03 +0000298 const Expression *createExpression(Instruction *);
299 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000300 PHIExpression *createPHIExpression(Instruction *);
301 const VariableExpression *createVariableExpression(Value *);
302 const ConstantExpression *createConstantExpression(Constant *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000303 const Expression *createVariableOrConstant(Value *V);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000304 const UnknownExpression *createUnknownExpression(Instruction *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000305 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000306 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin97718e62017-01-31 22:32:03 +0000307 MemoryAccess *);
308 const CallExpression *createCallExpression(CallInst *, MemoryAccess *);
309 const AggregateValueExpression *createAggregateValueExpression(Instruction *);
310 bool setBasicExpressionInfo(Instruction *, BasicExpression *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000311
312 // Congruence class handling.
313 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000314 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000315 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000316 return result;
317 }
318
319 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000320 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000321 CClass->Members.insert(Member);
322 ValueToClass[Member] = CClass;
323 return CClass;
324 }
325 void initializeCongruenceClasses(Function &F);
326
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000327 // Value number an Instruction or MemoryPhi.
328 void valueNumberMemoryPhi(MemoryPhi *);
329 void valueNumberInstruction(Instruction *);
330
Davide Italiano7e274e02016-12-22 16:03:48 +0000331 // Symbolic evaluation.
332 const Expression *checkSimplificationResults(Expression *, Instruction *,
333 Value *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000334 const Expression *performSymbolicEvaluation(Value *);
335 const Expression *performSymbolicLoadEvaluation(Instruction *);
336 const Expression *performSymbolicStoreEvaluation(Instruction *);
337 const Expression *performSymbolicCallEvaluation(Instruction *);
338 const Expression *performSymbolicPHIEvaluation(Instruction *);
339 const Expression *performSymbolicAggrValueEvaluation(Instruction *);
340 const Expression *performSymbolicCmpEvaluation(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000341
342 // Congruence finding.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000343 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000344 void performCongruenceFinding(Instruction *, const Expression *);
345 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000346 CongruenceClass *);
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000347 bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
348 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000349 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000350
Davide Italiano7e274e02016-12-22 16:03:48 +0000351 // Reachability handling.
352 void updateReachableEdge(BasicBlock *, BasicBlock *);
353 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000354 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Daniel Berlin97718e62017-01-31 22:32:03 +0000355 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000356
357 // Elimination.
358 struct ValueDFS;
Daniel Berlinc4796862017-01-27 02:37:11 +0000359 void convertDenseToDFSOrdered(const CongruenceClass::MemberSet &,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +0000360 SmallVectorImpl<ValueDFS> &);
Daniel Berlinc4796862017-01-27 02:37:11 +0000361 void convertDenseToLoadsAndStores(const CongruenceClass::MemberSet &,
362 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000363
364 bool eliminateInstructions(Function &);
365 void replaceInstruction(Instruction *, Value *);
366 void markInstructionForDeletion(Instruction *);
367 void deleteInstructionsInBlock(BasicBlock *);
368
369 // New instruction creation.
370 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000371
372 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000373 void markUsersTouched(Value *);
374 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000375 void markLeaderChangeTouched(CongruenceClass *CC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000376
377 // Utilities.
378 void cleanupTables();
379 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
380 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000381 void verifyMemoryCongruency() const;
382 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000383};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000384} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000385
386char NewGVN::ID = 0;
387
388// createGVNPass - The public interface to this file.
389FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
390
Davide Italianob1114092016-12-28 13:37:17 +0000391template <typename T>
392static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
393 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000394 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000395 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000396 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000397 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000398 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000399 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000400 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000401 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000402 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000403 return true;
404}
405
Davide Italianob1114092016-12-28 13:37:17 +0000406bool LoadExpression::equals(const Expression &Other) const {
407 return equalsLoadStoreHelper(*this, Other);
408}
Davide Italiano7e274e02016-12-22 16:03:48 +0000409
Davide Italianob1114092016-12-28 13:37:17 +0000410bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000411 bool Result = equalsLoadStoreHelper(*this, Other);
412 // Make sure that store vs store includes the value operand.
413 if (Result)
414 if (const auto *S = dyn_cast<StoreExpression>(&Other))
415 if (getStoredValue() != S->getStoredValue())
416 return false;
417 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000418}
419
420#ifndef NDEBUG
421static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000422 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000423}
424#endif
425
426INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
427INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
428INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
429INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
430INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
431INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
432INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
433INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
434
435PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000436 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000437 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000438 auto *E =
439 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000440
441 E->allocateOperands(ArgRecycler, ExpressionAllocator);
442 E->setType(I->getType());
443 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000444
Davide Italianob3886dd2017-01-25 23:37:49 +0000445 // Filter out unreachable phi operands.
446 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000447 return ReachableBlocks.count(PN->getIncomingBlock(U));
Davide Italianob3886dd2017-01-25 23:37:49 +0000448 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000449
450 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
451 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000452 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000453 if (U == PN)
454 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000455 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000456 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000457 return E;
458}
459
460// Set basic expression info (Arguments, type, opcode) for Expression
461// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000462bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000463 bool AllConstant = true;
464 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
465 E->setType(GEP->getSourceElementType());
466 else
467 E->setType(I->getType());
468 E->setOpcode(I->getOpcode());
469 E->allocateOperands(ArgRecycler, ExpressionAllocator);
470
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000471 // Transform the operand array into an operand leader array, and keep track of
472 // whether all members are constant.
473 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000474 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000475 AllConstant &= isa<Constant>(Operand);
476 return Operand;
477 });
478
Davide Italiano7e274e02016-12-22 16:03:48 +0000479 return AllConstant;
480}
481
482const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000483 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000484 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000485
486 E->setType(T);
487 E->setOpcode(Opcode);
488 E->allocateOperands(ArgRecycler, ExpressionAllocator);
489 if (Instruction::isCommutative(Opcode)) {
490 // Ensure that commutative instructions that only differ by a permutation
491 // of their operands get the same value number by sorting the operand value
492 // numbers. Since all commutative instructions have two operands it is more
493 // efficient to sort by hand rather than using, say, std::sort.
494 if (Arg1 > Arg2)
495 std::swap(Arg1, Arg2);
496 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000497 E->op_push_back(lookupOperandLeader(Arg1));
498 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000499
500 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
501 DT, AC);
502 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
503 return SimplifiedE;
504 return E;
505}
506
507// Take a Value returned by simplification of Expression E/Instruction
508// I, and see if it resulted in a simpler expression. If so, return
509// that expression.
510// TODO: Once finished, this should not take an Instruction, we only
511// use it for printing.
512const Expression *NewGVN::checkSimplificationResults(Expression *E,
513 Instruction *I, Value *V) {
514 if (!V)
515 return nullptr;
516 if (auto *C = dyn_cast<Constant>(V)) {
517 if (I)
518 DEBUG(dbgs() << "Simplified " << *I << " to "
519 << " constant " << *C << "\n");
520 NumGVNOpsSimplified++;
521 assert(isa<BasicExpression>(E) &&
522 "We should always have had a basic expression here");
523
524 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
525 ExpressionAllocator.Deallocate(E);
526 return createConstantExpression(C);
527 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
528 if (I)
529 DEBUG(dbgs() << "Simplified " << *I << " to "
530 << " variable " << *V << "\n");
531 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
532 ExpressionAllocator.Deallocate(E);
533 return createVariableExpression(V);
534 }
535
536 CongruenceClass *CC = ValueToClass.lookup(V);
537 if (CC && CC->DefiningExpr) {
538 if (I)
539 DEBUG(dbgs() << "Simplified " << *I << " to "
540 << " expression " << *V << "\n");
541 NumGVNOpsSimplified++;
542 assert(isa<BasicExpression>(E) &&
543 "We should always have had a basic expression here");
544 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
545 ExpressionAllocator.Deallocate(E);
546 return CC->DefiningExpr;
547 }
548 return nullptr;
549}
550
Daniel Berlin97718e62017-01-31 22:32:03 +0000551const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000552 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000553
Daniel Berlin97718e62017-01-31 22:32:03 +0000554 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000555
556 if (I->isCommutative()) {
557 // Ensure that commutative instructions that only differ by a permutation
558 // of their operands get the same value number by sorting the operand value
559 // numbers. Since all commutative instructions have two operands it is more
560 // efficient to sort by hand rather than using, say, std::sort.
561 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
562 if (E->getOperand(0) > E->getOperand(1))
563 E->swapOperands(0, 1);
564 }
565
566 // Perform simplificaiton
567 // TODO: Right now we only check to see if we get a constant result.
568 // We may get a less than constant, but still better, result for
569 // some operations.
570 // IE
571 // add 0, x -> x
572 // and x, x -> x
573 // We should handle this by simply rewriting the expression.
574 if (auto *CI = dyn_cast<CmpInst>(I)) {
575 // Sort the operand value numbers so x<y and y>x get the same value
576 // number.
577 CmpInst::Predicate Predicate = CI->getPredicate();
578 if (E->getOperand(0) > E->getOperand(1)) {
579 E->swapOperands(0, 1);
580 Predicate = CmpInst::getSwappedPredicate(Predicate);
581 }
582 E->setOpcode((CI->getOpcode() << 8) | Predicate);
583 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000584 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
585 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000586 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
587 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000588 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin97718e62017-01-31 22:32:03 +0000589 *DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000590 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
591 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000592 } else if (isa<SelectInst>(I)) {
593 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000594 E->getOperand(0) == E->getOperand(1)) {
595 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
596 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000597 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
598 E->getOperand(2), *DL, TLI, DT, AC);
599 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
600 return SimplifiedE;
601 }
602 } else if (I->isBinaryOp()) {
603 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
604 *DL, TLI, DT, AC);
605 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
606 return SimplifiedE;
607 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
608 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
609 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
610 return SimplifiedE;
611 } else if (isa<GetElementPtrInst>(I)) {
612 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000613 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000614 *DL, TLI, DT, AC);
615 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
616 return SimplifiedE;
617 } else if (AllConstant) {
618 // We don't bother trying to simplify unless all of the operands
619 // were constant.
620 // TODO: There are a lot of Simplify*'s we could call here, if we
621 // wanted to. The original motivating case for this code was a
622 // zext i1 false to i8, which we don't have an interface to
623 // simplify (IE there is no SimplifyZExt).
624
625 SmallVector<Constant *, 8> C;
626 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000627 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000628
629 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
630 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
631 return SimplifiedE;
632 }
633 return E;
634}
635
636const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000637NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000638 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000639 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000640 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000641 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000642 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000643 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000644 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000645 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000646 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000647 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000648 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000649 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000650 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000651 return E;
652 }
653 llvm_unreachable("Unhandled type of aggregate value operation");
654}
655
Daniel Berlin85f91b02016-12-26 20:06:58 +0000656const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000657 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000658 E->setOpcode(V->getValueID());
659 return E;
660}
661
Daniel Berlin97718e62017-01-31 22:32:03 +0000662const Expression *NewGVN::createVariableOrConstant(Value *V) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000663 auto Leader = lookupOperandLeader(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000664 if (auto *C = dyn_cast<Constant>(Leader))
665 return createConstantExpression(C);
666 return createVariableExpression(Leader);
667}
668
Daniel Berlin85f91b02016-12-26 20:06:58 +0000669const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000670 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000671 E->setOpcode(C->getValueID());
672 return E;
673}
674
Daniel Berlin02c6b172017-01-02 18:00:53 +0000675const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
676 auto *E = new (ExpressionAllocator) UnknownExpression(I);
677 E->setOpcode(I->getOpcode());
678 return E;
679}
680
Davide Italiano7e274e02016-12-22 16:03:48 +0000681const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000682 MemoryAccess *HV) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000683 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000684 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000685 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
Daniel Berlin97718e62017-01-31 22:32:03 +0000686 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000687 return E;
688}
689
690// See if we have a congruence class and leader for this operand, and if so,
691// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000692Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000693 CongruenceClass *CC = ValueToClass.lookup(V);
694 if (CC && (CC != InitialClass))
Daniel Berlin26addef2017-01-20 21:04:30 +0000695 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Davide Italiano7e274e02016-12-22 16:03:48 +0000696 return V;
697}
698
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000699MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000700 auto *CC = MemoryAccessToClass.lookup(MA);
701 if (CC && CC->RepMemoryAccess)
702 return CC->RepMemoryAccess;
703 // FIXME: We need to audit all the places that current set a nullptr To, and
704 // fix them. There should always be *some* congruence class, even if it is
705 // singular. Right now, we don't bother setting congruence classes for
706 // anything but stores, which means we have to return the original access
707 // here. Otherwise, this should be unreachable.
708 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000709}
710
Daniel Berlinc4796862017-01-27 02:37:11 +0000711// Return true if the MemoryAccess is really equivalent to everything. This is
712// equivalent to the lattice value "TOP" in most lattices. This is the initial
713// state of all memory accesses.
714bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
715 return MemoryAccessToClass.lookup(MA) == InitialClass;
716}
717
Davide Italiano7e274e02016-12-22 16:03:48 +0000718LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin97718e62017-01-31 22:32:03 +0000719 LoadInst *LI, MemoryAccess *DA) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000720 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000721 E->allocateOperands(ArgRecycler, ExpressionAllocator);
722 E->setType(LoadType);
723
724 // Give store and loads same opcode so they value number together.
725 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000726 E->op_push_back(lookupOperandLeader(PointerOp));
Davide Italiano7e274e02016-12-22 16:03:48 +0000727 if (LI)
728 E->setAlignment(LI->getAlignment());
729
730 // TODO: Value number heap versions. We may be able to discover
731 // things alias analysis can't on it's own (IE that a store and a
732 // load have the same value, and thus, it isn't clobbering the load).
733 return E;
734}
735
736const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000737 MemoryAccess *DA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000738 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000739 auto *E = new (ExpressionAllocator)
740 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000741 E->allocateOperands(ArgRecycler, ExpressionAllocator);
742 E->setType(SI->getValueOperand()->getType());
743
744 // Give store and loads same opcode so they value number together.
745 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000746 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000747
748 // TODO: Value number heap versions. We may be able to discover
749 // things alias analysis can't on it's own (IE that a store and a
750 // load have the same value, and thus, it isn't clobbering the load).
751 return E;
752}
753
Daniel Berlin97718e62017-01-31 22:32:03 +0000754const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000755 // Unlike loads, we never try to eliminate stores, so we do not check if they
756 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000757 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000758 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000759 // Get the expression, if any, for the RHS of the MemoryDef.
760 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
761 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
762 // If we are defined by ourselves, use the live on entry def.
763 if (StoreRHS == StoreAccess)
764 StoreRHS = MSSA->getLiveOnEntryDef();
765
Daniel Berlin589cecc2017-01-02 18:00:46 +0000766 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000767 // See if we are defined by a previous store expression, it already has a
768 // value, and it's the same value as our current store. FIXME: Right now, we
769 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin97718e62017-01-31 22:32:03 +0000770 const Expression *OldStore = createStoreExpression(SI, StoreRHS);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000771 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000772 // Basically, check if the congruence class the store is in is defined by a
773 // store that isn't us, and has the same value. MemorySSA takes care of
774 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000775 // The RepStoredValue gets nulled if all the stores disappear in a class, so
776 // we don't need to check if the class contains a store besides us.
Daniel Berlin808e3ff2017-01-31 22:31:56 +0000777 if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin97718e62017-01-31 22:32:03 +0000778 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +0000779 // Also check if our value operand is defined by a load of the same memory
780 // location, and the memory state is the same as it was then
781 // (otherwise, it could have been overwritten later. See test32 in
782 // transforms/DeadStoreElimination/simple.ll)
783 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000784 if ((lookupOperandLeader(LI->getPointerOperand()) ==
785 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinc4796862017-01-27 02:37:11 +0000786 (lookupMemoryAccessEquiv(
787 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
788 return createVariableExpression(LI);
789 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000790 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000791 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000792}
793
Daniel Berlin97718e62017-01-31 22:32:03 +0000794const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000795 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000796
797 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000798 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000799 if (!LI->isSimple())
800 return nullptr;
801
Daniel Berlin203f47b2017-01-31 22:31:53 +0000802 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +0000803 // Load of undef is undef.
804 if (isa<UndefValue>(LoadAddressLeader))
805 return createConstantExpression(UndefValue::get(LI->getType()));
806
807 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
808
809 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
810 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
811 Instruction *DefiningInst = MD->getMemoryInst();
812 // If the defining instruction is not reachable, replace with undef.
813 if (!ReachableBlocks.count(DefiningInst->getParent()))
814 return createConstantExpression(UndefValue::get(LI->getType()));
815 }
816 }
817
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000818 const Expression *E =
819 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000820 lookupMemoryAccessEquiv(DefiningAccess));
Davide Italiano7e274e02016-12-22 16:03:48 +0000821 return E;
822}
823
824// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000825const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000826 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000827 if (AA->doesNotAccessMemory(CI))
Daniel Berlin97718e62017-01-31 22:32:03 +0000828 return createCallExpression(CI, nullptr);
Davide Italianob2225492016-12-27 18:15:39 +0000829 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000830 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin97718e62017-01-31 22:32:03 +0000831 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess));
Davide Italianob2225492016-12-27 18:15:39 +0000832 }
833 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000834}
835
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000836// Update the memory access equivalence table to say that From is equal to To,
837// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000838// FIXME: We need to audit all the places that current set a nullptr To, and fix
839// them. There should always be *some* congruence class, even if it is singular.
840bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
841 DEBUG(dbgs() << "Setting " << *From);
842 if (To) {
843 DEBUG(dbgs() << " equivalent to congruence class ");
844 DEBUG(dbgs() << To->ID << " with current memory access leader ");
845 DEBUG(dbgs() << *To->RepMemoryAccess);
846 } else {
847 DEBUG(dbgs() << " equivalent to itself");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000848 }
Daniel Berlin9f376b72017-01-29 10:26:03 +0000849 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000850
851 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000852 bool Changed = false;
853 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000854 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000855 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000856 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000857 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000858 Changed = true;
859 } else if (!To) {
860 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000861 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000862 Changed = true;
863 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000864 } else {
865 assert(!To &&
866 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000867 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000868
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000869 return Changed;
870}
Davide Italiano7e274e02016-12-22 16:03:48 +0000871// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000872const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000873 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +0000874 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
875
876 // See if all arguaments are the same.
877 // We track if any were undef because they need special handling.
878 bool HasUndef = false;
879 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
880 if (Arg == I)
881 return false;
882 if (isa<UndefValue>(Arg)) {
883 HasUndef = true;
884 return false;
885 }
886 return true;
887 });
888 // If we are left with no operands, it's undef
889 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000890 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
891 << "\n");
892 E->deallocateOperands(ArgRecycler);
893 ExpressionAllocator.Deallocate(E);
894 return createConstantExpression(UndefValue::get(I->getType()));
895 }
Daniel Berlind92e7f92017-01-07 00:01:42 +0000896 Value *AllSameValue = *(Filtered.begin());
897 ++Filtered.begin();
898 // Can't use std::equal here, sadly, because filter.begin moves.
899 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
900 return V == AllSameValue;
901 })) {
902 // In LLVM's non-standard representation of phi nodes, it's possible to have
903 // phi nodes with cycles (IE dependent on other phis that are .... dependent
904 // on the original phi node), especially in weird CFG's where some arguments
905 // are unreachable, or uninitialized along certain paths. This can cause
906 // infinite loops during evaluation. We work around this by not trying to
907 // really evaluate them independently, but instead using a variable
908 // expression to say if one is equivalent to the other.
909 // We also special case undef, so that if we have an undef, we can't use the
910 // common value unless it dominates the phi block.
911 if (HasUndef) {
912 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +0000913 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +0000914 if (!DT->dominates(AllSameInst, I))
915 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000916 }
917
Davide Italiano7e274e02016-12-22 16:03:48 +0000918 NumGVNPhisAllSame++;
919 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
920 << "\n");
921 E->deallocateOperands(ArgRecycler);
922 ExpressionAllocator.Deallocate(E);
923 if (auto *C = dyn_cast<Constant>(AllSameValue))
924 return createConstantExpression(C);
925 return createVariableExpression(AllSameValue);
926 }
927 return E;
928}
929
Daniel Berlin97718e62017-01-31 22:32:03 +0000930const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000931 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
932 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
933 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
934 unsigned Opcode = 0;
935 // EI might be an extract from one of our recognised intrinsics. If it
936 // is we'll synthesize a semantically equivalent expression instead on
937 // an extract value expression.
938 switch (II->getIntrinsicID()) {
939 case Intrinsic::sadd_with_overflow:
940 case Intrinsic::uadd_with_overflow:
941 Opcode = Instruction::Add;
942 break;
943 case Intrinsic::ssub_with_overflow:
944 case Intrinsic::usub_with_overflow:
945 Opcode = Instruction::Sub;
946 break;
947 case Intrinsic::smul_with_overflow:
948 case Intrinsic::umul_with_overflow:
949 Opcode = Instruction::Mul;
950 break;
951 default:
952 break;
953 }
954
955 if (Opcode != 0) {
956 // Intrinsic recognized. Grab its args to finish building the
957 // expression.
958 assert(II->getNumArgOperands() == 2 &&
959 "Expect two args for recognised intrinsics.");
960 return createBinaryExpression(Opcode, EI->getType(),
961 II->getArgOperand(0),
Daniel Berlin97718e62017-01-31 22:32:03 +0000962 II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +0000963 }
964 }
965 }
966
Daniel Berlin97718e62017-01-31 22:32:03 +0000967 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000968}
Daniel Berlin97718e62017-01-31 22:32:03 +0000969const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinc22aafe2017-01-31 22:31:58 +0000970 CmpInst *CI = dyn_cast<CmpInst>(I);
971 // See if our operands are equal and that implies something.
972 auto Op0 = lookupOperandLeader(CI->getOperand(0));
973 auto Op1 = lookupOperandLeader(CI->getOperand(1));
974 if (Op0 == Op1) {
975 if (CI->isTrueWhenEqual())
976 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
977 else if (CI->isFalseWhenEqual())
978 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
979 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000980 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +0000981}
Davide Italiano7e274e02016-12-22 16:03:48 +0000982
983// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +0000984const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +0000985 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000986 if (auto *C = dyn_cast<Constant>(V))
987 E = createConstantExpression(C);
988 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
989 E = createVariableExpression(V);
990 } else {
991 // TODO: memory intrinsics.
992 // TODO: Some day, we should do the forward propagation and reassociation
993 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000994 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000995 switch (I->getOpcode()) {
996 case Instruction::ExtractValue:
997 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +0000998 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000999 break;
1000 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001001 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001002 break;
1003 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001004 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001005 break;
1006 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001007 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001008 break;
1009 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001010 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001011 break;
1012 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001013 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001014 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001015 case Instruction::ICmp:
1016 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001017 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001018 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001019 case Instruction::Add:
1020 case Instruction::FAdd:
1021 case Instruction::Sub:
1022 case Instruction::FSub:
1023 case Instruction::Mul:
1024 case Instruction::FMul:
1025 case Instruction::UDiv:
1026 case Instruction::SDiv:
1027 case Instruction::FDiv:
1028 case Instruction::URem:
1029 case Instruction::SRem:
1030 case Instruction::FRem:
1031 case Instruction::Shl:
1032 case Instruction::LShr:
1033 case Instruction::AShr:
1034 case Instruction::And:
1035 case Instruction::Or:
1036 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001037 case Instruction::Trunc:
1038 case Instruction::ZExt:
1039 case Instruction::SExt:
1040 case Instruction::FPToUI:
1041 case Instruction::FPToSI:
1042 case Instruction::UIToFP:
1043 case Instruction::SIToFP:
1044 case Instruction::FPTrunc:
1045 case Instruction::FPExt:
1046 case Instruction::PtrToInt:
1047 case Instruction::IntToPtr:
1048 case Instruction::Select:
1049 case Instruction::ExtractElement:
1050 case Instruction::InsertElement:
1051 case Instruction::ShuffleVector:
1052 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001053 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001054 break;
1055 default:
1056 return nullptr;
1057 }
1058 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001059 return E;
1060}
1061
1062// There is an edge from 'Src' to 'Dst'. Return true if every path from
1063// the entry block to 'Dst' passes via this edge. In particular 'Dst'
1064// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +00001065bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001066
1067 // While in theory it is interesting to consider the case in which Dst has
1068 // more than one predecessor, because Dst might be part of a loop which is
1069 // only reachable from Src, in practice it is pointless since at the time
1070 // GVN runs all such loops have preheaders, which means that Dst will have
1071 // been changed to have only one predecessor, namely Src.
1072 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1073 const BasicBlock *Src = E.getStart();
1074 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
1075 (void)Src;
1076 return Pred != nullptr;
1077}
1078
1079void NewGVN::markUsersTouched(Value *V) {
1080 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001081 for (auto *User : V->users()) {
1082 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001083 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001084 }
1085}
1086
1087void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1088 for (auto U : MA->users()) {
1089 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001090 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001091 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001092 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001093 }
1094}
1095
Daniel Berlin32f8d562017-01-07 16:55:14 +00001096// Touch the instructions that need to be updated after a congruence class has a
1097// leader change, and mark changed values.
1098void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1099 for (auto M : CC->Members) {
1100 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001101 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001102 LeaderChanges.insert(M);
1103 }
1104}
1105
1106// Move a value, currently in OldClass, to be part of NewClass
1107// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001108void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1109 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001110 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001111 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001112 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001113
1114 if (I == OldClass->NextLeader.first)
1115 OldClass->NextLeader = {nullptr, ~0U};
1116
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001117 // It's possible, though unlikely, for us to discover equivalences such
1118 // that the current leader does not dominate the old one.
1119 // This statistic tracks how often this happens.
1120 // We assert on phi nodes when this happens, currently, for debugging, because
1121 // we want to make sure we name phi node cycles properly.
1122 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1123 I != NewClass->RepLeader &&
1124 DT->properlyDominates(
1125 I->getParent(),
1126 cast<Instruction>(NewClass->RepLeader)->getParent())) {
1127 ++NumGVNNotMostDominatingLeader;
1128 assert(!isa<PHINode>(I) &&
1129 "New class for instruction should not be dominated by instruction");
1130 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001131
1132 if (NewClass->RepLeader != I) {
1133 auto DFSNum = InstrDFS.lookup(I);
1134 if (DFSNum < NewClass->NextLeader.second)
1135 NewClass->NextLeader = {I, DFSNum};
1136 }
1137
1138 OldClass->Members.erase(I);
1139 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001140 MemoryAccess *StoreAccess = nullptr;
1141 if (auto *SI = dyn_cast<StoreInst>(I)) {
1142 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001143 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001144 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001145 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001146 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001147 if (!NewClass->RepMemoryAccess) {
1148 // If we don't have a representative memory access, it better be the only
1149 // store in there.
1150 assert(NewClass->StoreCount == 1);
1151 NewClass->RepMemoryAccess = StoreAccess;
1152 }
1153 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001154 }
1155
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001156 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001157 // See if we destroyed the class or need to swap leaders.
1158 if (OldClass->Members.empty() && OldClass != InitialClass) {
1159 if (OldClass->DefiningExpr) {
1160 OldClass->Dead = true;
1161 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1162 << " from table\n");
1163 ExpressionToClass.erase(OldClass->DefiningExpr);
1164 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001165 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001166 // When the leader changes, the value numbering of
1167 // everything may change due to symbolization changes, so we need to
1168 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001169 DEBUG(dbgs() << "Leader change!\n");
1170 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001171 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001172 if (OldClass->StoreCount == 0) {
1173 if (OldClass->RepStoredValue != nullptr)
1174 OldClass->RepStoredValue = nullptr;
1175 if (OldClass->RepMemoryAccess != nullptr)
1176 OldClass->RepMemoryAccess = nullptr;
1177 }
1178
1179 // If we destroy the old access leader, we have to effectively destroy the
1180 // congruence class. When it comes to scalars, anything with the same value
1181 // is as good as any other. That means that one leader is as good as
1182 // another, and as long as you have some leader for the value, you are
1183 // good.. When it comes to *memory states*, only one particular thing really
1184 // represents the definition of a given memory state. Once it goes away, we
1185 // need to re-evaluate which pieces of memory are really still
1186 // equivalent. The best way to do this is to re-value number things. The
1187 // only way to really make that happen is to destroy the rest of the class.
1188 // In order to effectively destroy the class, we reset ExpressionToClass for
1189 // each by using the ValueToExpression mapping. The members later get
1190 // marked as touched due to the leader change. We will create new
1191 // congruence classes, and the pieces that are still equivalent will end
1192 // back together in a new class. If this becomes too expensive, it is
1193 // possible to use a versioning scheme for the congruence classes to avoid
1194 // the expressions finding this old class.
1195 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1196 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1197 << " because memory access leader changed");
1198 for (auto Member : OldClass->Members)
1199 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1200 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001201
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001202 // We don't need to sort members if there is only 1, and we don't care about
1203 // sorting the initial class because everything either gets out of it or is
1204 // unreachable.
1205 if (OldClass->Members.size() == 1 || OldClass == InitialClass) {
1206 OldClass->RepLeader = *(OldClass->Members.begin());
1207 } else if (OldClass->NextLeader.first) {
1208 ++NumGVNAvoidedSortedLeaderChanges;
1209 OldClass->RepLeader = OldClass->NextLeader.first;
1210 OldClass->NextLeader = {nullptr, ~0U};
1211 } else {
1212 ++NumGVNSortedLeaderChanges;
1213 // TODO: If this ends up to slow, we can maintain a dual structure for
1214 // member testing/insertion, or keep things mostly sorted, and sort only
1215 // here, or ....
1216 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1217 for (const auto X : OldClass->Members) {
1218 auto DFSNum = InstrDFS.lookup(X);
1219 if (DFSNum < MinDFS.second)
1220 MinDFS = {X, DFSNum};
1221 }
1222 OldClass->RepLeader = MinDFS.first;
1223 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001224 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001225 }
1226}
1227
Davide Italiano7e274e02016-12-22 16:03:48 +00001228// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001229void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1230 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001231 // This is guaranteed to return something, since it will at least find
1232 // INITIAL.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001233
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001234 CongruenceClass *IClass = ValueToClass[I];
1235 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001236 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001237 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001238
1239 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001240 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001241 EClass = ValueToClass[VE->getVariableValue()];
1242 } else {
1243 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1244
1245 // If it's not in the value table, create a new congruence class.
1246 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001247 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001248 auto place = lookupResult.first;
1249 place->second = NewClass;
1250
1251 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001252 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001253 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001254 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1255 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001256 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001257 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001258 // The RepMemoryAccess field will be filled in properly by the
1259 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001260 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001261 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001262 }
1263 assert(!isa<VariableExpression>(E) &&
1264 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001265
1266 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001267 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001268 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001269 << " and leader " << *(NewClass->RepLeader));
1270 if (NewClass->RepStoredValue)
1271 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1272 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001273 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1274 } else {
1275 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001276 if (isa<ConstantExpression>(E))
1277 assert(isa<Constant>(EClass->RepLeader) &&
1278 "Any class with a constant expression should have a "
1279 "constant leader");
1280
Davide Italiano7e274e02016-12-22 16:03:48 +00001281 assert(EClass && "Somehow don't have an eclass");
1282
1283 assert(!EClass->Dead && "We accidentally looked up a dead class");
1284 }
1285 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001286 bool ClassChanged = IClass != EClass;
1287 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001288 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001289 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1290 << "\n");
1291
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001292 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001293 moveValueToNewCongruenceClass(I, IClass, EClass);
1294 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001295 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001296 markMemoryUsersTouched(MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001297 }
1298}
1299
1300// Process the fact that Edge (from, to) is reachable, including marking
1301// any newly reachable blocks and instructions for processing.
1302void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1303 // Check if the Edge was reachable before.
1304 if (ReachableEdges.insert({From, To}).second) {
1305 // If this block wasn't reachable before, all instructions are touched.
1306 if (ReachableBlocks.insert(To).second) {
1307 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1308 const auto &InstRange = BlockInstRange.lookup(To);
1309 TouchedInstructions.set(InstRange.first, InstRange.second);
1310 } else {
1311 DEBUG(dbgs() << "Block " << getBlockName(To)
1312 << " was reachable, but new edge {" << getBlockName(From)
1313 << "," << getBlockName(To) << "} to it found\n");
1314
1315 // We've made an edge reachable to an existing block, which may
1316 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1317 // they are the only thing that depend on new edges. Anything using their
1318 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001319 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001320 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001321
Davide Italiano7e274e02016-12-22 16:03:48 +00001322 auto BI = To->begin();
1323 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001324 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001325 ++BI;
1326 }
1327 }
1328 }
1329}
1330
1331// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1332// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001333Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001334 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001335 if (isa<Constant>(Result))
1336 return Result;
1337 return nullptr;
1338}
1339
1340// Process the outgoing edges of a block for reachability.
1341void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1342 // Evaluate reachability of terminator instruction.
1343 BranchInst *BR;
1344 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1345 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001346 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001347 if (!CondEvaluated) {
1348 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001349 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001350 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1351 CondEvaluated = CE->getConstantValue();
1352 }
1353 } else if (isa<ConstantInt>(Cond)) {
1354 CondEvaluated = Cond;
1355 }
1356 }
1357 ConstantInt *CI;
1358 BasicBlock *TrueSucc = BR->getSuccessor(0);
1359 BasicBlock *FalseSucc = BR->getSuccessor(1);
1360 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1361 if (CI->isOne()) {
1362 DEBUG(dbgs() << "Condition for Terminator " << *TI
1363 << " evaluated to true\n");
1364 updateReachableEdge(B, TrueSucc);
1365 } else if (CI->isZero()) {
1366 DEBUG(dbgs() << "Condition for Terminator " << *TI
1367 << " evaluated to false\n");
1368 updateReachableEdge(B, FalseSucc);
1369 }
1370 } else {
1371 updateReachableEdge(B, TrueSucc);
1372 updateReachableEdge(B, FalseSucc);
1373 }
1374 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1375 // For switches, propagate the case values into the case
1376 // destinations.
1377
1378 // Remember how many outgoing edges there are to every successor.
1379 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1380
Davide Italiano7e274e02016-12-22 16:03:48 +00001381 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001382 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001383 // See if we were able to turn this switch statement into a constant.
1384 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001385 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001386 // We should be able to get case value for this.
1387 auto CaseVal = SI->findCaseValue(CondVal);
1388 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1389 // We proved the value is outside of the range of the case.
1390 // We can't do anything other than mark the default dest as reachable,
1391 // and go home.
1392 updateReachableEdge(B, SI->getDefaultDest());
1393 return;
1394 }
1395 // Now get where it goes and mark it reachable.
1396 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1397 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001398 } else {
1399 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1400 BasicBlock *TargetBlock = SI->getSuccessor(i);
1401 ++SwitchEdges[TargetBlock];
1402 updateReachableEdge(B, TargetBlock);
1403 }
1404 }
1405 } else {
1406 // Otherwise this is either unconditional, or a type we have no
1407 // idea about. Just mark successors as reachable.
1408 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1409 BasicBlock *TargetBlock = TI->getSuccessor(i);
1410 updateReachableEdge(B, TargetBlock);
1411 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001412
1413 // This also may be a memory defining terminator, in which case, set it
1414 // equivalent to nothing.
1415 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1416 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001417 }
1418}
1419
Daniel Berlin85f91b02016-12-26 20:06:58 +00001420// The algorithm initially places the values of the routine in the INITIAL
1421// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001422// class. The leader of INITIAL is the undetermined value `TOP`.
1423// When the algorithm has finished, values still in INITIAL are unreachable.
1424void NewGVN::initializeCongruenceClasses(Function &F) {
1425 // FIXME now i can't remember why this is 2
1426 NextCongruenceNum = 2;
1427 // Initialize all other instructions to be in INITIAL class.
1428 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001429 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001430 InitialClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001431 for (auto &B : F) {
1432 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001433 MemoryAccessToClass[MP] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001434
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001435 for (auto &I : B) {
1436 InitialValues.insert(&I);
1437 ValueToClass[&I] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001438 // All memory accesses are equivalent to live on entry to start. They must
1439 // be initialized to something so that initial changes are noticed. For
1440 // the maximal answer, we initialize them all to be the same as
1441 // liveOnEntry. Note that to save time, we only initialize the
1442 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1443 // other expression can generate a memory equivalence. If we start
1444 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001445 if (isa<StoreInst>(&I)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001446 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = InitialClass;
Davide Italianoeac05f62017-01-11 23:41:24 +00001447 ++InitialClass->StoreCount;
1448 assert(InitialClass->StoreCount > 0);
1449 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001450 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001451 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001452 InitialClass->Members.swap(InitialValues);
1453
1454 // Initialize arguments to be in their own unique congruence classes
1455 for (auto &FA : F.args())
1456 createSingletonCongruenceClass(&FA);
1457}
1458
1459void NewGVN::cleanupTables() {
1460 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1461 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1462 << CongruenceClasses[i]->Members.size() << " members\n");
1463 // Make sure we delete the congruence class (probably worth switching to
1464 // a unique_ptr at some point.
1465 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001466 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001467 }
1468
1469 ValueToClass.clear();
1470 ArgRecycler.clear(ExpressionAllocator);
1471 ExpressionAllocator.Reset();
1472 CongruenceClasses.clear();
1473 ExpressionToClass.clear();
1474 ValueToExpression.clear();
1475 ReachableBlocks.clear();
1476 ReachableEdges.clear();
1477#ifndef NDEBUG
1478 ProcessedCount.clear();
1479#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001480 InstrDFS.clear();
1481 InstructionsToErase.clear();
1482
1483 DFSToInstr.clear();
1484 BlockInstRange.clear();
1485 TouchedInstructions.clear();
1486 DominatedInstRange.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001487 MemoryAccessToClass.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001488}
1489
1490std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1491 unsigned Start) {
1492 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001493 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1494 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001495 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001496 }
1497
Davide Italiano7e274e02016-12-22 16:03:48 +00001498 for (auto &I : *B) {
1499 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001500 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001501 }
1502
1503 // All of the range functions taken half-open ranges (open on the end side).
1504 // So we do not subtract one from count, because at this point it is one
1505 // greater than the last instruction.
1506 return std::make_pair(Start, End);
1507}
1508
1509void NewGVN::updateProcessedCount(Value *V) {
1510#ifndef NDEBUG
1511 if (ProcessedCount.count(V) == 0) {
1512 ProcessedCount.insert({V, 1});
1513 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001514 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001515 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001516 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001517 }
1518#endif
1519}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001520// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1521void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1522 // If all the arguments are the same, the MemoryPhi has the same value as the
1523 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001524 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001525 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001526 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1527 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
1528 ReachableBlocks.count(MP->getIncomingBlock(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001529 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001530 // If all that is left is nothing, our memoryphi is undef. We keep it as
1531 // InitialClass. Note: The only case this should happen is if we have at
1532 // least one self-argument.
1533 if (Filtered.begin() == Filtered.end()) {
1534 if (setMemoryAccessEquivTo(MP, InitialClass))
1535 markMemoryUsersTouched(MP);
1536 return;
1537 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001538
1539 // Transform the remaining operands into operand leaders.
1540 // FIXME: mapped_iterator should have a range version.
1541 auto LookupFunc = [&](const Use &U) {
1542 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1543 };
1544 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1545 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1546
1547 // and now check if all the elements are equal.
1548 // Sadly, we can't use std::equals since these are random access iterators.
1549 MemoryAccess *AllSameValue = *MappedBegin;
1550 ++MappedBegin;
1551 bool AllEqual = std::all_of(
1552 MappedBegin, MappedEnd,
1553 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1554
1555 if (AllEqual)
1556 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1557 else
1558 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1559
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001560 if (setMemoryAccessEquivTo(
1561 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001562 markMemoryUsersTouched(MP);
1563}
1564
1565// Value number a single instruction, symbolically evaluating, performing
1566// congruence finding, and updating mappings.
1567void NewGVN::valueNumberInstruction(Instruction *I) {
1568 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001569
1570 // There's no need to call isInstructionTriviallyDead more than once on
1571 // an instruction. Therefore, once we know that an instruction is dead
1572 // we change its DFS number so that it doesn't get numbered again.
1573 if (InstrDFS[I] != 0 && isInstructionTriviallyDead(I, TLI)) {
1574 InstrDFS[I] = 0;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001575 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001576 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001577 return;
1578 }
1579 if (!I->isTerminator()) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001580 const auto *Symbolized = performSymbolicEvaluation(I);
Daniel Berlin02c6b172017-01-02 18:00:53 +00001581 // If we couldn't come up with a symbolic expression, use the unknown
1582 // expression
1583 if (Symbolized == nullptr)
1584 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001585 performCongruenceFinding(I, Symbolized);
1586 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001587 // Handle terminators that return values. All of them produce values we
1588 // don't currently understand.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001589 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001590 auto *Symbolized = createUnknownExpression(I);
1591 performCongruenceFinding(I, Symbolized);
1592 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001593 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1594 }
1595}
Davide Italiano7e274e02016-12-22 16:03:48 +00001596
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001597// Check if there is a path, using single or equal argument phi nodes, from
1598// First to Second.
1599bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1600 const MemoryAccess *Second) const {
1601 if (First == Second)
1602 return true;
1603
1604 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1605 auto *DefAccess = FirstDef->getDefiningAccess();
1606 return singleReachablePHIPath(DefAccess, Second);
1607 } else {
1608 auto *MP = cast<MemoryPhi>(First);
1609 auto ReachableOperandPred = [&](const Use &U) {
1610 return ReachableBlocks.count(MP->getIncomingBlock(U));
1611 };
1612 auto FilteredPhiArgs =
1613 make_filter_range(MP->operands(), ReachableOperandPred);
1614 SmallVector<const Value *, 32> OperandList;
1615 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1616 std::back_inserter(OperandList));
1617 bool Okay = OperandList.size() == 1;
1618 if (!Okay)
1619 Okay = std::equal(OperandList.begin(), OperandList.end(),
1620 OperandList.begin());
1621 if (Okay)
1622 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1623 return false;
1624 }
1625}
1626
Daniel Berlin589cecc2017-01-02 18:00:46 +00001627// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001628// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001629// subject to very rare false negatives. It is only useful for
1630// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001631void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001632 // Anything equivalent in the memory access table should be in the same
1633 // congruence class.
1634
1635 // Filter out the unreachable and trivially dead entries, because they may
1636 // never have been updated if the instructions were not processed.
1637 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001638 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001639 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1640 if (!Result)
1641 return false;
1642 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1643 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1644 return true;
1645 };
1646
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001647 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001648 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001649 // Unreachable instructions may not have changed because we never process
1650 // them.
1651 if (!ReachableBlocks.count(KV.first->getBlock()))
1652 continue;
1653 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001654 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001655 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001656 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001657 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1658 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1659 "The instructions for these memory operations should have "
1660 "been in the same congruence class or reachable through"
1661 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001662 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1663
1664 // We can only sanely verify that MemoryDefs in the operand list all have
1665 // the same class.
1666 auto ReachableOperandPred = [&](const Use &U) {
1667 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1668 isa<MemoryDef>(U);
1669
1670 };
1671 // All arguments should in the same class, ignoring unreachable arguments
1672 auto FilteredPhiArgs =
1673 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1674 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1675 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1676 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1677 const MemoryDef *MD = cast<MemoryDef>(U);
1678 return ValueToClass.lookup(MD->getMemoryInst());
1679 });
1680 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1681 PhiOpClasses.begin()) &&
1682 "All MemoryPhi arguments should be in the same class");
1683 }
1684 }
1685}
1686
Daniel Berlin85f91b02016-12-26 20:06:58 +00001687// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001688bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001689 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1690 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001691 bool Changed = false;
1692 DT = _DT;
1693 AC = _AC;
1694 TLI = _TLI;
1695 AA = _AA;
1696 MSSA = _MSSA;
1697 DL = &F.getParent()->getDataLayout();
1698 MSSAWalker = MSSA->getWalker();
1699
1700 // Count number of instructions for sizing of hash tables, and come
1701 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001702 unsigned ICount = 1;
1703 // Add an empty instruction to account for the fact that we start at 1
1704 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001705 // Note: We want RPO traversal of the blocks, which is not quite the same as
1706 // dominator tree order, particularly with regard whether backedges get
1707 // visited first or second, given a block with multiple successors.
1708 // If we visit in the wrong order, we will end up performing N times as many
1709 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001710 // The dominator tree does guarantee that, for a given dom tree node, it's
1711 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1712 // the siblings.
1713 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001714 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001715 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001716 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001717 auto *Node = DT->getNode(B);
1718 assert(Node && "RPO and Dominator tree should have same reachability");
1719 RPOOrdering[Node] = ++Counter;
1720 }
1721 // Sort dominator tree children arrays into RPO.
1722 for (auto &B : RPOT) {
1723 auto *Node = DT->getNode(B);
1724 if (Node->getChildren().size() > 1)
1725 std::sort(Node->begin(), Node->end(),
1726 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1727 return RPOOrdering[A] < RPOOrdering[B];
1728 });
1729 }
1730
1731 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1732 auto DFI = df_begin(DT->getRootNode());
1733 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1734 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001735 const auto &BlockRange = assignDFSNumbers(B, ICount);
1736 BlockInstRange.insert({B, BlockRange});
1737 ICount += BlockRange.second - BlockRange.first;
1738 }
1739
1740 // Handle forward unreachable blocks and figure out which blocks
1741 // have single preds.
1742 for (auto &B : F) {
1743 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001744 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001745 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1746 BlockInstRange.insert({&B, BlockRange});
1747 ICount += BlockRange.second - BlockRange.first;
1748 }
1749 }
1750
Daniel Berline0bd37e2016-12-29 22:15:12 +00001751 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001752 DominatedInstRange.reserve(F.size());
1753 // Ensure we don't end up resizing the expressionToClass map, as
1754 // that can be quite expensive. At most, we have one expression per
1755 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001756 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001757
1758 // Initialize the touched instructions to include the entry block.
1759 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1760 TouchedInstructions.set(InstRange.first, InstRange.second);
1761 ReachableBlocks.insert(&F.getEntryBlock());
1762
1763 initializeCongruenceClasses(F);
1764
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001765 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001766 // We start out in the entry block.
1767 BasicBlock *LastBlock = &F.getEntryBlock();
1768 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001769 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00001770 // Walk through all the instructions in all the blocks in RPO.
1771 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1772 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001773
1774 // This instruction was found to be dead. We don't bother looking
1775 // at it again.
1776 if (InstrNum == 0) {
1777 TouchedInstructions.reset(InstrNum);
1778 continue;
1779 }
1780
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001781 Value *V = DFSToInstr[InstrNum];
1782 BasicBlock *CurrBlock = nullptr;
1783
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001784 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001785 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001786 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001787 CurrBlock = MP->getBlock();
1788 else
1789 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001790
1791 // If we hit a new block, do reachability processing.
1792 if (CurrBlock != LastBlock) {
1793 LastBlock = CurrBlock;
1794 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1795 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1796
1797 // If it's not reachable, erase any touched instructions and move on.
1798 if (!BlockReachable) {
1799 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1800 DEBUG(dbgs() << "Skipping instructions in block "
1801 << getBlockName(CurrBlock)
1802 << " because it is unreachable\n");
1803 continue;
1804 }
1805 updateProcessedCount(CurrBlock);
1806 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001807
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001808 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001809 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1810 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001811 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001812 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001813 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001814 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001815 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001816 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001817 // Reset after processing (because we may mark ourselves as touched when
1818 // we propagate equalities).
1819 TouchedInstructions.reset(InstrNum);
1820 }
1821 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001822 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001823#ifndef NDEBUG
1824 verifyMemoryCongruency();
1825#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001826 Changed |= eliminateInstructions(F);
1827
1828 // Delete all instructions marked for deletion.
1829 for (Instruction *ToErase : InstructionsToErase) {
1830 if (!ToErase->use_empty())
1831 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1832
1833 ToErase->eraseFromParent();
1834 }
1835
1836 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001837 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1838 return !ReachableBlocks.count(&BB);
1839 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001840
1841 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1842 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001843 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001844 deleteInstructionsInBlock(&BB);
1845 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001846 }
1847
1848 cleanupTables();
1849 return Changed;
1850}
1851
1852bool NewGVN::runOnFunction(Function &F) {
1853 if (skipFunction(F))
1854 return false;
1855 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1856 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1857 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1858 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1859 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1860}
1861
Daniel Berlin85f91b02016-12-26 20:06:58 +00001862PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001863 NewGVN Impl;
1864
1865 // Apparently the order in which we get these results matter for
1866 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1867 // the same order here, just in case.
1868 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1869 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1870 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1871 auto &AA = AM.getResult<AAManager>(F);
1872 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1873 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1874 if (!Changed)
1875 return PreservedAnalyses::all();
1876 PreservedAnalyses PA;
1877 PA.preserve<DominatorTreeAnalysis>();
1878 PA.preserve<GlobalsAA>();
1879 return PA;
1880}
1881
1882// Return true if V is a value that will always be available (IE can
1883// be placed anywhere) in the function. We don't do globals here
1884// because they are often worse to put in place.
1885// TODO: Separate cost from availability
1886static bool alwaysAvailable(Value *V) {
1887 return isa<Constant>(V) || isa<Argument>(V);
1888}
1889
1890// Get the basic block from an instruction/value.
1891static BasicBlock *getBlockForValue(Value *V) {
1892 if (auto *I = dyn_cast<Instruction>(V))
1893 return I->getParent();
1894 return nullptr;
1895}
1896
1897struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001898 int DFSIn = 0;
1899 int DFSOut = 0;
1900 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001901 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001902 Value *Val = nullptr;
1903 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001904
1905 bool operator<(const ValueDFS &Other) const {
1906 // It's not enough that any given field be less than - we have sets
1907 // of fields that need to be evaluated together to give a proper ordering.
1908 // For example, if you have;
1909 // DFS (1, 3)
1910 // Val 0
1911 // DFS (1, 2)
1912 // Val 50
1913 // We want the second to be less than the first, but if we just go field
1914 // by field, we will get to Val 0 < Val 50 and say the first is less than
1915 // the second. We only want it to be less than if the DFS orders are equal.
1916 //
1917 // Each LLVM instruction only produces one value, and thus the lowest-level
1918 // differentiator that really matters for the stack (and what we use as as a
1919 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001920 // Everything else in the structure is instruction level, and only affects
1921 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001922 //
1923 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1924 // the order of replacement of uses does not matter.
1925 // IE given,
1926 // a = 5
1927 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001928 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1929 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001930 // The .val will be the same as well.
1931 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001932 // You will replace both, and it does not matter what order you replace them
1933 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1934 // operand 2).
1935 // Similarly for the case of same dfsin, dfsout, localnum, but different
1936 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001937 // a = 5
1938 // b = 6
1939 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001940 // in c, we will a valuedfs for a, and one for b,with everything the same
1941 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001942 // It does not matter what order we replace these operands in.
1943 // You will always end up with the same IR, and this is guaranteed.
1944 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1945 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1946 Other.U);
1947 }
1948};
1949
Daniel Berlinc4796862017-01-27 02:37:11 +00001950// This function converts the set of members for a congruence class from values,
1951// to sets of defs and uses with associated DFS info.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001952void NewGVN::convertDenseToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00001953 const CongruenceClass::MemberSet &Dense,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001954 SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001955 for (auto D : Dense) {
1956 // First add the value.
1957 BasicBlock *BB = getBlockForValue(D);
1958 // Constants are handled prior to ever calling this function, so
1959 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001960 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001961 ValueDFS VD;
Daniel Berlinb66164c2017-01-14 00:24:23 +00001962 DomTreeNode *DomNode = DT->getNode(BB);
1963 VD.DFSIn = DomNode->getDFSNumIn();
1964 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00001965 // If it's a store, use the leader of the value operand.
1966 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001967 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001968 VD.Val = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
1969 } else {
1970 VD.Val = D;
1971 }
1972
Davide Italiano7e274e02016-12-22 16:03:48 +00001973 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlinaac56842017-01-15 09:18:41 +00001974 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001975 else
1976 llvm_unreachable("Should have been an instruction");
1977
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001978 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001979
Daniel Berlinb66164c2017-01-14 00:24:23 +00001980 // Now add the uses.
Davide Italiano7e274e02016-12-22 16:03:48 +00001981 for (auto &U : D->uses()) {
1982 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1983 ValueDFS VD;
1984 // Put the phi node uses in the incoming block.
1985 BasicBlock *IBlock;
1986 if (auto *P = dyn_cast<PHINode>(I)) {
1987 IBlock = P->getIncomingBlock(U);
1988 // Make phi node users appear last in the incoming block
1989 // they are from.
1990 VD.LocalNum = InstrDFS.size() + 1;
1991 } else {
1992 IBlock = I->getParent();
Daniel Berlinaac56842017-01-15 09:18:41 +00001993 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001994 }
Davide Italianoccbbc832017-01-26 00:42:42 +00001995
1996 // Skip uses in unreachable blocks, as we're going
1997 // to delete them.
1998 if (ReachableBlocks.count(IBlock) == 0)
1999 continue;
2000
Daniel Berlinb66164c2017-01-14 00:24:23 +00002001 DomTreeNode *DomNode = DT->getNode(IBlock);
2002 VD.DFSIn = DomNode->getDFSNumIn();
2003 VD.DFSOut = DomNode->getDFSNumOut();
Davide Italiano7e274e02016-12-22 16:03:48 +00002004 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002005 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00002006 }
2007 }
2008 }
2009}
2010
Daniel Berlinc4796862017-01-27 02:37:11 +00002011// This function converts the set of members for a congruence class from values,
2012// to the set of defs for loads and stores, with associated DFS info.
2013void NewGVN::convertDenseToLoadsAndStores(
2014 const CongruenceClass::MemberSet &Dense,
2015 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2016 for (auto D : Dense) {
2017 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2018 continue;
2019
2020 BasicBlock *BB = getBlockForValue(D);
2021 ValueDFS VD;
2022 DomTreeNode *DomNode = DT->getNode(BB);
2023 VD.DFSIn = DomNode->getDFSNumIn();
2024 VD.DFSOut = DomNode->getDFSNumOut();
2025 VD.Val = D;
2026
2027 // If it's an instruction, use the real local dfs number.
2028 if (auto *I = dyn_cast<Instruction>(D))
2029 VD.LocalNum = InstrDFS.lookup(I);
2030 else
2031 llvm_unreachable("Should have been an instruction");
2032
2033 LoadsAndStores.emplace_back(VD);
2034 }
2035}
2036
Davide Italiano7e274e02016-12-22 16:03:48 +00002037static void patchReplacementInstruction(Instruction *I, Value *Repl) {
2038 // Patch the replacement so that it is not more restrictive than the value
2039 // being replaced.
2040 auto *Op = dyn_cast<BinaryOperator>(I);
2041 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
2042
2043 if (Op && ReplOp)
2044 ReplOp->andIRFlags(Op);
2045
2046 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
2047 // FIXME: If both the original and replacement value are part of the
2048 // same control-flow region (meaning that the execution of one
2049 // guarentees the executation of the other), then we can combine the
2050 // noalias scopes here and do better than the general conservative
2051 // answer used in combineMetadata().
2052
2053 // In general, GVN unifies expressions over different control-flow
2054 // regions, and so we need a conservative combination of the noalias
2055 // scopes.
2056 unsigned KnownIDs[] = {
2057 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2058 LLVMContext::MD_noalias, LLVMContext::MD_range,
2059 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2060 LLVMContext::MD_invariant_group};
2061 combineMetadata(ReplInst, I, KnownIDs);
2062 }
2063}
2064
2065static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2066 patchReplacementInstruction(I, Repl);
2067 I->replaceAllUsesWith(Repl);
2068}
2069
2070void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2071 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2072 ++NumGVNBlocksDeleted;
2073
Daniel Berline19f0e02017-01-30 17:06:55 +00002074 // Delete the instructions backwards, as it has a reduced likelihood of having
2075 // to update as many def-use and use-def chains. Start after the terminator.
2076 auto StartPoint = BB->rbegin();
2077 ++StartPoint;
2078 // Note that we explicitly recalculate BB->rend() on each iteration,
2079 // as it may change when we remove the first instruction.
2080 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2081 Instruction &Inst = *I++;
2082 if (!Inst.use_empty())
2083 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2084 if (isa<LandingPadInst>(Inst))
2085 continue;
2086
2087 Inst.eraseFromParent();
2088 ++NumGVNInstrDeleted;
2089 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002090 // Now insert something that simplifycfg will turn into an unreachable.
2091 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2092 new StoreInst(UndefValue::get(Int8Ty),
2093 Constant::getNullValue(Int8Ty->getPointerTo()),
2094 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002095}
2096
2097void NewGVN::markInstructionForDeletion(Instruction *I) {
2098 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2099 InstructionsToErase.insert(I);
2100}
2101
2102void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2103
2104 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2105 patchAndReplaceAllUsesWith(I, V);
2106 // We save the actual erasing to avoid invalidating memory
2107 // dependencies until we are done with everything.
2108 markInstructionForDeletion(I);
2109}
2110
2111namespace {
2112
2113// This is a stack that contains both the value and dfs info of where
2114// that value is valid.
2115class ValueDFSStack {
2116public:
2117 Value *back() const { return ValueStack.back(); }
2118 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2119
2120 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002121 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002122 DFSStack.emplace_back(DFSIn, DFSOut);
2123 }
2124 bool empty() const { return DFSStack.empty(); }
2125 bool isInScope(int DFSIn, int DFSOut) const {
2126 if (empty())
2127 return false;
2128 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2129 }
2130
2131 void popUntilDFSScope(int DFSIn, int DFSOut) {
2132
2133 // These two should always be in sync at this point.
2134 assert(ValueStack.size() == DFSStack.size() &&
2135 "Mismatch between ValueStack and DFSStack");
2136 while (
2137 !DFSStack.empty() &&
2138 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2139 DFSStack.pop_back();
2140 ValueStack.pop_back();
2141 }
2142 }
2143
2144private:
2145 SmallVector<Value *, 8> ValueStack;
2146 SmallVector<std::pair<int, int>, 8> DFSStack;
2147};
2148}
Daniel Berlin04443432017-01-07 03:23:47 +00002149
Davide Italiano7e274e02016-12-22 16:03:48 +00002150bool NewGVN::eliminateInstructions(Function &F) {
2151 // This is a non-standard eliminator. The normal way to eliminate is
2152 // to walk the dominator tree in order, keeping track of available
2153 // values, and eliminating them. However, this is mildly
2154 // pointless. It requires doing lookups on every instruction,
2155 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002156 // instructions part of most singleton congruence classes, we know we
2157 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002158
2159 // Instead, this eliminator looks at the congruence classes directly, sorts
2160 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002161 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002162 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002163 // last member. This is worst case O(E log E) where E = number of
2164 // instructions in a single congruence class. In theory, this is all
2165 // instructions. In practice, it is much faster, as most instructions are
2166 // either in singleton congruence classes or can't possibly be eliminated
2167 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002168 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002169 // for elimination purposes.
2170 // TODO: If we wanted to be faster, We could remove any members with no
2171 // overlapping ranges while sorting, as we will never eliminate anything
2172 // with those members, as they don't dominate anything else in our set.
2173
Davide Italiano7e274e02016-12-22 16:03:48 +00002174 bool AnythingReplaced = false;
2175
2176 // Since we are going to walk the domtree anyway, and we can't guarantee the
2177 // DFS numbers are updated, we compute some ourselves.
2178 DT->updateDFSNumbers();
2179
2180 for (auto &B : F) {
2181 if (!ReachableBlocks.count(&B)) {
2182 for (const auto S : successors(&B)) {
2183 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002184 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002185 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2186 << getBlockName(&B)
2187 << " with undef due to it being unreachable\n");
2188 for (auto &Operand : Phi.incoming_values())
2189 if (Phi.getIncomingBlock(Operand) == &B)
2190 Operand.set(UndefValue::get(Phi.getType()));
2191 }
2192 }
2193 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002194 }
2195
2196 for (CongruenceClass *CC : CongruenceClasses) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002197 // Track the equivalent store info so we can decide whether to try
2198 // dead store elimination.
2199 SmallVector<ValueDFS, 8> PossibleDeadStores;
2200
Davide Italiano7e274e02016-12-22 16:03:48 +00002201 // FIXME: We should eventually be able to replace everything still
2202 // in the initial class with undef, as they should be unreachable.
2203 // Right now, initial still contains some things we skip value
2204 // numbering of (UNREACHABLE's, for example).
2205 if (CC == InitialClass || CC->Dead)
2206 continue;
2207 assert(CC->RepLeader && "We should have had a leader");
2208
2209 // If this is a leader that is always available, and it's a
2210 // constant or has no equivalences, just replace everything with
2211 // it. We then update the congruence class with whatever members
2212 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002213 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2214 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002215 SmallPtrSet<Value *, 4> MembersLeft;
2216 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002217 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002218 // Void things have no uses we can replace.
2219 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2220 MembersLeft.insert(Member);
2221 continue;
2222 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002223 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2224 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002225 // Due to equality propagation, these may not always be
2226 // instructions, they may be real values. We don't really
2227 // care about trying to replace the non-instructions.
2228 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002229 assert(Leader != I && "About to accidentally remove our leader");
2230 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002231 AnythingReplaced = true;
2232
2233 continue;
2234 } else {
2235 MembersLeft.insert(I);
2236 }
2237 }
2238 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002239 } else {
2240 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2241 // If this is a singleton, we can skip it.
2242 if (CC->Members.size() != 1) {
2243
2244 // This is a stack because equality replacement/etc may place
2245 // constants in the middle of the member list, and we want to use
2246 // those constant values in preference to the current leader, over
2247 // the scope of those constants.
2248 ValueDFSStack EliminationStack;
2249
2250 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002251 SmallVector<ValueDFS, 8> DFSOrderedSet;
Davide Italiano7e274e02016-12-22 16:03:48 +00002252 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2253
2254 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002255 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002256 for (auto &VD : DFSOrderedSet) {
2257 int MemberDFSIn = VD.DFSIn;
2258 int MemberDFSOut = VD.DFSOut;
2259 Value *Member = VD.Val;
2260 Use *MemberUse = VD.U;
Davide Italiano7e274e02016-12-22 16:03:48 +00002261
Daniel Berlinc4796862017-01-27 02:37:11 +00002262 // We ignore void things because we can't get a value from them.
2263 if (Member && Member->getType()->isVoidTy())
2264 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002265
2266 if (EliminationStack.empty()) {
2267 DEBUG(dbgs() << "Elimination Stack is empty\n");
2268 } else {
2269 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2270 << EliminationStack.dfs_back().first << ","
2271 << EliminationStack.dfs_back().second << ")\n");
2272 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002273
2274 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2275 << MemberDFSOut << ")\n");
2276 // First, we see if we are out of scope or empty. If so,
2277 // and there equivalences, we try to replace the top of
2278 // stack with equivalences (if it's on the stack, it must
2279 // not have been eliminated yet).
2280 // Then we synchronize to our current scope, by
2281 // popping until we are back within a DFS scope that
2282 // dominates the current member.
2283 // Then, what happens depends on a few factors
2284 // If the stack is now empty, we need to push
2285 // If we have a constant or a local equivalence we want to
2286 // start using, we also push.
2287 // Otherwise, we walk along, processing members who are
2288 // dominated by this scope, and eliminate them.
2289 bool ShouldPush =
2290 Member && (EliminationStack.empty() || isa<Constant>(Member));
2291 bool OutOfScope =
2292 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2293
2294 if (OutOfScope || ShouldPush) {
2295 // Sync to our current scope.
2296 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2297 ShouldPush |= Member && EliminationStack.empty();
2298 if (ShouldPush) {
2299 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2300 }
2301 }
2302
2303 // If we get to this point, and the stack is empty we must have a use
2304 // with nothing we can use to eliminate it, just skip it.
2305 if (EliminationStack.empty())
2306 continue;
2307
2308 // Skip the Value's, we only want to eliminate on their uses.
2309 if (Member)
2310 continue;
2311 Value *Result = EliminationStack.back();
2312
Daniel Berlind92e7f92017-01-07 00:01:42 +00002313 // Don't replace our existing users with ourselves.
2314 if (MemberUse->get() == Result)
Davide Italiano7e274e02016-12-22 16:03:48 +00002315 continue;
2316
2317 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2318 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2319 << "\n");
2320
2321 // If we replaced something in an instruction, handle the patching of
2322 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002323 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002324 patchReplacementInstruction(ReplacedInst, Result);
2325
2326 assert(isa<Instruction>(MemberUse->getUser()));
2327 MemberUse->set(Result);
2328 AnythingReplaced = true;
2329 }
2330 }
2331 }
2332
2333 // Cleanup the congruence class.
2334 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002335 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002336 if (Member->getType()->isVoidTy()) {
2337 MembersLeft.insert(Member);
2338 continue;
2339 }
2340
2341 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2342 if (isInstructionTriviallyDead(MemberInst)) {
2343 // TODO: Don't mark loads of undefs.
2344 markInstructionForDeletion(MemberInst);
2345 continue;
2346 }
2347 }
2348 MembersLeft.insert(Member);
2349 }
2350 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002351
2352 // If we have possible dead stores to look at, try to eliminate them.
2353 if (CC->StoreCount > 0) {
2354 convertDenseToLoadsAndStores(CC->Members, PossibleDeadStores);
2355 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2356 ValueDFSStack EliminationStack;
2357 for (auto &VD : PossibleDeadStores) {
2358 int MemberDFSIn = VD.DFSIn;
2359 int MemberDFSOut = VD.DFSOut;
2360 Instruction *Member = cast<Instruction>(VD.Val);
2361 if (EliminationStack.empty() ||
2362 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2363 // Sync to our current scope.
2364 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2365 if (EliminationStack.empty()) {
2366 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2367 continue;
2368 }
2369 }
2370 // We already did load elimination, so nothing to do here.
2371 if (isa<LoadInst>(Member))
2372 continue;
2373 assert(!EliminationStack.empty());
2374 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002375 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002376 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2377 // Member is dominater by Leader, and thus dead
2378 DEBUG(dbgs() << "Marking dead store " << *Member
2379 << " that is dominated by " << *Leader << "\n");
2380 markInstructionForDeletion(Member);
2381 CC->Members.erase(Member);
2382 ++NumGVNDeadStores;
2383 }
2384 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002385 }
2386
2387 return AnythingReplaced;
2388}