blob: 6c4ee6eafb8b777a9c31ad993e226dd3ee11014c [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 {
Davide Italiano7e274e02016-12-22 16:03:48 +0000206class NewGVN : public FunctionPass {
207 DominatorTree *DT;
208 const DataLayout *DL;
209 const TargetLibraryInfo *TLI;
210 AssumptionCache *AC;
211 AliasAnalysis *AA;
212 MemorySSA *MSSA;
213 MemorySSAWalker *MSSAWalker;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000214 std::unique_ptr<PredicateInfo> PredInfo;
Davide Italiano7e274e02016-12-22 16:03:48 +0000215 BumpPtrAllocator ExpressionAllocator;
216 ArrayRecycler<Value *> ArgRecycler;
217
Daniel Berlin1c087672017-02-11 15:07:01 +0000218 // Number of function arguments, used by ranking
219 unsigned int NumFuncArgs;
220
Davide Italiano7e274e02016-12-22 16:03:48 +0000221 // Congruence class info.
Daniel Berlinb79f5362017-02-11 12:48:50 +0000222
223 // This class is called INITIAL in the paper. It is the class everything
224 // startsout in, and represents any value. Being an optimistic analysis,
225 // anything in the INITIAL class has the value TOP, which is indeterminate and
226 // equivalent to everything.
Davide Italiano7e274e02016-12-22 16:03:48 +0000227 CongruenceClass *InitialClass;
228 std::vector<CongruenceClass *> CongruenceClasses;
229 unsigned NextCongruenceNum;
230
231 // Value Mappings.
232 DenseMap<Value *, CongruenceClass *> ValueToClass;
233 DenseMap<Value *, const Expression *> ValueToExpression;
234
Daniel Berlinf7d95802017-02-18 23:06:50 +0000235 // Mapping from predicate info we used to the instructions we used it with.
236 // In order to correctly ensure propagation, we must keep track of what
237 // comparisons we used, so that when the values of the comparisons change, we
238 // propagate the information to the places we used the comparison.
239 DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> PredicateToUsers;
240
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000241 // A table storing which memorydefs/phis represent a memory state provably
242 // equivalent to another memory state.
243 // We could use the congruence class machinery, but the MemoryAccess's are
244 // abstract memory states, so they can only ever be equivalent to each other,
245 // and not to constants, etc.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000246 DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000247
Davide Italiano7e274e02016-12-22 16:03:48 +0000248 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000249 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000250 ExpressionClassMap ExpressionToClass;
251
252 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000253 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000254
255 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000256 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000257 DenseSet<BlockEdge> ReachableEdges;
258 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
259
260 // This is a bitvector because, on larger functions, we may have
261 // thousands of touched instructions at once (entire blocks,
262 // instructions with hundreds of uses, etc). Even with optimization
263 // for when we mark whole blocks as touched, when this was a
264 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
265 // the time in GVN just managing this list. The bitvector, on the
266 // other hand, efficiently supports test/set/clear of both
267 // individual and ranges, as well as "find next element" This
268 // enables us to use it as a worklist with essentially 0 cost.
269 BitVector TouchedInstructions;
270
271 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
272 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
273 DominatedInstRange;
274
275#ifndef NDEBUG
276 // Debugging for how many times each block and instruction got processed.
277 DenseMap<const Value *, unsigned> ProcessedCount;
278#endif
279
280 // DFS info.
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000281 // This contains a mapping from Instructions to DFS numbers.
282 // The numbering starts at 1. An instruction with DFS number zero
283 // means that the instruction is dead.
Davide Italiano7e274e02016-12-22 16:03:48 +0000284 DenseMap<const Value *, unsigned> InstrDFS;
Davide Italiano71f2d9c2017-01-20 23:29:28 +0000285
286 // This contains the mapping DFS numbers to instructions.
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000287 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000288
289 // Deletion info.
290 SmallPtrSet<Instruction *, 8> InstructionsToErase;
291
Daniel Berlin283a6082017-03-01 19:59:26 +0000292 // The set of things we gave unknown expressions to due to debug counting.
293 SmallPtrSet<Instruction *, 8> DebugUnknownExprs;
Davide Italiano7e274e02016-12-22 16:03:48 +0000294public:
295 static char ID; // Pass identification, replacement for typeid.
296 NewGVN() : FunctionPass(ID) {
297 initializeNewGVNPass(*PassRegistry::getPassRegistry());
298 }
299
300 bool runOnFunction(Function &F) override;
301 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000302 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000303
304private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000305 void getAnalysisUsage(AnalysisUsage &AU) const override {
306 AU.addRequired<AssumptionCacheTracker>();
307 AU.addRequired<DominatorTreeWrapperPass>();
308 AU.addRequired<TargetLibraryInfoWrapperPass>();
309 AU.addRequired<MemorySSAWrapperPass>();
310 AU.addRequired<AAResultsWrapperPass>();
Davide Italiano7e274e02016-12-22 16:03:48 +0000311 AU.addPreserved<DominatorTreeWrapperPass>();
312 AU.addPreserved<GlobalsAAWrapperPass>();
313 }
314
315 // Expression handling.
Daniel Berlin97718e62017-01-31 22:32:03 +0000316 const Expression *createExpression(Instruction *);
317 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000318 PHIExpression *createPHIExpression(Instruction *);
319 const VariableExpression *createVariableExpression(Value *);
320 const ConstantExpression *createConstantExpression(Constant *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000321 const Expression *createVariableOrConstant(Value *V);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000322 const UnknownExpression *createUnknownExpression(Instruction *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000323 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000324 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin97718e62017-01-31 22:32:03 +0000325 MemoryAccess *);
326 const CallExpression *createCallExpression(CallInst *, MemoryAccess *);
327 const AggregateValueExpression *createAggregateValueExpression(Instruction *);
328 bool setBasicExpressionInfo(Instruction *, BasicExpression *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000329
330 // Congruence class handling.
331 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000332 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000333 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000334 return result;
335 }
336
337 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000338 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000339 CClass->Members.insert(Member);
340 ValueToClass[Member] = CClass;
341 return CClass;
342 }
343 void initializeCongruenceClasses(Function &F);
344
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000345 // Value number an Instruction or MemoryPhi.
346 void valueNumberMemoryPhi(MemoryPhi *);
347 void valueNumberInstruction(Instruction *);
348
Davide Italiano7e274e02016-12-22 16:03:48 +0000349 // Symbolic evaluation.
350 const Expression *checkSimplificationResults(Expression *, Instruction *,
351 Value *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000352 const Expression *performSymbolicEvaluation(Value *);
353 const Expression *performSymbolicLoadEvaluation(Instruction *);
354 const Expression *performSymbolicStoreEvaluation(Instruction *);
355 const Expression *performSymbolicCallEvaluation(Instruction *);
356 const Expression *performSymbolicPHIEvaluation(Instruction *);
357 const Expression *performSymbolicAggrValueEvaluation(Instruction *);
358 const Expression *performSymbolicCmpEvaluation(Instruction *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000359 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000360
361 // Congruence finding.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000362 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000363 void performCongruenceFinding(Instruction *, const Expression *);
364 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000365 CongruenceClass *);
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000366 bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
367 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000368 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000369
Daniel Berlin1c087672017-02-11 15:07:01 +0000370 // Ranking
371 unsigned int getRank(const Value *) const;
372 bool shouldSwapOperands(const Value *, const Value *) const;
373
Davide Italiano7e274e02016-12-22 16:03:48 +0000374 // Reachability handling.
375 void updateReachableEdge(BasicBlock *, BasicBlock *);
376 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000377 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000378
379 // Elimination.
380 struct ValueDFS;
Daniel Berlinc4796862017-01-27 02:37:11 +0000381 void convertDenseToDFSOrdered(const CongruenceClass::MemberSet &,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +0000382 SmallVectorImpl<ValueDFS> &);
Daniel Berlinc4796862017-01-27 02:37:11 +0000383 void convertDenseToLoadsAndStores(const CongruenceClass::MemberSet &,
384 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000385
386 bool eliminateInstructions(Function &);
387 void replaceInstruction(Instruction *, Value *);
388 void markInstructionForDeletion(Instruction *);
389 void deleteInstructionsInBlock(BasicBlock *);
390
391 // New instruction creation.
392 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000393
394 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000395 void markUsersTouched(Value *);
396 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000397 void markPredicateUsersTouched(Instruction *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000398 void markLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000399 void addPredicateUsers(const PredicateBase *, Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000400
401 // Utilities.
402 void cleanupTables();
403 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
404 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000405 void verifyMemoryCongruency() const;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000406 void verifyComparisons(Function &F);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000407 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000408};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000409} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000410
411char NewGVN::ID = 0;
412
413// createGVNPass - The public interface to this file.
414FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
415
Davide Italianob1114092016-12-28 13:37:17 +0000416template <typename T>
417static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
418 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000419 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000420 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000421 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000422 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000423 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000424 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000425 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000426 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000427 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000428 return true;
429}
430
Davide Italianob1114092016-12-28 13:37:17 +0000431bool LoadExpression::equals(const Expression &Other) const {
432 return equalsLoadStoreHelper(*this, Other);
433}
Davide Italiano7e274e02016-12-22 16:03:48 +0000434
Davide Italianob1114092016-12-28 13:37:17 +0000435bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000436 bool Result = equalsLoadStoreHelper(*this, Other);
437 // Make sure that store vs store includes the value operand.
438 if (Result)
439 if (const auto *S = dyn_cast<StoreExpression>(&Other))
440 if (getStoredValue() != S->getStoredValue())
441 return false;
442 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000443}
444
445#ifndef NDEBUG
446static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000447 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000448}
449#endif
450
451INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
452INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
453INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
454INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
455INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
456INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
457INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
458INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
459
460PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000461 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000462 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000463 auto *E =
464 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000465
466 E->allocateOperands(ArgRecycler, ExpressionAllocator);
467 E->setType(I->getType());
468 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000469
Davide Italianob3886dd2017-01-25 23:37:49 +0000470 // Filter out unreachable phi operands.
471 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000472 return ReachableBlocks.count(PN->getIncomingBlock(U));
Davide Italianob3886dd2017-01-25 23:37:49 +0000473 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000474
475 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
476 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000477 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000478 if (U == PN)
479 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000480 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000481 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000482 return E;
483}
484
485// Set basic expression info (Arguments, type, opcode) for Expression
486// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000487bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000488 bool AllConstant = true;
489 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
490 E->setType(GEP->getSourceElementType());
491 else
492 E->setType(I->getType());
493 E->setOpcode(I->getOpcode());
494 E->allocateOperands(ArgRecycler, ExpressionAllocator);
495
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000496 // Transform the operand array into an operand leader array, and keep track of
497 // whether all members are constant.
498 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000499 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000500 AllConstant &= isa<Constant>(Operand);
501 return Operand;
502 });
503
Davide Italiano7e274e02016-12-22 16:03:48 +0000504 return AllConstant;
505}
506
507const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000508 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000509 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000510
511 E->setType(T);
512 E->setOpcode(Opcode);
513 E->allocateOperands(ArgRecycler, ExpressionAllocator);
514 if (Instruction::isCommutative(Opcode)) {
515 // Ensure that commutative instructions that only differ by a permutation
516 // of their operands get the same value number by sorting the operand value
517 // numbers. Since all commutative instructions have two operands it is more
518 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000519 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000520 std::swap(Arg1, Arg2);
521 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000522 E->op_push_back(lookupOperandLeader(Arg1));
523 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000524
525 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
526 DT, AC);
527 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
528 return SimplifiedE;
529 return E;
530}
531
532// Take a Value returned by simplification of Expression E/Instruction
533// I, and see if it resulted in a simpler expression. If so, return
534// that expression.
535// TODO: Once finished, this should not take an Instruction, we only
536// use it for printing.
537const Expression *NewGVN::checkSimplificationResults(Expression *E,
538 Instruction *I, Value *V) {
539 if (!V)
540 return nullptr;
541 if (auto *C = dyn_cast<Constant>(V)) {
542 if (I)
543 DEBUG(dbgs() << "Simplified " << *I << " to "
544 << " constant " << *C << "\n");
545 NumGVNOpsSimplified++;
546 assert(isa<BasicExpression>(E) &&
547 "We should always have had a basic expression here");
548
549 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
550 ExpressionAllocator.Deallocate(E);
551 return createConstantExpression(C);
552 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
553 if (I)
554 DEBUG(dbgs() << "Simplified " << *I << " to "
555 << " variable " << *V << "\n");
556 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
557 ExpressionAllocator.Deallocate(E);
558 return createVariableExpression(V);
559 }
560
561 CongruenceClass *CC = ValueToClass.lookup(V);
562 if (CC && CC->DefiningExpr) {
563 if (I)
564 DEBUG(dbgs() << "Simplified " << *I << " to "
565 << " expression " << *V << "\n");
566 NumGVNOpsSimplified++;
567 assert(isa<BasicExpression>(E) &&
568 "We should always have had a basic expression here");
569 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
570 ExpressionAllocator.Deallocate(E);
571 return CC->DefiningExpr;
572 }
573 return nullptr;
574}
575
Daniel Berlin97718e62017-01-31 22:32:03 +0000576const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000577 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000578
Daniel Berlin97718e62017-01-31 22:32:03 +0000579 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000580
581 if (I->isCommutative()) {
582 // Ensure that commutative instructions that only differ by a permutation
583 // of their operands get the same value number by sorting the operand value
584 // numbers. Since all commutative instructions have two operands it is more
585 // efficient to sort by hand rather than using, say, std::sort.
586 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000587 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000588 E->swapOperands(0, 1);
589 }
590
591 // Perform simplificaiton
592 // TODO: Right now we only check to see if we get a constant result.
593 // We may get a less than constant, but still better, result for
594 // some operations.
595 // IE
596 // add 0, x -> x
597 // and x, x -> x
598 // We should handle this by simply rewriting the expression.
599 if (auto *CI = dyn_cast<CmpInst>(I)) {
600 // Sort the operand value numbers so x<y and y>x get the same value
601 // number.
602 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000603 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000604 E->swapOperands(0, 1);
605 Predicate = CmpInst::getSwappedPredicate(Predicate);
606 }
607 E->setOpcode((CI->getOpcode() << 8) | Predicate);
608 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000609 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
610 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000611 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
612 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000613 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin97718e62017-01-31 22:32:03 +0000614 *DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000615 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
616 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000617 } else if (isa<SelectInst>(I)) {
618 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000619 E->getOperand(0) == E->getOperand(1)) {
620 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
621 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000622 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
623 E->getOperand(2), *DL, TLI, DT, AC);
624 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
625 return SimplifiedE;
626 }
627 } else if (I->isBinaryOp()) {
628 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
629 *DL, TLI, DT, AC);
630 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
631 return SimplifiedE;
632 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
633 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
634 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
635 return SimplifiedE;
636 } else if (isa<GetElementPtrInst>(I)) {
637 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000638 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000639 *DL, TLI, DT, AC);
640 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
641 return SimplifiedE;
642 } else if (AllConstant) {
643 // We don't bother trying to simplify unless all of the operands
644 // were constant.
645 // TODO: There are a lot of Simplify*'s we could call here, if we
646 // wanted to. The original motivating case for this code was a
647 // zext i1 false to i8, which we don't have an interface to
648 // simplify (IE there is no SimplifyZExt).
649
650 SmallVector<Constant *, 8> C;
651 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000652 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000653
654 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
655 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
656 return SimplifiedE;
657 }
658 return E;
659}
660
661const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000662NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000663 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000664 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000665 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000666 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000667 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000668 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000669 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000670 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000671 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000672 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000673 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000674 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000675 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000676 return E;
677 }
678 llvm_unreachable("Unhandled type of aggregate value operation");
679}
680
Daniel Berlin85f91b02016-12-26 20:06:58 +0000681const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000682 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000683 E->setOpcode(V->getValueID());
684 return E;
685}
686
Daniel Berlinf7d95802017-02-18 23:06:50 +0000687const Expression *NewGVN::createVariableOrConstant(Value *V) {
688 if (auto *C = dyn_cast<Constant>(V))
689 return createConstantExpression(C);
690 return createVariableExpression(V);
691}
692
Daniel Berlin85f91b02016-12-26 20:06:58 +0000693const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000694 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000695 E->setOpcode(C->getValueID());
696 return E;
697}
698
Daniel Berlin02c6b172017-01-02 18:00:53 +0000699const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
700 auto *E = new (ExpressionAllocator) UnknownExpression(I);
701 E->setOpcode(I->getOpcode());
702 return E;
703}
704
Davide Italiano7e274e02016-12-22 16:03:48 +0000705const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000706 MemoryAccess *HV) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000707 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000708 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000709 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
Daniel Berlin97718e62017-01-31 22:32:03 +0000710 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000711 return E;
712}
713
714// See if we have a congruence class and leader for this operand, and if so,
715// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000716Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000717 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +0000718 if (CC) {
719 // Everything in INITIAL is represneted by undef, as it can be any value.
720 // We do have to make sure we get the type right though, so we can't set the
721 // RepLeader to undef.
722 if (CC == InitialClass)
723 return UndefValue::get(V->getType());
Daniel Berlin26addef2017-01-20 21:04:30 +0000724 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Daniel Berlinb79f5362017-02-11 12:48:50 +0000725 }
726
Davide Italiano7e274e02016-12-22 16:03:48 +0000727 return V;
728}
729
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000730MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000731 auto *CC = MemoryAccessToClass.lookup(MA);
732 if (CC && CC->RepMemoryAccess)
733 return CC->RepMemoryAccess;
734 // FIXME: We need to audit all the places that current set a nullptr To, and
735 // fix them. There should always be *some* congruence class, even if it is
736 // singular. Right now, we don't bother setting congruence classes for
737 // anything but stores, which means we have to return the original access
738 // here. Otherwise, this should be unreachable.
739 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000740}
741
Daniel Berlinc4796862017-01-27 02:37:11 +0000742// Return true if the MemoryAccess is really equivalent to everything. This is
743// equivalent to the lattice value "TOP" in most lattices. This is the initial
744// state of all memory accesses.
745bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
746 return MemoryAccessToClass.lookup(MA) == InitialClass;
747}
748
Davide Italiano7e274e02016-12-22 16:03:48 +0000749LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin97718e62017-01-31 22:32:03 +0000750 LoadInst *LI, MemoryAccess *DA) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000751 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000752 E->allocateOperands(ArgRecycler, ExpressionAllocator);
753 E->setType(LoadType);
754
755 // Give store and loads same opcode so they value number together.
756 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000757 E->op_push_back(lookupOperandLeader(PointerOp));
Davide Italiano7e274e02016-12-22 16:03:48 +0000758 if (LI)
759 E->setAlignment(LI->getAlignment());
760
761 // TODO: Value number heap versions. We may be able to discover
762 // things alias analysis can't on it's own (IE that a store and a
763 // load have the same value, and thus, it isn't clobbering the load).
764 return E;
765}
766
767const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000768 MemoryAccess *DA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000769 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000770 auto *E = new (ExpressionAllocator)
771 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000772 E->allocateOperands(ArgRecycler, ExpressionAllocator);
773 E->setType(SI->getValueOperand()->getType());
774
775 // Give store and loads same opcode so they value number together.
776 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000777 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000778
779 // TODO: Value number heap versions. We may be able to discover
780 // things alias analysis can't on it's own (IE that a store and a
781 // load have the same value, and thus, it isn't clobbering the load).
782 return E;
783}
784
Daniel Berlin97718e62017-01-31 22:32:03 +0000785const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000786 // Unlike loads, we never try to eliminate stores, so we do not check if they
787 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000788 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000789 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000790 // Get the expression, if any, for the RHS of the MemoryDef.
791 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
792 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
793 // If we are defined by ourselves, use the live on entry def.
794 if (StoreRHS == StoreAccess)
795 StoreRHS = MSSA->getLiveOnEntryDef();
796
Daniel Berlin589cecc2017-01-02 18:00:46 +0000797 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000798 // See if we are defined by a previous store expression, it already has a
799 // value, and it's the same value as our current store. FIXME: Right now, we
800 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin97718e62017-01-31 22:32:03 +0000801 const Expression *OldStore = createStoreExpression(SI, StoreRHS);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000802 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000803 // Basically, check if the congruence class the store is in is defined by a
804 // store that isn't us, and has the same value. MemorySSA takes care of
805 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000806 // The RepStoredValue gets nulled if all the stores disappear in a class, so
807 // we don't need to check if the class contains a store besides us.
Daniel Berlin808e3ff2017-01-31 22:31:56 +0000808 if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin97718e62017-01-31 22:32:03 +0000809 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +0000810 // Also check if our value operand is defined by a load of the same memory
811 // location, and the memory state is the same as it was then
812 // (otherwise, it could have been overwritten later. See test32 in
813 // transforms/DeadStoreElimination/simple.ll)
814 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000815 if ((lookupOperandLeader(LI->getPointerOperand()) ==
816 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinc4796862017-01-27 02:37:11 +0000817 (lookupMemoryAccessEquiv(
818 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
819 return createVariableExpression(LI);
820 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000821 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000822 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000823}
824
Daniel Berlin97718e62017-01-31 22:32:03 +0000825const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000826 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000827
828 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000829 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000830 if (!LI->isSimple())
831 return nullptr;
832
Daniel Berlin203f47b2017-01-31 22:31:53 +0000833 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +0000834 // Load of undef is undef.
835 if (isa<UndefValue>(LoadAddressLeader))
836 return createConstantExpression(UndefValue::get(LI->getType()));
837
838 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
839
840 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
841 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
842 Instruction *DefiningInst = MD->getMemoryInst();
843 // If the defining instruction is not reachable, replace with undef.
844 if (!ReachableBlocks.count(DefiningInst->getParent()))
845 return createConstantExpression(UndefValue::get(LI->getType()));
846 }
847 }
848
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000849 const Expression *E =
850 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000851 lookupMemoryAccessEquiv(DefiningAccess));
Davide Italiano7e274e02016-12-22 16:03:48 +0000852 return E;
853}
854
Daniel Berlinf7d95802017-02-18 23:06:50 +0000855const Expression *
856NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
857 auto *PI = PredInfo->getPredicateInfoFor(I);
858 if (!PI)
859 return nullptr;
860
861 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +0000862
863 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
864 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +0000865 return nullptr;
866
Daniel Berlinfccbda92017-02-22 22:20:58 +0000867 auto *CopyOf = I->getOperand(0);
868 auto *Cond = PWC->Condition;
869
Daniel Berlinf7d95802017-02-18 23:06:50 +0000870 // If this a copy of the condition, it must be either true or false depending
871 // on the predicate info type and edge
872 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +0000873 // We should not need to add predicate users because the predicate info is
874 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +0000875 if (isa<PredicateAssume>(PI))
876 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
877 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
878 if (PBranch->TrueEdge)
879 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
880 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
881 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000882 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
883 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000884 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000885
Daniel Berlinf7d95802017-02-18 23:06:50 +0000886 // Not a copy of the condition, so see what the predicates tell us about this
887 // value. First, though, we check to make sure the value is actually a copy
888 // of one of the condition operands. It's possible, in certain cases, for it
889 // to be a copy of a predicateinfo copy. In particular, if two branch
890 // operations use the same condition, and one branch dominates the other, we
891 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +0000892 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +0000893 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000894
895 // Everything below relies on the condition being a comparison.
896 auto *Cmp = dyn_cast<CmpInst>(Cond);
897 if (!Cmp)
898 return nullptr;
899
900 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +0000901 DEBUG(dbgs() << "Copy is not of any condition operands!");
902 return nullptr;
903 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000904 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
905 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000906 bool SwappedOps = false;
907 // Sort the ops
908 if (shouldSwapOperands(FirstOp, SecondOp)) {
909 std::swap(FirstOp, SecondOp);
910 SwappedOps = true;
911 }
Daniel Berlinf7d95802017-02-18 23:06:50 +0000912 CmpInst::Predicate Predicate =
913 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
914
915 if (isa<PredicateAssume>(PI)) {
916 // If the comparison is true when the operands are equal, then we know the
917 // operands are equal, because assumes must always be true.
918 if (CmpInst::isTrueWhenEqual(Predicate)) {
919 addPredicateUsers(PI, I);
920 return createVariableOrConstant(FirstOp);
921 }
922 }
923 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
924 // If we are *not* a copy of the comparison, we may equal to the other
925 // operand when the predicate implies something about equality of
926 // operations. In particular, if the comparison is true/false when the
927 // operands are equal, and we are on the right edge, we know this operation
928 // is equal to something.
929 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
930 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
931 addPredicateUsers(PI, I);
932 return createVariableOrConstant(FirstOp);
933 }
934 // Handle the special case of floating point.
935 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
936 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
937 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
938 addPredicateUsers(PI, I);
939 return createConstantExpression(cast<Constant>(FirstOp));
940 }
941 }
942 return nullptr;
943}
944
Davide Italiano7e274e02016-12-22 16:03:48 +0000945// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000946const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000947 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000948 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
949 // Instrinsics with the returned attribute are copies of arguments.
950 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
951 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
952 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
953 return Result;
954 return createVariableOrConstant(ReturnedValue);
955 }
956 }
957 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlin97718e62017-01-31 22:32:03 +0000958 return createCallExpression(CI, nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000959 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000960 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin97718e62017-01-31 22:32:03 +0000961 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess));
Davide Italianob2225492016-12-27 18:15:39 +0000962 }
963 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000964}
965
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000966// Update the memory access equivalence table to say that From is equal to To,
967// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000968// FIXME: We need to audit all the places that current set a nullptr To, and fix
969// them. There should always be *some* congruence class, even if it is singular.
970bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
971 DEBUG(dbgs() << "Setting " << *From);
972 if (To) {
973 DEBUG(dbgs() << " equivalent to congruence class ");
974 DEBUG(dbgs() << To->ID << " with current memory access leader ");
975 DEBUG(dbgs() << *To->RepMemoryAccess);
976 } else {
977 DEBUG(dbgs() << " equivalent to itself");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000978 }
Daniel Berlin9f376b72017-01-29 10:26:03 +0000979 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000980
981 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000982 bool Changed = false;
983 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000984 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000985 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000986 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000987 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000988 Changed = true;
989 } else if (!To) {
990 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000991 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000992 Changed = true;
993 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000994 } else {
995 assert(!To &&
996 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000997 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000998
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000999 return Changed;
1000}
Davide Italiano7e274e02016-12-22 16:03:48 +00001001// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001002const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001003 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001004 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1005
1006 // See if all arguaments are the same.
1007 // We track if any were undef because they need special handling.
1008 bool HasUndef = false;
1009 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1010 if (Arg == I)
1011 return false;
1012 if (isa<UndefValue>(Arg)) {
1013 HasUndef = true;
1014 return false;
1015 }
1016 return true;
1017 });
1018 // If we are left with no operands, it's undef
1019 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001020 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1021 << "\n");
1022 E->deallocateOperands(ArgRecycler);
1023 ExpressionAllocator.Deallocate(E);
1024 return createConstantExpression(UndefValue::get(I->getType()));
1025 }
Daniel Berlind92e7f92017-01-07 00:01:42 +00001026 Value *AllSameValue = *(Filtered.begin());
1027 ++Filtered.begin();
1028 // Can't use std::equal here, sadly, because filter.begin moves.
1029 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
1030 return V == AllSameValue;
1031 })) {
1032 // In LLVM's non-standard representation of phi nodes, it's possible to have
1033 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1034 // on the original phi node), especially in weird CFG's where some arguments
1035 // are unreachable, or uninitialized along certain paths. This can cause
1036 // infinite loops during evaluation. We work around this by not trying to
1037 // really evaluate them independently, but instead using a variable
1038 // expression to say if one is equivalent to the other.
1039 // We also special case undef, so that if we have an undef, we can't use the
1040 // common value unless it dominates the phi block.
1041 if (HasUndef) {
1042 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001043 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001044 if (!DT->dominates(AllSameInst, I))
1045 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001046 }
1047
Davide Italiano7e274e02016-12-22 16:03:48 +00001048 NumGVNPhisAllSame++;
1049 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1050 << "\n");
1051 E->deallocateOperands(ArgRecycler);
1052 ExpressionAllocator.Deallocate(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001053 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001054 }
1055 return E;
1056}
1057
Daniel Berlin97718e62017-01-31 22:32:03 +00001058const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001059 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1060 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1061 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1062 unsigned Opcode = 0;
1063 // EI might be an extract from one of our recognised intrinsics. If it
1064 // is we'll synthesize a semantically equivalent expression instead on
1065 // an extract value expression.
1066 switch (II->getIntrinsicID()) {
1067 case Intrinsic::sadd_with_overflow:
1068 case Intrinsic::uadd_with_overflow:
1069 Opcode = Instruction::Add;
1070 break;
1071 case Intrinsic::ssub_with_overflow:
1072 case Intrinsic::usub_with_overflow:
1073 Opcode = Instruction::Sub;
1074 break;
1075 case Intrinsic::smul_with_overflow:
1076 case Intrinsic::umul_with_overflow:
1077 Opcode = Instruction::Mul;
1078 break;
1079 default:
1080 break;
1081 }
1082
1083 if (Opcode != 0) {
1084 // Intrinsic recognized. Grab its args to finish building the
1085 // expression.
1086 assert(II->getNumArgOperands() == 2 &&
1087 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001088 return createBinaryExpression(
1089 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001090 }
1091 }
1092 }
1093
Daniel Berlin97718e62017-01-31 22:32:03 +00001094 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001095}
Daniel Berlin97718e62017-01-31 22:32:03 +00001096const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001097 auto *CI = dyn_cast<CmpInst>(I);
1098 // See if our operands are equal to those of a previous predicate, and if so,
1099 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001100 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1101 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001102 auto OurPredicate = CI->getPredicate();
1103 if (shouldSwapOperands(Op1, Op0)) {
1104 std::swap(Op0, Op1);
1105 OurPredicate = CI->getSwappedPredicate();
1106 }
1107
1108 // Avoid processing the same info twice
1109 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001110 // See if we know something about the comparison itself, like it is the target
1111 // of an assume.
1112 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1113 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1114 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1115
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001116 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001117 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001118 if (CI->isTrueWhenEqual())
1119 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1120 else if (CI->isFalseWhenEqual())
1121 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1122 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001123
1124 // NOTE: Because we are comparing both operands here and below, and using
1125 // previous comparisons, we rely on fact that predicateinfo knows to mark
1126 // comparisons that use renamed operands as users of the earlier comparisons.
1127 // It is *not* enough to just mark predicateinfo renamed operands as users of
1128 // the earlier comparisons, because the *other* operand may have changed in a
1129 // previous iteration.
1130 // Example:
1131 // icmp slt %a, %b
1132 // %b.0 = ssa.copy(%b)
1133 // false branch:
1134 // icmp slt %c, %b.0
1135
1136 // %c and %a may start out equal, and thus, the code below will say the second
1137 // %icmp is false. c may become equal to something else, and in that case the
1138 // %second icmp *must* be reexamined, but would not if only the renamed
1139 // %operands are considered users of the icmp.
1140
1141 // *Currently* we only check one level of comparisons back, and only mark one
1142 // level back as touched when changes appen . If you modify this code to look
1143 // back farther through comparisons, you *must* mark the appropriate
1144 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1145 // we know something just from the operands themselves
1146
1147 // See if our operands have predicate info, so that we may be able to derive
1148 // something from a previous comparison.
1149 for (const auto &Op : CI->operands()) {
1150 auto *PI = PredInfo->getPredicateInfoFor(Op);
1151 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1152 if (PI == LastPredInfo)
1153 continue;
1154 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001155
Daniel Berlinf7d95802017-02-18 23:06:50 +00001156 // TODO: Along the false edge, we may know more things too, like icmp of
1157 // same operands is false.
1158 // TODO: We only handle actual comparison conditions below, not and/or.
1159 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1160 if (!BranchCond)
1161 continue;
1162 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1163 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1164 auto BranchPredicate = BranchCond->getPredicate();
1165 if (shouldSwapOperands(BranchOp1, BranchOp0)) {
1166 std::swap(BranchOp0, BranchOp1);
1167 BranchPredicate = BranchCond->getSwappedPredicate();
1168 }
1169 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1170 if (PBranch->TrueEdge) {
1171 // If we know the previous predicate is true and we are in the true
1172 // edge then we may be implied true or false.
1173 if (CmpInst::isImpliedTrueByMatchingCmp(OurPredicate,
1174 BranchPredicate)) {
1175 addPredicateUsers(PI, I);
1176 return createConstantExpression(
1177 ConstantInt::getTrue(CI->getType()));
1178 }
1179
1180 if (CmpInst::isImpliedFalseByMatchingCmp(OurPredicate,
1181 BranchPredicate)) {
1182 addPredicateUsers(PI, I);
1183 return createConstantExpression(
1184 ConstantInt::getFalse(CI->getType()));
1185 }
1186
1187 } else {
1188 // Just handle the ne and eq cases, where if we have the same
1189 // operands, we may know something.
1190 if (BranchPredicate == OurPredicate) {
1191 addPredicateUsers(PI, I);
1192 // Same predicate, same ops,we know it was false, so this is false.
1193 return createConstantExpression(
1194 ConstantInt::getFalse(CI->getType()));
1195 } else if (BranchPredicate ==
1196 CmpInst::getInversePredicate(OurPredicate)) {
1197 addPredicateUsers(PI, I);
1198 // Inverse predicate, we know the other was false, so this is true.
1199 // FIXME: Double check this
1200 return createConstantExpression(
1201 ConstantInt::getTrue(CI->getType()));
1202 }
1203 }
1204 }
1205 }
1206 }
1207 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001208 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001209}
Davide Italiano7e274e02016-12-22 16:03:48 +00001210
1211// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +00001212const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001213 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001214 if (auto *C = dyn_cast<Constant>(V))
1215 E = createConstantExpression(C);
1216 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1217 E = createVariableExpression(V);
1218 } else {
1219 // TODO: memory intrinsics.
1220 // TODO: Some day, we should do the forward propagation and reassociation
1221 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001222 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001223 switch (I->getOpcode()) {
1224 case Instruction::ExtractValue:
1225 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001226 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001227 break;
1228 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001229 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001230 break;
1231 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001232 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001233 break;
1234 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001235 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001236 break;
1237 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001238 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001239 break;
1240 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001241 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001242 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001243 case Instruction::ICmp:
1244 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001245 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001246 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001247 case Instruction::Add:
1248 case Instruction::FAdd:
1249 case Instruction::Sub:
1250 case Instruction::FSub:
1251 case Instruction::Mul:
1252 case Instruction::FMul:
1253 case Instruction::UDiv:
1254 case Instruction::SDiv:
1255 case Instruction::FDiv:
1256 case Instruction::URem:
1257 case Instruction::SRem:
1258 case Instruction::FRem:
1259 case Instruction::Shl:
1260 case Instruction::LShr:
1261 case Instruction::AShr:
1262 case Instruction::And:
1263 case Instruction::Or:
1264 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001265 case Instruction::Trunc:
1266 case Instruction::ZExt:
1267 case Instruction::SExt:
1268 case Instruction::FPToUI:
1269 case Instruction::FPToSI:
1270 case Instruction::UIToFP:
1271 case Instruction::SIToFP:
1272 case Instruction::FPTrunc:
1273 case Instruction::FPExt:
1274 case Instruction::PtrToInt:
1275 case Instruction::IntToPtr:
1276 case Instruction::Select:
1277 case Instruction::ExtractElement:
1278 case Instruction::InsertElement:
1279 case Instruction::ShuffleVector:
1280 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001281 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001282 break;
1283 default:
1284 return nullptr;
1285 }
1286 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001287 return E;
1288}
1289
Davide Italiano7e274e02016-12-22 16:03:48 +00001290void NewGVN::markUsersTouched(Value *V) {
1291 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001292 for (auto *User : V->users()) {
1293 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001294 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001295 }
1296}
1297
1298void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1299 for (auto U : MA->users()) {
1300 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001301 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001302 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001303 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001304 }
1305}
1306
Daniel Berlinf7d95802017-02-18 23:06:50 +00001307// Add I to the set of users of a given predicate.
1308void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1309 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1310 PredicateToUsers[PBranch->Condition].insert(I);
1311 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1312 PredicateToUsers[PAssume->Condition].insert(I);
1313}
1314
1315// Touch all the predicates that depend on this instruction.
1316void NewGVN::markPredicateUsersTouched(Instruction *I) {
1317 const auto Result = PredicateToUsers.find(I);
1318 if (Result != PredicateToUsers.end())
1319 for (auto *User : Result->second)
1320 TouchedInstructions.set(InstrDFS.lookup(User));
1321}
1322
Daniel Berlin32f8d562017-01-07 16:55:14 +00001323// Touch the instructions that need to be updated after a congruence class has a
1324// leader change, and mark changed values.
1325void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1326 for (auto M : CC->Members) {
1327 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001328 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001329 LeaderChanges.insert(M);
1330 }
1331}
1332
1333// Move a value, currently in OldClass, to be part of NewClass
1334// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001335void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1336 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001337 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001338 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001339 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001340
1341 if (I == OldClass->NextLeader.first)
1342 OldClass->NextLeader = {nullptr, ~0U};
1343
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001344 // It's possible, though unlikely, for us to discover equivalences such
1345 // that the current leader does not dominate the old one.
1346 // This statistic tracks how often this happens.
1347 // We assert on phi nodes when this happens, currently, for debugging, because
1348 // we want to make sure we name phi node cycles properly.
1349 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1350 I != NewClass->RepLeader &&
1351 DT->properlyDominates(
1352 I->getParent(),
1353 cast<Instruction>(NewClass->RepLeader)->getParent())) {
1354 ++NumGVNNotMostDominatingLeader;
1355 assert(!isa<PHINode>(I) &&
1356 "New class for instruction should not be dominated by instruction");
1357 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001358
1359 if (NewClass->RepLeader != I) {
1360 auto DFSNum = InstrDFS.lookup(I);
1361 if (DFSNum < NewClass->NextLeader.second)
1362 NewClass->NextLeader = {I, DFSNum};
1363 }
1364
1365 OldClass->Members.erase(I);
1366 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001367 MemoryAccess *StoreAccess = nullptr;
1368 if (auto *SI = dyn_cast<StoreInst>(I)) {
1369 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001370 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001371 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001372 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001373 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001374 if (!NewClass->RepMemoryAccess) {
1375 // If we don't have a representative memory access, it better be the only
1376 // store in there.
1377 assert(NewClass->StoreCount == 1);
1378 NewClass->RepMemoryAccess = StoreAccess;
1379 }
1380 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001381 }
1382
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001383 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001384 // See if we destroyed the class or need to swap leaders.
1385 if (OldClass->Members.empty() && OldClass != InitialClass) {
1386 if (OldClass->DefiningExpr) {
1387 OldClass->Dead = true;
1388 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1389 << " from table\n");
1390 ExpressionToClass.erase(OldClass->DefiningExpr);
1391 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001392 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001393 // When the leader changes, the value numbering of
1394 // everything may change due to symbolization changes, so we need to
1395 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001396 DEBUG(dbgs() << "Leader change!\n");
1397 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001398 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001399 if (OldClass->StoreCount == 0) {
1400 if (OldClass->RepStoredValue != nullptr)
1401 OldClass->RepStoredValue = nullptr;
1402 if (OldClass->RepMemoryAccess != nullptr)
1403 OldClass->RepMemoryAccess = nullptr;
1404 }
1405
1406 // If we destroy the old access leader, we have to effectively destroy the
1407 // congruence class. When it comes to scalars, anything with the same value
1408 // is as good as any other. That means that one leader is as good as
1409 // another, and as long as you have some leader for the value, you are
1410 // good.. When it comes to *memory states*, only one particular thing really
1411 // represents the definition of a given memory state. Once it goes away, we
1412 // need to re-evaluate which pieces of memory are really still
1413 // equivalent. The best way to do this is to re-value number things. The
1414 // only way to really make that happen is to destroy the rest of the class.
1415 // In order to effectively destroy the class, we reset ExpressionToClass for
1416 // each by using the ValueToExpression mapping. The members later get
1417 // marked as touched due to the leader change. We will create new
1418 // congruence classes, and the pieces that are still equivalent will end
1419 // back together in a new class. If this becomes too expensive, it is
1420 // possible to use a versioning scheme for the congruence classes to avoid
1421 // the expressions finding this old class.
1422 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1423 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1424 << " because memory access leader changed");
1425 for (auto Member : OldClass->Members)
1426 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1427 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001428
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001429 // We don't need to sort members if there is only 1, and we don't care about
Daniel Berlinb79f5362017-02-11 12:48:50 +00001430 // sorting the INITIAL class because everything either gets out of it or is
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001431 // unreachable.
1432 if (OldClass->Members.size() == 1 || OldClass == InitialClass) {
1433 OldClass->RepLeader = *(OldClass->Members.begin());
1434 } else if (OldClass->NextLeader.first) {
1435 ++NumGVNAvoidedSortedLeaderChanges;
1436 OldClass->RepLeader = OldClass->NextLeader.first;
1437 OldClass->NextLeader = {nullptr, ~0U};
1438 } else {
1439 ++NumGVNSortedLeaderChanges;
1440 // TODO: If this ends up to slow, we can maintain a dual structure for
1441 // member testing/insertion, or keep things mostly sorted, and sort only
1442 // here, or ....
1443 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1444 for (const auto X : OldClass->Members) {
1445 auto DFSNum = InstrDFS.lookup(X);
1446 if (DFSNum < MinDFS.second)
1447 MinDFS = {X, DFSNum};
1448 }
1449 OldClass->RepLeader = MinDFS.first;
1450 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001451 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001452 }
1453}
1454
Davide Italiano7e274e02016-12-22 16:03:48 +00001455// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001456void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1457 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001458 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00001459 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001460
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001461 CongruenceClass *IClass = ValueToClass[I];
1462 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001463 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001464 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001465
1466 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001467 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001468 EClass = ValueToClass[VE->getVariableValue()];
1469 } else {
1470 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1471
1472 // If it's not in the value table, create a new congruence class.
1473 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001474 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001475 auto place = lookupResult.first;
1476 place->second = NewClass;
1477
1478 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001479 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001480 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001481 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1482 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001483 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001484 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001485 // The RepMemoryAccess field will be filled in properly by the
1486 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001487 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001488 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001489 }
1490 assert(!isa<VariableExpression>(E) &&
1491 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001492
1493 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001494 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001495 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001496 << " and leader " << *(NewClass->RepLeader));
1497 if (NewClass->RepStoredValue)
1498 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1499 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001500 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1501 } else {
1502 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001503 if (isa<ConstantExpression>(E))
1504 assert(isa<Constant>(EClass->RepLeader) &&
1505 "Any class with a constant expression should have a "
1506 "constant leader");
1507
Davide Italiano7e274e02016-12-22 16:03:48 +00001508 assert(EClass && "Somehow don't have an eclass");
1509
1510 assert(!EClass->Dead && "We accidentally looked up a dead class");
1511 }
1512 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001513 bool ClassChanged = IClass != EClass;
1514 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001515 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001516 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1517 << "\n");
1518
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001519 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001520 moveValueToNewCongruenceClass(I, IClass, EClass);
1521 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001522 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001523 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001524 if (auto *CI = dyn_cast<CmpInst>(I))
1525 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00001526 }
1527}
1528
1529// Process the fact that Edge (from, to) is reachable, including marking
1530// any newly reachable blocks and instructions for processing.
1531void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1532 // Check if the Edge was reachable before.
1533 if (ReachableEdges.insert({From, To}).second) {
1534 // If this block wasn't reachable before, all instructions are touched.
1535 if (ReachableBlocks.insert(To).second) {
1536 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1537 const auto &InstRange = BlockInstRange.lookup(To);
1538 TouchedInstructions.set(InstRange.first, InstRange.second);
1539 } else {
1540 DEBUG(dbgs() << "Block " << getBlockName(To)
1541 << " was reachable, but new edge {" << getBlockName(From)
1542 << "," << getBlockName(To) << "} to it found\n");
1543
1544 // We've made an edge reachable to an existing block, which may
1545 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1546 // they are the only thing that depend on new edges. Anything using their
1547 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001548 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001549 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001550
Davide Italiano7e274e02016-12-22 16:03:48 +00001551 auto BI = To->begin();
1552 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001553 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001554 ++BI;
1555 }
1556 }
1557 }
1558}
1559
1560// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1561// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001562Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001563 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001564 if (isa<Constant>(Result))
1565 return Result;
1566 return nullptr;
1567}
1568
1569// Process the outgoing edges of a block for reachability.
1570void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1571 // Evaluate reachability of terminator instruction.
1572 BranchInst *BR;
1573 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1574 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001575 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001576 if (!CondEvaluated) {
1577 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001578 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001579 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1580 CondEvaluated = CE->getConstantValue();
1581 }
1582 } else if (isa<ConstantInt>(Cond)) {
1583 CondEvaluated = Cond;
1584 }
1585 }
1586 ConstantInt *CI;
1587 BasicBlock *TrueSucc = BR->getSuccessor(0);
1588 BasicBlock *FalseSucc = BR->getSuccessor(1);
1589 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1590 if (CI->isOne()) {
1591 DEBUG(dbgs() << "Condition for Terminator " << *TI
1592 << " evaluated to true\n");
1593 updateReachableEdge(B, TrueSucc);
1594 } else if (CI->isZero()) {
1595 DEBUG(dbgs() << "Condition for Terminator " << *TI
1596 << " evaluated to false\n");
1597 updateReachableEdge(B, FalseSucc);
1598 }
1599 } else {
1600 updateReachableEdge(B, TrueSucc);
1601 updateReachableEdge(B, FalseSucc);
1602 }
1603 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1604 // For switches, propagate the case values into the case
1605 // destinations.
1606
1607 // Remember how many outgoing edges there are to every successor.
1608 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1609
Davide Italiano7e274e02016-12-22 16:03:48 +00001610 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001611 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001612 // See if we were able to turn this switch statement into a constant.
1613 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001614 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001615 // We should be able to get case value for this.
1616 auto CaseVal = SI->findCaseValue(CondVal);
1617 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1618 // We proved the value is outside of the range of the case.
1619 // We can't do anything other than mark the default dest as reachable,
1620 // and go home.
1621 updateReachableEdge(B, SI->getDefaultDest());
1622 return;
1623 }
1624 // Now get where it goes and mark it reachable.
1625 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1626 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001627 } else {
1628 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1629 BasicBlock *TargetBlock = SI->getSuccessor(i);
1630 ++SwitchEdges[TargetBlock];
1631 updateReachableEdge(B, TargetBlock);
1632 }
1633 }
1634 } else {
1635 // Otherwise this is either unconditional, or a type we have no
1636 // idea about. Just mark successors as reachable.
1637 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1638 BasicBlock *TargetBlock = TI->getSuccessor(i);
1639 updateReachableEdge(B, TargetBlock);
1640 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001641
1642 // This also may be a memory defining terminator, in which case, set it
1643 // equivalent to nothing.
1644 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1645 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001646 }
1647}
1648
Daniel Berlin85f91b02016-12-26 20:06:58 +00001649// The algorithm initially places the values of the routine in the INITIAL
Daniel Berlinb79f5362017-02-11 12:48:50 +00001650// congruence class. The leader of INITIAL is the undetermined value `TOP`.
Davide Italiano7e274e02016-12-22 16:03:48 +00001651// When the algorithm has finished, values still in INITIAL are unreachable.
1652void NewGVN::initializeCongruenceClasses(Function &F) {
1653 // FIXME now i can't remember why this is 2
1654 NextCongruenceNum = 2;
1655 // Initialize all other instructions to be in INITIAL class.
1656 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001657 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001658 InitialClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001659 for (auto &B : F) {
1660 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001661 MemoryAccessToClass[MP] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001662
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001663 for (auto &I : B) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00001664 // Don't insert void terminators into the class. We don't value number
1665 // them, and they just end up sitting in INITIAL.
1666 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
1667 continue;
1668 InitialValues.insert(&I);
1669 ValueToClass[&I] = InitialClass;
1670
Daniel Berlin589cecc2017-01-02 18:00:46 +00001671 // All memory accesses are equivalent to live on entry to start. They must
1672 // be initialized to something so that initial changes are noticed. For
1673 // the maximal answer, we initialize them all to be the same as
1674 // liveOnEntry. Note that to save time, we only initialize the
1675 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1676 // other expression can generate a memory equivalence. If we start
1677 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001678 if (isa<StoreInst>(&I)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001679 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = InitialClass;
Davide Italianoeac05f62017-01-11 23:41:24 +00001680 ++InitialClass->StoreCount;
1681 assert(InitialClass->StoreCount > 0);
1682 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001683 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001684 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001685 InitialClass->Members.swap(InitialValues);
1686
1687 // Initialize arguments to be in their own unique congruence classes
1688 for (auto &FA : F.args())
1689 createSingletonCongruenceClass(&FA);
1690}
1691
1692void NewGVN::cleanupTables() {
1693 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1694 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1695 << CongruenceClasses[i]->Members.size() << " members\n");
1696 // Make sure we delete the congruence class (probably worth switching to
1697 // a unique_ptr at some point.
1698 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001699 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001700 }
1701
1702 ValueToClass.clear();
1703 ArgRecycler.clear(ExpressionAllocator);
1704 ExpressionAllocator.Reset();
1705 CongruenceClasses.clear();
1706 ExpressionToClass.clear();
1707 ValueToExpression.clear();
1708 ReachableBlocks.clear();
1709 ReachableEdges.clear();
1710#ifndef NDEBUG
1711 ProcessedCount.clear();
1712#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001713 InstrDFS.clear();
1714 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001715 DFSToInstr.clear();
1716 BlockInstRange.clear();
1717 TouchedInstructions.clear();
1718 DominatedInstRange.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001719 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00001720 PredicateToUsers.clear();
Daniel Berlin283a6082017-03-01 19:59:26 +00001721 DebugUnknownExprs.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001722}
1723
1724std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1725 unsigned Start) {
1726 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001727 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1728 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001729 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001730 }
1731
Davide Italiano7e274e02016-12-22 16:03:48 +00001732 for (auto &I : *B) {
1733 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001734 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001735 }
1736
1737 // All of the range functions taken half-open ranges (open on the end side).
1738 // So we do not subtract one from count, because at this point it is one
1739 // greater than the last instruction.
1740 return std::make_pair(Start, End);
1741}
1742
1743void NewGVN::updateProcessedCount(Value *V) {
1744#ifndef NDEBUG
1745 if (ProcessedCount.count(V) == 0) {
1746 ProcessedCount.insert({V, 1});
1747 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001748 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001749 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001750 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001751 }
1752#endif
1753}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001754// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1755void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1756 // If all the arguments are the same, the MemoryPhi has the same value as the
1757 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001758 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001759 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001760 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1761 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
1762 ReachableBlocks.count(MP->getIncomingBlock(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001763 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001764 // If all that is left is nothing, our memoryphi is undef. We keep it as
1765 // InitialClass. Note: The only case this should happen is if we have at
1766 // least one self-argument.
1767 if (Filtered.begin() == Filtered.end()) {
1768 if (setMemoryAccessEquivTo(MP, InitialClass))
1769 markMemoryUsersTouched(MP);
1770 return;
1771 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001772
1773 // Transform the remaining operands into operand leaders.
1774 // FIXME: mapped_iterator should have a range version.
1775 auto LookupFunc = [&](const Use &U) {
1776 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1777 };
1778 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1779 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1780
1781 // and now check if all the elements are equal.
1782 // Sadly, we can't use std::equals since these are random access iterators.
1783 MemoryAccess *AllSameValue = *MappedBegin;
1784 ++MappedBegin;
1785 bool AllEqual = std::all_of(
1786 MappedBegin, MappedEnd,
1787 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1788
1789 if (AllEqual)
1790 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1791 else
1792 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1793
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001794 if (setMemoryAccessEquivTo(
1795 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001796 markMemoryUsersTouched(MP);
1797}
1798
1799// Value number a single instruction, symbolically evaluating, performing
1800// congruence finding, and updating mappings.
1801void NewGVN::valueNumberInstruction(Instruction *I) {
1802 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Davide Italiano71f2d9c2017-01-20 23:29:28 +00001803 // There's no need to call isInstructionTriviallyDead more than once on
1804 // an instruction. Therefore, once we know that an instruction is dead
1805 // we change its DFS number so that it doesn't get numbered again.
1806 if (InstrDFS[I] != 0 && isInstructionTriviallyDead(I, TLI)) {
1807 InstrDFS[I] = 0;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001808 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001809 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001810 return;
1811 }
1812 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00001813 const Expression *Symbolized = nullptr;
1814 if (DebugCounter::shouldExecute(VNCounter)) {
1815 Symbolized = performSymbolicEvaluation(I);
1816 } else {
1817 // Used to track which we marked unknown so we can skip verification of
1818 // comparisons.
1819 DebugUnknownExprs.insert(I);
1820 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00001821 // If we couldn't come up with a symbolic expression, use the unknown
1822 // expression
1823 if (Symbolized == nullptr)
1824 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001825 performCongruenceFinding(I, Symbolized);
1826 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001827 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00001828 // don't currently understand. We don't place non-value producing
1829 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001830 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001831 auto *Symbolized = createUnknownExpression(I);
1832 performCongruenceFinding(I, Symbolized);
1833 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001834 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1835 }
1836}
Davide Italiano7e274e02016-12-22 16:03:48 +00001837
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001838// Check if there is a path, using single or equal argument phi nodes, from
1839// First to Second.
1840bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1841 const MemoryAccess *Second) const {
1842 if (First == Second)
1843 return true;
1844
1845 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1846 auto *DefAccess = FirstDef->getDefiningAccess();
1847 return singleReachablePHIPath(DefAccess, Second);
1848 } else {
1849 auto *MP = cast<MemoryPhi>(First);
1850 auto ReachableOperandPred = [&](const Use &U) {
1851 return ReachableBlocks.count(MP->getIncomingBlock(U));
1852 };
1853 auto FilteredPhiArgs =
1854 make_filter_range(MP->operands(), ReachableOperandPred);
1855 SmallVector<const Value *, 32> OperandList;
1856 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1857 std::back_inserter(OperandList));
1858 bool Okay = OperandList.size() == 1;
1859 if (!Okay)
1860 Okay = std::equal(OperandList.begin(), OperandList.end(),
1861 OperandList.begin());
1862 if (Okay)
1863 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1864 return false;
1865 }
1866}
1867
Daniel Berlin589cecc2017-01-02 18:00:46 +00001868// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001869// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001870// subject to very rare false negatives. It is only useful for
1871// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001872void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001873 // Anything equivalent in the memory access table should be in the same
1874 // congruence class.
1875
1876 // Filter out the unreachable and trivially dead entries, because they may
1877 // never have been updated if the instructions were not processed.
1878 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001879 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001880 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1881 if (!Result)
1882 return false;
1883 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1884 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1885 return true;
1886 };
1887
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001888 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001889 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001890 // Unreachable instructions may not have changed because we never process
1891 // them.
1892 if (!ReachableBlocks.count(KV.first->getBlock()))
1893 continue;
1894 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001895 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001896 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001897 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001898 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1899 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1900 "The instructions for these memory operations should have "
1901 "been in the same congruence class or reachable through"
1902 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001903 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1904
1905 // We can only sanely verify that MemoryDefs in the operand list all have
1906 // the same class.
1907 auto ReachableOperandPred = [&](const Use &U) {
1908 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1909 isa<MemoryDef>(U);
1910
1911 };
1912 // All arguments should in the same class, ignoring unreachable arguments
1913 auto FilteredPhiArgs =
1914 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1915 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1916 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1917 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1918 const MemoryDef *MD = cast<MemoryDef>(U);
1919 return ValueToClass.lookup(MD->getMemoryInst());
1920 });
1921 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1922 PhiOpClasses.begin()) &&
1923 "All MemoryPhi arguments should be in the same class");
1924 }
1925 }
1926}
1927
Daniel Berlinf7d95802017-02-18 23:06:50 +00001928// Re-evaluate all the comparisons after value numbering and ensure they don't
1929// change. If they changed, we didn't mark them touched properly.
1930void NewGVN::verifyComparisons(Function &F) {
1931#ifndef NDEBUG
1932 for (auto &BB : F) {
1933 if (!ReachableBlocks.count(&BB))
1934 continue;
1935 for (auto &I : BB) {
Daniel Berlin283a6082017-03-01 19:59:26 +00001936 if (InstructionsToErase.count(&I) || DebugUnknownExprs.count(&I))
Daniel Berlinf7d95802017-02-18 23:06:50 +00001937 continue;
1938 if (isa<CmpInst>(&I)) {
1939 auto *CurrentVal = ValueToClass.lookup(&I);
1940 valueNumberInstruction(&I);
1941 assert(CurrentVal == ValueToClass.lookup(&I) &&
1942 "Re-evaluating comparison changed value");
1943 }
1944 }
1945 }
1946#endif
1947}
1948
Daniel Berlin85f91b02016-12-26 20:06:58 +00001949// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001950bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001951 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1952 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001953 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00001954 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00001955 DT = _DT;
1956 AC = _AC;
1957 TLI = _TLI;
1958 AA = _AA;
1959 MSSA = _MSSA;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001960 PredInfo = make_unique<PredicateInfo>(F, *DT, *AC);
Davide Italiano7e274e02016-12-22 16:03:48 +00001961 DL = &F.getParent()->getDataLayout();
1962 MSSAWalker = MSSA->getWalker();
1963
1964 // Count number of instructions for sizing of hash tables, and come
1965 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001966 unsigned ICount = 1;
1967 // Add an empty instruction to account for the fact that we start at 1
1968 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001969 // Note: We want ideal RPO traversal of the blocks, which is not quite the
1970 // same as dominator tree order, particularly with regard whether backedges
1971 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00001972 // If we visit in the wrong order, we will end up performing N times as many
1973 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001974 // The dominator tree does guarantee that, for a given dom tree node, it's
1975 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1976 // the siblings.
1977 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001978 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001979 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001980 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001981 auto *Node = DT->getNode(B);
1982 assert(Node && "RPO and Dominator tree should have same reachability");
1983 RPOOrdering[Node] = ++Counter;
1984 }
1985 // Sort dominator tree children arrays into RPO.
1986 for (auto &B : RPOT) {
1987 auto *Node = DT->getNode(B);
1988 if (Node->getChildren().size() > 1)
1989 std::sort(Node->begin(), Node->end(),
1990 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1991 return RPOOrdering[A] < RPOOrdering[B];
1992 });
1993 }
1994
1995 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1996 auto DFI = df_begin(DT->getRootNode());
1997 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1998 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001999 const auto &BlockRange = assignDFSNumbers(B, ICount);
2000 BlockInstRange.insert({B, BlockRange});
2001 ICount += BlockRange.second - BlockRange.first;
2002 }
2003
2004 // Handle forward unreachable blocks and figure out which blocks
2005 // have single preds.
2006 for (auto &B : F) {
2007 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002008 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002009 const auto &BlockRange = assignDFSNumbers(&B, ICount);
2010 BlockInstRange.insert({&B, BlockRange});
2011 ICount += BlockRange.second - BlockRange.first;
2012 }
2013 }
2014
Daniel Berline0bd37e2016-12-29 22:15:12 +00002015 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002016 DominatedInstRange.reserve(F.size());
2017 // Ensure we don't end up resizing the expressionToClass map, as
2018 // that can be quite expensive. At most, we have one expression per
2019 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002020 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002021
2022 // Initialize the touched instructions to include the entry block.
2023 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2024 TouchedInstructions.set(InstRange.first, InstRange.second);
2025 ReachableBlocks.insert(&F.getEntryBlock());
2026
2027 initializeCongruenceClasses(F);
2028
Daniel Berlin6cc5e442017-01-04 21:01:02 +00002029 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002030 // We start out in the entry block.
2031 BasicBlock *LastBlock = &F.getEntryBlock();
2032 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00002033 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00002034 // Walk through all the instructions in all the blocks in RPO.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002035 // TODO: As we hit a new block, we should push and pop equalities into a
2036 // table lookupOperandLeader can use, to catch things PredicateInfo
2037 // might miss, like edge-only equivalences.
Davide Italiano7e274e02016-12-22 16:03:48 +00002038 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2039 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Davide Italiano71f2d9c2017-01-20 23:29:28 +00002040
2041 // This instruction was found to be dead. We don't bother looking
2042 // at it again.
2043 if (InstrNum == 0) {
2044 TouchedInstructions.reset(InstrNum);
2045 continue;
2046 }
2047
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002048 Value *V = DFSToInstr[InstrNum];
2049 BasicBlock *CurrBlock = nullptr;
2050
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002051 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002052 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002053 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002054 CurrBlock = MP->getBlock();
2055 else
2056 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00002057
2058 // If we hit a new block, do reachability processing.
2059 if (CurrBlock != LastBlock) {
2060 LastBlock = CurrBlock;
2061 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2062 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2063
2064 // If it's not reachable, erase any touched instructions and move on.
2065 if (!BlockReachable) {
2066 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2067 DEBUG(dbgs() << "Skipping instructions in block "
2068 << getBlockName(CurrBlock)
2069 << " because it is unreachable\n");
2070 continue;
2071 }
2072 updateProcessedCount(CurrBlock);
2073 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002074
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002075 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002076 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2077 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002078 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002079 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002080 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002081 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00002082 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002083 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002084 // Reset after processing (because we may mark ourselves as touched when
2085 // we propagate equalities).
2086 TouchedInstructions.reset(InstrNum);
2087 }
2088 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00002089 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002090#ifndef NDEBUG
2091 verifyMemoryCongruency();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002092 verifyComparisons(F);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002093#endif
Daniel Berlinf7d95802017-02-18 23:06:50 +00002094
Davide Italiano7e274e02016-12-22 16:03:48 +00002095 Changed |= eliminateInstructions(F);
2096
2097 // Delete all instructions marked for deletion.
2098 for (Instruction *ToErase : InstructionsToErase) {
2099 if (!ToErase->use_empty())
2100 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2101
2102 ToErase->eraseFromParent();
2103 }
2104
2105 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002106 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2107 return !ReachableBlocks.count(&BB);
2108 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002109
2110 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2111 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002112 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002113 deleteInstructionsInBlock(&BB);
2114 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002115 }
2116
2117 cleanupTables();
2118 return Changed;
2119}
2120
2121bool NewGVN::runOnFunction(Function &F) {
2122 if (skipFunction(F))
2123 return false;
2124 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2125 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2126 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2127 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
2128 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
2129}
2130
Daniel Berlin85f91b02016-12-26 20:06:58 +00002131PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002132 NewGVN Impl;
2133
2134 // Apparently the order in which we get these results matter for
2135 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
2136 // the same order here, just in case.
2137 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2138 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2139 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2140 auto &AA = AM.getResult<AAManager>(F);
2141 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2142 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
2143 if (!Changed)
2144 return PreservedAnalyses::all();
2145 PreservedAnalyses PA;
2146 PA.preserve<DominatorTreeAnalysis>();
2147 PA.preserve<GlobalsAA>();
2148 return PA;
2149}
2150
2151// Return true if V is a value that will always be available (IE can
2152// be placed anywhere) in the function. We don't do globals here
2153// because they are often worse to put in place.
2154// TODO: Separate cost from availability
2155static bool alwaysAvailable(Value *V) {
2156 return isa<Constant>(V) || isa<Argument>(V);
2157}
2158
2159// Get the basic block from an instruction/value.
2160static BasicBlock *getBlockForValue(Value *V) {
2161 if (auto *I = dyn_cast<Instruction>(V))
2162 return I->getParent();
2163 return nullptr;
2164}
2165
2166struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002167 int DFSIn = 0;
2168 int DFSOut = 0;
2169 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002170 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002171 Value *Val = nullptr;
2172 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002173
2174 bool operator<(const ValueDFS &Other) const {
2175 // It's not enough that any given field be less than - we have sets
2176 // of fields that need to be evaluated together to give a proper ordering.
2177 // For example, if you have;
2178 // DFS (1, 3)
2179 // Val 0
2180 // DFS (1, 2)
2181 // Val 50
2182 // We want the second to be less than the first, but if we just go field
2183 // by field, we will get to Val 0 < Val 50 and say the first is less than
2184 // the second. We only want it to be less than if the DFS orders are equal.
2185 //
2186 // Each LLVM instruction only produces one value, and thus the lowest-level
2187 // differentiator that really matters for the stack (and what we use as as a
2188 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002189 // Everything else in the structure is instruction level, and only affects
2190 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002191 //
2192 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2193 // the order of replacement of uses does not matter.
2194 // IE given,
2195 // a = 5
2196 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002197 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2198 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002199 // The .val will be the same as well.
2200 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002201 // You will replace both, and it does not matter what order you replace them
2202 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2203 // operand 2).
2204 // Similarly for the case of same dfsin, dfsout, localnum, but different
2205 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002206 // a = 5
2207 // b = 6
2208 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002209 // in c, we will a valuedfs for a, and one for b,with everything the same
2210 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002211 // It does not matter what order we replace these operands in.
2212 // You will always end up with the same IR, and this is guaranteed.
2213 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
2214 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
2215 Other.U);
2216 }
2217};
2218
Daniel Berlinc4796862017-01-27 02:37:11 +00002219// This function converts the set of members for a congruence class from values,
2220// to sets of defs and uses with associated DFS info.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002221void NewGVN::convertDenseToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00002222 const CongruenceClass::MemberSet &Dense,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002223 SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002224 for (auto D : Dense) {
2225 // First add the value.
2226 BasicBlock *BB = getBlockForValue(D);
2227 // Constants are handled prior to ever calling this function, so
2228 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002229 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00002230 ValueDFS VD;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002231 DomTreeNode *DomNode = DT->getNode(BB);
2232 VD.DFSIn = DomNode->getDFSNumIn();
2233 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00002234 // If it's a store, use the leader of the value operand.
2235 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002236 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +00002237 VD.Val = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
2238 } else {
2239 VD.Val = D;
2240 }
2241
Davide Italiano7e274e02016-12-22 16:03:48 +00002242 if (auto *I = dyn_cast<Instruction>(D))
Daniel Berlinaac56842017-01-15 09:18:41 +00002243 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002244 else
2245 llvm_unreachable("Should have been an instruction");
2246
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002247 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00002248
Daniel Berlinb66164c2017-01-14 00:24:23 +00002249 // Now add the uses.
Davide Italiano7e274e02016-12-22 16:03:48 +00002250 for (auto &U : D->uses()) {
2251 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
2252 ValueDFS VD;
2253 // Put the phi node uses in the incoming block.
2254 BasicBlock *IBlock;
2255 if (auto *P = dyn_cast<PHINode>(I)) {
2256 IBlock = P->getIncomingBlock(U);
2257 // Make phi node users appear last in the incoming block
2258 // they are from.
2259 VD.LocalNum = InstrDFS.size() + 1;
2260 } else {
2261 IBlock = I->getParent();
Daniel Berlinaac56842017-01-15 09:18:41 +00002262 VD.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002263 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002264
2265 // Skip uses in unreachable blocks, as we're going
2266 // to delete them.
2267 if (ReachableBlocks.count(IBlock) == 0)
2268 continue;
2269
Daniel Berlinb66164c2017-01-14 00:24:23 +00002270 DomTreeNode *DomNode = DT->getNode(IBlock);
2271 VD.DFSIn = DomNode->getDFSNumIn();
2272 VD.DFSOut = DomNode->getDFSNumOut();
Davide Italiano7e274e02016-12-22 16:03:48 +00002273 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002274 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00002275 }
2276 }
2277 }
2278}
2279
Daniel Berlinc4796862017-01-27 02:37:11 +00002280// This function converts the set of members for a congruence class from values,
2281// to the set of defs for loads and stores, with associated DFS info.
2282void NewGVN::convertDenseToLoadsAndStores(
2283 const CongruenceClass::MemberSet &Dense,
2284 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2285 for (auto D : Dense) {
2286 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2287 continue;
2288
2289 BasicBlock *BB = getBlockForValue(D);
2290 ValueDFS VD;
2291 DomTreeNode *DomNode = DT->getNode(BB);
2292 VD.DFSIn = DomNode->getDFSNumIn();
2293 VD.DFSOut = DomNode->getDFSNumOut();
2294 VD.Val = D;
2295
2296 // If it's an instruction, use the real local dfs number.
2297 if (auto *I = dyn_cast<Instruction>(D))
2298 VD.LocalNum = InstrDFS.lookup(I);
2299 else
2300 llvm_unreachable("Should have been an instruction");
2301
2302 LoadsAndStores.emplace_back(VD);
2303 }
2304}
2305
Davide Italiano7e274e02016-12-22 16:03:48 +00002306static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00002307 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00002308 if (!ReplInst)
2309 return;
2310
Davide Italiano7e274e02016-12-22 16:03:48 +00002311 // Patch the replacement so that it is not more restrictive than the value
2312 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00002313 // Note that if 'I' is a load being replaced by some operation,
2314 // for example, by an arithmetic operation, then andIRFlags()
2315 // would just erase all math flags from the original arithmetic
2316 // operation, which is clearly not wanted and not needed.
2317 if (!isa<LoadInst>(I))
2318 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002319
Daniel Berlin86eab152017-02-12 22:25:20 +00002320 // FIXME: If both the original and replacement value are part of the
2321 // same control-flow region (meaning that the execution of one
2322 // guarantees the execution of the other), then we can combine the
2323 // noalias scopes here and do better than the general conservative
2324 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00002325
Daniel Berlin86eab152017-02-12 22:25:20 +00002326 // In general, GVN unifies expressions over different control-flow
2327 // regions, and so we need a conservative combination of the noalias
2328 // scopes.
2329 static const unsigned KnownIDs[] = {
2330 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2331 LLVMContext::MD_noalias, LLVMContext::MD_range,
2332 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2333 LLVMContext::MD_invariant_group};
2334 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00002335}
2336
2337static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2338 patchReplacementInstruction(I, Repl);
2339 I->replaceAllUsesWith(Repl);
2340}
2341
2342void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2343 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2344 ++NumGVNBlocksDeleted;
2345
Daniel Berline19f0e02017-01-30 17:06:55 +00002346 // Delete the instructions backwards, as it has a reduced likelihood of having
2347 // to update as many def-use and use-def chains. Start after the terminator.
2348 auto StartPoint = BB->rbegin();
2349 ++StartPoint;
2350 // Note that we explicitly recalculate BB->rend() on each iteration,
2351 // as it may change when we remove the first instruction.
2352 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2353 Instruction &Inst = *I++;
2354 if (!Inst.use_empty())
2355 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2356 if (isa<LandingPadInst>(Inst))
2357 continue;
2358
2359 Inst.eraseFromParent();
2360 ++NumGVNInstrDeleted;
2361 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002362 // Now insert something that simplifycfg will turn into an unreachable.
2363 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2364 new StoreInst(UndefValue::get(Int8Ty),
2365 Constant::getNullValue(Int8Ty->getPointerTo()),
2366 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002367}
2368
2369void NewGVN::markInstructionForDeletion(Instruction *I) {
2370 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2371 InstructionsToErase.insert(I);
2372}
2373
2374void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2375
2376 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2377 patchAndReplaceAllUsesWith(I, V);
2378 // We save the actual erasing to avoid invalidating memory
2379 // dependencies until we are done with everything.
2380 markInstructionForDeletion(I);
2381}
2382
2383namespace {
2384
2385// This is a stack that contains both the value and dfs info of where
2386// that value is valid.
2387class ValueDFSStack {
2388public:
2389 Value *back() const { return ValueStack.back(); }
2390 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2391
2392 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002393 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002394 DFSStack.emplace_back(DFSIn, DFSOut);
2395 }
2396 bool empty() const { return DFSStack.empty(); }
2397 bool isInScope(int DFSIn, int DFSOut) const {
2398 if (empty())
2399 return false;
2400 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2401 }
2402
2403 void popUntilDFSScope(int DFSIn, int DFSOut) {
2404
2405 // These two should always be in sync at this point.
2406 assert(ValueStack.size() == DFSStack.size() &&
2407 "Mismatch between ValueStack and DFSStack");
2408 while (
2409 !DFSStack.empty() &&
2410 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2411 DFSStack.pop_back();
2412 ValueStack.pop_back();
2413 }
2414 }
2415
2416private:
2417 SmallVector<Value *, 8> ValueStack;
2418 SmallVector<std::pair<int, int>, 8> DFSStack;
2419};
2420}
Daniel Berlin04443432017-01-07 03:23:47 +00002421
Davide Italiano7e274e02016-12-22 16:03:48 +00002422bool NewGVN::eliminateInstructions(Function &F) {
2423 // This is a non-standard eliminator. The normal way to eliminate is
2424 // to walk the dominator tree in order, keeping track of available
2425 // values, and eliminating them. However, this is mildly
2426 // pointless. It requires doing lookups on every instruction,
2427 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002428 // instructions part of most singleton congruence classes, we know we
2429 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002430
2431 // Instead, this eliminator looks at the congruence classes directly, sorts
2432 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002433 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002434 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002435 // last member. This is worst case O(E log E) where E = number of
2436 // instructions in a single congruence class. In theory, this is all
2437 // instructions. In practice, it is much faster, as most instructions are
2438 // either in singleton congruence classes or can't possibly be eliminated
2439 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002440 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002441 // for elimination purposes.
2442 // TODO: If we wanted to be faster, We could remove any members with no
2443 // overlapping ranges while sorting, as we will never eliminate anything
2444 // with those members, as they don't dominate anything else in our set.
2445
Davide Italiano7e274e02016-12-22 16:03:48 +00002446 bool AnythingReplaced = false;
2447
2448 // Since we are going to walk the domtree anyway, and we can't guarantee the
2449 // DFS numbers are updated, we compute some ourselves.
2450 DT->updateDFSNumbers();
2451
2452 for (auto &B : F) {
2453 if (!ReachableBlocks.count(&B)) {
2454 for (const auto S : successors(&B)) {
2455 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002456 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002457 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2458 << getBlockName(&B)
2459 << " with undef due to it being unreachable\n");
2460 for (auto &Operand : Phi.incoming_values())
2461 if (Phi.getIncomingBlock(Operand) == &B)
2462 Operand.set(UndefValue::get(Phi.getType()));
2463 }
2464 }
2465 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002466 }
2467
Daniel Berlin4d547962017-02-12 23:24:45 +00002468 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002469 // Track the equivalent store info so we can decide whether to try
2470 // dead store elimination.
2471 SmallVector<ValueDFS, 8> PossibleDeadStores;
2472
Daniel Berlinb79f5362017-02-11 12:48:50 +00002473 if (CC->Dead)
Davide Italiano7e274e02016-12-22 16:03:48 +00002474 continue;
Daniel Berlinb79f5362017-02-11 12:48:50 +00002475 // Everything still in the INITIAL class is unreachable or dead.
2476 if (CC == InitialClass) {
2477#ifndef NDEBUG
2478 for (auto M : CC->Members)
2479 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2480 InstructionsToErase.count(cast<Instruction>(M))) &&
2481 "Everything in INITIAL should be unreachable or dead at this "
2482 "point");
2483#endif
2484 continue;
2485 }
2486
Davide Italiano7e274e02016-12-22 16:03:48 +00002487 assert(CC->RepLeader && "We should have had a leader");
2488
2489 // If this is a leader that is always available, and it's a
2490 // constant or has no equivalences, just replace everything with
2491 // it. We then update the congruence class with whatever members
2492 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002493 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2494 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002495 SmallPtrSet<Value *, 4> MembersLeft;
2496 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002497 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002498 // Void things have no uses we can replace.
2499 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2500 MembersLeft.insert(Member);
2501 continue;
2502 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002503 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2504 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002505 // Due to equality propagation, these may not always be
2506 // instructions, they may be real values. We don't really
2507 // care about trying to replace the non-instructions.
2508 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002509 assert(Leader != I && "About to accidentally remove our leader");
2510 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002511 AnythingReplaced = true;
2512
2513 continue;
2514 } else {
2515 MembersLeft.insert(I);
2516 }
2517 }
2518 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002519 } else {
2520 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2521 // If this is a singleton, we can skip it.
2522 if (CC->Members.size() != 1) {
2523
2524 // This is a stack because equality replacement/etc may place
2525 // constants in the middle of the member list, and we want to use
2526 // those constant values in preference to the current leader, over
2527 // the scope of those constants.
2528 ValueDFSStack EliminationStack;
2529
2530 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002531 SmallVector<ValueDFS, 8> DFSOrderedSet;
Davide Italiano7e274e02016-12-22 16:03:48 +00002532 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2533
2534 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002535 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002536 for (auto &VD : DFSOrderedSet) {
2537 int MemberDFSIn = VD.DFSIn;
2538 int MemberDFSOut = VD.DFSOut;
2539 Value *Member = VD.Val;
2540 Use *MemberUse = VD.U;
Davide Italiano7e274e02016-12-22 16:03:48 +00002541
Daniel Berlinc4796862017-01-27 02:37:11 +00002542 // We ignore void things because we can't get a value from them.
2543 if (Member && Member->getType()->isVoidTy())
2544 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002545
2546 if (EliminationStack.empty()) {
2547 DEBUG(dbgs() << "Elimination Stack is empty\n");
2548 } else {
2549 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2550 << EliminationStack.dfs_back().first << ","
2551 << EliminationStack.dfs_back().second << ")\n");
2552 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002553
2554 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2555 << MemberDFSOut << ")\n");
2556 // First, we see if we are out of scope or empty. If so,
2557 // and there equivalences, we try to replace the top of
2558 // stack with equivalences (if it's on the stack, it must
2559 // not have been eliminated yet).
2560 // Then we synchronize to our current scope, by
2561 // popping until we are back within a DFS scope that
2562 // dominates the current member.
2563 // Then, what happens depends on a few factors
2564 // If the stack is now empty, we need to push
2565 // If we have a constant or a local equivalence we want to
2566 // start using, we also push.
2567 // Otherwise, we walk along, processing members who are
2568 // dominated by this scope, and eliminate them.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002569 bool ShouldPush = Member && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002570 bool OutOfScope =
2571 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2572
2573 if (OutOfScope || ShouldPush) {
2574 // Sync to our current scope.
2575 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002576 bool ShouldPush = Member && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002577 if (ShouldPush) {
2578 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2579 }
2580 }
2581
2582 // If we get to this point, and the stack is empty we must have a use
2583 // with nothing we can use to eliminate it, just skip it.
2584 if (EliminationStack.empty())
2585 continue;
2586
2587 // Skip the Value's, we only want to eliminate on their uses.
2588 if (Member)
2589 continue;
2590 Value *Result = EliminationStack.back();
2591
Daniel Berlind92e7f92017-01-07 00:01:42 +00002592 // Don't replace our existing users with ourselves.
2593 if (MemberUse->get() == Result)
Davide Italiano7e274e02016-12-22 16:03:48 +00002594 continue;
2595
2596 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2597 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2598 << "\n");
2599
2600 // If we replaced something in an instruction, handle the patching of
2601 // metadata.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002602 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get())) {
2603 // Skip this if we are replacing predicateinfo with its original
2604 // operand, as we already know we can just drop it.
2605 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
2606 if (!PI || Result != PI->OriginalOp)
2607 patchReplacementInstruction(ReplacedInst, Result);
2608 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002609
2610 assert(isa<Instruction>(MemberUse->getUser()));
2611 MemberUse->set(Result);
2612 AnythingReplaced = true;
2613 }
2614 }
2615 }
2616
2617 // Cleanup the congruence class.
2618 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002619 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002620 if (Member->getType()->isVoidTy()) {
2621 MembersLeft.insert(Member);
2622 continue;
2623 }
2624
2625 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2626 if (isInstructionTriviallyDead(MemberInst)) {
2627 // TODO: Don't mark loads of undefs.
2628 markInstructionForDeletion(MemberInst);
2629 continue;
2630 }
2631 }
2632 MembersLeft.insert(Member);
2633 }
2634 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002635
2636 // If we have possible dead stores to look at, try to eliminate them.
2637 if (CC->StoreCount > 0) {
2638 convertDenseToLoadsAndStores(CC->Members, PossibleDeadStores);
2639 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2640 ValueDFSStack EliminationStack;
2641 for (auto &VD : PossibleDeadStores) {
2642 int MemberDFSIn = VD.DFSIn;
2643 int MemberDFSOut = VD.DFSOut;
2644 Instruction *Member = cast<Instruction>(VD.Val);
2645 if (EliminationStack.empty() ||
2646 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2647 // Sync to our current scope.
2648 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2649 if (EliminationStack.empty()) {
2650 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2651 continue;
2652 }
2653 }
2654 // We already did load elimination, so nothing to do here.
2655 if (isa<LoadInst>(Member))
2656 continue;
2657 assert(!EliminationStack.empty());
2658 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002659 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002660 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2661 // Member is dominater by Leader, and thus dead
2662 DEBUG(dbgs() << "Marking dead store " << *Member
2663 << " that is dominated by " << *Leader << "\n");
2664 markInstructionForDeletion(Member);
2665 CC->Members.erase(Member);
2666 ++NumGVNDeadStores;
2667 }
2668 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002669 }
2670
2671 return AnythingReplaced;
2672}
Daniel Berlin1c087672017-02-11 15:07:01 +00002673
2674// This function provides global ranking of operations so that we can place them
2675// in a canonical order. Note that rank alone is not necessarily enough for a
2676// complete ordering, as constants all have the same rank. However, generally,
2677// we will simplify an operation with all constants so that it doesn't matter
2678// what order they appear in.
2679unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002680 // Prefer undef to anything else
2681 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00002682 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002683 if (isa<Constant>(V))
2684 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00002685 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002686 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00002687
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002688 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00002689 // the constant and argument ranking above.
2690 unsigned Result = InstrDFS.lookup(V);
2691 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002692 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00002693 // Unreachable or something else, just return a really large number.
2694 return ~0;
2695}
2696
2697// This is a function that says whether two commutative operations should
2698// have their order swapped when canonicalizing.
2699bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
2700 // Because we only care about a total ordering, and don't rewrite expressions
2701 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002702 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002703 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00002704}