blob: 594f6771c8bca8b0cef8904e51e1d488004eb8e7 [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.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000216
217 // This class is called INITIAL in the paper. It is the class everything
218 // startsout in, and represents any value. Being an optimistic analysis,
219 // anything in the INITIAL class has the value TOP, which is indeterminate and
220 // equivalent to everything.
Davide Italiano7e274e02016-12-22 16:03:48 +0000221 CongruenceClass *InitialClass;
222 std::vector<CongruenceClass *> CongruenceClasses;
223 unsigned NextCongruenceNum;
224
225 // Value Mappings.
226 DenseMap<Value *, CongruenceClass *> ValueToClass;
227 DenseMap<Value *, const Expression *> ValueToExpression;
228
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000229 // A table storing which memorydefs/phis represent a memory state provably
230 // equivalent to another memory state.
231 // We could use the congruence class machinery, but the MemoryAccess's are
232 // abstract memory states, so they can only ever be equivalent to each other,
233 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000234 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000235
Davide Italiano7e274e02016-12-22 16:03:48 +0000236 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000237 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000238 ExpressionClassMap ExpressionToClass;
239
240 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000241 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000242
243 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000244 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000245 DenseSet<BlockEdge> ReachableEdges;
246 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
247
248 // This is a bitvector because, on larger functions, we may have
249 // thousands of touched instructions at once (entire blocks,
250 // instructions with hundreds of uses, etc). Even with optimization
251 // for when we mark whole blocks as touched, when this was a
252 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
253 // the time in GVN just managing this list. The bitvector, on the
254 // other hand, efficiently supports test/set/clear of both
255 // individual and ranges, as well as "find next element" This
256 // enables us to use it as a worklist with essentially 0 cost.
257 BitVector TouchedInstructions;
258
259 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
260 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
261 DominatedInstRange;
262
263#ifndef NDEBUG
264 // Debugging for how many times each block and instruction got processed.
265 DenseMap<const Value *, unsigned> ProcessedCount;
266#endif
267
268 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000269 // This contains a mapping from Instructions to DFS numbers.
270 // The numbering starts at 1. An instruction with DFS number zero
271 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000272 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000273
274 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000275 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000276
277 // Deletion info.
278 SmallPtrSet<Instruction *, 8> InstructionsToErase;
279
280public:
281 static char ID; // Pass identification, replacement for typeid.
282 NewGVN() : FunctionPass(ID) {
283 initializeNewGVNPass(*PassRegistry::getPassRegistry());
284 }
285
286 bool runOnFunction(Function &F) override;
287 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000288 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000289
290private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000291 void getAnalysisUsage(AnalysisUsage &AU) const override {
292 AU.addRequired<AssumptionCacheTracker>();
293 AU.addRequired<DominatorTreeWrapperPass>();
294 AU.addRequired<TargetLibraryInfoWrapperPass>();
295 AU.addRequired<MemorySSAWrapperPass>();
296 AU.addRequired<AAResultsWrapperPass>();
297
298 AU.addPreserved<DominatorTreeWrapperPass>();
299 AU.addPreserved<GlobalsAAWrapperPass>();
300 }
301
302 // Expression handling.
Daniel Berlin97718e62017-01-31 22:32:03 +0000303 const Expression *createExpression(Instruction *);
304 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000305 PHIExpression *createPHIExpression(Instruction *);
306 const VariableExpression *createVariableExpression(Value *);
307 const ConstantExpression *createConstantExpression(Constant *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000308 const Expression *createVariableOrConstant(Value *V);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000309 const UnknownExpression *createUnknownExpression(Instruction *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000310 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000311 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin97718e62017-01-31 22:32:03 +0000312 MemoryAccess *);
313 const CallExpression *createCallExpression(CallInst *, MemoryAccess *);
314 const AggregateValueExpression *createAggregateValueExpression(Instruction *);
315 bool setBasicExpressionInfo(Instruction *, BasicExpression *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000316
317 // Congruence class handling.
318 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000319 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000320 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000321 return result;
322 }
323
324 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000325 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000326 CClass->Members.insert(Member);
327 ValueToClass[Member] = CClass;
328 return CClass;
329 }
330 void initializeCongruenceClasses(Function &F);
331
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000332 // Value number an Instruction or MemoryPhi.
333 void valueNumberMemoryPhi(MemoryPhi *);
334 void valueNumberInstruction(Instruction *);
335
Davide Italiano7e274e02016-12-22 16:03:48 +0000336 // Symbolic evaluation.
337 const Expression *checkSimplificationResults(Expression *, Instruction *,
338 Value *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000339 const Expression *performSymbolicEvaluation(Value *);
340 const Expression *performSymbolicLoadEvaluation(Instruction *);
341 const Expression *performSymbolicStoreEvaluation(Instruction *);
342 const Expression *performSymbolicCallEvaluation(Instruction *);
343 const Expression *performSymbolicPHIEvaluation(Instruction *);
344 const Expression *performSymbolicAggrValueEvaluation(Instruction *);
345 const Expression *performSymbolicCmpEvaluation(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000346
347 // Congruence finding.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000348 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000349 void performCongruenceFinding(Instruction *, const Expression *);
350 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000351 CongruenceClass *);
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000352 bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
353 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000354 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000355
Davide Italiano7e274e02016-12-22 16:03:48 +0000356 // Reachability handling.
357 void updateReachableEdge(BasicBlock *, BasicBlock *);
358 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000359 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Daniel Berlin97718e62017-01-31 22:32:03 +0000360 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000361
362 // Elimination.
363 struct ValueDFS;
Daniel Berlinc4796862017-01-27 02:37:11 +0000364 void convertDenseToDFSOrdered(const CongruenceClass::MemberSet &,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +0000365 SmallVectorImpl<ValueDFS> &);
Daniel Berlinc4796862017-01-27 02:37:11 +0000366 void convertDenseToLoadsAndStores(const CongruenceClass::MemberSet &,
367 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000368
369 bool eliminateInstructions(Function &);
370 void replaceInstruction(Instruction *, Value *);
371 void markInstructionForDeletion(Instruction *);
372 void deleteInstructionsInBlock(BasicBlock *);
373
374 // New instruction creation.
375 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000376
377 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000378 void markUsersTouched(Value *);
379 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000380 void markLeaderChangeTouched(CongruenceClass *CC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000381
382 // Utilities.
383 void cleanupTables();
384 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
385 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000386 void verifyMemoryCongruency() const;
387 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000388};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000389} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000390
391char NewGVN::ID = 0;
392
393// createGVNPass - The public interface to this file.
394FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
395
Davide Italianob1114092016-12-28 13:37:17 +0000396template <typename T>
397static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
398 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000399 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000400 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000401 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000402 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000403 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000404 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000405 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000406 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000407 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000408 return true;
409}
410
Davide Italianob1114092016-12-28 13:37:17 +0000411bool LoadExpression::equals(const Expression &Other) const {
412 return equalsLoadStoreHelper(*this, Other);
413}
Davide Italiano7e274e02016-12-22 16:03:48 +0000414
Davide Italianob1114092016-12-28 13:37:17 +0000415bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000416 bool Result = equalsLoadStoreHelper(*this, Other);
417 // Make sure that store vs store includes the value operand.
418 if (Result)
419 if (const auto *S = dyn_cast<StoreExpression>(&Other))
420 if (getStoredValue() != S->getStoredValue())
421 return false;
422 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000423}
424
425#ifndef NDEBUG
426static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000427 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000428}
429#endif
430
431INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
432INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
433INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
434INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
435INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
436INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
437INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
438INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
439
440PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000441 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000442 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000443 auto *E =
444 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000445
446 E->allocateOperands(ArgRecycler, ExpressionAllocator);
447 E->setType(I->getType());
448 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000449
Davide Italianob3886dd2017-01-25 23:37:49 +0000450 // Filter out unreachable phi operands.
451 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000452 return ReachableBlocks.count(PN->getIncomingBlock(U));
Davide Italianob3886dd2017-01-25 23:37:49 +0000453 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000454
455 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
456 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000457 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000458 if (U == PN)
459 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000460 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000461 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000462 return E;
463}
464
465// Set basic expression info (Arguments, type, opcode) for Expression
466// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000467bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000468 bool AllConstant = true;
469 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
470 E->setType(GEP->getSourceElementType());
471 else
472 E->setType(I->getType());
473 E->setOpcode(I->getOpcode());
474 E->allocateOperands(ArgRecycler, ExpressionAllocator);
475
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000476 // Transform the operand array into an operand leader array, and keep track of
477 // whether all members are constant.
478 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000479 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000480 AllConstant &= isa<Constant>(Operand);
481 return Operand;
482 });
483
Davide Italiano7e274e02016-12-22 16:03:48 +0000484 return AllConstant;
485}
486
487const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000488 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000489 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000490
491 E->setType(T);
492 E->setOpcode(Opcode);
493 E->allocateOperands(ArgRecycler, ExpressionAllocator);
494 if (Instruction::isCommutative(Opcode)) {
495 // Ensure that commutative instructions that only differ by a permutation
496 // of their operands get the same value number by sorting the operand value
497 // numbers. Since all commutative instructions have two operands it is more
498 // efficient to sort by hand rather than using, say, std::sort.
499 if (Arg1 > Arg2)
500 std::swap(Arg1, Arg2);
501 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000502 E->op_push_back(lookupOperandLeader(Arg1));
503 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000504
505 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
506 DT, AC);
507 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
508 return SimplifiedE;
509 return E;
510}
511
512// Take a Value returned by simplification of Expression E/Instruction
513// I, and see if it resulted in a simpler expression. If so, return
514// that expression.
515// TODO: Once finished, this should not take an Instruction, we only
516// use it for printing.
517const Expression *NewGVN::checkSimplificationResults(Expression *E,
518 Instruction *I, Value *V) {
519 if (!V)
520 return nullptr;
521 if (auto *C = dyn_cast<Constant>(V)) {
522 if (I)
523 DEBUG(dbgs() << "Simplified " << *I << " to "
524 << " constant " << *C << "\n");
525 NumGVNOpsSimplified++;
526 assert(isa<BasicExpression>(E) &&
527 "We should always have had a basic expression here");
528
529 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
530 ExpressionAllocator.Deallocate(E);
531 return createConstantExpression(C);
532 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
533 if (I)
534 DEBUG(dbgs() << "Simplified " << *I << " to "
535 << " variable " << *V << "\n");
536 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
537 ExpressionAllocator.Deallocate(E);
538 return createVariableExpression(V);
539 }
540
541 CongruenceClass *CC = ValueToClass.lookup(V);
542 if (CC && CC->DefiningExpr) {
543 if (I)
544 DEBUG(dbgs() << "Simplified " << *I << " to "
545 << " expression " << *V << "\n");
546 NumGVNOpsSimplified++;
547 assert(isa<BasicExpression>(E) &&
548 "We should always have had a basic expression here");
549 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
550 ExpressionAllocator.Deallocate(E);
551 return CC->DefiningExpr;
552 }
553 return nullptr;
554}
555
Daniel Berlin97718e62017-01-31 22:32:03 +0000556const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000557 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000558
Daniel Berlin97718e62017-01-31 22:32:03 +0000559 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000560
561 if (I->isCommutative()) {
562 // Ensure that commutative instructions that only differ by a permutation
563 // of their operands get the same value number by sorting the operand value
564 // numbers. Since all commutative instructions have two operands it is more
565 // efficient to sort by hand rather than using, say, std::sort.
566 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
567 if (E->getOperand(0) > E->getOperand(1))
568 E->swapOperands(0, 1);
569 }
570
571 // Perform simplificaiton
572 // TODO: Right now we only check to see if we get a constant result.
573 // We may get a less than constant, but still better, result for
574 // some operations.
575 // IE
576 // add 0, x -> x
577 // and x, x -> x
578 // We should handle this by simply rewriting the expression.
579 if (auto *CI = dyn_cast<CmpInst>(I)) {
580 // Sort the operand value numbers so x<y and y>x get the same value
581 // number.
582 CmpInst::Predicate Predicate = CI->getPredicate();
583 if (E->getOperand(0) > E->getOperand(1)) {
584 E->swapOperands(0, 1);
585 Predicate = CmpInst::getSwappedPredicate(Predicate);
586 }
587 E->setOpcode((CI->getOpcode() << 8) | Predicate);
588 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000589 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
590 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000591 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
592 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000593 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin97718e62017-01-31 22:32:03 +0000594 *DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000595 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
596 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000597 } else if (isa<SelectInst>(I)) {
598 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000599 E->getOperand(0) == E->getOperand(1)) {
600 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
601 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000602 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
603 E->getOperand(2), *DL, TLI, DT, AC);
604 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
605 return SimplifiedE;
606 }
607 } else if (I->isBinaryOp()) {
608 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
609 *DL, TLI, DT, AC);
610 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
611 return SimplifiedE;
612 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
613 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
614 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
615 return SimplifiedE;
616 } else if (isa<GetElementPtrInst>(I)) {
617 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000618 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000619 *DL, TLI, DT, AC);
620 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
621 return SimplifiedE;
622 } else if (AllConstant) {
623 // We don't bother trying to simplify unless all of the operands
624 // were constant.
625 // TODO: There are a lot of Simplify*'s we could call here, if we
626 // wanted to. The original motivating case for this code was a
627 // zext i1 false to i8, which we don't have an interface to
628 // simplify (IE there is no SimplifyZExt).
629
630 SmallVector<Constant *, 8> C;
631 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000632 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000633
634 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
635 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
636 return SimplifiedE;
637 }
638 return E;
639}
640
641const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000642NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000643 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000644 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000645 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000646 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000647 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000648 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000649 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000650 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000651 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000652 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000653 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000654 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000655 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000656 return E;
657 }
658 llvm_unreachable("Unhandled type of aggregate value operation");
659}
660
Daniel Berlin85f91b02016-12-26 20:06:58 +0000661const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000662 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000663 E->setOpcode(V->getValueID());
664 return E;
665}
666
Daniel Berlin97718e62017-01-31 22:32:03 +0000667const Expression *NewGVN::createVariableOrConstant(Value *V) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000668 auto Leader = lookupOperandLeader(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000669 if (auto *C = dyn_cast<Constant>(Leader))
670 return createConstantExpression(C);
671 return createVariableExpression(Leader);
672}
673
Daniel Berlin85f91b02016-12-26 20:06:58 +0000674const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000675 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000676 E->setOpcode(C->getValueID());
677 return E;
678}
679
Daniel Berlin02c6b172017-01-02 18:00:53 +0000680const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
681 auto *E = new (ExpressionAllocator) UnknownExpression(I);
682 E->setOpcode(I->getOpcode());
683 return E;
684}
685
Davide Italiano7e274e02016-12-22 16:03:48 +0000686const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000687 MemoryAccess *HV) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000688 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000689 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000690 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
Daniel Berlin97718e62017-01-31 22:32:03 +0000691 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000692 return E;
693}
694
695// See if we have a congruence class and leader for this operand, and if so,
696// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000697Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000698 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +0000699 if (CC) {
700 // Everything in INITIAL is represneted by undef, as it can be any value.
701 // We do have to make sure we get the type right though, so we can't set the
702 // RepLeader to undef.
703 if (CC == InitialClass)
704 return UndefValue::get(V->getType());
Daniel Berlin26addef2017-01-20 21:04:30 +0000705 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Daniel Berlinb79f5362017-02-11 12:48:50 +0000706 }
707
Davide Italiano7e274e02016-12-22 16:03:48 +0000708 return V;
709}
710
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000711MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000712 auto *CC = MemoryAccessToClass.lookup(MA);
713 if (CC && CC->RepMemoryAccess)
714 return CC->RepMemoryAccess;
715 // FIXME: We need to audit all the places that current set a nullptr To, and
716 // fix them. There should always be *some* congruence class, even if it is
717 // singular. Right now, we don't bother setting congruence classes for
718 // anything but stores, which means we have to return the original access
719 // here. Otherwise, this should be unreachable.
720 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000721}
722
Daniel Berlinc4796862017-01-27 02:37:11 +0000723// Return true if the MemoryAccess is really equivalent to everything. This is
724// equivalent to the lattice value "TOP" in most lattices. This is the initial
725// state of all memory accesses.
726bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
727 return MemoryAccessToClass.lookup(MA) == InitialClass;
728}
729
Davide Italiano7e274e02016-12-22 16:03:48 +0000730LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin97718e62017-01-31 22:32:03 +0000731 LoadInst *LI, MemoryAccess *DA) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000732 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000733 E->allocateOperands(ArgRecycler, ExpressionAllocator);
734 E->setType(LoadType);
735
736 // Give store and loads same opcode so they value number together.
737 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000738 E->op_push_back(lookupOperandLeader(PointerOp));
Davide Italiano7e274e02016-12-22 16:03:48 +0000739 if (LI)
740 E->setAlignment(LI->getAlignment());
741
742 // TODO: Value number heap versions. We may be able to discover
743 // things alias analysis can't on it's own (IE that a store and a
744 // load have the same value, and thus, it isn't clobbering the load).
745 return E;
746}
747
748const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000749 MemoryAccess *DA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000750 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000751 auto *E = new (ExpressionAllocator)
752 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000753 E->allocateOperands(ArgRecycler, ExpressionAllocator);
754 E->setType(SI->getValueOperand()->getType());
755
756 // Give store and loads same opcode so they value number together.
757 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000758 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000759
760 // TODO: Value number heap versions. We may be able to discover
761 // things alias analysis can't on it's own (IE that a store and a
762 // load have the same value, and thus, it isn't clobbering the load).
763 return E;
764}
765
Daniel Berlin97718e62017-01-31 22:32:03 +0000766const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000767 // Unlike loads, we never try to eliminate stores, so we do not check if they
768 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000769 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000770 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000771 // Get the expression, if any, for the RHS of the MemoryDef.
772 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
773 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
774 // If we are defined by ourselves, use the live on entry def.
775 if (StoreRHS == StoreAccess)
776 StoreRHS = MSSA->getLiveOnEntryDef();
777
Daniel Berlin589cecc2017-01-02 18:00:46 +0000778 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000779 // See if we are defined by a previous store expression, it already has a
780 // value, and it's the same value as our current store. FIXME: Right now, we
781 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin97718e62017-01-31 22:32:03 +0000782 const Expression *OldStore = createStoreExpression(SI, StoreRHS);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000783 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000784 // Basically, check if the congruence class the store is in is defined by a
785 // store that isn't us, and has the same value. MemorySSA takes care of
786 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000787 // The RepStoredValue gets nulled if all the stores disappear in a class, so
788 // we don't need to check if the class contains a store besides us.
Daniel Berlin808e3ff2017-01-31 22:31:56 +0000789 if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin97718e62017-01-31 22:32:03 +0000790 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +0000791 // Also check if our value operand is defined by a load of the same memory
792 // location, and the memory state is the same as it was then
793 // (otherwise, it could have been overwritten later. See test32 in
794 // transforms/DeadStoreElimination/simple.ll)
795 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000796 if ((lookupOperandLeader(LI->getPointerOperand()) ==
797 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinc4796862017-01-27 02:37:11 +0000798 (lookupMemoryAccessEquiv(
799 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
800 return createVariableExpression(LI);
801 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000802 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000803 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000804}
805
Daniel Berlin97718e62017-01-31 22:32:03 +0000806const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000807 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000808
809 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000810 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000811 if (!LI->isSimple())
812 return nullptr;
813
Daniel Berlin203f47b2017-01-31 22:31:53 +0000814 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +0000815 // Load of undef is undef.
816 if (isa<UndefValue>(LoadAddressLeader))
817 return createConstantExpression(UndefValue::get(LI->getType()));
818
819 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
820
821 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
822 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
823 Instruction *DefiningInst = MD->getMemoryInst();
824 // If the defining instruction is not reachable, replace with undef.
825 if (!ReachableBlocks.count(DefiningInst->getParent()))
826 return createConstantExpression(UndefValue::get(LI->getType()));
827 }
828 }
829
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000830 const Expression *E =
831 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000832 lookupMemoryAccessEquiv(DefiningAccess));
Davide Italiano7e274e02016-12-22 16:03:48 +0000833 return E;
834}
835
836// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000837const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000838 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000839 if (AA->doesNotAccessMemory(CI))
Daniel Berlin97718e62017-01-31 22:32:03 +0000840 return createCallExpression(CI, nullptr);
Davide Italianob2225492016-12-27 18:15:39 +0000841 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000842 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin97718e62017-01-31 22:32:03 +0000843 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess));
Davide Italianob2225492016-12-27 18:15:39 +0000844 }
845 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000846}
847
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000848// Update the memory access equivalence table to say that From is equal to To,
849// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000850// FIXME: We need to audit all the places that current set a nullptr To, and fix
851// them. There should always be *some* congruence class, even if it is singular.
852bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
853 DEBUG(dbgs() << "Setting " << *From);
854 if (To) {
855 DEBUG(dbgs() << " equivalent to congruence class ");
856 DEBUG(dbgs() << To->ID << " with current memory access leader ");
857 DEBUG(dbgs() << *To->RepMemoryAccess);
858 } else {
859 DEBUG(dbgs() << " equivalent to itself");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000860 }
Daniel Berlin9f376b72017-01-29 10:26:03 +0000861 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000862
863 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000864 bool Changed = false;
865 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000866 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000867 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000868 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000869 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000870 Changed = true;
871 } else if (!To) {
872 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000873 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000874 Changed = true;
875 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000876 } else {
877 assert(!To &&
878 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000879 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000880
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000881 return Changed;
882}
Davide Italiano7e274e02016-12-22 16:03:48 +0000883// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000884const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000885 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +0000886 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
887
888 // See if all arguaments are the same.
889 // We track if any were undef because they need special handling.
890 bool HasUndef = false;
891 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
892 if (Arg == I)
893 return false;
894 if (isa<UndefValue>(Arg)) {
895 HasUndef = true;
896 return false;
897 }
898 return true;
899 });
900 // If we are left with no operands, it's undef
901 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000902 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
903 << "\n");
904 E->deallocateOperands(ArgRecycler);
905 ExpressionAllocator.Deallocate(E);
906 return createConstantExpression(UndefValue::get(I->getType()));
907 }
Daniel Berlind92e7f92017-01-07 00:01:42 +0000908 Value *AllSameValue = *(Filtered.begin());
909 ++Filtered.begin();
910 // Can't use std::equal here, sadly, because filter.begin moves.
911 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
912 return V == AllSameValue;
913 })) {
914 // In LLVM's non-standard representation of phi nodes, it's possible to have
915 // phi nodes with cycles (IE dependent on other phis that are .... dependent
916 // on the original phi node), especially in weird CFG's where some arguments
917 // are unreachable, or uninitialized along certain paths. This can cause
918 // infinite loops during evaluation. We work around this by not trying to
919 // really evaluate them independently, but instead using a variable
920 // expression to say if one is equivalent to the other.
921 // We also special case undef, so that if we have an undef, we can't use the
922 // common value unless it dominates the phi block.
923 if (HasUndef) {
924 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +0000925 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +0000926 if (!DT->dominates(AllSameInst, I))
927 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000928 }
929
Davide Italiano7e274e02016-12-22 16:03:48 +0000930 NumGVNPhisAllSame++;
931 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
932 << "\n");
933 E->deallocateOperands(ArgRecycler);
934 ExpressionAllocator.Deallocate(E);
935 if (auto *C = dyn_cast<Constant>(AllSameValue))
936 return createConstantExpression(C);
937 return createVariableExpression(AllSameValue);
938 }
939 return E;
940}
941
Daniel Berlin97718e62017-01-31 22:32:03 +0000942const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000943 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
944 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
945 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
946 unsigned Opcode = 0;
947 // EI might be an extract from one of our recognised intrinsics. If it
948 // is we'll synthesize a semantically equivalent expression instead on
949 // an extract value expression.
950 switch (II->getIntrinsicID()) {
951 case Intrinsic::sadd_with_overflow:
952 case Intrinsic::uadd_with_overflow:
953 Opcode = Instruction::Add;
954 break;
955 case Intrinsic::ssub_with_overflow:
956 case Intrinsic::usub_with_overflow:
957 Opcode = Instruction::Sub;
958 break;
959 case Intrinsic::smul_with_overflow:
960 case Intrinsic::umul_with_overflow:
961 Opcode = Instruction::Mul;
962 break;
963 default:
964 break;
965 }
966
967 if (Opcode != 0) {
968 // Intrinsic recognized. Grab its args to finish building the
969 // expression.
970 assert(II->getNumArgOperands() == 2 &&
971 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +0000972 return createBinaryExpression(
973 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +0000974 }
975 }
976 }
977
Daniel Berlin97718e62017-01-31 22:32:03 +0000978 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000979}
Daniel Berlin97718e62017-01-31 22:32:03 +0000980const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinc22aafe2017-01-31 22:31:58 +0000981 CmpInst *CI = dyn_cast<CmpInst>(I);
982 // See if our operands are equal and that implies something.
983 auto Op0 = lookupOperandLeader(CI->getOperand(0));
984 auto Op1 = lookupOperandLeader(CI->getOperand(1));
985 if (Op0 == Op1) {
986 if (CI->isTrueWhenEqual())
987 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
988 else if (CI->isFalseWhenEqual())
989 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
990 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000991 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +0000992}
Davide Italiano7e274e02016-12-22 16:03:48 +0000993
994// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +0000995const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +0000996 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000997 if (auto *C = dyn_cast<Constant>(V))
998 E = createConstantExpression(C);
999 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1000 E = createVariableExpression(V);
1001 } else {
1002 // TODO: memory intrinsics.
1003 // TODO: Some day, we should do the forward propagation and reassociation
1004 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001005 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001006 switch (I->getOpcode()) {
1007 case Instruction::ExtractValue:
1008 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001009 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001010 break;
1011 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001012 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001013 break;
1014 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001015 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001016 break;
1017 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001018 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001019 break;
1020 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001021 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001022 break;
1023 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001024 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001025 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001026 case Instruction::ICmp:
1027 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001028 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001029 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001030 case Instruction::Add:
1031 case Instruction::FAdd:
1032 case Instruction::Sub:
1033 case Instruction::FSub:
1034 case Instruction::Mul:
1035 case Instruction::FMul:
1036 case Instruction::UDiv:
1037 case Instruction::SDiv:
1038 case Instruction::FDiv:
1039 case Instruction::URem:
1040 case Instruction::SRem:
1041 case Instruction::FRem:
1042 case Instruction::Shl:
1043 case Instruction::LShr:
1044 case Instruction::AShr:
1045 case Instruction::And:
1046 case Instruction::Or:
1047 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001048 case Instruction::Trunc:
1049 case Instruction::ZExt:
1050 case Instruction::SExt:
1051 case Instruction::FPToUI:
1052 case Instruction::FPToSI:
1053 case Instruction::UIToFP:
1054 case Instruction::SIToFP:
1055 case Instruction::FPTrunc:
1056 case Instruction::FPExt:
1057 case Instruction::PtrToInt:
1058 case Instruction::IntToPtr:
1059 case Instruction::Select:
1060 case Instruction::ExtractElement:
1061 case Instruction::InsertElement:
1062 case Instruction::ShuffleVector:
1063 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001064 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001065 break;
1066 default:
1067 return nullptr;
1068 }
1069 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001070 return E;
1071}
1072
1073// There is an edge from 'Src' to 'Dst'. Return true if every path from
1074// the entry block to 'Dst' passes via this edge. In particular 'Dst'
1075// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +00001076bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001077
1078 // While in theory it is interesting to consider the case in which Dst has
1079 // more than one predecessor, because Dst might be part of a loop which is
1080 // only reachable from Src, in practice it is pointless since at the time
1081 // GVN runs all such loops have preheaders, which means that Dst will have
1082 // been changed to have only one predecessor, namely Src.
1083 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1084 const BasicBlock *Src = E.getStart();
1085 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
1086 (void)Src;
1087 return Pred != nullptr;
1088}
1089
1090void NewGVN::markUsersTouched(Value *V) {
1091 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001092 for (auto *User : V->users()) {
1093 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001094 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001095 }
1096}
1097
1098void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1099 for (auto U : MA->users()) {
1100 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001101 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001102 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001103 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001104 }
1105}
1106
Daniel Berlin32f8d562017-01-07 16:55:14 +00001107// Touch the instructions that need to be updated after a congruence class has a
1108// leader change, and mark changed values.
1109void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1110 for (auto M : CC->Members) {
1111 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001112 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001113 LeaderChanges.insert(M);
1114 }
1115}
1116
1117// Move a value, currently in OldClass, to be part of NewClass
1118// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001119void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1120 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001121 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001122 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001123 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001124
1125 if (I == OldClass->NextLeader.first)
1126 OldClass->NextLeader = {nullptr, ~0U};
1127
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001128 // It's possible, though unlikely, for us to discover equivalences such
1129 // that the current leader does not dominate the old one.
1130 // This statistic tracks how often this happens.
1131 // We assert on phi nodes when this happens, currently, for debugging, because
1132 // we want to make sure we name phi node cycles properly.
1133 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1134 I != NewClass->RepLeader &&
1135 DT->properlyDominates(
1136 I->getParent(),
1137 cast<Instruction>(NewClass->RepLeader)->getParent())) {
1138 ++NumGVNNotMostDominatingLeader;
1139 assert(!isa<PHINode>(I) &&
1140 "New class for instruction should not be dominated by instruction");
1141 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001142
1143 if (NewClass->RepLeader != I) {
1144 auto DFSNum = InstrDFS.lookup(I);
1145 if (DFSNum < NewClass->NextLeader.second)
1146 NewClass->NextLeader = {I, DFSNum};
1147 }
1148
1149 OldClass->Members.erase(I);
1150 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001151 MemoryAccess *StoreAccess = nullptr;
1152 if (auto *SI = dyn_cast<StoreInst>(I)) {
1153 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001154 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001155 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001156 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001157 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001158 if (!NewClass->RepMemoryAccess) {
1159 // If we don't have a representative memory access, it better be the only
1160 // store in there.
1161 assert(NewClass->StoreCount == 1);
1162 NewClass->RepMemoryAccess = StoreAccess;
1163 }
1164 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001165 }
1166
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001167 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001168 // See if we destroyed the class or need to swap leaders.
1169 if (OldClass->Members.empty() && OldClass != InitialClass) {
1170 if (OldClass->DefiningExpr) {
1171 OldClass->Dead = true;
1172 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1173 << " from table\n");
1174 ExpressionToClass.erase(OldClass->DefiningExpr);
1175 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001176 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001177 // When the leader changes, the value numbering of
1178 // everything may change due to symbolization changes, so we need to
1179 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001180 DEBUG(dbgs() << "Leader change!\n");
1181 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001182 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001183 if (OldClass->StoreCount == 0) {
1184 if (OldClass->RepStoredValue != nullptr)
1185 OldClass->RepStoredValue = nullptr;
1186 if (OldClass->RepMemoryAccess != nullptr)
1187 OldClass->RepMemoryAccess = nullptr;
1188 }
1189
1190 // If we destroy the old access leader, we have to effectively destroy the
1191 // congruence class. When it comes to scalars, anything with the same value
1192 // is as good as any other. That means that one leader is as good as
1193 // another, and as long as you have some leader for the value, you are
1194 // good.. When it comes to *memory states*, only one particular thing really
1195 // represents the definition of a given memory state. Once it goes away, we
1196 // need to re-evaluate which pieces of memory are really still
1197 // equivalent. The best way to do this is to re-value number things. The
1198 // only way to really make that happen is to destroy the rest of the class.
1199 // In order to effectively destroy the class, we reset ExpressionToClass for
1200 // each by using the ValueToExpression mapping. The members later get
1201 // marked as touched due to the leader change. We will create new
1202 // congruence classes, and the pieces that are still equivalent will end
1203 // back together in a new class. If this becomes too expensive, it is
1204 // possible to use a versioning scheme for the congruence classes to avoid
1205 // the expressions finding this old class.
1206 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1207 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1208 << " because memory access leader changed");
1209 for (auto Member : OldClass->Members)
1210 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1211 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001212
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001213 // We don't need to sort members if there is only 1, and we don't care about
Daniel Berlinb79f5362017-02-11 12:48:50 +00001214 // sorting the INITIAL class because everything either gets out of it or is
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001215 // unreachable.
1216 if (OldClass->Members.size() == 1 || OldClass == InitialClass) {
1217 OldClass->RepLeader = *(OldClass->Members.begin());
1218 } else if (OldClass->NextLeader.first) {
1219 ++NumGVNAvoidedSortedLeaderChanges;
1220 OldClass->RepLeader = OldClass->NextLeader.first;
1221 OldClass->NextLeader = {nullptr, ~0U};
1222 } else {
1223 ++NumGVNSortedLeaderChanges;
1224 // TODO: If this ends up to slow, we can maintain a dual structure for
1225 // member testing/insertion, or keep things mostly sorted, and sort only
1226 // here, or ....
1227 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1228 for (const auto X : OldClass->Members) {
1229 auto DFSNum = InstrDFS.lookup(X);
1230 if (DFSNum < MinDFS.second)
1231 MinDFS = {X, DFSNum};
1232 }
1233 OldClass->RepLeader = MinDFS.first;
1234 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001235 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001236 }
1237}
1238
Davide Italiano7e274e02016-12-22 16:03:48 +00001239// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001240void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1241 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001242 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00001243 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001244
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001245 CongruenceClass *IClass = ValueToClass[I];
1246 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001247 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001248 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001249
1250 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001251 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001252 EClass = ValueToClass[VE->getVariableValue()];
1253 } else {
1254 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1255
1256 // If it's not in the value table, create a new congruence class.
1257 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001258 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001259 auto place = lookupResult.first;
1260 place->second = NewClass;
1261
1262 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001263 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001264 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001265 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1266 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001267 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001268 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001269 // The RepMemoryAccess field will be filled in properly by the
1270 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001271 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001272 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001273 }
1274 assert(!isa<VariableExpression>(E) &&
1275 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001276
1277 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001278 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001279 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001280 << " and leader " << *(NewClass->RepLeader));
1281 if (NewClass->RepStoredValue)
1282 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1283 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001284 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1285 } else {
1286 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001287 if (isa<ConstantExpression>(E))
1288 assert(isa<Constant>(EClass->RepLeader) &&
1289 "Any class with a constant expression should have a "
1290 "constant leader");
1291
Davide Italiano7e274e02016-12-22 16:03:48 +00001292 assert(EClass && "Somehow don't have an eclass");
1293
1294 assert(!EClass->Dead && "We accidentally looked up a dead class");
1295 }
1296 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001297 bool ClassChanged = IClass != EClass;
1298 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001299 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001300 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1301 << "\n");
1302
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001303 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001304 moveValueToNewCongruenceClass(I, IClass, EClass);
1305 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001306 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001307 markMemoryUsersTouched(MA);
Davide Italiano7e274e02016-12-22 16:03:48 +00001308 }
1309}
1310
1311// Process the fact that Edge (from, to) is reachable, including marking
1312// any newly reachable blocks and instructions for processing.
1313void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1314 // Check if the Edge was reachable before.
1315 if (ReachableEdges.insert({From, To}).second) {
1316 // If this block wasn't reachable before, all instructions are touched.
1317 if (ReachableBlocks.insert(To).second) {
1318 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1319 const auto &InstRange = BlockInstRange.lookup(To);
1320 TouchedInstructions.set(InstRange.first, InstRange.second);
1321 } else {
1322 DEBUG(dbgs() << "Block " << getBlockName(To)
1323 << " was reachable, but new edge {" << getBlockName(From)
1324 << "," << getBlockName(To) << "} to it found\n");
1325
1326 // We've made an edge reachable to an existing block, which may
1327 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1328 // they are the only thing that depend on new edges. Anything using their
1329 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001330 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001331 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001332
Davide Italiano7e274e02016-12-22 16:03:48 +00001333 auto BI = To->begin();
1334 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001335 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001336 ++BI;
1337 }
1338 }
1339 }
1340}
1341
1342// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1343// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001344Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001345 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001346 if (isa<Constant>(Result))
1347 return Result;
1348 return nullptr;
1349}
1350
1351// Process the outgoing edges of a block for reachability.
1352void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1353 // Evaluate reachability of terminator instruction.
1354 BranchInst *BR;
1355 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1356 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001357 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001358 if (!CondEvaluated) {
1359 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001360 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001361 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1362 CondEvaluated = CE->getConstantValue();
1363 }
1364 } else if (isa<ConstantInt>(Cond)) {
1365 CondEvaluated = Cond;
1366 }
1367 }
1368 ConstantInt *CI;
1369 BasicBlock *TrueSucc = BR->getSuccessor(0);
1370 BasicBlock *FalseSucc = BR->getSuccessor(1);
1371 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1372 if (CI->isOne()) {
1373 DEBUG(dbgs() << "Condition for Terminator " << *TI
1374 << " evaluated to true\n");
1375 updateReachableEdge(B, TrueSucc);
1376 } else if (CI->isZero()) {
1377 DEBUG(dbgs() << "Condition for Terminator " << *TI
1378 << " evaluated to false\n");
1379 updateReachableEdge(B, FalseSucc);
1380 }
1381 } else {
1382 updateReachableEdge(B, TrueSucc);
1383 updateReachableEdge(B, FalseSucc);
1384 }
1385 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1386 // For switches, propagate the case values into the case
1387 // destinations.
1388
1389 // Remember how many outgoing edges there are to every successor.
1390 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1391
Davide Italiano7e274e02016-12-22 16:03:48 +00001392 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001393 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001394 // See if we were able to turn this switch statement into a constant.
1395 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001396 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001397 // We should be able to get case value for this.
1398 auto CaseVal = SI->findCaseValue(CondVal);
1399 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1400 // We proved the value is outside of the range of the case.
1401 // We can't do anything other than mark the default dest as reachable,
1402 // and go home.
1403 updateReachableEdge(B, SI->getDefaultDest());
1404 return;
1405 }
1406 // Now get where it goes and mark it reachable.
1407 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1408 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001409 } else {
1410 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1411 BasicBlock *TargetBlock = SI->getSuccessor(i);
1412 ++SwitchEdges[TargetBlock];
1413 updateReachableEdge(B, TargetBlock);
1414 }
1415 }
1416 } else {
1417 // Otherwise this is either unconditional, or a type we have no
1418 // idea about. Just mark successors as reachable.
1419 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1420 BasicBlock *TargetBlock = TI->getSuccessor(i);
1421 updateReachableEdge(B, TargetBlock);
1422 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001423
1424 // This also may be a memory defining terminator, in which case, set it
1425 // equivalent to nothing.
1426 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1427 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001428 }
1429}
1430
Daniel Berlin85f91b02016-12-26 20:06:58 +00001431// The algorithm initially places the values of the routine in the INITIAL
Daniel Berlinb79f5362017-02-11 12:48:50 +00001432// congruence class. The leader of INITIAL is the undetermined value `TOP`.
Davide Italiano7e274e02016-12-22 16:03:48 +00001433// When the algorithm has finished, values still in INITIAL are unreachable.
1434void NewGVN::initializeCongruenceClasses(Function &F) {
1435 // FIXME now i can't remember why this is 2
1436 NextCongruenceNum = 2;
1437 // Initialize all other instructions to be in INITIAL class.
1438 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001439 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001440 InitialClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001441 for (auto &B : F) {
1442 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001443 MemoryAccessToClass[MP] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001444
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001445 for (auto &I : B) {
Daniel Berlinb79f5362017-02-11 12:48:50 +00001446 // Don't insert void terminators into the class
1447 if (!isa<TerminatorInst>(I) || !I.getType()->isVoidTy()) {
1448 InitialValues.insert(&I);
1449 ValueToClass[&I] = InitialClass;
1450 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001451 // All memory accesses are equivalent to live on entry to start. They must
1452 // be initialized to something so that initial changes are noticed. For
1453 // the maximal answer, we initialize them all to be the same as
1454 // liveOnEntry. Note that to save time, we only initialize the
1455 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1456 // other expression can generate a memory equivalence. If we start
1457 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001458 if (isa<StoreInst>(&I)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001459 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = InitialClass;
Davide Italianoeac05f62017-01-11 23:41:24 +00001460 ++InitialClass->StoreCount;
1461 assert(InitialClass->StoreCount > 0);
1462 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001463 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001464 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001465 InitialClass->Members.swap(InitialValues);
1466
1467 // Initialize arguments to be in their own unique congruence classes
1468 for (auto &FA : F.args())
1469 createSingletonCongruenceClass(&FA);
1470}
1471
1472void NewGVN::cleanupTables() {
1473 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1474 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1475 << CongruenceClasses[i]->Members.size() << " members\n");
1476 // Make sure we delete the congruence class (probably worth switching to
1477 // a unique_ptr at some point.
1478 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001479 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001480 }
1481
1482 ValueToClass.clear();
1483 ArgRecycler.clear(ExpressionAllocator);
1484 ExpressionAllocator.Reset();
1485 CongruenceClasses.clear();
1486 ExpressionToClass.clear();
1487 ValueToExpression.clear();
1488 ReachableBlocks.clear();
1489 ReachableEdges.clear();
1490#ifndef NDEBUG
1491 ProcessedCount.clear();
1492#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001493 InstrDFS.clear();
1494 InstructionsToErase.clear();
1495
1496 DFSToInstr.clear();
1497 BlockInstRange.clear();
1498 TouchedInstructions.clear();
1499 DominatedInstRange.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001500 MemoryAccessToClass.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001501}
1502
1503std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1504 unsigned Start) {
1505 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001506 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1507 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001508 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001509 }
1510
Davide Italiano7e274e02016-12-22 16:03:48 +00001511 for (auto &I : *B) {
1512 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001513 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001514 }
1515
1516 // All of the range functions taken half-open ranges (open on the end side).
1517 // So we do not subtract one from count, because at this point it is one
1518 // greater than the last instruction.
1519 return std::make_pair(Start, End);
1520}
1521
1522void NewGVN::updateProcessedCount(Value *V) {
1523#ifndef NDEBUG
1524 if (ProcessedCount.count(V) == 0) {
1525 ProcessedCount.insert({V, 1});
1526 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001527 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001528 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001529 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001530 }
1531#endif
1532}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001533// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1534void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1535 // If all the arguments are the same, the MemoryPhi has the same value as the
1536 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001537 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001538 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001539 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1540 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
1541 ReachableBlocks.count(MP->getIncomingBlock(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001542 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001543 // If all that is left is nothing, our memoryphi is undef. We keep it as
1544 // InitialClass. Note: The only case this should happen is if we have at
1545 // least one self-argument.
1546 if (Filtered.begin() == Filtered.end()) {
1547 if (setMemoryAccessEquivTo(MP, InitialClass))
1548 markMemoryUsersTouched(MP);
1549 return;
1550 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001551
1552 // Transform the remaining operands into operand leaders.
1553 // FIXME: mapped_iterator should have a range version.
1554 auto LookupFunc = [&](const Use &U) {
1555 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1556 };
1557 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1558 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1559
1560 // and now check if all the elements are equal.
1561 // Sadly, we can't use std::equals since these are random access iterators.
1562 MemoryAccess *AllSameValue = *MappedBegin;
1563 ++MappedBegin;
1564 bool AllEqual = std::all_of(
1565 MappedBegin, MappedEnd,
1566 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1567
1568 if (AllEqual)
1569 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1570 else
1571 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1572
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001573 if (setMemoryAccessEquivTo(
1574 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001575 markMemoryUsersTouched(MP);
1576}
1577
1578// Value number a single instruction, symbolically evaluating, performing
1579// congruence finding, and updating mappings.
1580void NewGVN::valueNumberInstruction(Instruction *I) {
1581 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001582
1583 // There's no need to call isInstructionTriviallyDead more than once on
1584 // an instruction. Therefore, once we know that an instruction is dead
1585 // we change its DFS number so that it doesn't get numbered again.
1586 if (InstrDFS[I] != 0 && isInstructionTriviallyDead(I, TLI)) {
1587 InstrDFS[I] = 0;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001588 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001589 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001590 return;
1591 }
1592 if (!I->isTerminator()) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001593 const auto *Symbolized = performSymbolicEvaluation(I);
Daniel Berlin02c6b172017-01-02 18:00:53 +00001594 // If we couldn't come up with a symbolic expression, use the unknown
1595 // expression
1596 if (Symbolized == nullptr)
1597 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001598 performCongruenceFinding(I, Symbolized);
1599 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001600 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00001601 // don't currently understand. We don't place non-value producing
1602 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001603 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001604 auto *Symbolized = createUnknownExpression(I);
1605 performCongruenceFinding(I, Symbolized);
1606 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001607 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1608 }
1609}
Davide Italiano7e274e02016-12-22 16:03:48 +00001610
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001611// Check if there is a path, using single or equal argument phi nodes, from
1612// First to Second.
1613bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1614 const MemoryAccess *Second) const {
1615 if (First == Second)
1616 return true;
1617
1618 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1619 auto *DefAccess = FirstDef->getDefiningAccess();
1620 return singleReachablePHIPath(DefAccess, Second);
1621 } else {
1622 auto *MP = cast<MemoryPhi>(First);
1623 auto ReachableOperandPred = [&](const Use &U) {
1624 return ReachableBlocks.count(MP->getIncomingBlock(U));
1625 };
1626 auto FilteredPhiArgs =
1627 make_filter_range(MP->operands(), ReachableOperandPred);
1628 SmallVector<const Value *, 32> OperandList;
1629 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1630 std::back_inserter(OperandList));
1631 bool Okay = OperandList.size() == 1;
1632 if (!Okay)
1633 Okay = std::equal(OperandList.begin(), OperandList.end(),
1634 OperandList.begin());
1635 if (Okay)
1636 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1637 return false;
1638 }
1639}
1640
Daniel Berlin589cecc2017-01-02 18:00:46 +00001641// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001642// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001643// subject to very rare false negatives. It is only useful for
1644// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001645void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001646 // Anything equivalent in the memory access table should be in the same
1647 // congruence class.
1648
1649 // Filter out the unreachable and trivially dead entries, because they may
1650 // never have been updated if the instructions were not processed.
1651 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001652 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001653 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1654 if (!Result)
1655 return false;
1656 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1657 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1658 return true;
1659 };
1660
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001661 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001662 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001663 // Unreachable instructions may not have changed because we never process
1664 // them.
1665 if (!ReachableBlocks.count(KV.first->getBlock()))
1666 continue;
1667 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001668 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001669 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001670 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001671 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1672 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1673 "The instructions for these memory operations should have "
1674 "been in the same congruence class or reachable through"
1675 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001676 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1677
1678 // We can only sanely verify that MemoryDefs in the operand list all have
1679 // the same class.
1680 auto ReachableOperandPred = [&](const Use &U) {
1681 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1682 isa<MemoryDef>(U);
1683
1684 };
1685 // All arguments should in the same class, ignoring unreachable arguments
1686 auto FilteredPhiArgs =
1687 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1688 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1689 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1690 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1691 const MemoryDef *MD = cast<MemoryDef>(U);
1692 return ValueToClass.lookup(MD->getMemoryInst());
1693 });
1694 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1695 PhiOpClasses.begin()) &&
1696 "All MemoryPhi arguments should be in the same class");
1697 }
1698 }
1699}
1700
Daniel Berlin85f91b02016-12-26 20:06:58 +00001701// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001702bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001703 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1704 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001705 bool Changed = false;
1706 DT = _DT;
1707 AC = _AC;
1708 TLI = _TLI;
1709 AA = _AA;
1710 MSSA = _MSSA;
1711 DL = &F.getParent()->getDataLayout();
1712 MSSAWalker = MSSA->getWalker();
1713
1714 // Count number of instructions for sizing of hash tables, and come
1715 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001716 unsigned ICount = 1;
1717 // Add an empty instruction to account for the fact that we start at 1
1718 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001719 // Note: We want RPO traversal of the blocks, which is not quite the same as
1720 // dominator tree order, particularly with regard whether backedges get
1721 // visited first or second, given a block with multiple successors.
1722 // If we visit in the wrong order, we will end up performing N times as many
1723 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001724 // The dominator tree does guarantee that, for a given dom tree node, it's
1725 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1726 // the siblings.
1727 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001728 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001729 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001730 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001731 auto *Node = DT->getNode(B);
1732 assert(Node && "RPO and Dominator tree should have same reachability");
1733 RPOOrdering[Node] = ++Counter;
1734 }
1735 // Sort dominator tree children arrays into RPO.
1736 for (auto &B : RPOT) {
1737 auto *Node = DT->getNode(B);
1738 if (Node->getChildren().size() > 1)
1739 std::sort(Node->begin(), Node->end(),
1740 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1741 return RPOOrdering[A] < RPOOrdering[B];
1742 });
1743 }
1744
1745 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1746 auto DFI = df_begin(DT->getRootNode());
1747 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1748 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001749 const auto &BlockRange = assignDFSNumbers(B, ICount);
1750 BlockInstRange.insert({B, BlockRange});
1751 ICount += BlockRange.second - BlockRange.first;
1752 }
1753
1754 // Handle forward unreachable blocks and figure out which blocks
1755 // have single preds.
1756 for (auto &B : F) {
1757 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001758 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001759 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1760 BlockInstRange.insert({&B, BlockRange});
1761 ICount += BlockRange.second - BlockRange.first;
1762 }
1763 }
1764
Daniel Berline0bd37e2016-12-29 22:15:12 +00001765 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001766 DominatedInstRange.reserve(F.size());
1767 // Ensure we don't end up resizing the expressionToClass map, as
1768 // that can be quite expensive. At most, we have one expression per
1769 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001770 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001771
1772 // Initialize the touched instructions to include the entry block.
1773 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1774 TouchedInstructions.set(InstRange.first, InstRange.second);
1775 ReachableBlocks.insert(&F.getEntryBlock());
1776
1777 initializeCongruenceClasses(F);
1778
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001779 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001780 // We start out in the entry block.
1781 BasicBlock *LastBlock = &F.getEntryBlock();
1782 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001783 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00001784 // Walk through all the instructions in all the blocks in RPO.
1785 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1786 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001787
1788 // This instruction was found to be dead. We don't bother looking
1789 // at it again.
1790 if (InstrNum == 0) {
1791 TouchedInstructions.reset(InstrNum);
1792 continue;
1793 }
1794
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001795 Value *V = DFSToInstr[InstrNum];
1796 BasicBlock *CurrBlock = nullptr;
1797
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001798 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001799 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001800 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001801 CurrBlock = MP->getBlock();
1802 else
1803 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001804
1805 // If we hit a new block, do reachability processing.
1806 if (CurrBlock != LastBlock) {
1807 LastBlock = CurrBlock;
1808 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1809 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1810
1811 // If it's not reachable, erase any touched instructions and move on.
1812 if (!BlockReachable) {
1813 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1814 DEBUG(dbgs() << "Skipping instructions in block "
1815 << getBlockName(CurrBlock)
1816 << " because it is unreachable\n");
1817 continue;
1818 }
1819 updateProcessedCount(CurrBlock);
1820 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001821
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001822 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001823 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1824 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001825 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001826 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001827 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001828 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001829 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001830 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001831 // Reset after processing (because we may mark ourselves as touched when
1832 // we propagate equalities).
1833 TouchedInstructions.reset(InstrNum);
1834 }
1835 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001836 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001837#ifndef NDEBUG
1838 verifyMemoryCongruency();
1839#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001840 Changed |= eliminateInstructions(F);
1841
1842 // Delete all instructions marked for deletion.
1843 for (Instruction *ToErase : InstructionsToErase) {
1844 if (!ToErase->use_empty())
1845 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1846
1847 ToErase->eraseFromParent();
1848 }
1849
1850 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001851 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1852 return !ReachableBlocks.count(&BB);
1853 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001854
1855 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1856 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001857 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001858 deleteInstructionsInBlock(&BB);
1859 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001860 }
1861
1862 cleanupTables();
1863 return Changed;
1864}
1865
1866bool NewGVN::runOnFunction(Function &F) {
1867 if (skipFunction(F))
1868 return false;
1869 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1870 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1871 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1872 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1873 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1874}
1875
Daniel Berlin85f91b02016-12-26 20:06:58 +00001876PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001877 NewGVN Impl;
1878
1879 // Apparently the order in which we get these results matter for
1880 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1881 // the same order here, just in case.
1882 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1883 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1884 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1885 auto &AA = AM.getResult<AAManager>(F);
1886 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1887 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1888 if (!Changed)
1889 return PreservedAnalyses::all();
1890 PreservedAnalyses PA;
1891 PA.preserve<DominatorTreeAnalysis>();
1892 PA.preserve<GlobalsAA>();
1893 return PA;
1894}
1895
1896// Return true if V is a value that will always be available (IE can
1897// be placed anywhere) in the function. We don't do globals here
1898// because they are often worse to put in place.
1899// TODO: Separate cost from availability
1900static bool alwaysAvailable(Value *V) {
1901 return isa<Constant>(V) || isa<Argument>(V);
1902}
1903
1904// Get the basic block from an instruction/value.
1905static BasicBlock *getBlockForValue(Value *V) {
1906 if (auto *I = dyn_cast<Instruction>(V))
1907 return I->getParent();
1908 return nullptr;
1909}
1910
1911struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001912 int DFSIn = 0;
1913 int DFSOut = 0;
1914 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001915 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001916 Value *Val = nullptr;
1917 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001918
1919 bool operator<(const ValueDFS &Other) const {
1920 // It's not enough that any given field be less than - we have sets
1921 // of fields that need to be evaluated together to give a proper ordering.
1922 // For example, if you have;
1923 // DFS (1, 3)
1924 // Val 0
1925 // DFS (1, 2)
1926 // Val 50
1927 // We want the second to be less than the first, but if we just go field
1928 // by field, we will get to Val 0 < Val 50 and say the first is less than
1929 // the second. We only want it to be less than if the DFS orders are equal.
1930 //
1931 // Each LLVM instruction only produces one value, and thus the lowest-level
1932 // differentiator that really matters for the stack (and what we use as as a
1933 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001934 // Everything else in the structure is instruction level, and only affects
1935 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001936 //
1937 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1938 // the order of replacement of uses does not matter.
1939 // IE given,
1940 // a = 5
1941 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001942 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1943 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001944 // The .val will be the same as well.
1945 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001946 // You will replace both, and it does not matter what order you replace them
1947 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1948 // operand 2).
1949 // Similarly for the case of same dfsin, dfsout, localnum, but different
1950 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001951 // a = 5
1952 // b = 6
1953 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001954 // in c, we will a valuedfs for a, and one for b,with everything the same
1955 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001956 // It does not matter what order we replace these operands in.
1957 // You will always end up with the same IR, and this is guaranteed.
1958 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1959 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1960 Other.U);
1961 }
1962};
1963
Daniel Berlinc4796862017-01-27 02:37:11 +00001964// This function converts the set of members for a congruence class from values,
1965// to sets of defs and uses with associated DFS info.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001966void NewGVN::convertDenseToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00001967 const CongruenceClass::MemberSet &Dense,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001968 SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001969 for (auto D : Dense) {
1970 // First add the value.
1971 BasicBlock *BB = getBlockForValue(D);
1972 // Constants are handled prior to ever calling this function, so
1973 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001974 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001975 ValueDFS VD;
Daniel Berlinb66164c2017-01-14 00:24:23 +00001976 DomTreeNode *DomNode = DT->getNode(BB);
1977 VD.DFSIn = DomNode->getDFSNumIn();
1978 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00001979 // If it's a store, use the leader of the value operand.
1980 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001981 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00001982 VD.Val = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
1983 } else {
1984 VD.Val = D;
1985 }
1986
Davide Italiano7e274e02016-12-22 16:03:48 +00001987 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlinaac56842017-01-15 09:18:41 +00001988 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001989 else
1990 llvm_unreachable("Should have been an instruction");
1991
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001992 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001993
Daniel Berlinb66164c2017-01-14 00:24:23 +00001994 // Now add the uses.
Davide Italiano7e274e02016-12-22 16:03:48 +00001995 for (auto &U : D->uses()) {
1996 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1997 ValueDFS VD;
1998 // Put the phi node uses in the incoming block.
1999 BasicBlock *IBlock;
2000 if (auto *P = dyn_cast<PHINode>(I)) {
2001 IBlock = P->getIncomingBlock(U);
2002 // Make phi node users appear last in the incoming block
2003 // they are from.
2004 VD.LocalNum = InstrDFS.size() + 1;
2005 } else {
2006 IBlock = I->getParent();
Daniel Berlinaac56842017-01-15 09:18:41 +00002007 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002008 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002009
2010 // Skip uses in unreachable blocks, as we're going
2011 // to delete them.
2012 if (ReachableBlocks.count(IBlock) == 0)
2013 continue;
2014
Daniel Berlinb66164c2017-01-14 00:24:23 +00002015 DomTreeNode *DomNode = DT->getNode(IBlock);
2016 VD.DFSIn = DomNode->getDFSNumIn();
2017 VD.DFSOut = DomNode->getDFSNumOut();
Davide Italiano7e274e02016-12-22 16:03:48 +00002018 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002019 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00002020 }
2021 }
2022 }
2023}
2024
Daniel Berlinc4796862017-01-27 02:37:11 +00002025// This function converts the set of members for a congruence class from values,
2026// to the set of defs for loads and stores, with associated DFS info.
2027void NewGVN::convertDenseToLoadsAndStores(
2028 const CongruenceClass::MemberSet &Dense,
2029 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2030 for (auto D : Dense) {
2031 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2032 continue;
2033
2034 BasicBlock *BB = getBlockForValue(D);
2035 ValueDFS VD;
2036 DomTreeNode *DomNode = DT->getNode(BB);
2037 VD.DFSIn = DomNode->getDFSNumIn();
2038 VD.DFSOut = DomNode->getDFSNumOut();
2039 VD.Val = D;
2040
2041 // If it's an instruction, use the real local dfs number.
2042 if (auto *I = dyn_cast<Instruction>(D))
2043 VD.LocalNum = InstrDFS.lookup(I);
2044 else
2045 llvm_unreachable("Should have been an instruction");
2046
2047 LoadsAndStores.emplace_back(VD);
2048 }
2049}
2050
Davide Italiano7e274e02016-12-22 16:03:48 +00002051static void patchReplacementInstruction(Instruction *I, Value *Repl) {
2052 // Patch the replacement so that it is not more restrictive than the value
2053 // being replaced.
2054 auto *Op = dyn_cast<BinaryOperator>(I);
2055 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
2056
2057 if (Op && ReplOp)
2058 ReplOp->andIRFlags(Op);
2059
2060 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
2061 // FIXME: If both the original and replacement value are part of the
2062 // same control-flow region (meaning that the execution of one
2063 // guarentees the executation of the other), then we can combine the
2064 // noalias scopes here and do better than the general conservative
2065 // answer used in combineMetadata().
2066
2067 // In general, GVN unifies expressions over different control-flow
2068 // regions, and so we need a conservative combination of the noalias
2069 // scopes.
2070 unsigned KnownIDs[] = {
2071 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2072 LLVMContext::MD_noalias, LLVMContext::MD_range,
2073 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2074 LLVMContext::MD_invariant_group};
2075 combineMetadata(ReplInst, I, KnownIDs);
2076 }
2077}
2078
2079static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2080 patchReplacementInstruction(I, Repl);
2081 I->replaceAllUsesWith(Repl);
2082}
2083
2084void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2085 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2086 ++NumGVNBlocksDeleted;
2087
Daniel Berline19f0e02017-01-30 17:06:55 +00002088 // Delete the instructions backwards, as it has a reduced likelihood of having
2089 // to update as many def-use and use-def chains. Start after the terminator.
2090 auto StartPoint = BB->rbegin();
2091 ++StartPoint;
2092 // Note that we explicitly recalculate BB->rend() on each iteration,
2093 // as it may change when we remove the first instruction.
2094 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2095 Instruction &Inst = *I++;
2096 if (!Inst.use_empty())
2097 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2098 if (isa<LandingPadInst>(Inst))
2099 continue;
2100
2101 Inst.eraseFromParent();
2102 ++NumGVNInstrDeleted;
2103 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002104 // Now insert something that simplifycfg will turn into an unreachable.
2105 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2106 new StoreInst(UndefValue::get(Int8Ty),
2107 Constant::getNullValue(Int8Ty->getPointerTo()),
2108 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002109}
2110
2111void NewGVN::markInstructionForDeletion(Instruction *I) {
2112 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2113 InstructionsToErase.insert(I);
2114}
2115
2116void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2117
2118 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2119 patchAndReplaceAllUsesWith(I, V);
2120 // We save the actual erasing to avoid invalidating memory
2121 // dependencies until we are done with everything.
2122 markInstructionForDeletion(I);
2123}
2124
2125namespace {
2126
2127// This is a stack that contains both the value and dfs info of where
2128// that value is valid.
2129class ValueDFSStack {
2130public:
2131 Value *back() const { return ValueStack.back(); }
2132 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2133
2134 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002135 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002136 DFSStack.emplace_back(DFSIn, DFSOut);
2137 }
2138 bool empty() const { return DFSStack.empty(); }
2139 bool isInScope(int DFSIn, int DFSOut) const {
2140 if (empty())
2141 return false;
2142 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2143 }
2144
2145 void popUntilDFSScope(int DFSIn, int DFSOut) {
2146
2147 // These two should always be in sync at this point.
2148 assert(ValueStack.size() == DFSStack.size() &&
2149 "Mismatch between ValueStack and DFSStack");
2150 while (
2151 !DFSStack.empty() &&
2152 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2153 DFSStack.pop_back();
2154 ValueStack.pop_back();
2155 }
2156 }
2157
2158private:
2159 SmallVector<Value *, 8> ValueStack;
2160 SmallVector<std::pair<int, int>, 8> DFSStack;
2161};
2162}
Daniel Berlin04443432017-01-07 03:23:47 +00002163
Davide Italiano7e274e02016-12-22 16:03:48 +00002164bool NewGVN::eliminateInstructions(Function &F) {
2165 // This is a non-standard eliminator. The normal way to eliminate is
2166 // to walk the dominator tree in order, keeping track of available
2167 // values, and eliminating them. However, this is mildly
2168 // pointless. It requires doing lookups on every instruction,
2169 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002170 // instructions part of most singleton congruence classes, we know we
2171 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002172
2173 // Instead, this eliminator looks at the congruence classes directly, sorts
2174 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002175 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002176 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002177 // last member. This is worst case O(E log E) where E = number of
2178 // instructions in a single congruence class. In theory, this is all
2179 // instructions. In practice, it is much faster, as most instructions are
2180 // either in singleton congruence classes or can't possibly be eliminated
2181 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002182 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002183 // for elimination purposes.
2184 // TODO: If we wanted to be faster, We could remove any members with no
2185 // overlapping ranges while sorting, as we will never eliminate anything
2186 // with those members, as they don't dominate anything else in our set.
2187
Davide Italiano7e274e02016-12-22 16:03:48 +00002188 bool AnythingReplaced = false;
2189
2190 // Since we are going to walk the domtree anyway, and we can't guarantee the
2191 // DFS numbers are updated, we compute some ourselves.
2192 DT->updateDFSNumbers();
2193
2194 for (auto &B : F) {
2195 if (!ReachableBlocks.count(&B)) {
2196 for (const auto S : successors(&B)) {
2197 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002198 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002199 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2200 << getBlockName(&B)
2201 << " with undef due to it being unreachable\n");
2202 for (auto &Operand : Phi.incoming_values())
2203 if (Phi.getIncomingBlock(Operand) == &B)
2204 Operand.set(UndefValue::get(Phi.getType()));
2205 }
2206 }
2207 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002208 }
2209
2210 for (CongruenceClass *CC : CongruenceClasses) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002211 // Track the equivalent store info so we can decide whether to try
2212 // dead store elimination.
2213 SmallVector<ValueDFS, 8> PossibleDeadStores;
2214
Daniel Berlinb79f5362017-02-11 12:48:50 +00002215 if (CC->Dead)
Davide Italiano7e274e02016-12-22 16:03:48 +00002216 continue;
Daniel Berlinb79f5362017-02-11 12:48:50 +00002217 // Everything still in the INITIAL class is unreachable or dead.
2218 if (CC == InitialClass) {
2219#ifndef NDEBUG
2220 for (auto M : CC->Members)
2221 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2222 InstructionsToErase.count(cast<Instruction>(M))) &&
2223 "Everything in INITIAL should be unreachable or dead at this "
2224 "point");
2225#endif
2226 continue;
2227 }
2228
Davide Italiano7e274e02016-12-22 16:03:48 +00002229 assert(CC->RepLeader && "We should have had a leader");
2230
2231 // If this is a leader that is always available, and it's a
2232 // constant or has no equivalences, just replace everything with
2233 // it. We then update the congruence class with whatever members
2234 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002235 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2236 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002237 SmallPtrSet<Value *, 4> MembersLeft;
2238 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002239 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002240 // Void things have no uses we can replace.
2241 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2242 MembersLeft.insert(Member);
2243 continue;
2244 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002245 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2246 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002247 // Due to equality propagation, these may not always be
2248 // instructions, they may be real values. We don't really
2249 // care about trying to replace the non-instructions.
2250 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002251 assert(Leader != I && "About to accidentally remove our leader");
2252 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002253 AnythingReplaced = true;
2254
2255 continue;
2256 } else {
2257 MembersLeft.insert(I);
2258 }
2259 }
2260 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002261 } else {
2262 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2263 // If this is a singleton, we can skip it.
2264 if (CC->Members.size() != 1) {
2265
2266 // This is a stack because equality replacement/etc may place
2267 // constants in the middle of the member list, and we want to use
2268 // those constant values in preference to the current leader, over
2269 // the scope of those constants.
2270 ValueDFSStack EliminationStack;
2271
2272 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002273 SmallVector<ValueDFS, 8> DFSOrderedSet;
Davide Italiano7e274e02016-12-22 16:03:48 +00002274 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2275
2276 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002277 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002278 for (auto &VD : DFSOrderedSet) {
2279 int MemberDFSIn = VD.DFSIn;
2280 int MemberDFSOut = VD.DFSOut;
2281 Value *Member = VD.Val;
2282 Use *MemberUse = VD.U;
Davide Italiano7e274e02016-12-22 16:03:48 +00002283
Daniel Berlinc4796862017-01-27 02:37:11 +00002284 // We ignore void things because we can't get a value from them.
2285 if (Member && Member->getType()->isVoidTy())
2286 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002287
2288 if (EliminationStack.empty()) {
2289 DEBUG(dbgs() << "Elimination Stack is empty\n");
2290 } else {
2291 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2292 << EliminationStack.dfs_back().first << ","
2293 << EliminationStack.dfs_back().second << ")\n");
2294 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002295
2296 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2297 << MemberDFSOut << ")\n");
2298 // First, we see if we are out of scope or empty. If so,
2299 // and there equivalences, we try to replace the top of
2300 // stack with equivalences (if it's on the stack, it must
2301 // not have been eliminated yet).
2302 // Then we synchronize to our current scope, by
2303 // popping until we are back within a DFS scope that
2304 // dominates the current member.
2305 // Then, what happens depends on a few factors
2306 // If the stack is now empty, we need to push
2307 // If we have a constant or a local equivalence we want to
2308 // start using, we also push.
2309 // Otherwise, we walk along, processing members who are
2310 // dominated by this scope, and eliminate them.
2311 bool ShouldPush =
2312 Member && (EliminationStack.empty() || isa<Constant>(Member));
2313 bool OutOfScope =
2314 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2315
2316 if (OutOfScope || ShouldPush) {
2317 // Sync to our current scope.
2318 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2319 ShouldPush |= Member && EliminationStack.empty();
2320 if (ShouldPush) {
2321 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2322 }
2323 }
2324
2325 // If we get to this point, and the stack is empty we must have a use
2326 // with nothing we can use to eliminate it, just skip it.
2327 if (EliminationStack.empty())
2328 continue;
2329
2330 // Skip the Value's, we only want to eliminate on their uses.
2331 if (Member)
2332 continue;
2333 Value *Result = EliminationStack.back();
2334
Daniel Berlind92e7f92017-01-07 00:01:42 +00002335 // Don't replace our existing users with ourselves.
2336 if (MemberUse->get() == Result)
Davide Italiano7e274e02016-12-22 16:03:48 +00002337 continue;
2338
2339 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2340 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2341 << "\n");
2342
2343 // If we replaced something in an instruction, handle the patching of
2344 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002345 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002346 patchReplacementInstruction(ReplacedInst, Result);
2347
2348 assert(isa<Instruction>(MemberUse->getUser()));
2349 MemberUse->set(Result);
2350 AnythingReplaced = true;
2351 }
2352 }
2353 }
2354
2355 // Cleanup the congruence class.
2356 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002357 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002358 if (Member->getType()->isVoidTy()) {
2359 MembersLeft.insert(Member);
2360 continue;
2361 }
2362
2363 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2364 if (isInstructionTriviallyDead(MemberInst)) {
2365 // TODO: Don't mark loads of undefs.
2366 markInstructionForDeletion(MemberInst);
2367 continue;
2368 }
2369 }
2370 MembersLeft.insert(Member);
2371 }
2372 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002373
2374 // If we have possible dead stores to look at, try to eliminate them.
2375 if (CC->StoreCount > 0) {
2376 convertDenseToLoadsAndStores(CC->Members, PossibleDeadStores);
2377 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2378 ValueDFSStack EliminationStack;
2379 for (auto &VD : PossibleDeadStores) {
2380 int MemberDFSIn = VD.DFSIn;
2381 int MemberDFSOut = VD.DFSOut;
2382 Instruction *Member = cast<Instruction>(VD.Val);
2383 if (EliminationStack.empty() ||
2384 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2385 // Sync to our current scope.
2386 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2387 if (EliminationStack.empty()) {
2388 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2389 continue;
2390 }
2391 }
2392 // We already did load elimination, so nothing to do here.
2393 if (isa<LoadInst>(Member))
2394 continue;
2395 assert(!EliminationStack.empty());
2396 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002397 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002398 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2399 // Member is dominater by Leader, and thus dead
2400 DEBUG(dbgs() << "Marking dead store " << *Member
2401 << " that is dominated by " << *Leader << "\n");
2402 markInstructionForDeletion(Member);
2403 CC->Members.erase(Member);
2404 ++NumGVNDeadStores;
2405 }
2406 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002407 }
2408
2409 return AnythingReplaced;
2410}