blob: 5b43f4fd2c225d5ab34c96c03fd26e00c6c6fcbc [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
292public:
293 static char ID; // Pass identification, replacement for typeid.
294 NewGVN() : FunctionPass(ID) {
295 initializeNewGVNPass(*PassRegistry::getPassRegistry());
296 }
297
298 bool runOnFunction(Function &F) override;
299 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000300 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000301
302private:
Davide Italiano7e274e02016-12-22 16:03:48 +0000303 void getAnalysisUsage(AnalysisUsage &AU) const override {
304 AU.addRequired<AssumptionCacheTracker>();
305 AU.addRequired<DominatorTreeWrapperPass>();
306 AU.addRequired<TargetLibraryInfoWrapperPass>();
307 AU.addRequired<MemorySSAWrapperPass>();
308 AU.addRequired<AAResultsWrapperPass>();
Davide Italiano7e274e02016-12-22 16:03:48 +0000309 AU.addPreserved<DominatorTreeWrapperPass>();
310 AU.addPreserved<GlobalsAAWrapperPass>();
311 }
312
313 // Expression handling.
Daniel Berlin97718e62017-01-31 22:32:03 +0000314 const Expression *createExpression(Instruction *);
315 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000316 PHIExpression *createPHIExpression(Instruction *);
317 const VariableExpression *createVariableExpression(Value *);
318 const ConstantExpression *createConstantExpression(Constant *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000319 const Expression *createVariableOrConstant(Value *V);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000320 const UnknownExpression *createUnknownExpression(Instruction *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000321 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000322 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
Daniel Berlin97718e62017-01-31 22:32:03 +0000323 MemoryAccess *);
324 const CallExpression *createCallExpression(CallInst *, MemoryAccess *);
325 const AggregateValueExpression *createAggregateValueExpression(Instruction *);
326 bool setBasicExpressionInfo(Instruction *, BasicExpression *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000327
328 // Congruence class handling.
329 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000330 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000331 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000332 return result;
333 }
334
335 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000336 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000337 CClass->Members.insert(Member);
338 ValueToClass[Member] = CClass;
339 return CClass;
340 }
341 void initializeCongruenceClasses(Function &F);
342
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000343 // Value number an Instruction or MemoryPhi.
344 void valueNumberMemoryPhi(MemoryPhi *);
345 void valueNumberInstruction(Instruction *);
346
Davide Italiano7e274e02016-12-22 16:03:48 +0000347 // Symbolic evaluation.
348 const Expression *checkSimplificationResults(Expression *, Instruction *,
349 Value *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000350 const Expression *performSymbolicEvaluation(Value *);
351 const Expression *performSymbolicLoadEvaluation(Instruction *);
352 const Expression *performSymbolicStoreEvaluation(Instruction *);
353 const Expression *performSymbolicCallEvaluation(Instruction *);
354 const Expression *performSymbolicPHIEvaluation(Instruction *);
355 const Expression *performSymbolicAggrValueEvaluation(Instruction *);
356 const Expression *performSymbolicCmpEvaluation(Instruction *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000357 const Expression *performSymbolicPredicateInfoEvaluation(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000358
359 // Congruence finding.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000360 Value *lookupOperandLeader(Value *) const;
Daniel Berlinc0431fd2017-01-13 22:40:01 +0000361 void performCongruenceFinding(Instruction *, const Expression *);
362 void moveValueToNewCongruenceClass(Instruction *, CongruenceClass *,
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000363 CongruenceClass *);
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000364 bool setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To);
365 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Daniel Berlinc4796862017-01-27 02:37:11 +0000366 bool isMemoryAccessTop(const MemoryAccess *) const;
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000367
Daniel Berlin1c087672017-02-11 15:07:01 +0000368 // Ranking
369 unsigned int getRank(const Value *) const;
370 bool shouldSwapOperands(const Value *, const Value *) const;
371
Davide Italiano7e274e02016-12-22 16:03:48 +0000372 // Reachability handling.
373 void updateReachableEdge(BasicBlock *, BasicBlock *);
374 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin97718e62017-01-31 22:32:03 +0000375 Value *findConditionEquivalence(Value *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000376
377 // Elimination.
378 struct ValueDFS;
Daniel Berlinc4796862017-01-27 02:37:11 +0000379 void convertDenseToDFSOrdered(const CongruenceClass::MemberSet &,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +0000380 SmallVectorImpl<ValueDFS> &);
Daniel Berlinc4796862017-01-27 02:37:11 +0000381 void convertDenseToLoadsAndStores(const CongruenceClass::MemberSet &,
382 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000383
384 bool eliminateInstructions(Function &);
385 void replaceInstruction(Instruction *, Value *);
386 void markInstructionForDeletion(Instruction *);
387 void deleteInstructionsInBlock(BasicBlock *);
388
389 // New instruction creation.
390 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000391
392 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000393 void markUsersTouched(Value *);
394 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000395 void markPredicateUsersTouched(Instruction *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000396 void markLeaderChangeTouched(CongruenceClass *CC);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000397 void addPredicateUsers(const PredicateBase *, Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000398
399 // Utilities.
400 void cleanupTables();
401 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
402 void updateProcessedCount(Value *V);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000403 void verifyMemoryCongruency() const;
Daniel Berlinf7d95802017-02-18 23:06:50 +0000404 void verifyComparisons(Function &F);
Daniel Berlinf6eba4b2017-01-11 20:22:36 +0000405 bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000406};
Benjamin Kramerefcf06f2017-02-11 11:06:55 +0000407} // end anonymous namespace
Davide Italiano7e274e02016-12-22 16:03:48 +0000408
409char NewGVN::ID = 0;
410
411// createGVNPass - The public interface to this file.
412FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
413
Davide Italianob1114092016-12-28 13:37:17 +0000414template <typename T>
415static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
416 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000417 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000418 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000419 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000420 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000421 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000422 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000423 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000424 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000425 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000426 return true;
427}
428
Davide Italianob1114092016-12-28 13:37:17 +0000429bool LoadExpression::equals(const Expression &Other) const {
430 return equalsLoadStoreHelper(*this, Other);
431}
Davide Italiano7e274e02016-12-22 16:03:48 +0000432
Davide Italianob1114092016-12-28 13:37:17 +0000433bool StoreExpression::equals(const Expression &Other) const {
Daniel Berlin26addef2017-01-20 21:04:30 +0000434 bool Result = equalsLoadStoreHelper(*this, Other);
435 // Make sure that store vs store includes the value operand.
436 if (Result)
437 if (const auto *S = dyn_cast<StoreExpression>(&Other))
438 if (getStoredValue() != S->getStoredValue())
439 return false;
440 return Result;
Davide Italiano7e274e02016-12-22 16:03:48 +0000441}
442
443#ifndef NDEBUG
444static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000445 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000446}
447#endif
448
449INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
450INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
451INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
452INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
453INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
454INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
455INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
456INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
457
458PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000459 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000460 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000461 auto *E =
462 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000463
464 E->allocateOperands(ArgRecycler, ExpressionAllocator);
465 E->setType(I->getType());
466 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000467
Davide Italianob3886dd2017-01-25 23:37:49 +0000468 // Filter out unreachable phi operands.
469 auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000470 return ReachableBlocks.count(PN->getIncomingBlock(U));
Davide Italianob3886dd2017-01-25 23:37:49 +0000471 });
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000472
473 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
474 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000475 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000476 if (U == PN)
477 return PN;
Daniel Berlin203f47b2017-01-31 22:31:53 +0000478 return lookupOperandLeader(U);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000479 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000480 return E;
481}
482
483// Set basic expression info (Arguments, type, opcode) for Expression
484// E from Instruction I in block B.
Daniel Berlin97718e62017-01-31 22:32:03 +0000485bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000486 bool AllConstant = true;
487 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
488 E->setType(GEP->getSourceElementType());
489 else
490 E->setType(I->getType());
491 E->setOpcode(I->getOpcode());
492 E->allocateOperands(ArgRecycler, ExpressionAllocator);
493
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000494 // Transform the operand array into an operand leader array, and keep track of
495 // whether all members are constant.
496 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000497 auto Operand = lookupOperandLeader(O);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000498 AllConstant &= isa<Constant>(Operand);
499 return Operand;
500 });
501
Davide Italiano7e274e02016-12-22 16:03:48 +0000502 return AllConstant;
503}
504
505const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
Daniel Berlin97718e62017-01-31 22:32:03 +0000506 Value *Arg1, Value *Arg2) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000507 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000508
509 E->setType(T);
510 E->setOpcode(Opcode);
511 E->allocateOperands(ArgRecycler, ExpressionAllocator);
512 if (Instruction::isCommutative(Opcode)) {
513 // Ensure that commutative instructions that only differ by a permutation
514 // of their operands get the same value number by sorting the operand value
515 // numbers. Since all commutative instructions have two operands it is more
516 // efficient to sort by hand rather than using, say, std::sort.
Daniel Berlin1c087672017-02-11 15:07:01 +0000517 if (shouldSwapOperands(Arg1, Arg2))
Davide Italiano7e274e02016-12-22 16:03:48 +0000518 std::swap(Arg1, Arg2);
519 }
Daniel Berlin203f47b2017-01-31 22:31:53 +0000520 E->op_push_back(lookupOperandLeader(Arg1));
521 E->op_push_back(lookupOperandLeader(Arg2));
Davide Italiano7e274e02016-12-22 16:03:48 +0000522
523 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
524 DT, AC);
525 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
526 return SimplifiedE;
527 return E;
528}
529
530// Take a Value returned by simplification of Expression E/Instruction
531// I, and see if it resulted in a simpler expression. If so, return
532// that expression.
533// TODO: Once finished, this should not take an Instruction, we only
534// use it for printing.
535const Expression *NewGVN::checkSimplificationResults(Expression *E,
536 Instruction *I, Value *V) {
537 if (!V)
538 return nullptr;
539 if (auto *C = dyn_cast<Constant>(V)) {
540 if (I)
541 DEBUG(dbgs() << "Simplified " << *I << " to "
542 << " constant " << *C << "\n");
543 NumGVNOpsSimplified++;
544 assert(isa<BasicExpression>(E) &&
545 "We should always have had a basic expression here");
546
547 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
548 ExpressionAllocator.Deallocate(E);
549 return createConstantExpression(C);
550 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
551 if (I)
552 DEBUG(dbgs() << "Simplified " << *I << " to "
553 << " variable " << *V << "\n");
554 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
555 ExpressionAllocator.Deallocate(E);
556 return createVariableExpression(V);
557 }
558
559 CongruenceClass *CC = ValueToClass.lookup(V);
560 if (CC && CC->DefiningExpr) {
561 if (I)
562 DEBUG(dbgs() << "Simplified " << *I << " to "
563 << " expression " << *V << "\n");
564 NumGVNOpsSimplified++;
565 assert(isa<BasicExpression>(E) &&
566 "We should always have had a basic expression here");
567 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
568 ExpressionAllocator.Deallocate(E);
569 return CC->DefiningExpr;
570 }
571 return nullptr;
572}
573
Daniel Berlin97718e62017-01-31 22:32:03 +0000574const Expression *NewGVN::createExpression(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000575 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000576
Daniel Berlin97718e62017-01-31 22:32:03 +0000577 bool AllConstant = setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000578
579 if (I->isCommutative()) {
580 // Ensure that commutative instructions that only differ by a permutation
581 // of their operands get the same value number by sorting the operand value
582 // numbers. Since all commutative instructions have two operands it is more
583 // efficient to sort by hand rather than using, say, std::sort.
584 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
Daniel Berlin508a1de2017-02-12 23:24:42 +0000585 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
Davide Italiano7e274e02016-12-22 16:03:48 +0000586 E->swapOperands(0, 1);
587 }
588
589 // Perform simplificaiton
590 // TODO: Right now we only check to see if we get a constant result.
591 // We may get a less than constant, but still better, result for
592 // some operations.
593 // IE
594 // add 0, x -> x
595 // and x, x -> x
596 // We should handle this by simply rewriting the expression.
597 if (auto *CI = dyn_cast<CmpInst>(I)) {
598 // Sort the operand value numbers so x<y and y>x get the same value
599 // number.
600 CmpInst::Predicate Predicate = CI->getPredicate();
Daniel Berlin1c087672017-02-11 15:07:01 +0000601 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000602 E->swapOperands(0, 1);
603 Predicate = CmpInst::getSwappedPredicate(Predicate);
604 }
605 E->setOpcode((CI->getOpcode() << 8) | Predicate);
606 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
Davide Italiano7e274e02016-12-22 16:03:48 +0000607 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
608 "Wrong types on cmp instruction");
Daniel Berlin97718e62017-01-31 22:32:03 +0000609 assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
610 E->getOperand(1)->getType() == I->getOperand(1)->getType()));
Daniel Berlinff12c922017-01-31 22:32:01 +0000611 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
Daniel Berlin97718e62017-01-31 22:32:03 +0000612 *DL, TLI, DT, AC);
Daniel Berlinff12c922017-01-31 22:32:01 +0000613 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
614 return SimplifiedE;
Davide Italiano7e274e02016-12-22 16:03:48 +0000615 } else if (isa<SelectInst>(I)) {
616 if (isa<Constant>(E->getOperand(0)) ||
Daniel Berlin97718e62017-01-31 22:32:03 +0000617 E->getOperand(0) == E->getOperand(1)) {
618 assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
619 E->getOperand(2)->getType() == I->getOperand(2)->getType());
Davide Italiano7e274e02016-12-22 16:03:48 +0000620 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
621 E->getOperand(2), *DL, TLI, DT, AC);
622 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
623 return SimplifiedE;
624 }
625 } else if (I->isBinaryOp()) {
626 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
627 *DL, TLI, DT, AC);
628 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
629 return SimplifiedE;
630 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
631 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
632 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
633 return SimplifiedE;
634 } else if (isa<GetElementPtrInst>(I)) {
635 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000636 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000637 *DL, TLI, DT, AC);
638 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
639 return SimplifiedE;
640 } else if (AllConstant) {
641 // We don't bother trying to simplify unless all of the operands
642 // were constant.
643 // TODO: There are a lot of Simplify*'s we could call here, if we
644 // wanted to. The original motivating case for this code was a
645 // zext i1 false to i8, which we don't have an interface to
646 // simplify (IE there is no SimplifyZExt).
647
648 SmallVector<Constant *, 8> C;
649 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000650 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000651
652 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
653 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
654 return SimplifiedE;
655 }
656 return E;
657}
658
659const AggregateValueExpression *
Daniel Berlin97718e62017-01-31 22:32:03 +0000660NewGVN::createAggregateValueExpression(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000661 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000662 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000663 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000664 setBasicExpressionInfo(I, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000665 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000666 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000667 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000668 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000669 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000670 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
Daniel Berlin97718e62017-01-31 22:32:03 +0000671 setBasicExpressionInfo(EI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000672 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000673 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000674 return E;
675 }
676 llvm_unreachable("Unhandled type of aggregate value operation");
677}
678
Daniel Berlin85f91b02016-12-26 20:06:58 +0000679const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000680 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000681 E->setOpcode(V->getValueID());
682 return E;
683}
684
Daniel Berlinf7d95802017-02-18 23:06:50 +0000685const Expression *NewGVN::createVariableOrConstant(Value *V) {
686 if (auto *C = dyn_cast<Constant>(V))
687 return createConstantExpression(C);
688 return createVariableExpression(V);
689}
690
Daniel Berlin85f91b02016-12-26 20:06:58 +0000691const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000692 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000693 E->setOpcode(C->getValueID());
694 return E;
695}
696
Daniel Berlin02c6b172017-01-02 18:00:53 +0000697const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
698 auto *E = new (ExpressionAllocator) UnknownExpression(I);
699 E->setOpcode(I->getOpcode());
700 return E;
701}
702
Davide Italiano7e274e02016-12-22 16:03:48 +0000703const CallExpression *NewGVN::createCallExpression(CallInst *CI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000704 MemoryAccess *HV) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000705 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000706 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000707 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
Daniel Berlin97718e62017-01-31 22:32:03 +0000708 setBasicExpressionInfo(CI, E);
Davide Italiano7e274e02016-12-22 16:03:48 +0000709 return E;
710}
711
712// See if we have a congruence class and leader for this operand, and if so,
713// return it. Otherwise, return the operand itself.
Daniel Berlin203f47b2017-01-31 22:31:53 +0000714Value *NewGVN::lookupOperandLeader(Value *V) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000715 CongruenceClass *CC = ValueToClass.lookup(V);
Daniel Berlinb79f5362017-02-11 12:48:50 +0000716 if (CC) {
717 // Everything in INITIAL is represneted by undef, as it can be any value.
718 // We do have to make sure we get the type right though, so we can't set the
719 // RepLeader to undef.
720 if (CC == InitialClass)
721 return UndefValue::get(V->getType());
Daniel Berlin26addef2017-01-20 21:04:30 +0000722 return CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
Daniel Berlinb79f5362017-02-11 12:48:50 +0000723 }
724
Davide Italiano7e274e02016-12-22 16:03:48 +0000725 return V;
726}
727
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000728MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000729 auto *CC = MemoryAccessToClass.lookup(MA);
730 if (CC && CC->RepMemoryAccess)
731 return CC->RepMemoryAccess;
732 // FIXME: We need to audit all the places that current set a nullptr To, and
733 // fix them. There should always be *some* congruence class, even if it is
734 // singular. Right now, we don't bother setting congruence classes for
735 // anything but stores, which means we have to return the original access
736 // here. Otherwise, this should be unreachable.
737 return MA;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000738}
739
Daniel Berlinc4796862017-01-27 02:37:11 +0000740// Return true if the MemoryAccess is really equivalent to everything. This is
741// equivalent to the lattice value "TOP" in most lattices. This is the initial
742// state of all memory accesses.
743bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
744 return MemoryAccessToClass.lookup(MA) == InitialClass;
745}
746
Davide Italiano7e274e02016-12-22 16:03:48 +0000747LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
Daniel Berlin97718e62017-01-31 22:32:03 +0000748 LoadInst *LI, MemoryAccess *DA) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000749 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000750 E->allocateOperands(ArgRecycler, ExpressionAllocator);
751 E->setType(LoadType);
752
753 // Give store and loads same opcode so they value number together.
754 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000755 E->op_push_back(lookupOperandLeader(PointerOp));
Davide Italiano7e274e02016-12-22 16:03:48 +0000756 if (LI)
757 E->setAlignment(LI->getAlignment());
758
759 // TODO: Value number heap versions. We may be able to discover
760 // things alias analysis can't on it's own (IE that a store and a
761 // load have the same value, and thus, it isn't clobbering the load).
762 return E;
763}
764
765const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000766 MemoryAccess *DA) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000767 auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin26addef2017-01-20 21:04:30 +0000768 auto *E = new (ExpressionAllocator)
769 StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000770 E->allocateOperands(ArgRecycler, ExpressionAllocator);
771 E->setType(SI->getValueOperand()->getType());
772
773 // Give store and loads same opcode so they value number together.
774 E->setOpcode(0);
Daniel Berlin203f47b2017-01-31 22:31:53 +0000775 E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
Davide Italiano7e274e02016-12-22 16:03:48 +0000776
777 // TODO: Value number heap versions. We may be able to discover
778 // things alias analysis can't on it's own (IE that a store and a
779 // load have the same value, and thus, it isn't clobbering the load).
780 return E;
781}
782
Daniel Berlin97718e62017-01-31 22:32:03 +0000783const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000784 // Unlike loads, we never try to eliminate stores, so we do not check if they
785 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000786 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000787 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinc4796862017-01-27 02:37:11 +0000788 // Get the expression, if any, for the RHS of the MemoryDef.
789 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
790 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
791 // If we are defined by ourselves, use the live on entry def.
792 if (StoreRHS == StoreAccess)
793 StoreRHS = MSSA->getLiveOnEntryDef();
794
Daniel Berlin589cecc2017-01-02 18:00:46 +0000795 if (SI->isSimple()) {
Daniel Berlinc4796862017-01-27 02:37:11 +0000796 // See if we are defined by a previous store expression, it already has a
797 // value, and it's the same value as our current store. FIXME: Right now, we
798 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin97718e62017-01-31 22:32:03 +0000799 const Expression *OldStore = createStoreExpression(SI, StoreRHS);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000800 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000801 // Basically, check if the congruence class the store is in is defined by a
802 // store that isn't us, and has the same value. MemorySSA takes care of
803 // ensuring the store has the same memory state as us already.
Daniel Berlin26addef2017-01-20 21:04:30 +0000804 // The RepStoredValue gets nulled if all the stores disappear in a class, so
805 // we don't need to check if the class contains a store besides us.
Daniel Berlin808e3ff2017-01-31 22:31:56 +0000806 if (CC && CC->RepStoredValue == lookupOperandLeader(SI->getValueOperand()))
Daniel Berlin97718e62017-01-31 22:32:03 +0000807 return createStoreExpression(SI, StoreRHS);
Daniel Berlinc4796862017-01-27 02:37:11 +0000808 // Also check if our value operand is defined by a load of the same memory
809 // location, and the memory state is the same as it was then
810 // (otherwise, it could have been overwritten later. See test32 in
811 // transforms/DeadStoreElimination/simple.ll)
812 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand())) {
Daniel Berlin203f47b2017-01-31 22:31:53 +0000813 if ((lookupOperandLeader(LI->getPointerOperand()) ==
814 lookupOperandLeader(SI->getPointerOperand())) &&
Daniel Berlinc4796862017-01-27 02:37:11 +0000815 (lookupMemoryAccessEquiv(
816 MSSA->getMemoryAccess(LI)->getDefiningAccess()) == StoreRHS))
817 return createVariableExpression(LI);
818 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000819 }
Daniel Berlin97718e62017-01-31 22:32:03 +0000820 return createStoreExpression(SI, StoreAccess);
Davide Italiano7e274e02016-12-22 16:03:48 +0000821}
822
Daniel Berlin97718e62017-01-31 22:32:03 +0000823const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000824 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000825
826 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000827 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000828 if (!LI->isSimple())
829 return nullptr;
830
Daniel Berlin203f47b2017-01-31 22:31:53 +0000831 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
Davide Italiano7e274e02016-12-22 16:03:48 +0000832 // Load of undef is undef.
833 if (isa<UndefValue>(LoadAddressLeader))
834 return createConstantExpression(UndefValue::get(LI->getType()));
835
836 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
837
838 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
839 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
840 Instruction *DefiningInst = MD->getMemoryInst();
841 // If the defining instruction is not reachable, replace with undef.
842 if (!ReachableBlocks.count(DefiningInst->getParent()))
843 return createConstantExpression(UndefValue::get(LI->getType()));
844 }
845 }
846
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000847 const Expression *E =
848 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
Daniel Berlin97718e62017-01-31 22:32:03 +0000849 lookupMemoryAccessEquiv(DefiningAccess));
Davide Italiano7e274e02016-12-22 16:03:48 +0000850 return E;
851}
852
Daniel Berlinf7d95802017-02-18 23:06:50 +0000853const Expression *
854NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
855 auto *PI = PredInfo->getPredicateInfoFor(I);
856 if (!PI)
857 return nullptr;
858
859 DEBUG(dbgs() << "Found predicate info from instruction !\n");
Daniel Berlinfccbda92017-02-22 22:20:58 +0000860
861 auto *PWC = dyn_cast<PredicateWithCondition>(PI);
862 if (!PWC)
Daniel Berlinf7d95802017-02-18 23:06:50 +0000863 return nullptr;
864
Daniel Berlinfccbda92017-02-22 22:20:58 +0000865 auto *CopyOf = I->getOperand(0);
866 auto *Cond = PWC->Condition;
867
Daniel Berlinf7d95802017-02-18 23:06:50 +0000868 // If this a copy of the condition, it must be either true or false depending
869 // on the predicate info type and edge
870 if (CopyOf == Cond) {
Daniel Berlinfccbda92017-02-22 22:20:58 +0000871 // We should not need to add predicate users because the predicate info is
872 // already a use of this operand.
Daniel Berlinf7d95802017-02-18 23:06:50 +0000873 if (isa<PredicateAssume>(PI))
874 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
875 if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
876 if (PBranch->TrueEdge)
877 return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
878 return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
879 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000880 if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
881 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000882 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000883
Daniel Berlinf7d95802017-02-18 23:06:50 +0000884 // Not a copy of the condition, so see what the predicates tell us about this
885 // value. First, though, we check to make sure the value is actually a copy
886 // of one of the condition operands. It's possible, in certain cases, for it
887 // to be a copy of a predicateinfo copy. In particular, if two branch
888 // operations use the same condition, and one branch dominates the other, we
889 // will end up with a copy of a copy. This is currently a small deficiency in
Daniel Berlinfccbda92017-02-22 22:20:58 +0000890 // predicateinfo. What will end up happening here is that we will value
Daniel Berlinf7d95802017-02-18 23:06:50 +0000891 // number both copies the same anyway.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000892
893 // Everything below relies on the condition being a comparison.
894 auto *Cmp = dyn_cast<CmpInst>(Cond);
895 if (!Cmp)
896 return nullptr;
897
898 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +0000899 DEBUG(dbgs() << "Copy is not of any condition operands!");
900 return nullptr;
901 }
Daniel Berlinfccbda92017-02-22 22:20:58 +0000902 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
903 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +0000904 bool SwappedOps = false;
905 // Sort the ops
906 if (shouldSwapOperands(FirstOp, SecondOp)) {
907 std::swap(FirstOp, SecondOp);
908 SwappedOps = true;
909 }
Daniel Berlinf7d95802017-02-18 23:06:50 +0000910 CmpInst::Predicate Predicate =
911 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
912
913 if (isa<PredicateAssume>(PI)) {
914 // If the comparison is true when the operands are equal, then we know the
915 // operands are equal, because assumes must always be true.
916 if (CmpInst::isTrueWhenEqual(Predicate)) {
917 addPredicateUsers(PI, I);
918 return createVariableOrConstant(FirstOp);
919 }
920 }
921 if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
922 // If we are *not* a copy of the comparison, we may equal to the other
923 // operand when the predicate implies something about equality of
924 // operations. In particular, if the comparison is true/false when the
925 // operands are equal, and we are on the right edge, we know this operation
926 // is equal to something.
927 if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
928 (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
929 addPredicateUsers(PI, I);
930 return createVariableOrConstant(FirstOp);
931 }
932 // Handle the special case of floating point.
933 if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
934 (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
935 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
936 addPredicateUsers(PI, I);
937 return createConstantExpression(cast<Constant>(FirstOp));
938 }
939 }
940 return nullptr;
941}
942
Davide Italiano7e274e02016-12-22 16:03:48 +0000943// Evaluate read only and pure calls, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +0000944const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000945 auto *CI = cast<CallInst>(I);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000946 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
947 // Instrinsics with the returned attribute are copies of arguments.
948 if (auto *ReturnedValue = II->getReturnedArgOperand()) {
949 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
950 if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
951 return Result;
952 return createVariableOrConstant(ReturnedValue);
953 }
954 }
955 if (AA->doesNotAccessMemory(CI)) {
Daniel Berlin97718e62017-01-31 22:32:03 +0000956 return createCallExpression(CI, nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +0000957 } else if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000958 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin97718e62017-01-31 22:32:03 +0000959 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess));
Davide Italianob2225492016-12-27 18:15:39 +0000960 }
961 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000962}
963
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000964// Update the memory access equivalence table to say that From is equal to To,
965// and return true if this is different from what already existed in the table.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000966// FIXME: We need to audit all the places that current set a nullptr To, and fix
967// them. There should always be *some* congruence class, even if it is singular.
968bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, CongruenceClass *To) {
969 DEBUG(dbgs() << "Setting " << *From);
970 if (To) {
971 DEBUG(dbgs() << " equivalent to congruence class ");
972 DEBUG(dbgs() << To->ID << " with current memory access leader ");
973 DEBUG(dbgs() << *To->RepMemoryAccess);
974 } else {
975 DEBUG(dbgs() << " equivalent to itself");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000976 }
Daniel Berlin9f376b72017-01-29 10:26:03 +0000977 DEBUG(dbgs() << "\n");
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000978
979 auto LookupResult = MemoryAccessToClass.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000980 bool Changed = false;
981 // If it's already in the table, see if the value changed.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000982 if (LookupResult != MemoryAccessToClass.end()) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000983 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000984 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000985 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000986 Changed = true;
987 } else if (!To) {
988 // It used to be equivalent to something, and now it's not.
Daniel Berlin1ea5f322017-01-26 22:21:48 +0000989 MemoryAccessToClass.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000990 Changed = true;
991 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000992 } else {
993 assert(!To &&
994 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000995 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000996
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000997 return Changed;
998}
Davide Italiano7e274e02016-12-22 16:03:48 +0000999// Evaluate PHI nodes symbolically, and create an expression result.
Daniel Berlin97718e62017-01-31 22:32:03 +00001000const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001001 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +00001002 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1003
1004 // See if all arguaments are the same.
1005 // We track if any were undef because they need special handling.
1006 bool HasUndef = false;
1007 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1008 if (Arg == I)
1009 return false;
1010 if (isa<UndefValue>(Arg)) {
1011 HasUndef = true;
1012 return false;
1013 }
1014 return true;
1015 });
1016 // If we are left with no operands, it's undef
1017 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001018 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1019 << "\n");
1020 E->deallocateOperands(ArgRecycler);
1021 ExpressionAllocator.Deallocate(E);
1022 return createConstantExpression(UndefValue::get(I->getType()));
1023 }
Daniel Berlind92e7f92017-01-07 00:01:42 +00001024 Value *AllSameValue = *(Filtered.begin());
1025 ++Filtered.begin();
1026 // Can't use std::equal here, sadly, because filter.begin moves.
1027 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
1028 return V == AllSameValue;
1029 })) {
1030 // In LLVM's non-standard representation of phi nodes, it's possible to have
1031 // phi nodes with cycles (IE dependent on other phis that are .... dependent
1032 // on the original phi node), especially in weird CFG's where some arguments
1033 // are unreachable, or uninitialized along certain paths. This can cause
1034 // infinite loops during evaluation. We work around this by not trying to
1035 // really evaluate them independently, but instead using a variable
1036 // expression to say if one is equivalent to the other.
1037 // We also special case undef, so that if we have an undef, we can't use the
1038 // common value unless it dominates the phi block.
1039 if (HasUndef) {
1040 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +00001041 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +00001042 if (!DT->dominates(AllSameInst, I))
1043 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001044 }
1045
Davide Italiano7e274e02016-12-22 16:03:48 +00001046 NumGVNPhisAllSame++;
1047 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1048 << "\n");
1049 E->deallocateOperands(ArgRecycler);
1050 ExpressionAllocator.Deallocate(E);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001051 return createVariableOrConstant(AllSameValue);
Davide Italiano7e274e02016-12-22 16:03:48 +00001052 }
1053 return E;
1054}
1055
Daniel Berlin97718e62017-01-31 22:32:03 +00001056const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001057 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1058 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1059 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1060 unsigned Opcode = 0;
1061 // EI might be an extract from one of our recognised intrinsics. If it
1062 // is we'll synthesize a semantically equivalent expression instead on
1063 // an extract value expression.
1064 switch (II->getIntrinsicID()) {
1065 case Intrinsic::sadd_with_overflow:
1066 case Intrinsic::uadd_with_overflow:
1067 Opcode = Instruction::Add;
1068 break;
1069 case Intrinsic::ssub_with_overflow:
1070 case Intrinsic::usub_with_overflow:
1071 Opcode = Instruction::Sub;
1072 break;
1073 case Intrinsic::smul_with_overflow:
1074 case Intrinsic::umul_with_overflow:
1075 Opcode = Instruction::Mul;
1076 break;
1077 default:
1078 break;
1079 }
1080
1081 if (Opcode != 0) {
1082 // Intrinsic recognized. Grab its args to finish building the
1083 // expression.
1084 assert(II->getNumArgOperands() == 2 &&
1085 "Expect two args for recognised intrinsics.");
Daniel Berlinb79f5362017-02-11 12:48:50 +00001086 return createBinaryExpression(
1087 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
Davide Italiano7e274e02016-12-22 16:03:48 +00001088 }
1089 }
1090 }
1091
Daniel Berlin97718e62017-01-31 22:32:03 +00001092 return createAggregateValueExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001093}
Daniel Berlin97718e62017-01-31 22:32:03 +00001094const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001095 auto *CI = dyn_cast<CmpInst>(I);
1096 // See if our operands are equal to those of a previous predicate, and if so,
1097 // if it implies true or false.
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001098 auto Op0 = lookupOperandLeader(CI->getOperand(0));
1099 auto Op1 = lookupOperandLeader(CI->getOperand(1));
Daniel Berlinf7d95802017-02-18 23:06:50 +00001100 auto OurPredicate = CI->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001101 if (shouldSwapOperands(Op0, Op1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001102 std::swap(Op0, Op1);
1103 OurPredicate = CI->getSwappedPredicate();
1104 }
1105
1106 // Avoid processing the same info twice
1107 const PredicateBase *LastPredInfo = nullptr;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001108 // See if we know something about the comparison itself, like it is the target
1109 // of an assume.
1110 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1111 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1112 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1113
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001114 if (Op0 == Op1) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001115 // This condition does not depend on predicates, no need to add users
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001116 if (CI->isTrueWhenEqual())
1117 return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1118 else if (CI->isFalseWhenEqual())
1119 return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1120 }
Daniel Berlinf7d95802017-02-18 23:06:50 +00001121
1122 // NOTE: Because we are comparing both operands here and below, and using
1123 // previous comparisons, we rely on fact that predicateinfo knows to mark
1124 // comparisons that use renamed operands as users of the earlier comparisons.
1125 // It is *not* enough to just mark predicateinfo renamed operands as users of
1126 // the earlier comparisons, because the *other* operand may have changed in a
1127 // previous iteration.
1128 // Example:
1129 // icmp slt %a, %b
1130 // %b.0 = ssa.copy(%b)
1131 // false branch:
1132 // icmp slt %c, %b.0
1133
1134 // %c and %a may start out equal, and thus, the code below will say the second
1135 // %icmp is false. c may become equal to something else, and in that case the
1136 // %second icmp *must* be reexamined, but would not if only the renamed
1137 // %operands are considered users of the icmp.
1138
1139 // *Currently* we only check one level of comparisons back, and only mark one
1140 // level back as touched when changes appen . If you modify this code to look
1141 // back farther through comparisons, you *must* mark the appropriate
1142 // comparisons as users in PredicateInfo.cpp, or you will cause bugs. See if
1143 // we know something just from the operands themselves
1144
1145 // See if our operands have predicate info, so that we may be able to derive
1146 // something from a previous comparison.
1147 for (const auto &Op : CI->operands()) {
1148 auto *PI = PredInfo->getPredicateInfoFor(Op);
1149 if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1150 if (PI == LastPredInfo)
1151 continue;
1152 LastPredInfo = PI;
Daniel Berlinfccbda92017-02-22 22:20:58 +00001153
Daniel Berlinf7d95802017-02-18 23:06:50 +00001154 // TODO: Along the false edge, we may know more things too, like icmp of
1155 // same operands is false.
1156 // TODO: We only handle actual comparison conditions below, not and/or.
1157 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1158 if (!BranchCond)
1159 continue;
1160 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1161 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1162 auto BranchPredicate = BranchCond->getPredicate();
Daniel Berlin0350a872017-03-04 00:44:43 +00001163 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
Daniel Berlinf7d95802017-02-18 23:06:50 +00001164 std::swap(BranchOp0, BranchOp1);
1165 BranchPredicate = BranchCond->getSwappedPredicate();
1166 }
1167 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1168 if (PBranch->TrueEdge) {
1169 // If we know the previous predicate is true and we are in the true
1170 // edge then we may be implied true or false.
1171 if (CmpInst::isImpliedTrueByMatchingCmp(OurPredicate,
1172 BranchPredicate)) {
1173 addPredicateUsers(PI, I);
1174 return createConstantExpression(
1175 ConstantInt::getTrue(CI->getType()));
1176 }
1177
1178 if (CmpInst::isImpliedFalseByMatchingCmp(OurPredicate,
1179 BranchPredicate)) {
1180 addPredicateUsers(PI, I);
1181 return createConstantExpression(
1182 ConstantInt::getFalse(CI->getType()));
1183 }
1184
1185 } else {
1186 // Just handle the ne and eq cases, where if we have the same
1187 // operands, we may know something.
1188 if (BranchPredicate == OurPredicate) {
1189 addPredicateUsers(PI, I);
1190 // Same predicate, same ops,we know it was false, so this is false.
1191 return createConstantExpression(
1192 ConstantInt::getFalse(CI->getType()));
1193 } else if (BranchPredicate ==
1194 CmpInst::getInversePredicate(OurPredicate)) {
1195 addPredicateUsers(PI, I);
1196 // Inverse predicate, we know the other was false, so this is true.
1197 // FIXME: Double check this
1198 return createConstantExpression(
1199 ConstantInt::getTrue(CI->getType()));
1200 }
1201 }
1202 }
1203 }
1204 }
1205 // Create expression will take care of simplifyCmpInst
Daniel Berlin97718e62017-01-31 22:32:03 +00001206 return createExpression(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001207}
Davide Italiano7e274e02016-12-22 16:03:48 +00001208
1209// Substitute and symbolize the value before value numbering.
Daniel Berlin97718e62017-01-31 22:32:03 +00001210const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001211 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001212 if (auto *C = dyn_cast<Constant>(V))
1213 E = createConstantExpression(C);
1214 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1215 E = createVariableExpression(V);
1216 } else {
1217 // TODO: memory intrinsics.
1218 // TODO: Some day, we should do the forward propagation and reassociation
1219 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001220 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001221 switch (I->getOpcode()) {
1222 case Instruction::ExtractValue:
1223 case Instruction::InsertValue:
Daniel Berlin97718e62017-01-31 22:32:03 +00001224 E = performSymbolicAggrValueEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001225 break;
1226 case Instruction::PHI:
Daniel Berlin97718e62017-01-31 22:32:03 +00001227 E = performSymbolicPHIEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001228 break;
1229 case Instruction::Call:
Daniel Berlin97718e62017-01-31 22:32:03 +00001230 E = performSymbolicCallEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001231 break;
1232 case Instruction::Store:
Daniel Berlin97718e62017-01-31 22:32:03 +00001233 E = performSymbolicStoreEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001234 break;
1235 case Instruction::Load:
Daniel Berlin97718e62017-01-31 22:32:03 +00001236 E = performSymbolicLoadEvaluation(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001237 break;
1238 case Instruction::BitCast: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001239 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001240 } break;
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001241 case Instruction::ICmp:
1242 case Instruction::FCmp: {
Daniel Berlin97718e62017-01-31 22:32:03 +00001243 E = performSymbolicCmpEvaluation(I);
Daniel Berlinc22aafe2017-01-31 22:31:58 +00001244 } break;
Davide Italiano7e274e02016-12-22 16:03:48 +00001245 case Instruction::Add:
1246 case Instruction::FAdd:
1247 case Instruction::Sub:
1248 case Instruction::FSub:
1249 case Instruction::Mul:
1250 case Instruction::FMul:
1251 case Instruction::UDiv:
1252 case Instruction::SDiv:
1253 case Instruction::FDiv:
1254 case Instruction::URem:
1255 case Instruction::SRem:
1256 case Instruction::FRem:
1257 case Instruction::Shl:
1258 case Instruction::LShr:
1259 case Instruction::AShr:
1260 case Instruction::And:
1261 case Instruction::Or:
1262 case Instruction::Xor:
Davide Italiano7e274e02016-12-22 16:03:48 +00001263 case Instruction::Trunc:
1264 case Instruction::ZExt:
1265 case Instruction::SExt:
1266 case Instruction::FPToUI:
1267 case Instruction::FPToSI:
1268 case Instruction::UIToFP:
1269 case Instruction::SIToFP:
1270 case Instruction::FPTrunc:
1271 case Instruction::FPExt:
1272 case Instruction::PtrToInt:
1273 case Instruction::IntToPtr:
1274 case Instruction::Select:
1275 case Instruction::ExtractElement:
1276 case Instruction::InsertElement:
1277 case Instruction::ShuffleVector:
1278 case Instruction::GetElementPtr:
Daniel Berlin97718e62017-01-31 22:32:03 +00001279 E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001280 break;
1281 default:
1282 return nullptr;
1283 }
1284 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001285 return E;
1286}
1287
Davide Italiano7e274e02016-12-22 16:03:48 +00001288void NewGVN::markUsersTouched(Value *V) {
1289 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001290 for (auto *User : V->users()) {
1291 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Daniel Berlinaac56842017-01-15 09:18:41 +00001292 TouchedInstructions.set(InstrDFS.lookup(User));
Davide Italiano7e274e02016-12-22 16:03:48 +00001293 }
1294}
1295
1296void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1297 for (auto U : MA->users()) {
1298 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
Daniel Berlinaac56842017-01-15 09:18:41 +00001299 TouchedInstructions.set(InstrDFS.lookup(MUD->getMemoryInst()));
Davide Italiano7e274e02016-12-22 16:03:48 +00001300 else
Daniel Berlinaac56842017-01-15 09:18:41 +00001301 TouchedInstructions.set(InstrDFS.lookup(U));
Davide Italiano7e274e02016-12-22 16:03:48 +00001302 }
1303}
1304
Daniel Berlinf7d95802017-02-18 23:06:50 +00001305// Add I to the set of users of a given predicate.
1306void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1307 if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1308 PredicateToUsers[PBranch->Condition].insert(I);
1309 else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1310 PredicateToUsers[PAssume->Condition].insert(I);
1311}
1312
1313// Touch all the predicates that depend on this instruction.
1314void NewGVN::markPredicateUsersTouched(Instruction *I) {
1315 const auto Result = PredicateToUsers.find(I);
1316 if (Result != PredicateToUsers.end())
1317 for (auto *User : Result->second)
1318 TouchedInstructions.set(InstrDFS.lookup(User));
1319}
1320
Daniel Berlin32f8d562017-01-07 16:55:14 +00001321// Touch the instructions that need to be updated after a congruence class has a
1322// leader change, and mark changed values.
1323void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1324 for (auto M : CC->Members) {
1325 if (auto *I = dyn_cast<Instruction>(M))
Daniel Berlinaac56842017-01-15 09:18:41 +00001326 TouchedInstructions.set(InstrDFS.lookup(I));
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001327 LeaderChanges.insert(M);
1328 }
1329}
1330
1331// Move a value, currently in OldClass, to be part of NewClass
1332// Update OldClass for the move (including changing leaders, etc)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001333void NewGVN::moveValueToNewCongruenceClass(Instruction *I,
1334 CongruenceClass *OldClass,
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001335 CongruenceClass *NewClass) {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001336 DEBUG(dbgs() << "New congruence class for " << I << " is " << NewClass->ID
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001337 << "\n");
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001338
1339 if (I == OldClass->NextLeader.first)
1340 OldClass->NextLeader = {nullptr, ~0U};
1341
Daniel Berlin89fea6f2017-01-20 06:38:41 +00001342 // It's possible, though unlikely, for us to discover equivalences such
1343 // that the current leader does not dominate the old one.
1344 // This statistic tracks how often this happens.
1345 // We assert on phi nodes when this happens, currently, for debugging, because
1346 // we want to make sure we name phi node cycles properly.
1347 if (isa<Instruction>(NewClass->RepLeader) && NewClass->RepLeader &&
1348 I != NewClass->RepLeader &&
1349 DT->properlyDominates(
1350 I->getParent(),
1351 cast<Instruction>(NewClass->RepLeader)->getParent())) {
1352 ++NumGVNNotMostDominatingLeader;
1353 assert(!isa<PHINode>(I) &&
1354 "New class for instruction should not be dominated by instruction");
1355 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001356
1357 if (NewClass->RepLeader != I) {
1358 auto DFSNum = InstrDFS.lookup(I);
1359 if (DFSNum < NewClass->NextLeader.second)
1360 NewClass->NextLeader = {I, DFSNum};
1361 }
1362
1363 OldClass->Members.erase(I);
1364 NewClass->Members.insert(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001365 MemoryAccess *StoreAccess = nullptr;
1366 if (auto *SI = dyn_cast<StoreInst>(I)) {
1367 StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001368 --OldClass->StoreCount;
Davide Italiano0dc68bf2017-01-11 22:00:29 +00001369 assert(OldClass->StoreCount >= 0);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001370 ++NewClass->StoreCount;
Davide Italianoeac05f62017-01-11 23:41:24 +00001371 assert(NewClass->StoreCount > 0);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001372 if (!NewClass->RepMemoryAccess) {
1373 // If we don't have a representative memory access, it better be the only
1374 // store in there.
1375 assert(NewClass->StoreCount == 1);
1376 NewClass->RepMemoryAccess = StoreAccess;
1377 }
1378 setMemoryAccessEquivTo(StoreAccess, NewClass);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001379 }
1380
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001381 ValueToClass[I] = NewClass;
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001382 // See if we destroyed the class or need to swap leaders.
1383 if (OldClass->Members.empty() && OldClass != InitialClass) {
1384 if (OldClass->DefiningExpr) {
1385 OldClass->Dead = true;
1386 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1387 << " from table\n");
1388 ExpressionToClass.erase(OldClass->DefiningExpr);
1389 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001390 } else if (OldClass->RepLeader == I) {
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001391 // When the leader changes, the value numbering of
1392 // everything may change due to symbolization changes, so we need to
1393 // reprocess.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001394 DEBUG(dbgs() << "Leader change!\n");
1395 ++NumGVNLeaderChanges;
Daniel Berlin26addef2017-01-20 21:04:30 +00001396 // Destroy the stored value if there are no more stores to represent it.
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001397 if (OldClass->StoreCount == 0) {
1398 if (OldClass->RepStoredValue != nullptr)
1399 OldClass->RepStoredValue = nullptr;
1400 if (OldClass->RepMemoryAccess != nullptr)
1401 OldClass->RepMemoryAccess = nullptr;
1402 }
1403
1404 // If we destroy the old access leader, we have to effectively destroy the
1405 // congruence class. When it comes to scalars, anything with the same value
1406 // is as good as any other. That means that one leader is as good as
1407 // another, and as long as you have some leader for the value, you are
1408 // good.. When it comes to *memory states*, only one particular thing really
1409 // represents the definition of a given memory state. Once it goes away, we
1410 // need to re-evaluate which pieces of memory are really still
1411 // equivalent. The best way to do this is to re-value number things. The
1412 // only way to really make that happen is to destroy the rest of the class.
1413 // In order to effectively destroy the class, we reset ExpressionToClass for
1414 // each by using the ValueToExpression mapping. The members later get
1415 // marked as touched due to the leader change. We will create new
1416 // congruence classes, and the pieces that are still equivalent will end
1417 // back together in a new class. If this becomes too expensive, it is
1418 // possible to use a versioning scheme for the congruence classes to avoid
1419 // the expressions finding this old class.
1420 if (OldClass->StoreCount > 0 && OldClass->RepMemoryAccess == StoreAccess) {
1421 DEBUG(dbgs() << "Kicking everything out of class " << OldClass->ID
1422 << " because memory access leader changed");
1423 for (auto Member : OldClass->Members)
1424 ExpressionToClass.erase(ValueToExpression.lookup(Member));
1425 }
Daniel Berlin26addef2017-01-20 21:04:30 +00001426
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001427 // 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 +00001428 // sorting the INITIAL class because everything either gets out of it or is
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001429 // unreachable.
1430 if (OldClass->Members.size() == 1 || OldClass == InitialClass) {
1431 OldClass->RepLeader = *(OldClass->Members.begin());
1432 } else if (OldClass->NextLeader.first) {
1433 ++NumGVNAvoidedSortedLeaderChanges;
1434 OldClass->RepLeader = OldClass->NextLeader.first;
1435 OldClass->NextLeader = {nullptr, ~0U};
1436 } else {
1437 ++NumGVNSortedLeaderChanges;
1438 // TODO: If this ends up to slow, we can maintain a dual structure for
1439 // member testing/insertion, or keep things mostly sorted, and sort only
1440 // here, or ....
1441 std::pair<Value *, unsigned> MinDFS = {nullptr, ~0U};
1442 for (const auto X : OldClass->Members) {
1443 auto DFSNum = InstrDFS.lookup(X);
1444 if (DFSNum < MinDFS.second)
1445 MinDFS = {X, DFSNum};
1446 }
1447 OldClass->RepLeader = MinDFS.first;
1448 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001449 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001450 }
1451}
1452
Davide Italiano7e274e02016-12-22 16:03:48 +00001453// Perform congruence finding on a given value numbering expression.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001454void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
1455 ValueToExpression[I] = E;
Davide Italiano7e274e02016-12-22 16:03:48 +00001456 // This is guaranteed to return something, since it will at least find
Daniel Berlinb79f5362017-02-11 12:48:50 +00001457 // TOP.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001458
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001459 CongruenceClass *IClass = ValueToClass[I];
1460 assert(IClass && "Should have found a IClass");
Davide Italiano7e274e02016-12-22 16:03:48 +00001461 // Dead classes should have been eliminated from the mapping.
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001462 assert(!IClass->Dead && "Found a dead class");
Davide Italiano7e274e02016-12-22 16:03:48 +00001463
1464 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001465 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001466 EClass = ValueToClass[VE->getVariableValue()];
1467 } else {
1468 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1469
1470 // If it's not in the value table, create a new congruence class.
1471 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001472 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001473 auto place = lookupResult.first;
1474 place->second = NewClass;
1475
1476 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001477 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001478 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001479 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1480 StoreInst *SI = SE->getStoreInst();
Daniel Berlin26addef2017-01-20 21:04:30 +00001481 NewClass->RepLeader = SI;
Daniel Berlin808e3ff2017-01-31 22:31:56 +00001482 NewClass->RepStoredValue = lookupOperandLeader(SI->getValueOperand());
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001483 // The RepMemoryAccess field will be filled in properly by the
1484 // moveValueToNewCongruenceClass call.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001485 } else {
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001486 NewClass->RepLeader = I;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001487 }
1488 assert(!isa<VariableExpression>(E) &&
1489 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001490
1491 EClass = NewClass;
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001492 DEBUG(dbgs() << "Created new congruence class for " << *I
Davide Italiano7e274e02016-12-22 16:03:48 +00001493 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin26addef2017-01-20 21:04:30 +00001494 << " and leader " << *(NewClass->RepLeader));
1495 if (NewClass->RepStoredValue)
1496 DEBUG(dbgs() << " and stored value " << *(NewClass->RepStoredValue));
1497 DEBUG(dbgs() << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001498 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1499 } else {
1500 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001501 if (isa<ConstantExpression>(E))
1502 assert(isa<Constant>(EClass->RepLeader) &&
1503 "Any class with a constant expression should have a "
1504 "constant leader");
1505
Davide Italiano7e274e02016-12-22 16:03:48 +00001506 assert(EClass && "Somehow don't have an eclass");
1507
1508 assert(!EClass->Dead && "We accidentally looked up a dead class");
1509 }
1510 }
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001511 bool ClassChanged = IClass != EClass;
1512 bool LeaderChanged = LeaderChanges.erase(I);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001513 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001514 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1515 << "\n");
1516
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001517 if (ClassChanged)
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001518 moveValueToNewCongruenceClass(I, IClass, EClass);
1519 markUsersTouched(I);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001520 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
Daniel Berlinc0431fd2017-01-13 22:40:01 +00001521 markMemoryUsersTouched(MA);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001522 if (auto *CI = dyn_cast<CmpInst>(I))
1523 markPredicateUsersTouched(CI);
Davide Italiano7e274e02016-12-22 16:03:48 +00001524 }
1525}
1526
1527// Process the fact that Edge (from, to) is reachable, including marking
1528// any newly reachable blocks and instructions for processing.
1529void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1530 // Check if the Edge was reachable before.
1531 if (ReachableEdges.insert({From, To}).second) {
1532 // If this block wasn't reachable before, all instructions are touched.
1533 if (ReachableBlocks.insert(To).second) {
1534 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1535 const auto &InstRange = BlockInstRange.lookup(To);
1536 TouchedInstructions.set(InstRange.first, InstRange.second);
1537 } else {
1538 DEBUG(dbgs() << "Block " << getBlockName(To)
1539 << " was reachable, but new edge {" << getBlockName(From)
1540 << "," << getBlockName(To) << "} to it found\n");
1541
1542 // We've made an edge reachable to an existing block, which may
1543 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1544 // they are the only thing that depend on new edges. Anything using their
1545 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001546 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
Daniel Berlinaac56842017-01-15 09:18:41 +00001547 TouchedInstructions.set(InstrDFS.lookup(MemPhi));
Daniel Berlin589cecc2017-01-02 18:00:46 +00001548
Davide Italiano7e274e02016-12-22 16:03:48 +00001549 auto BI = To->begin();
1550 while (isa<PHINode>(BI)) {
Daniel Berlinaac56842017-01-15 09:18:41 +00001551 TouchedInstructions.set(InstrDFS.lookup(&*BI));
Davide Italiano7e274e02016-12-22 16:03:48 +00001552 ++BI;
1553 }
1554 }
1555 }
1556}
1557
1558// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1559// see if we know some constant value for it already.
Daniel Berlin97718e62017-01-31 22:32:03 +00001560Value *NewGVN::findConditionEquivalence(Value *Cond) const {
Daniel Berlin203f47b2017-01-31 22:31:53 +00001561 auto Result = lookupOperandLeader(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001562 if (isa<Constant>(Result))
1563 return Result;
1564 return nullptr;
1565}
1566
1567// Process the outgoing edges of a block for reachability.
1568void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1569 // Evaluate reachability of terminator instruction.
1570 BranchInst *BR;
1571 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1572 Value *Cond = BR->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001573 Value *CondEvaluated = findConditionEquivalence(Cond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001574 if (!CondEvaluated) {
1575 if (auto *I = dyn_cast<Instruction>(Cond)) {
Daniel Berlin97718e62017-01-31 22:32:03 +00001576 const Expression *E = createExpression(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001577 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1578 CondEvaluated = CE->getConstantValue();
1579 }
1580 } else if (isa<ConstantInt>(Cond)) {
1581 CondEvaluated = Cond;
1582 }
1583 }
1584 ConstantInt *CI;
1585 BasicBlock *TrueSucc = BR->getSuccessor(0);
1586 BasicBlock *FalseSucc = BR->getSuccessor(1);
1587 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1588 if (CI->isOne()) {
1589 DEBUG(dbgs() << "Condition for Terminator " << *TI
1590 << " evaluated to true\n");
1591 updateReachableEdge(B, TrueSucc);
1592 } else if (CI->isZero()) {
1593 DEBUG(dbgs() << "Condition for Terminator " << *TI
1594 << " evaluated to false\n");
1595 updateReachableEdge(B, FalseSucc);
1596 }
1597 } else {
1598 updateReachableEdge(B, TrueSucc);
1599 updateReachableEdge(B, FalseSucc);
1600 }
1601 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1602 // For switches, propagate the case values into the case
1603 // destinations.
1604
1605 // Remember how many outgoing edges there are to every successor.
1606 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1607
Davide Italiano7e274e02016-12-22 16:03:48 +00001608 Value *SwitchCond = SI->getCondition();
Daniel Berlin97718e62017-01-31 22:32:03 +00001609 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
Davide Italiano7e274e02016-12-22 16:03:48 +00001610 // See if we were able to turn this switch statement into a constant.
1611 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001612 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001613 // We should be able to get case value for this.
1614 auto CaseVal = SI->findCaseValue(CondVal);
1615 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1616 // We proved the value is outside of the range of the case.
1617 // We can't do anything other than mark the default dest as reachable,
1618 // and go home.
1619 updateReachableEdge(B, SI->getDefaultDest());
1620 return;
1621 }
1622 // Now get where it goes and mark it reachable.
1623 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1624 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001625 } else {
1626 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1627 BasicBlock *TargetBlock = SI->getSuccessor(i);
1628 ++SwitchEdges[TargetBlock];
1629 updateReachableEdge(B, TargetBlock);
1630 }
1631 }
1632 } else {
1633 // Otherwise this is either unconditional, or a type we have no
1634 // idea about. Just mark successors as reachable.
1635 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1636 BasicBlock *TargetBlock = TI->getSuccessor(i);
1637 updateReachableEdge(B, TargetBlock);
1638 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001639
1640 // This also may be a memory defining terminator, in which case, set it
1641 // equivalent to nothing.
1642 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1643 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001644 }
1645}
1646
Daniel Berlin85f91b02016-12-26 20:06:58 +00001647// The algorithm initially places the values of the routine in the INITIAL
Daniel Berlinb79f5362017-02-11 12:48:50 +00001648// congruence class. The leader of INITIAL is the undetermined value `TOP`.
Davide Italiano7e274e02016-12-22 16:03:48 +00001649// When the algorithm has finished, values still in INITIAL are unreachable.
1650void NewGVN::initializeCongruenceClasses(Function &F) {
1651 // FIXME now i can't remember why this is 2
1652 NextCongruenceNum = 2;
1653 // Initialize all other instructions to be in INITIAL class.
1654 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001655 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001656 InitialClass->RepMemoryAccess = MSSA->getLiveOnEntryDef();
Daniel Berlin589cecc2017-01-02 18:00:46 +00001657 for (auto &B : F) {
1658 if (auto *MP = MSSA->getMemoryAccess(&B))
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001659 MemoryAccessToClass[MP] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001660
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001661 for (auto &I : B) {
Daniel Berlin22a4a012017-02-11 15:20:15 +00001662 // Don't insert void terminators into the class. We don't value number
1663 // them, and they just end up sitting in INITIAL.
1664 if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
1665 continue;
1666 InitialValues.insert(&I);
1667 ValueToClass[&I] = InitialClass;
1668
Daniel Berlin589cecc2017-01-02 18:00:46 +00001669 // All memory accesses are equivalent to live on entry to start. They must
1670 // be initialized to something so that initial changes are noticed. For
1671 // the maximal answer, we initialize them all to be the same as
1672 // liveOnEntry. Note that to save time, we only initialize the
1673 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1674 // other expression can generate a memory equivalence. If we start
1675 // handling memcpy/etc, we can expand this.
Davide Italianoeac05f62017-01-11 23:41:24 +00001676 if (isa<StoreInst>(&I)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001677 MemoryAccessToClass[MSSA->getMemoryAccess(&I)] = InitialClass;
Davide Italianoeac05f62017-01-11 23:41:24 +00001678 ++InitialClass->StoreCount;
1679 assert(InitialClass->StoreCount > 0);
1680 }
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001681 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001682 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001683 InitialClass->Members.swap(InitialValues);
1684
1685 // Initialize arguments to be in their own unique congruence classes
1686 for (auto &FA : F.args())
1687 createSingletonCongruenceClass(&FA);
1688}
1689
1690void NewGVN::cleanupTables() {
1691 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1692 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1693 << CongruenceClasses[i]->Members.size() << " members\n");
1694 // Make sure we delete the congruence class (probably worth switching to
1695 // a unique_ptr at some point.
1696 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001697 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001698 }
1699
1700 ValueToClass.clear();
1701 ArgRecycler.clear(ExpressionAllocator);
1702 ExpressionAllocator.Reset();
1703 CongruenceClasses.clear();
1704 ExpressionToClass.clear();
1705 ValueToExpression.clear();
1706 ReachableBlocks.clear();
1707 ReachableEdges.clear();
1708#ifndef NDEBUG
1709 ProcessedCount.clear();
1710#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001711 InstrDFS.clear();
1712 InstructionsToErase.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001713 DFSToInstr.clear();
1714 BlockInstRange.clear();
1715 TouchedInstructions.clear();
1716 DominatedInstRange.clear();
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001717 MemoryAccessToClass.clear();
Daniel Berlinf7d95802017-02-18 23:06:50 +00001718 PredicateToUsers.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001719}
1720
1721std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1722 unsigned Start) {
1723 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001724 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1725 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001726 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001727 }
1728
Davide Italiano7e274e02016-12-22 16:03:48 +00001729 for (auto &I : *B) {
Daniel Berlin856fa142017-03-06 18:42:27 +00001730 // There's no need to call isInstructionTriviallyDead more than once on
1731 // an instruction. Therefore, once we know that an instruction is dead
1732 // we change its DFS number so that it doesn't get value numbered.
1733 if (isInstructionTriviallyDead(&I, TLI)) {
1734 InstrDFS[&I] = 0;
1735 DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
1736 markInstructionForDeletion(&I);
1737 continue;
1738 }
1739
Davide Italiano7e274e02016-12-22 16:03:48 +00001740 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001741 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001742 }
1743
1744 // All of the range functions taken half-open ranges (open on the end side).
1745 // So we do not subtract one from count, because at this point it is one
1746 // greater than the last instruction.
1747 return std::make_pair(Start, End);
1748}
1749
1750void NewGVN::updateProcessedCount(Value *V) {
1751#ifndef NDEBUG
1752 if (ProcessedCount.count(V) == 0) {
1753 ProcessedCount.insert({V, 1});
1754 } else {
Davide Italiano7cf29dc2017-01-14 20:13:18 +00001755 ++ProcessedCount[V];
Davide Italiano7e274e02016-12-22 16:03:48 +00001756 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001757 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001758 }
1759#endif
1760}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001761// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1762void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1763 // If all the arguments are the same, the MemoryPhi has the same value as the
1764 // argument.
Daniel Berlinc4796862017-01-27 02:37:11 +00001765 // Filter out unreachable blocks and self phis from our operands.
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001766 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
Daniel Berlinc4796862017-01-27 02:37:11 +00001767 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U)) != MP &&
1768 !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
1769 ReachableBlocks.count(MP->getIncomingBlock(U));
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001770 });
Daniel Berlinc4796862017-01-27 02:37:11 +00001771 // If all that is left is nothing, our memoryphi is undef. We keep it as
1772 // InitialClass. Note: The only case this should happen is if we have at
1773 // least one self-argument.
1774 if (Filtered.begin() == Filtered.end()) {
1775 if (setMemoryAccessEquivTo(MP, InitialClass))
1776 markMemoryUsersTouched(MP);
1777 return;
1778 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001779
1780 // Transform the remaining operands into operand leaders.
1781 // FIXME: mapped_iterator should have a range version.
1782 auto LookupFunc = [&](const Use &U) {
1783 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1784 };
1785 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1786 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1787
1788 // and now check if all the elements are equal.
1789 // Sadly, we can't use std::equals since these are random access iterators.
1790 MemoryAccess *AllSameValue = *MappedBegin;
1791 ++MappedBegin;
1792 bool AllEqual = std::all_of(
1793 MappedBegin, MappedEnd,
1794 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1795
1796 if (AllEqual)
1797 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1798 else
1799 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1800
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001801 if (setMemoryAccessEquivTo(
1802 MP, AllEqual ? MemoryAccessToClass.lookup(AllSameValue) : nullptr))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001803 markMemoryUsersTouched(MP);
1804}
1805
1806// Value number a single instruction, symbolically evaluating, performing
1807// congruence finding, and updating mappings.
1808void NewGVN::valueNumberInstruction(Instruction *I) {
1809 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001810 if (!I->isTerminator()) {
Daniel Berlin283a6082017-03-01 19:59:26 +00001811 const Expression *Symbolized = nullptr;
1812 if (DebugCounter::shouldExecute(VNCounter)) {
1813 Symbolized = performSymbolicEvaluation(I);
1814 } else {
Daniel Berlin343576a2017-03-06 18:42:39 +00001815 // Mark the instruction as unused so we don't value number it again.
1816 InstrDFS[I] = 0;
Daniel Berlin283a6082017-03-01 19:59:26 +00001817 }
Daniel Berlin02c6b172017-01-02 18:00:53 +00001818 // If we couldn't come up with a symbolic expression, use the unknown
1819 // expression
1820 if (Symbolized == nullptr)
1821 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001822 performCongruenceFinding(I, Symbolized);
1823 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001824 // Handle terminators that return values. All of them produce values we
Daniel Berlinb79f5362017-02-11 12:48:50 +00001825 // don't currently understand. We don't place non-value producing
1826 // terminators in a class.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001827 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001828 auto *Symbolized = createUnknownExpression(I);
1829 performCongruenceFinding(I, Symbolized);
1830 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001831 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1832 }
1833}
Davide Italiano7e274e02016-12-22 16:03:48 +00001834
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001835// Check if there is a path, using single or equal argument phi nodes, from
1836// First to Second.
1837bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
1838 const MemoryAccess *Second) const {
1839 if (First == Second)
1840 return true;
1841
1842 if (auto *FirstDef = dyn_cast<MemoryUseOrDef>(First)) {
1843 auto *DefAccess = FirstDef->getDefiningAccess();
1844 return singleReachablePHIPath(DefAccess, Second);
1845 } else {
1846 auto *MP = cast<MemoryPhi>(First);
1847 auto ReachableOperandPred = [&](const Use &U) {
1848 return ReachableBlocks.count(MP->getIncomingBlock(U));
1849 };
1850 auto FilteredPhiArgs =
1851 make_filter_range(MP->operands(), ReachableOperandPred);
1852 SmallVector<const Value *, 32> OperandList;
1853 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1854 std::back_inserter(OperandList));
1855 bool Okay = OperandList.size() == 1;
1856 if (!Okay)
1857 Okay = std::equal(OperandList.begin(), OperandList.end(),
1858 OperandList.begin());
1859 if (Okay)
1860 return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
1861 return false;
1862 }
1863}
1864
Daniel Berlin589cecc2017-01-02 18:00:46 +00001865// Verify the that the memory equivalence table makes sense relative to the
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001866// congruence classes. Note that this checking is not perfect, and is currently
Davide Italianoed67f192017-01-14 20:15:04 +00001867// subject to very rare false negatives. It is only useful for
1868// testing/debugging.
Daniel Berlinf6eba4b2017-01-11 20:22:36 +00001869void NewGVN::verifyMemoryCongruency() const {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001870 // Anything equivalent in the memory access table should be in the same
1871 // congruence class.
1872
1873 // Filter out the unreachable and trivially dead entries, because they may
1874 // never have been updated if the instructions were not processed.
1875 auto ReachableAccessPred =
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001876 [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001877 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1878 if (!Result)
1879 return false;
1880 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1881 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1882 return true;
1883 };
1884
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001885 auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001886 for (auto KV : Filtered) {
Daniel Berlin589cecc2017-01-02 18:00:46 +00001887 // Unreachable instructions may not have changed because we never process
1888 // them.
1889 if (!ReachableBlocks.count(KV.first->getBlock()))
1890 continue;
1891 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
Daniel Berlin1ea5f322017-01-26 22:21:48 +00001892 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->RepMemoryAccess);
Davide Italiano67ada752017-01-02 19:03:16 +00001893 if (FirstMUD && SecondMUD)
Davide Italianoff694052017-01-11 21:58:42 +00001894 assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
Davide Italianoed67f192017-01-14 20:15:04 +00001895 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1896 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
1897 "The instructions for these memory operations should have "
1898 "been in the same congruence class or reachable through"
1899 "a single argument phi");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001900 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1901
1902 // We can only sanely verify that MemoryDefs in the operand list all have
1903 // the same class.
1904 auto ReachableOperandPred = [&](const Use &U) {
1905 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1906 isa<MemoryDef>(U);
1907
1908 };
1909 // All arguments should in the same class, ignoring unreachable arguments
1910 auto FilteredPhiArgs =
1911 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1912 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1913 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1914 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1915 const MemoryDef *MD = cast<MemoryDef>(U);
1916 return ValueToClass.lookup(MD->getMemoryInst());
1917 });
1918 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1919 PhiOpClasses.begin()) &&
1920 "All MemoryPhi arguments should be in the same class");
1921 }
1922 }
1923}
1924
Daniel Berlinf7d95802017-02-18 23:06:50 +00001925// Re-evaluate all the comparisons after value numbering and ensure they don't
1926// change. If they changed, we didn't mark them touched properly.
1927void NewGVN::verifyComparisons(Function &F) {
1928#ifndef NDEBUG
1929 for (auto &BB : F) {
1930 if (!ReachableBlocks.count(&BB))
1931 continue;
1932 for (auto &I : BB) {
Daniel Berlin343576a2017-03-06 18:42:39 +00001933 if (InstrDFS.lookup(&I) == 0)
Daniel Berlinf7d95802017-02-18 23:06:50 +00001934 continue;
1935 if (isa<CmpInst>(&I)) {
1936 auto *CurrentVal = ValueToClass.lookup(&I);
1937 valueNumberInstruction(&I);
1938 assert(CurrentVal == ValueToClass.lookup(&I) &&
1939 "Re-evaluating comparison changed value");
1940 }
1941 }
1942 }
1943#endif
1944}
1945
Daniel Berlin85f91b02016-12-26 20:06:58 +00001946// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001947bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001948 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1949 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001950 bool Changed = false;
Daniel Berlin1529bb92017-02-11 15:13:49 +00001951 NumFuncArgs = F.arg_size();
Davide Italiano7e274e02016-12-22 16:03:48 +00001952 DT = _DT;
1953 AC = _AC;
1954 TLI = _TLI;
1955 AA = _AA;
1956 MSSA = _MSSA;
Daniel Berlinf7d95802017-02-18 23:06:50 +00001957 PredInfo = make_unique<PredicateInfo>(F, *DT, *AC);
Davide Italiano7e274e02016-12-22 16:03:48 +00001958 DL = &F.getParent()->getDataLayout();
1959 MSSAWalker = MSSA->getWalker();
1960
1961 // Count number of instructions for sizing of hash tables, and come
1962 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001963 unsigned ICount = 1;
1964 // Add an empty instruction to account for the fact that we start at 1
1965 DFSToInstr.emplace_back(nullptr);
Daniel Berlinf7d95802017-02-18 23:06:50 +00001966 // Note: We want ideal RPO traversal of the blocks, which is not quite the
1967 // same as dominator tree order, particularly with regard whether backedges
1968 // get visited first or second, given a block with multiple successors.
Davide Italiano7e274e02016-12-22 16:03:48 +00001969 // If we visit in the wrong order, we will end up performing N times as many
1970 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001971 // The dominator tree does guarantee that, for a given dom tree node, it's
1972 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1973 // the siblings.
1974 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001975 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001976 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001977 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001978 auto *Node = DT->getNode(B);
1979 assert(Node && "RPO and Dominator tree should have same reachability");
1980 RPOOrdering[Node] = ++Counter;
1981 }
1982 // Sort dominator tree children arrays into RPO.
1983 for (auto &B : RPOT) {
1984 auto *Node = DT->getNode(B);
1985 if (Node->getChildren().size() > 1)
1986 std::sort(Node->begin(), Node->end(),
1987 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1988 return RPOOrdering[A] < RPOOrdering[B];
1989 });
1990 }
1991
1992 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1993 auto DFI = df_begin(DT->getRootNode());
1994 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1995 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001996 const auto &BlockRange = assignDFSNumbers(B, ICount);
1997 BlockInstRange.insert({B, BlockRange});
1998 ICount += BlockRange.second - BlockRange.first;
1999 }
2000
2001 // Handle forward unreachable blocks and figure out which blocks
2002 // have single preds.
2003 for (auto &B : F) {
2004 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00002005 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002006 const auto &BlockRange = assignDFSNumbers(&B, ICount);
2007 BlockInstRange.insert({&B, BlockRange});
2008 ICount += BlockRange.second - BlockRange.first;
2009 }
2010 }
2011
Daniel Berline0bd37e2016-12-29 22:15:12 +00002012 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002013 DominatedInstRange.reserve(F.size());
2014 // Ensure we don't end up resizing the expressionToClass map, as
2015 // that can be quite expensive. At most, we have one expression per
2016 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00002017 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00002018
2019 // Initialize the touched instructions to include the entry block.
2020 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2021 TouchedInstructions.set(InstRange.first, InstRange.second);
2022 ReachableBlocks.insert(&F.getEntryBlock());
2023
2024 initializeCongruenceClasses(F);
2025
Daniel Berlin6cc5e442017-01-04 21:01:02 +00002026 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00002027 // We start out in the entry block.
2028 BasicBlock *LastBlock = &F.getEntryBlock();
2029 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00002030 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00002031 // Walk through all the instructions in all the blocks in RPO.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002032 // TODO: As we hit a new block, we should push and pop equalities into a
2033 // table lookupOperandLeader can use, to catch things PredicateInfo
2034 // might miss, like edge-only equivalences.
Davide Italiano7e274e02016-12-22 16:03:48 +00002035 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2036 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Davide Italiano71f2d9c2017-01-20 23:29:28 +00002037
2038 // This instruction was found to be dead. We don't bother looking
2039 // at it again.
2040 if (InstrNum == 0) {
2041 TouchedInstructions.reset(InstrNum);
2042 continue;
2043 }
2044
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002045 Value *V = DFSToInstr[InstrNum];
2046 BasicBlock *CurrBlock = nullptr;
2047
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002048 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002049 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002050 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002051 CurrBlock = MP->getBlock();
2052 else
2053 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00002054
2055 // If we hit a new block, do reachability processing.
2056 if (CurrBlock != LastBlock) {
2057 LastBlock = CurrBlock;
2058 bool BlockReachable = ReachableBlocks.count(CurrBlock);
2059 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2060
2061 // If it's not reachable, erase any touched instructions and move on.
2062 if (!BlockReachable) {
2063 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2064 DEBUG(dbgs() << "Skipping instructions in block "
2065 << getBlockName(CurrBlock)
2066 << " because it is unreachable\n");
2067 continue;
2068 }
2069 updateProcessedCount(CurrBlock);
2070 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002071
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002072 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002073 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2074 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002075 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002076 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002077 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002078 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00002079 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00002080 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002081 // Reset after processing (because we may mark ourselves as touched when
2082 // we propagate equalities).
2083 TouchedInstructions.reset(InstrNum);
2084 }
2085 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00002086 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002087#ifndef NDEBUG
2088 verifyMemoryCongruency();
Daniel Berlinf7d95802017-02-18 23:06:50 +00002089 verifyComparisons(F);
Daniel Berlin589cecc2017-01-02 18:00:46 +00002090#endif
Daniel Berlinf7d95802017-02-18 23:06:50 +00002091
Davide Italiano7e274e02016-12-22 16:03:48 +00002092 Changed |= eliminateInstructions(F);
2093
2094 // Delete all instructions marked for deletion.
2095 for (Instruction *ToErase : InstructionsToErase) {
2096 if (!ToErase->use_empty())
2097 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2098
2099 ToErase->eraseFromParent();
2100 }
2101
2102 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002103 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2104 return !ReachableBlocks.count(&BB);
2105 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002106
2107 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2108 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00002109 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002110 deleteInstructionsInBlock(&BB);
2111 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00002112 }
2113
2114 cleanupTables();
2115 return Changed;
2116}
2117
2118bool NewGVN::runOnFunction(Function &F) {
2119 if (skipFunction(F))
2120 return false;
2121 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2122 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2123 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2124 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
2125 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
2126}
2127
Daniel Berlin85f91b02016-12-26 20:06:58 +00002128PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002129 NewGVN Impl;
2130
2131 // Apparently the order in which we get these results matter for
2132 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
2133 // the same order here, just in case.
2134 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2135 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2136 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2137 auto &AA = AM.getResult<AAManager>(F);
2138 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2139 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
2140 if (!Changed)
2141 return PreservedAnalyses::all();
2142 PreservedAnalyses PA;
2143 PA.preserve<DominatorTreeAnalysis>();
2144 PA.preserve<GlobalsAA>();
2145 return PA;
2146}
2147
2148// Return true if V is a value that will always be available (IE can
2149// be placed anywhere) in the function. We don't do globals here
2150// because they are often worse to put in place.
2151// TODO: Separate cost from availability
2152static bool alwaysAvailable(Value *V) {
2153 return isa<Constant>(V) || isa<Argument>(V);
2154}
2155
2156// Get the basic block from an instruction/value.
2157static BasicBlock *getBlockForValue(Value *V) {
2158 if (auto *I = dyn_cast<Instruction>(V))
2159 return I->getParent();
2160 return nullptr;
2161}
2162
2163struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002164 int DFSIn = 0;
2165 int DFSOut = 0;
2166 int LocalNum = 0;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002167 // Only one of Def and U will be set.
2168 Value *Def = nullptr;
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002169 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00002170 bool operator<(const ValueDFS &Other) const {
2171 // It's not enough that any given field be less than - we have sets
2172 // of fields that need to be evaluated together to give a proper ordering.
2173 // For example, if you have;
2174 // DFS (1, 3)
2175 // Val 0
2176 // DFS (1, 2)
2177 // Val 50
2178 // We want the second to be less than the first, but if we just go field
2179 // by field, we will get to Val 0 < Val 50 and say the first is less than
2180 // the second. We only want it to be less than if the DFS orders are equal.
2181 //
2182 // Each LLVM instruction only produces one value, and thus the lowest-level
2183 // differentiator that really matters for the stack (and what we use as as a
2184 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002185 // Everything else in the structure is instruction level, and only affects
2186 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00002187 //
2188 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2189 // the order of replacement of uses does not matter.
2190 // IE given,
2191 // a = 5
2192 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00002193 // When you hit b, you will have two valuedfs with the same dfsin, out, and
2194 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00002195 // The .val will be the same as well.
2196 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002197 // You will replace both, and it does not matter what order you replace them
2198 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2199 // operand 2).
2200 // Similarly for the case of same dfsin, dfsout, localnum, but different
2201 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00002202 // a = 5
2203 // b = 6
2204 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00002205 // in c, we will a valuedfs for a, and one for b,with everything the same
2206 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00002207 // It does not matter what order we replace these operands in.
2208 // You will always end up with the same IR, and this is guaranteed.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002209 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2210 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
Davide Italiano7e274e02016-12-22 16:03:48 +00002211 Other.U);
2212 }
2213};
2214
Daniel Berlinc4796862017-01-27 02:37:11 +00002215// This function converts the set of members for a congruence class from values,
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002216// to sets of defs and uses with associated DFS info. The total number of
2217// reachable uses for each value is stored in UseCount.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002218void NewGVN::convertDenseToDFSOrdered(
Daniel Berlinc4796862017-01-27 02:37:11 +00002219 const CongruenceClass::MemberSet &Dense,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002220 SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002221 for (auto D : Dense) {
2222 // First add the value.
2223 BasicBlock *BB = getBlockForValue(D);
2224 // Constants are handled prior to ever calling this function, so
2225 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00002226 assert(BB && "Should have figured out a basic block for value");
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002227 ValueDFS VDDef;
Daniel Berlinb66164c2017-01-14 00:24:23 +00002228 DomTreeNode *DomNode = DT->getNode(BB);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002229 VDDef.DFSIn = DomNode->getDFSNumIn();
2230 VDDef.DFSOut = DomNode->getDFSNumOut();
Daniel Berlin26addef2017-01-20 21:04:30 +00002231 // If it's a store, use the leader of the value operand.
2232 if (auto *SI = dyn_cast<StoreInst>(D)) {
Daniel Berlin808e3ff2017-01-31 22:31:56 +00002233 auto Leader = lookupOperandLeader(SI->getValueOperand());
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002234 VDDef.Def = alwaysAvailable(Leader) ? Leader : SI->getValueOperand();
Daniel Berlin26addef2017-01-20 21:04:30 +00002235 } else {
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002236 VDDef.Def = D;
Daniel Berlin26addef2017-01-20 21:04:30 +00002237 }
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002238 assert(isa<Instruction>(D) &&
2239 "The dense set member should always be an instruction");
2240 VDDef.LocalNum = InstrDFS.lookup(D);
Daniel Berlin26addef2017-01-20 21:04:30 +00002241
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002242 DFSOrderedSet.emplace_back(VDDef);
Daniel Berlinb66164c2017-01-14 00:24:23 +00002243 // Now add the uses.
Davide Italiano7e274e02016-12-22 16:03:48 +00002244 for (auto &U : D->uses()) {
2245 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002246 ValueDFS VDUse;
Davide Italiano7e274e02016-12-22 16:03:48 +00002247 // Put the phi node uses in the incoming block.
2248 BasicBlock *IBlock;
2249 if (auto *P = dyn_cast<PHINode>(I)) {
2250 IBlock = P->getIncomingBlock(U);
2251 // Make phi node users appear last in the incoming block
2252 // they are from.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002253 VDUse.LocalNum = InstrDFS.size() + 1;
Davide Italiano7e274e02016-12-22 16:03:48 +00002254 } else {
2255 IBlock = I->getParent();
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002256 VDUse.LocalNum = InstrDFS.lookup(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002257 }
Davide Italianoccbbc832017-01-26 00:42:42 +00002258
2259 // Skip uses in unreachable blocks, as we're going
2260 // to delete them.
2261 if (ReachableBlocks.count(IBlock) == 0)
2262 continue;
2263
Daniel Berlinb66164c2017-01-14 00:24:23 +00002264 DomTreeNode *DomNode = DT->getNode(IBlock);
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002265 VDUse.DFSIn = DomNode->getDFSNumIn();
2266 VDUse.DFSOut = DomNode->getDFSNumOut();
2267 VDUse.U = &U;
2268 DFSOrderedSet.emplace_back(VDUse);
Davide Italiano7e274e02016-12-22 16:03:48 +00002269 }
2270 }
2271 }
2272}
2273
Daniel Berlinc4796862017-01-27 02:37:11 +00002274// This function converts the set of members for a congruence class from values,
2275// to the set of defs for loads and stores, with associated DFS info.
2276void NewGVN::convertDenseToLoadsAndStores(
2277 const CongruenceClass::MemberSet &Dense,
2278 SmallVectorImpl<ValueDFS> &LoadsAndStores) {
2279 for (auto D : Dense) {
2280 if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2281 continue;
2282
2283 BasicBlock *BB = getBlockForValue(D);
2284 ValueDFS VD;
2285 DomTreeNode *DomNode = DT->getNode(BB);
2286 VD.DFSIn = DomNode->getDFSNumIn();
2287 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002288 VD.Def = D;
Daniel Berlinc4796862017-01-27 02:37:11 +00002289
2290 // If it's an instruction, use the real local dfs number.
2291 if (auto *I = dyn_cast<Instruction>(D))
2292 VD.LocalNum = InstrDFS.lookup(I);
2293 else
2294 llvm_unreachable("Should have been an instruction");
2295
2296 LoadsAndStores.emplace_back(VD);
2297 }
2298}
2299
Davide Italiano7e274e02016-12-22 16:03:48 +00002300static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Daniel Berlin4d547962017-02-12 23:24:45 +00002301 auto *ReplInst = dyn_cast<Instruction>(Repl);
Daniel Berlin86eab152017-02-12 22:25:20 +00002302 if (!ReplInst)
2303 return;
2304
Davide Italiano7e274e02016-12-22 16:03:48 +00002305 // Patch the replacement so that it is not more restrictive than the value
2306 // being replaced.
Daniel Berlin86eab152017-02-12 22:25:20 +00002307 // Note that if 'I' is a load being replaced by some operation,
2308 // for example, by an arithmetic operation, then andIRFlags()
2309 // would just erase all math flags from the original arithmetic
2310 // operation, which is clearly not wanted and not needed.
2311 if (!isa<LoadInst>(I))
2312 ReplInst->andIRFlags(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00002313
Daniel Berlin86eab152017-02-12 22:25:20 +00002314 // FIXME: If both the original and replacement value are part of the
2315 // same control-flow region (meaning that the execution of one
2316 // guarantees the execution of the other), then we can combine the
2317 // noalias scopes here and do better than the general conservative
2318 // answer used in combineMetadata().
Davide Italiano7e274e02016-12-22 16:03:48 +00002319
Daniel Berlin86eab152017-02-12 22:25:20 +00002320 // In general, GVN unifies expressions over different control-flow
2321 // regions, and so we need a conservative combination of the noalias
2322 // scopes.
2323 static const unsigned KnownIDs[] = {
2324 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
2325 LLVMContext::MD_noalias, LLVMContext::MD_range,
2326 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
2327 LLVMContext::MD_invariant_group};
2328 combineMetadata(ReplInst, I, KnownIDs);
Davide Italiano7e274e02016-12-22 16:03:48 +00002329}
2330
2331static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2332 patchReplacementInstruction(I, Repl);
2333 I->replaceAllUsesWith(Repl);
2334}
2335
2336void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2337 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
2338 ++NumGVNBlocksDeleted;
2339
Daniel Berline19f0e02017-01-30 17:06:55 +00002340 // Delete the instructions backwards, as it has a reduced likelihood of having
2341 // to update as many def-use and use-def chains. Start after the terminator.
2342 auto StartPoint = BB->rbegin();
2343 ++StartPoint;
2344 // Note that we explicitly recalculate BB->rend() on each iteration,
2345 // as it may change when we remove the first instruction.
2346 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2347 Instruction &Inst = *I++;
2348 if (!Inst.use_empty())
2349 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2350 if (isa<LandingPadInst>(Inst))
2351 continue;
2352
2353 Inst.eraseFromParent();
2354 ++NumGVNInstrDeleted;
2355 }
Daniel Berlina53a7222017-01-30 18:12:56 +00002356 // Now insert something that simplifycfg will turn into an unreachable.
2357 Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2358 new StoreInst(UndefValue::get(Int8Ty),
2359 Constant::getNullValue(Int8Ty->getPointerTo()),
2360 BB->getTerminator());
Davide Italiano7e274e02016-12-22 16:03:48 +00002361}
2362
2363void NewGVN::markInstructionForDeletion(Instruction *I) {
2364 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
2365 InstructionsToErase.insert(I);
2366}
2367
2368void NewGVN::replaceInstruction(Instruction *I, Value *V) {
2369
2370 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
2371 patchAndReplaceAllUsesWith(I, V);
2372 // We save the actual erasing to avoid invalidating memory
2373 // dependencies until we are done with everything.
2374 markInstructionForDeletion(I);
2375}
2376
2377namespace {
2378
2379// This is a stack that contains both the value and dfs info of where
2380// that value is valid.
2381class ValueDFSStack {
2382public:
2383 Value *back() const { return ValueStack.back(); }
2384 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
2385
2386 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00002387 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00002388 DFSStack.emplace_back(DFSIn, DFSOut);
2389 }
2390 bool empty() const { return DFSStack.empty(); }
2391 bool isInScope(int DFSIn, int DFSOut) const {
2392 if (empty())
2393 return false;
2394 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
2395 }
2396
2397 void popUntilDFSScope(int DFSIn, int DFSOut) {
2398
2399 // These two should always be in sync at this point.
2400 assert(ValueStack.size() == DFSStack.size() &&
2401 "Mismatch between ValueStack and DFSStack");
2402 while (
2403 !DFSStack.empty() &&
2404 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
2405 DFSStack.pop_back();
2406 ValueStack.pop_back();
2407 }
2408 }
2409
2410private:
2411 SmallVector<Value *, 8> ValueStack;
2412 SmallVector<std::pair<int, int>, 8> DFSStack;
2413};
2414}
Daniel Berlin04443432017-01-07 03:23:47 +00002415
Davide Italiano7e274e02016-12-22 16:03:48 +00002416bool NewGVN::eliminateInstructions(Function &F) {
2417 // This is a non-standard eliminator. The normal way to eliminate is
2418 // to walk the dominator tree in order, keeping track of available
2419 // values, and eliminating them. However, this is mildly
2420 // pointless. It requires doing lookups on every instruction,
2421 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002422 // instructions part of most singleton congruence classes, we know we
2423 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00002424
2425 // Instead, this eliminator looks at the congruence classes directly, sorts
2426 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002427 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00002428 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002429 // last member. This is worst case O(E log E) where E = number of
2430 // instructions in a single congruence class. In theory, this is all
2431 // instructions. In practice, it is much faster, as most instructions are
2432 // either in singleton congruence classes or can't possibly be eliminated
2433 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00002434 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00002435 // for elimination purposes.
2436 // TODO: If we wanted to be faster, We could remove any members with no
2437 // overlapping ranges while sorting, as we will never eliminate anything
2438 // with those members, as they don't dominate anything else in our set.
2439
Davide Italiano7e274e02016-12-22 16:03:48 +00002440 bool AnythingReplaced = false;
2441
2442 // Since we are going to walk the domtree anyway, and we can't guarantee the
2443 // DFS numbers are updated, we compute some ourselves.
2444 DT->updateDFSNumbers();
2445
2446 for (auto &B : F) {
2447 if (!ReachableBlocks.count(&B)) {
2448 for (const auto S : successors(&B)) {
2449 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00002450 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00002451 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
2452 << getBlockName(&B)
2453 << " with undef due to it being unreachable\n");
2454 for (auto &Operand : Phi.incoming_values())
2455 if (Phi.getIncomingBlock(Operand) == &B)
2456 Operand.set(UndefValue::get(Phi.getType()));
2457 }
2458 }
2459 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002460 }
2461
Daniel Berlin4d547962017-02-12 23:24:45 +00002462 for (CongruenceClass *CC : reverse(CongruenceClasses)) {
Daniel Berlinc4796862017-01-27 02:37:11 +00002463 // Track the equivalent store info so we can decide whether to try
2464 // dead store elimination.
2465 SmallVector<ValueDFS, 8> PossibleDeadStores;
2466
Daniel Berlinb79f5362017-02-11 12:48:50 +00002467 if (CC->Dead)
Davide Italiano7e274e02016-12-22 16:03:48 +00002468 continue;
Daniel Berlinb79f5362017-02-11 12:48:50 +00002469 // Everything still in the INITIAL class is unreachable or dead.
2470 if (CC == InitialClass) {
2471#ifndef NDEBUG
2472 for (auto M : CC->Members)
2473 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
2474 InstructionsToErase.count(cast<Instruction>(M))) &&
2475 "Everything in INITIAL should be unreachable or dead at this "
2476 "point");
2477#endif
2478 continue;
2479 }
2480
Davide Italiano7e274e02016-12-22 16:03:48 +00002481 assert(CC->RepLeader && "We should have had a leader");
2482
2483 // If this is a leader that is always available, and it's a
2484 // constant or has no equivalences, just replace everything with
2485 // it. We then update the congruence class with whatever members
2486 // are left.
Daniel Berlin26addef2017-01-20 21:04:30 +00002487 Value *Leader = CC->RepStoredValue ? CC->RepStoredValue : CC->RepLeader;
2488 if (alwaysAvailable(Leader)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002489 SmallPtrSet<Value *, 4> MembersLeft;
2490 for (auto M : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002491 Value *Member = M;
Davide Italiano7e274e02016-12-22 16:03:48 +00002492 // Void things have no uses we can replace.
2493 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2494 MembersLeft.insert(Member);
2495 continue;
2496 }
Daniel Berlin26addef2017-01-20 21:04:30 +00002497 DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
2498 << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00002499 // Due to equality propagation, these may not always be
2500 // instructions, they may be real values. We don't really
2501 // care about trying to replace the non-instructions.
2502 if (auto *I = dyn_cast<Instruction>(Member)) {
Daniel Berlin26addef2017-01-20 21:04:30 +00002503 assert(Leader != I && "About to accidentally remove our leader");
2504 replaceInstruction(I, Leader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002505 AnythingReplaced = true;
2506
2507 continue;
2508 } else {
2509 MembersLeft.insert(I);
2510 }
2511 }
2512 CC->Members.swap(MembersLeft);
Davide Italiano7e274e02016-12-22 16:03:48 +00002513 } else {
2514 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2515 // If this is a singleton, we can skip it.
2516 if (CC->Members.size() != 1) {
2517
2518 // This is a stack because equality replacement/etc may place
2519 // constants in the middle of the member list, and we want to use
2520 // those constant values in preference to the current leader, over
2521 // the scope of those constants.
2522 ValueDFSStack EliminationStack;
2523
2524 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002525 SmallVector<ValueDFS, 8> DFSOrderedSet;
Davide Italiano7e274e02016-12-22 16:03:48 +00002526 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2527
2528 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002529 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002530 for (auto &VD : DFSOrderedSet) {
2531 int MemberDFSIn = VD.DFSIn;
2532 int MemberDFSOut = VD.DFSOut;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002533 Value *Member = VD.Def;
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002534 Use *MemberUse = VD.U;
Davide Italiano7e274e02016-12-22 16:03:48 +00002535
Daniel Berlinc4796862017-01-27 02:37:11 +00002536 // We ignore void things because we can't get a value from them.
2537 if (Member && Member->getType()->isVoidTy())
2538 continue;
Davide Italiano7e274e02016-12-22 16:03:48 +00002539
2540 if (EliminationStack.empty()) {
2541 DEBUG(dbgs() << "Elimination Stack is empty\n");
2542 } else {
2543 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2544 << EliminationStack.dfs_back().first << ","
2545 << EliminationStack.dfs_back().second << ")\n");
2546 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002547
2548 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2549 << MemberDFSOut << ")\n");
2550 // First, we see if we are out of scope or empty. If so,
2551 // and there equivalences, we try to replace the top of
2552 // stack with equivalences (if it's on the stack, it must
2553 // not have been eliminated yet).
2554 // Then we synchronize to our current scope, by
2555 // popping until we are back within a DFS scope that
2556 // dominates the current member.
2557 // Then, what happens depends on a few factors
2558 // If the stack is now empty, we need to push
2559 // If we have a constant or a local equivalence we want to
2560 // start using, we also push.
2561 // Otherwise, we walk along, processing members who are
2562 // dominated by this scope, and eliminate them.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002563 bool ShouldPush = Member && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002564 bool OutOfScope =
2565 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2566
2567 if (OutOfScope || ShouldPush) {
2568 // Sync to our current scope.
2569 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
Daniel Berlinf7d95802017-02-18 23:06:50 +00002570 bool ShouldPush = Member && EliminationStack.empty();
Davide Italiano7e274e02016-12-22 16:03:48 +00002571 if (ShouldPush) {
2572 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2573 }
2574 }
2575
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002576 if (MemberUse) {
2577 // Any def or use we hit at this point must be in an instruction.
2578 // We assert so in convertDenseToDFSOrdered about defs, but assert
2579 // it here too just make sure we are consistent.
2580 assert(isa<Instruction>(MemberUse->get()) &&
2581 "Use should have been in an instruction");
2582 assert(isa<Instruction>(MemberUse->getUser()) &&
2583 "Def should have been in an instruction");
2584 }
2585
Davide Italiano7e274e02016-12-22 16:03:48 +00002586 // If we get to this point, and the stack is empty we must have a use
2587 // with nothing we can use to eliminate it, just skip it.
2588 if (EliminationStack.empty())
2589 continue;
2590
2591 // Skip the Value's, we only want to eliminate on their uses.
2592 if (Member)
2593 continue;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002594 Value *DominatingLeader = EliminationStack.back();
Davide Italiano7e274e02016-12-22 16:03:48 +00002595
Daniel Berlind92e7f92017-01-07 00:01:42 +00002596 // Don't replace our existing users with ourselves.
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002597 if (MemberUse->get() == DominatingLeader)
Davide Italiano7e274e02016-12-22 16:03:48 +00002598 continue;
2599
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002600 DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
Davide Italiano7e274e02016-12-22 16:03:48 +00002601 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2602 << "\n");
2603
2604 // If we replaced something in an instruction, handle the patching of
2605 // metadata.
Davide Italiano7e274e02016-12-22 16:03:48 +00002606
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002607 auto *ReplacedInst = cast<Instruction>(MemberUse->get());
2608 // Skip this if we are replacing predicateinfo with its original
2609 // operand, as we already know we can just drop it.
2610 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
2611 if (!PI || DominatingLeader != PI->OriginalOp)
2612 patchReplacementInstruction(ReplacedInst, DominatingLeader);
2613 MemberUse->set(DominatingLeader);
Davide Italiano7e274e02016-12-22 16:03:48 +00002614 AnythingReplaced = true;
2615 }
2616 }
2617 }
2618
2619 // Cleanup the congruence class.
2620 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002621 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002622 if (Member->getType()->isVoidTy()) {
2623 MembersLeft.insert(Member);
2624 continue;
2625 }
2626
2627 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2628 if (isInstructionTriviallyDead(MemberInst)) {
2629 // TODO: Don't mark loads of undefs.
2630 markInstructionForDeletion(MemberInst);
2631 continue;
2632 }
2633 }
2634 MembersLeft.insert(Member);
2635 }
2636 CC->Members.swap(MembersLeft);
Daniel Berlinc4796862017-01-27 02:37:11 +00002637
2638 // If we have possible dead stores to look at, try to eliminate them.
2639 if (CC->StoreCount > 0) {
2640 convertDenseToLoadsAndStores(CC->Members, PossibleDeadStores);
2641 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
2642 ValueDFSStack EliminationStack;
2643 for (auto &VD : PossibleDeadStores) {
2644 int MemberDFSIn = VD.DFSIn;
2645 int MemberDFSOut = VD.DFSOut;
Daniel Berlinc0e008d2017-03-10 00:32:26 +00002646 Instruction *Member = cast<Instruction>(VD.Def);
Daniel Berlinc4796862017-01-27 02:37:11 +00002647 if (EliminationStack.empty() ||
2648 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
2649 // Sync to our current scope.
2650 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2651 if (EliminationStack.empty()) {
2652 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2653 continue;
2654 }
2655 }
2656 // We already did load elimination, so nothing to do here.
2657 if (isa<LoadInst>(Member))
2658 continue;
2659 assert(!EliminationStack.empty());
2660 Instruction *Leader = cast<Instruction>(EliminationStack.back());
Richard Trieu0b79aa32017-01-27 06:06:05 +00002661 (void)Leader;
Daniel Berlinc4796862017-01-27 02:37:11 +00002662 assert(DT->dominates(Leader->getParent(), Member->getParent()));
2663 // Member is dominater by Leader, and thus dead
2664 DEBUG(dbgs() << "Marking dead store " << *Member
2665 << " that is dominated by " << *Leader << "\n");
2666 markInstructionForDeletion(Member);
2667 CC->Members.erase(Member);
2668 ++NumGVNDeadStores;
2669 }
2670 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002671 }
2672
2673 return AnythingReplaced;
2674}
Daniel Berlin1c087672017-02-11 15:07:01 +00002675
2676// This function provides global ranking of operations so that we can place them
2677// in a canonical order. Note that rank alone is not necessarily enough for a
2678// complete ordering, as constants all have the same rank. However, generally,
2679// we will simplify an operation with all constants so that it doesn't matter
2680// what order they appear in.
2681unsigned int NewGVN::getRank(const Value *V) const {
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002682 // Prefer undef to anything else
2683 if (isa<UndefValue>(V))
Daniel Berlin1c087672017-02-11 15:07:01 +00002684 return 0;
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002685 if (isa<Constant>(V))
2686 return 1;
Daniel Berlin1c087672017-02-11 15:07:01 +00002687 else if (auto *A = dyn_cast<Argument>(V))
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002688 return 2 + A->getArgNo();
Daniel Berlin1c087672017-02-11 15:07:01 +00002689
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002690 // Need to shift the instruction DFS by number of arguments + 3 to account for
Daniel Berlin1c087672017-02-11 15:07:01 +00002691 // the constant and argument ranking above.
2692 unsigned Result = InstrDFS.lookup(V);
2693 if (Result > 0)
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002694 return 3 + NumFuncArgs + Result;
Daniel Berlin1c087672017-02-11 15:07:01 +00002695 // Unreachable or something else, just return a really large number.
2696 return ~0;
2697}
2698
2699// This is a function that says whether two commutative operations should
2700// have their order swapped when canonicalizing.
2701bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
2702 // Because we only care about a total ordering, and don't rewrite expressions
2703 // in this order, we order by rank, which will give a strict weak ordering to
Daniel Berlinb355c4f2017-02-18 23:06:47 +00002704 // everything but constants, and then we order by pointer address.
Daniel Berlinf7d95802017-02-18 23:06:50 +00002705 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
Daniel Berlin1c087672017-02-11 15:07:01 +00002706}