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