blob: 33b3e9ad6e08a8584003339111ee2de6166ceaeb [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///
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar/NewGVN.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/DepthFirstIterator.h"
27#include "llvm/ADT/Hashing.h"
28#include "llvm/ADT/MapVector.h"
29#include "llvm/ADT/PostOrderIterator.h"
Daniel Berlind7c12ee2016-12-25 22:23:49 +000030#include "llvm/ADT/STLExtras.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000031#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/SparseBitVector.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/TinyPtrVector.h"
36#include "llvm/Analysis/AliasAnalysis.h"
37#include "llvm/Analysis/AssumptionCache.h"
38#include "llvm/Analysis/CFG.h"
39#include "llvm/Analysis/CFGPrinter.h"
40#include "llvm/Analysis/ConstantFolding.h"
41#include "llvm/Analysis/GlobalsModRef.h"
42#include "llvm/Analysis/InstructionSimplify.h"
43#include "llvm/Analysis/Loads.h"
44#include "llvm/Analysis/MemoryBuiltins.h"
45#include "llvm/Analysis/MemoryDependenceAnalysis.h"
46#include "llvm/Analysis/MemoryLocation.h"
47#include "llvm/Analysis/PHITransAddr.h"
48#include "llvm/Analysis/TargetLibraryInfo.h"
49#include "llvm/Analysis/ValueTracking.h"
50#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/GlobalVariable.h"
53#include "llvm/IR/IRBuilder.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
57#include "llvm/IR/PatternMatch.h"
58#include "llvm/IR/PredIteratorCache.h"
59#include "llvm/IR/Type.h"
60#include "llvm/Support/Allocator.h"
61#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/Debug.h"
63#include "llvm/Transforms/Scalar.h"
64#include "llvm/Transforms/Scalar/GVNExpression.h"
65#include "llvm/Transforms/Utils/BasicBlockUtils.h"
66#include "llvm/Transforms/Utils/Local.h"
67#include "llvm/Transforms/Utils/MemorySSA.h"
68#include "llvm/Transforms/Utils/SSAUpdater.h"
69#include <unordered_map>
70#include <utility>
71#include <vector>
72using namespace llvm;
73using namespace PatternMatch;
74using namespace llvm::GVNExpression;
75
76#define DEBUG_TYPE "newgvn"
77
78STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
79STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
80STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
81STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +000082STATISTIC(NumGVNMaxIterations,
83 "Maximum Number of iterations it took to converge GVN");
Davide Italiano7e274e02016-12-22 16:03:48 +000084
85//===----------------------------------------------------------------------===//
86// GVN Pass
87//===----------------------------------------------------------------------===//
88
89// Anchor methods.
90namespace llvm {
91namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +000092Expression::~Expression() = default;
93BasicExpression::~BasicExpression() = default;
94CallExpression::~CallExpression() = default;
95LoadExpression::~LoadExpression() = default;
96StoreExpression::~StoreExpression() = default;
97AggregateValueExpression::~AggregateValueExpression() = default;
98PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +000099}
100}
101
102// Congruence classes represent the set of expressions/instructions
103// that are all the same *during some scope in the function*.
104// That is, because of the way we perform equality propagation, and
105// because of memory value numbering, it is not correct to assume
106// you can willy-nilly replace any member with any other at any
107// point in the function.
108//
109// For any Value in the Member set, it is valid to replace any dominated member
110// with that Value.
111//
112// Every congruence class has a leader, and the leader is used to
113// symbolize instructions in a canonical way (IE every operand of an
114// instruction that is a member of the same congruence class will
115// always be replaced with leader during symbolization).
116// To simplify symbolization, we keep the leader as a constant if class can be
117// proved to be a constant value.
118// Otherwise, the leader is a randomly chosen member of the value set, it does
119// not matter which one is chosen.
120// Each congruence class also has a defining expression,
121// though the expression may be null. If it exists, it can be used for forward
122// propagation and reassociation of values.
123//
124struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000125 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000126 unsigned ID;
127 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000128 Value *RepLeader = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000129 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000130 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000131 // Actual members of this class.
132 MemberSet Members;
133
134 // True if this class has no members left. This is mainly used for assertion
135 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000136 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000137
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000138 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000139 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000140 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000141};
142
143namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000144template <> struct DenseMapInfo<const Expression *> {
145 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000146 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000147 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
148 return reinterpret_cast<const Expression *>(Val);
149 }
150 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000151 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000152 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
153 return reinterpret_cast<const Expression *>(Val);
154 }
155 static unsigned getHashValue(const Expression *V) {
156 return static_cast<unsigned>(V->getHashValue());
157 }
158 static bool isEqual(const Expression *LHS, const Expression *RHS) {
159 if (LHS == RHS)
160 return true;
161 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
162 LHS == getEmptyKey() || RHS == getEmptyKey())
163 return false;
164 return *LHS == *RHS;
165 }
166};
Davide Italiano7e274e02016-12-22 16:03:48 +0000167} // end namespace llvm
168
169class NewGVN : public FunctionPass {
170 DominatorTree *DT;
171 const DataLayout *DL;
172 const TargetLibraryInfo *TLI;
173 AssumptionCache *AC;
174 AliasAnalysis *AA;
175 MemorySSA *MSSA;
176 MemorySSAWalker *MSSAWalker;
177 BumpPtrAllocator ExpressionAllocator;
178 ArrayRecycler<Value *> ArgRecycler;
179
180 // Congruence class info.
181 CongruenceClass *InitialClass;
182 std::vector<CongruenceClass *> CongruenceClasses;
183 unsigned NextCongruenceNum;
184
185 // Value Mappings.
186 DenseMap<Value *, CongruenceClass *> ValueToClass;
187 DenseMap<Value *, const Expression *> ValueToExpression;
188
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000189 // A table storing which memorydefs/phis represent a memory state provably
190 // equivalent to another memory state.
191 // We could use the congruence class machinery, but the MemoryAccess's are
192 // abstract memory states, so they can only ever be equivalent to each other,
193 // and not to constants, etc.
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000194 DenseMap<const MemoryAccess *, MemoryAccess *> MemoryAccessEquiv;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000195
Davide Italiano7e274e02016-12-22 16:03:48 +0000196 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000197 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000198 ExpressionClassMap ExpressionToClass;
199
200 // Which values have changed as a result of leader changes.
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000201 SmallPtrSet<Value *, 8> LeaderChanges;
Davide Italiano7e274e02016-12-22 16:03:48 +0000202
203 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000204 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000205 DenseSet<BlockEdge> ReachableEdges;
206 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
207
208 // This is a bitvector because, on larger functions, we may have
209 // thousands of touched instructions at once (entire blocks,
210 // instructions with hundreds of uses, etc). Even with optimization
211 // for when we mark whole blocks as touched, when this was a
212 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
213 // the time in GVN just managing this list. The bitvector, on the
214 // other hand, efficiently supports test/set/clear of both
215 // individual and ranges, as well as "find next element" This
216 // enables us to use it as a worklist with essentially 0 cost.
217 BitVector TouchedInstructions;
218
219 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
220 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
221 DominatedInstRange;
222
223#ifndef NDEBUG
224 // Debugging for how many times each block and instruction got processed.
225 DenseMap<const Value *, unsigned> ProcessedCount;
226#endif
227
228 // DFS info.
229 DenseMap<const BasicBlock *, std::pair<int, int>> DFSDomMap;
230 DenseMap<const Value *, unsigned> InstrDFS;
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000231 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000232
233 // Deletion info.
234 SmallPtrSet<Instruction *, 8> InstructionsToErase;
235
236public:
237 static char ID; // Pass identification, replacement for typeid.
238 NewGVN() : FunctionPass(ID) {
239 initializeNewGVNPass(*PassRegistry::getPassRegistry());
240 }
241
242 bool runOnFunction(Function &F) override;
243 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000244 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000245
246private:
247 // This transformation requires dominator postdominator info.
248 void getAnalysisUsage(AnalysisUsage &AU) const override {
249 AU.addRequired<AssumptionCacheTracker>();
250 AU.addRequired<DominatorTreeWrapperPass>();
251 AU.addRequired<TargetLibraryInfoWrapperPass>();
252 AU.addRequired<MemorySSAWrapperPass>();
253 AU.addRequired<AAResultsWrapperPass>();
254
255 AU.addPreserved<DominatorTreeWrapperPass>();
256 AU.addPreserved<GlobalsAAWrapperPass>();
257 }
258
259 // Expression handling.
260 const Expression *createExpression(Instruction *, const BasicBlock *);
261 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
262 const BasicBlock *);
263 PHIExpression *createPHIExpression(Instruction *);
264 const VariableExpression *createVariableExpression(Value *);
265 const ConstantExpression *createConstantExpression(Constant *);
266 const Expression *createVariableOrConstant(Value *V, const BasicBlock *B);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000267 const UnknownExpression *createUnknownExpression(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000268 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
269 const BasicBlock *);
270 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
271 MemoryAccess *, const BasicBlock *);
272
273 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
274 const BasicBlock *);
275 const AggregateValueExpression *
276 createAggregateValueExpression(Instruction *, const BasicBlock *);
277 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
278 const BasicBlock *);
279
280 // Congruence class handling.
281 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000282 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000283 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000284 return result;
285 }
286
287 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000288 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000289 CClass->Members.insert(Member);
290 ValueToClass[Member] = CClass;
291 return CClass;
292 }
293 void initializeCongruenceClasses(Function &F);
294
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000295 // Value number an Instruction or MemoryPhi.
296 void valueNumberMemoryPhi(MemoryPhi *);
297 void valueNumberInstruction(Instruction *);
298
Davide Italiano7e274e02016-12-22 16:03:48 +0000299 // Symbolic evaluation.
300 const Expression *checkSimplificationResults(Expression *, Instruction *,
301 Value *);
302 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
303 const Expression *performSymbolicLoadEvaluation(Instruction *,
304 const BasicBlock *);
305 const Expression *performSymbolicStoreEvaluation(Instruction *,
306 const BasicBlock *);
307 const Expression *performSymbolicCallEvaluation(Instruction *,
308 const BasicBlock *);
309 const Expression *performSymbolicPHIEvaluation(Instruction *,
310 const BasicBlock *);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000311 bool setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To);
Davide Italiano7e274e02016-12-22 16:03:48 +0000312 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
313 const BasicBlock *);
314
315 // Congruence finding.
316 // Templated to allow them to work both on BB's and BB-edges.
317 template <class T>
318 Value *lookupOperandLeader(Value *, const User *, const T &) const;
319 void performCongruenceFinding(Value *, const Expression *);
Daniel Berlin3a1bd022017-01-11 20:22:05 +0000320 void moveValueToNewCongruenceClass(Value *, CongruenceClass *,
321 CongruenceClass *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000322 // Reachability handling.
323 void updateReachableEdge(BasicBlock *, BasicBlock *);
324 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000325 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000326 Value *findConditionEquivalence(Value *, BasicBlock *) const;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000327 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000328
329 // Elimination.
330 struct ValueDFS;
331 void convertDenseToDFSOrdered(CongruenceClass::MemberSet &,
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +0000332 SmallVectorImpl<ValueDFS> &);
Davide Italiano7e274e02016-12-22 16:03:48 +0000333
334 bool eliminateInstructions(Function &);
335 void replaceInstruction(Instruction *, Value *);
336 void markInstructionForDeletion(Instruction *);
337 void deleteInstructionsInBlock(BasicBlock *);
338
339 // New instruction creation.
340 void handleNewInstruction(Instruction *){};
Daniel Berlin32f8d562017-01-07 16:55:14 +0000341
342 // Various instruction touch utilities
Davide Italiano7e274e02016-12-22 16:03:48 +0000343 void markUsersTouched(Value *);
344 void markMemoryUsersTouched(MemoryAccess *);
Daniel Berlin32f8d562017-01-07 16:55:14 +0000345 void markLeaderChangeTouched(CongruenceClass *CC);
Davide Italiano7e274e02016-12-22 16:03:48 +0000346
347 // Utilities.
348 void cleanupTables();
349 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
350 void updateProcessedCount(Value *V);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000351 void verifyMemoryCongruency();
Davide Italiano7e274e02016-12-22 16:03:48 +0000352};
353
354char NewGVN::ID = 0;
355
356// createGVNPass - The public interface to this file.
357FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
358
Davide Italianob1114092016-12-28 13:37:17 +0000359template <typename T>
360static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
361 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000362 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000363 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000364 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000365 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000366 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000367 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000368 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000369 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000370 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000371 return true;
372}
373
Davide Italianob1114092016-12-28 13:37:17 +0000374bool LoadExpression::equals(const Expression &Other) const {
375 return equalsLoadStoreHelper(*this, Other);
376}
Davide Italiano7e274e02016-12-22 16:03:48 +0000377
Davide Italianob1114092016-12-28 13:37:17 +0000378bool StoreExpression::equals(const Expression &Other) const {
379 return equalsLoadStoreHelper(*this, Other);
Davide Italiano7e274e02016-12-22 16:03:48 +0000380}
381
382#ifndef NDEBUG
383static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000384 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000385}
386#endif
387
388INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
389INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
390INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
391INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
392INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
393INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
394INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
395INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
396
397PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000398 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000399 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000400 auto *E =
401 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000402
403 E->allocateOperands(ArgRecycler, ExpressionAllocator);
404 E->setType(I->getType());
405 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000406
407 auto ReachablePhiArg = [&](const Use &U) {
408 return ReachableBlocks.count(PN->getIncomingBlock(U));
409 };
410
411 // Filter out unreachable operands
412 auto Filtered = make_filter_range(PN->operands(), ReachablePhiArg);
413
414 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
415 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000416 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000417 if (U == PN)
418 return PN;
Daniel Berlind92e7f92017-01-07 00:01:42 +0000419 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PHIBlock);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000420 return lookupOperandLeader(U, I, BBE);
421 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000422 return E;
423}
424
425// Set basic expression info (Arguments, type, opcode) for Expression
426// E from Instruction I in block B.
427bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
428 const BasicBlock *B) {
429 bool AllConstant = true;
430 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
431 E->setType(GEP->getSourceElementType());
432 else
433 E->setType(I->getType());
434 E->setOpcode(I->getOpcode());
435 E->allocateOperands(ArgRecycler, ExpressionAllocator);
436
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000437 // Transform the operand array into an operand leader array, and keep track of
438 // whether all members are constant.
439 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000440 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000441 AllConstant &= isa<Constant>(Operand);
442 return Operand;
443 });
444
Davide Italiano7e274e02016-12-22 16:03:48 +0000445 return AllConstant;
446}
447
448const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
449 Value *Arg1, Value *Arg2,
450 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000451 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000452
453 E->setType(T);
454 E->setOpcode(Opcode);
455 E->allocateOperands(ArgRecycler, ExpressionAllocator);
456 if (Instruction::isCommutative(Opcode)) {
457 // Ensure that commutative instructions that only differ by a permutation
458 // of their operands get the same value number by sorting the operand value
459 // numbers. Since all commutative instructions have two operands it is more
460 // efficient to sort by hand rather than using, say, std::sort.
461 if (Arg1 > Arg2)
462 std::swap(Arg1, Arg2);
463 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000464 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
465 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000466
467 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
468 DT, AC);
469 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
470 return SimplifiedE;
471 return E;
472}
473
474// Take a Value returned by simplification of Expression E/Instruction
475// I, and see if it resulted in a simpler expression. If so, return
476// that expression.
477// TODO: Once finished, this should not take an Instruction, we only
478// use it for printing.
479const Expression *NewGVN::checkSimplificationResults(Expression *E,
480 Instruction *I, Value *V) {
481 if (!V)
482 return nullptr;
483 if (auto *C = dyn_cast<Constant>(V)) {
484 if (I)
485 DEBUG(dbgs() << "Simplified " << *I << " to "
486 << " constant " << *C << "\n");
487 NumGVNOpsSimplified++;
488 assert(isa<BasicExpression>(E) &&
489 "We should always have had a basic expression here");
490
491 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
492 ExpressionAllocator.Deallocate(E);
493 return createConstantExpression(C);
494 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
495 if (I)
496 DEBUG(dbgs() << "Simplified " << *I << " to "
497 << " variable " << *V << "\n");
498 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
499 ExpressionAllocator.Deallocate(E);
500 return createVariableExpression(V);
501 }
502
503 CongruenceClass *CC = ValueToClass.lookup(V);
504 if (CC && CC->DefiningExpr) {
505 if (I)
506 DEBUG(dbgs() << "Simplified " << *I << " to "
507 << " expression " << *V << "\n");
508 NumGVNOpsSimplified++;
509 assert(isa<BasicExpression>(E) &&
510 "We should always have had a basic expression here");
511 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
512 ExpressionAllocator.Deallocate(E);
513 return CC->DefiningExpr;
514 }
515 return nullptr;
516}
517
518const Expression *NewGVN::createExpression(Instruction *I,
519 const BasicBlock *B) {
520
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000521 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000522
523 bool AllConstant = setBasicExpressionInfo(I, E, B);
524
525 if (I->isCommutative()) {
526 // Ensure that commutative instructions that only differ by a permutation
527 // of their operands get the same value number by sorting the operand value
528 // numbers. Since all commutative instructions have two operands it is more
529 // efficient to sort by hand rather than using, say, std::sort.
530 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
531 if (E->getOperand(0) > E->getOperand(1))
532 E->swapOperands(0, 1);
533 }
534
535 // Perform simplificaiton
536 // TODO: Right now we only check to see if we get a constant result.
537 // We may get a less than constant, but still better, result for
538 // some operations.
539 // IE
540 // add 0, x -> x
541 // and x, x -> x
542 // We should handle this by simply rewriting the expression.
543 if (auto *CI = dyn_cast<CmpInst>(I)) {
544 // Sort the operand value numbers so x<y and y>x get the same value
545 // number.
546 CmpInst::Predicate Predicate = CI->getPredicate();
547 if (E->getOperand(0) > E->getOperand(1)) {
548 E->swapOperands(0, 1);
549 Predicate = CmpInst::getSwappedPredicate(Predicate);
550 }
551 E->setOpcode((CI->getOpcode() << 8) | Predicate);
552 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
553 // TODO: Since we noop bitcasts, we may need to check types before
554 // simplifying, so that we don't end up simplifying based on a wrong
555 // type assumption. We should clean this up so we can use constants of the
556 // wrong type
557
558 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
559 "Wrong types on cmp instruction");
560 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
561 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
562 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
563 *DL, TLI, DT, AC);
564 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
565 return SimplifiedE;
566 }
567 } else if (isa<SelectInst>(I)) {
568 if (isa<Constant>(E->getOperand(0)) ||
569 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
570 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
571 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
572 E->getOperand(2), *DL, TLI, DT, AC);
573 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
574 return SimplifiedE;
575 }
576 } else if (I->isBinaryOp()) {
577 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
578 *DL, TLI, DT, AC);
579 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
580 return SimplifiedE;
581 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
582 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
583 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
584 return SimplifiedE;
585 } else if (isa<GetElementPtrInst>(I)) {
586 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000587 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000588 *DL, TLI, DT, AC);
589 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
590 return SimplifiedE;
591 } else if (AllConstant) {
592 // We don't bother trying to simplify unless all of the operands
593 // were constant.
594 // TODO: There are a lot of Simplify*'s we could call here, if we
595 // wanted to. The original motivating case for this code was a
596 // zext i1 false to i8, which we don't have an interface to
597 // simplify (IE there is no SimplifyZExt).
598
599 SmallVector<Constant *, 8> C;
600 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000601 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000602
603 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
604 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
605 return SimplifiedE;
606 }
607 return E;
608}
609
610const AggregateValueExpression *
611NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
612 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000613 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000614 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
615 setBasicExpressionInfo(I, E, B);
616 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000617 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000618 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000619 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000620 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000621 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
622 setBasicExpressionInfo(EI, E, B);
623 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000624 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000625 return E;
626 }
627 llvm_unreachable("Unhandled type of aggregate value operation");
628}
629
Daniel Berlin85f91b02016-12-26 20:06:58 +0000630const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000631 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000632 E->setOpcode(V->getValueID());
633 return E;
634}
635
636const Expression *NewGVN::createVariableOrConstant(Value *V,
637 const BasicBlock *B) {
638 auto Leader = lookupOperandLeader(V, nullptr, B);
639 if (auto *C = dyn_cast<Constant>(Leader))
640 return createConstantExpression(C);
641 return createVariableExpression(Leader);
642}
643
Daniel Berlin85f91b02016-12-26 20:06:58 +0000644const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000645 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000646 E->setOpcode(C->getValueID());
647 return E;
648}
649
Daniel Berlin02c6b172017-01-02 18:00:53 +0000650const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
651 auto *E = new (ExpressionAllocator) UnknownExpression(I);
652 E->setOpcode(I->getOpcode());
653 return E;
654}
655
Davide Italiano7e274e02016-12-22 16:03:48 +0000656const CallExpression *NewGVN::createCallExpression(CallInst *CI,
657 MemoryAccess *HV,
658 const BasicBlock *B) {
659 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000660 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000661 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
662 setBasicExpressionInfo(CI, E, B);
663 return E;
664}
665
666// See if we have a congruence class and leader for this operand, and if so,
667// return it. Otherwise, return the operand itself.
668template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000669Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000670 CongruenceClass *CC = ValueToClass.lookup(V);
671 if (CC && (CC != InitialClass))
672 return CC->RepLeader;
673 return V;
674}
675
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000676MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
677 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA);
678 return Result ? Result : MA;
679}
680
Davide Italiano7e274e02016-12-22 16:03:48 +0000681LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
682 LoadInst *LI, MemoryAccess *DA,
683 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000684 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000685 E->allocateOperands(ArgRecycler, ExpressionAllocator);
686 E->setType(LoadType);
687
688 // Give store and loads same opcode so they value number together.
689 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000690 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000691 if (LI)
692 E->setAlignment(LI->getAlignment());
693
694 // TODO: Value number heap versions. We may be able to discover
695 // things alias analysis can't on it's own (IE that a store and a
696 // load have the same value, and thus, it isn't clobbering the load).
697 return E;
698}
699
700const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
701 MemoryAccess *DA,
702 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000703 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000704 new (ExpressionAllocator) StoreExpression(SI->getNumOperands(), SI, DA);
705 E->allocateOperands(ArgRecycler, ExpressionAllocator);
706 E->setType(SI->getValueOperand()->getType());
707
708 // Give store and loads same opcode so they value number together.
709 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000710 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000711
712 // TODO: Value number heap versions. We may be able to discover
713 // things alias analysis can't on it's own (IE that a store and a
714 // load have the same value, and thus, it isn't clobbering the load).
715 return E;
716}
717
Daniel Berlinb755aea2017-01-09 05:34:29 +0000718// Utility function to check whether the congruence class has a member other
719// than the given instruction.
720bool hasMemberOtherThanUs(const CongruenceClass *CC, Instruction *I) {
721 // Either it has more than one member, in which case it must contain something
722 // other than us (because it's indexed by value), or if it only has one member
723 // right now, that member should not be us.
724 return CC->Members.size() > 1 || CC->Members.count(I) == 0;
725}
726
Davide Italiano7e274e02016-12-22 16:03:48 +0000727const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
728 const BasicBlock *B) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000729 // Unlike loads, we never try to eliminate stores, so we do not check if they
730 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000731 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000732 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinde43ef92017-01-02 19:49:17 +0000733 // See if we are defined by a previous store expression, it already has a
734 // value, and it's the same value as our current store. FIXME: Right now, we
735 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000736 if (SI->isSimple()) {
Daniel Berlinde43ef92017-01-02 19:49:17 +0000737 // Get the expression, if any, for the RHS of the MemoryDef.
738 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
739 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
740 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000741 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
Daniel Berlinb755aea2017-01-09 05:34:29 +0000742 // Basically, check if the congruence class the store is in is defined by a
743 // store that isn't us, and has the same value. MemorySSA takes care of
744 // ensuring the store has the same memory state as us already.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000745 if (CC && CC->DefiningExpr && isa<StoreExpression>(CC->DefiningExpr) &&
Daniel Berlinb755aea2017-01-09 05:34:29 +0000746 CC->RepLeader == lookupOperandLeader(SI->getValueOperand(), SI, B) &&
747 hasMemberOtherThanUs(CC, I))
Daniel Berlin589cecc2017-01-02 18:00:46 +0000748 return createStoreExpression(SI, StoreRHS, B);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000749 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000750
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000751 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000752}
753
754const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
755 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000756 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000757
758 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000759 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000760 if (!LI->isSimple())
761 return nullptr;
762
Daniel Berlin85f91b02016-12-26 20:06:58 +0000763 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000764 // Load of undef is undef.
765 if (isa<UndefValue>(LoadAddressLeader))
766 return createConstantExpression(UndefValue::get(LI->getType()));
767
768 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
769
770 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
771 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
772 Instruction *DefiningInst = MD->getMemoryInst();
773 // If the defining instruction is not reachable, replace with undef.
774 if (!ReachableBlocks.count(DefiningInst->getParent()))
775 return createConstantExpression(UndefValue::get(LI->getType()));
776 }
777 }
778
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000779 const Expression *E =
780 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
781 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000782 return E;
783}
784
785// Evaluate read only and pure calls, and create an expression result.
786const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
787 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000788 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000789 if (AA->doesNotAccessMemory(CI))
790 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000791 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000792 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000793 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000794 }
795 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000796}
797
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000798// Update the memory access equivalence table to say that From is equal to To,
799// and return true if this is different from what already existed in the table.
800bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To) {
Davide Italiano84126162017-01-02 18:41:34 +0000801 DEBUG(dbgs() << "Setting " << *From << " equivalent to ");
802 if (!To)
803 DEBUG(dbgs() << "itself");
804 else
805 DEBUG(dbgs() << *To);
806 DEBUG(dbgs() << "\n");
Daniel Berlin589cecc2017-01-02 18:00:46 +0000807 auto LookupResult = MemoryAccessEquiv.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000808 bool Changed = false;
809 // If it's already in the table, see if the value changed.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000810 if (LookupResult != MemoryAccessEquiv.end()) {
811 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000812 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000813 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000814 Changed = true;
815 } else if (!To) {
816 // It used to be equivalent to something, and now it's not.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000817 MemoryAccessEquiv.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000818 Changed = true;
819 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000820 } else {
821 assert(!To &&
822 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000823 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000824
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000825 return Changed;
826}
Davide Italiano7e274e02016-12-22 16:03:48 +0000827// Evaluate PHI nodes symbolically, and create an expression result.
828const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
829 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000830 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +0000831 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
832
833 // See if all arguaments are the same.
834 // We track if any were undef because they need special handling.
835 bool HasUndef = false;
836 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
837 if (Arg == I)
838 return false;
839 if (isa<UndefValue>(Arg)) {
840 HasUndef = true;
841 return false;
842 }
843 return true;
844 });
845 // If we are left with no operands, it's undef
846 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000847 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
848 << "\n");
849 E->deallocateOperands(ArgRecycler);
850 ExpressionAllocator.Deallocate(E);
851 return createConstantExpression(UndefValue::get(I->getType()));
852 }
Daniel Berlind92e7f92017-01-07 00:01:42 +0000853 Value *AllSameValue = *(Filtered.begin());
854 ++Filtered.begin();
855 // Can't use std::equal here, sadly, because filter.begin moves.
856 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
857 return V == AllSameValue;
858 })) {
859 // In LLVM's non-standard representation of phi nodes, it's possible to have
860 // phi nodes with cycles (IE dependent on other phis that are .... dependent
861 // on the original phi node), especially in weird CFG's where some arguments
862 // are unreachable, or uninitialized along certain paths. This can cause
863 // infinite loops during evaluation. We work around this by not trying to
864 // really evaluate them independently, but instead using a variable
865 // expression to say if one is equivalent to the other.
866 // We also special case undef, so that if we have an undef, we can't use the
867 // common value unless it dominates the phi block.
868 if (HasUndef) {
869 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +0000870 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +0000871 if (!DT->dominates(AllSameInst, I))
872 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000873 }
874
Davide Italiano7e274e02016-12-22 16:03:48 +0000875 NumGVNPhisAllSame++;
876 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
877 << "\n");
878 E->deallocateOperands(ArgRecycler);
879 ExpressionAllocator.Deallocate(E);
880 if (auto *C = dyn_cast<Constant>(AllSameValue))
881 return createConstantExpression(C);
882 return createVariableExpression(AllSameValue);
883 }
884 return E;
885}
886
887const Expression *
888NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
889 const BasicBlock *B) {
890 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
891 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
892 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
893 unsigned Opcode = 0;
894 // EI might be an extract from one of our recognised intrinsics. If it
895 // is we'll synthesize a semantically equivalent expression instead on
896 // an extract value expression.
897 switch (II->getIntrinsicID()) {
898 case Intrinsic::sadd_with_overflow:
899 case Intrinsic::uadd_with_overflow:
900 Opcode = Instruction::Add;
901 break;
902 case Intrinsic::ssub_with_overflow:
903 case Intrinsic::usub_with_overflow:
904 Opcode = Instruction::Sub;
905 break;
906 case Intrinsic::smul_with_overflow:
907 case Intrinsic::umul_with_overflow:
908 Opcode = Instruction::Mul;
909 break;
910 default:
911 break;
912 }
913
914 if (Opcode != 0) {
915 // Intrinsic recognized. Grab its args to finish building the
916 // expression.
917 assert(II->getNumArgOperands() == 2 &&
918 "Expect two args for recognised intrinsics.");
919 return createBinaryExpression(Opcode, EI->getType(),
920 II->getArgOperand(0),
921 II->getArgOperand(1), B);
922 }
923 }
924 }
925
926 return createAggregateValueExpression(I, B);
927}
928
929// Substitute and symbolize the value before value numbering.
930const Expression *NewGVN::performSymbolicEvaluation(Value *V,
931 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000932 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000933 if (auto *C = dyn_cast<Constant>(V))
934 E = createConstantExpression(C);
935 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
936 E = createVariableExpression(V);
937 } else {
938 // TODO: memory intrinsics.
939 // TODO: Some day, we should do the forward propagation and reassociation
940 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000941 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000942 switch (I->getOpcode()) {
943 case Instruction::ExtractValue:
944 case Instruction::InsertValue:
945 E = performSymbolicAggrValueEvaluation(I, B);
946 break;
947 case Instruction::PHI:
948 E = performSymbolicPHIEvaluation(I, B);
949 break;
950 case Instruction::Call:
951 E = performSymbolicCallEvaluation(I, B);
952 break;
953 case Instruction::Store:
954 E = performSymbolicStoreEvaluation(I, B);
955 break;
956 case Instruction::Load:
957 E = performSymbolicLoadEvaluation(I, B);
958 break;
959 case Instruction::BitCast: {
960 E = createExpression(I, B);
961 } break;
962
963 case Instruction::Add:
964 case Instruction::FAdd:
965 case Instruction::Sub:
966 case Instruction::FSub:
967 case Instruction::Mul:
968 case Instruction::FMul:
969 case Instruction::UDiv:
970 case Instruction::SDiv:
971 case Instruction::FDiv:
972 case Instruction::URem:
973 case Instruction::SRem:
974 case Instruction::FRem:
975 case Instruction::Shl:
976 case Instruction::LShr:
977 case Instruction::AShr:
978 case Instruction::And:
979 case Instruction::Or:
980 case Instruction::Xor:
981 case Instruction::ICmp:
982 case Instruction::FCmp:
983 case Instruction::Trunc:
984 case Instruction::ZExt:
985 case Instruction::SExt:
986 case Instruction::FPToUI:
987 case Instruction::FPToSI:
988 case Instruction::UIToFP:
989 case Instruction::SIToFP:
990 case Instruction::FPTrunc:
991 case Instruction::FPExt:
992 case Instruction::PtrToInt:
993 case Instruction::IntToPtr:
994 case Instruction::Select:
995 case Instruction::ExtractElement:
996 case Instruction::InsertElement:
997 case Instruction::ShuffleVector:
998 case Instruction::GetElementPtr:
999 E = createExpression(I, B);
1000 break;
1001 default:
1002 return nullptr;
1003 }
1004 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001005 return E;
1006}
1007
1008// There is an edge from 'Src' to 'Dst'. Return true if every path from
1009// the entry block to 'Dst' passes via this edge. In particular 'Dst'
1010// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +00001011bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +00001012
1013 // While in theory it is interesting to consider the case in which Dst has
1014 // more than one predecessor, because Dst might be part of a loop which is
1015 // only reachable from Src, in practice it is pointless since at the time
1016 // GVN runs all such loops have preheaders, which means that Dst will have
1017 // been changed to have only one predecessor, namely Src.
1018 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1019 const BasicBlock *Src = E.getStart();
1020 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
1021 (void)Src;
1022 return Pred != nullptr;
1023}
1024
1025void NewGVN::markUsersTouched(Value *V) {
1026 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001027 for (auto *User : V->users()) {
1028 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Davide Italiano7e274e02016-12-22 16:03:48 +00001029 TouchedInstructions.set(InstrDFS[User]);
1030 }
1031}
1032
1033void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1034 for (auto U : MA->users()) {
1035 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
1036 TouchedInstructions.set(InstrDFS[MUD->getMemoryInst()]);
1037 else
Daniel Berline0bd37e2016-12-29 22:15:12 +00001038 TouchedInstructions.set(InstrDFS[U]);
Davide Italiano7e274e02016-12-22 16:03:48 +00001039 }
1040}
1041
Daniel Berlin32f8d562017-01-07 16:55:14 +00001042// Touch the instructions that need to be updated after a congruence class has a
1043// leader change, and mark changed values.
1044void NewGVN::markLeaderChangeTouched(CongruenceClass *CC) {
1045 for (auto M : CC->Members) {
1046 if (auto *I = dyn_cast<Instruction>(M))
1047 TouchedInstructions.set(InstrDFS[I]);
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001048 LeaderChanges.insert(M);
1049 }
1050}
1051
1052// Move a value, currently in OldClass, to be part of NewClass
1053// Update OldClass for the move (including changing leaders, etc)
1054void NewGVN::moveValueToNewCongruenceClass(Value *V, CongruenceClass *OldClass,
1055 CongruenceClass *NewClass) {
1056 DEBUG(dbgs() << "New congruence class for " << V << " is " << NewClass->ID
1057 << "\n");
1058 OldClass->Members.erase(V);
1059 NewClass->Members.insert(V);
1060 if (isa<StoreInst>(V)) {
1061 --OldClass->StoreCount;
1062 assert(OldClass->StoreCount >= 0);
1063 ++NewClass->StoreCount;
1064 assert(NewClass->StoreCount >= 0);
1065 }
1066
1067 ValueToClass[V] = NewClass;
1068 // See if we destroyed the class or need to swap leaders.
1069 if (OldClass->Members.empty() && OldClass != InitialClass) {
1070 if (OldClass->DefiningExpr) {
1071 OldClass->Dead = true;
1072 DEBUG(dbgs() << "Erasing expression " << OldClass->DefiningExpr
1073 << " from table\n");
1074 ExpressionToClass.erase(OldClass->DefiningExpr);
1075 }
1076 } else if (OldClass->RepLeader == V) {
1077 // When the leader changes, the value numbering of
1078 // everything may change due to symbolization changes, so we need to
1079 // reprocess.
1080 OldClass->RepLeader = *(OldClass->Members.begin());
1081 markLeaderChangeTouched(OldClass);
Daniel Berlin32f8d562017-01-07 16:55:14 +00001082 }
1083}
1084
Davide Italiano7e274e02016-12-22 16:03:48 +00001085// Perform congruence finding on a given value numbering expression.
1086void NewGVN::performCongruenceFinding(Value *V, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001087 ValueToExpression[V] = E;
1088 // This is guaranteed to return something, since it will at least find
1089 // INITIAL.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001090
Davide Italiano7e274e02016-12-22 16:03:48 +00001091 CongruenceClass *VClass = ValueToClass[V];
1092 assert(VClass && "Should have found a vclass");
1093 // Dead classes should have been eliminated from the mapping.
1094 assert(!VClass->Dead && "Found a dead class");
1095
1096 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001097 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001098 EClass = ValueToClass[VE->getVariableValue()];
1099 } else {
1100 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1101
1102 // If it's not in the value table, create a new congruence class.
1103 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001104 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001105 auto place = lookupResult.first;
1106 place->second = NewClass;
1107
1108 // Constants and variables should always be made the leader.
Daniel Berlin32f8d562017-01-07 16:55:14 +00001109 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001110 NewClass->RepLeader = CE->getConstantValue();
Daniel Berlin32f8d562017-01-07 16:55:14 +00001111 } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
1112 StoreInst *SI = SE->getStoreInst();
1113 NewClass->RepLeader =
1114 lookupOperandLeader(SI->getValueOperand(), SI, SI->getParent());
1115 } else {
Davide Italiano7e274e02016-12-22 16:03:48 +00001116 NewClass->RepLeader = V;
Daniel Berlin32f8d562017-01-07 16:55:14 +00001117 }
1118 assert(!isa<VariableExpression>(E) &&
1119 "VariableExpression should have been handled already");
Davide Italiano7e274e02016-12-22 16:03:48 +00001120
1121 EClass = NewClass;
1122 DEBUG(dbgs() << "Created new congruence class for " << *V
1123 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin589cecc2017-01-02 18:00:46 +00001124 << " and leader " << *(NewClass->RepLeader) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001125 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1126 } else {
1127 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001128 if (isa<ConstantExpression>(E))
1129 assert(isa<Constant>(EClass->RepLeader) &&
1130 "Any class with a constant expression should have a "
1131 "constant leader");
1132
Davide Italiano7e274e02016-12-22 16:03:48 +00001133 assert(EClass && "Somehow don't have an eclass");
1134
1135 assert(!EClass->Dead && "We accidentally looked up a dead class");
1136 }
1137 }
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001138 bool ClassChanged = VClass != EClass;
1139 bool LeaderChanged = LeaderChanges.erase(V);
1140 if (ClassChanged || LeaderChanged) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001141 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1142 << "\n");
1143
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001144 if (ClassChanged)
Davide Italiano7e274e02016-12-22 16:03:48 +00001145
Daniel Berlin3a1bd022017-01-11 20:22:05 +00001146 moveValueToNewCongruenceClass(V, VClass, EClass);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001147
Davide Italiano7e274e02016-12-22 16:03:48 +00001148 markUsersTouched(V);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001149 if (auto *I = dyn_cast<Instruction>(V)) {
1150 if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
1151 // If this is a MemoryDef, we need to update the equivalence table. If
Daniel Berlin25f05b02017-01-02 18:22:38 +00001152 // we determined the expression is congruent to a different memory
1153 // state, use that different memory state. If we determined it didn't,
Daniel Berlinde43ef92017-01-02 19:49:17 +00001154 // we update that as well. Right now, we only support store
Daniel Berlin25f05b02017-01-02 18:22:38 +00001155 // expressions.
Daniel Berlinde43ef92017-01-02 19:49:17 +00001156 if (!isa<MemoryUse>(MA) && isa<StoreExpression>(E) &&
1157 EClass->Members.size() != 1) {
1158 auto *DefAccess = cast<StoreExpression>(E)->getDefiningAccess();
1159 setMemoryAccessEquivTo(MA, DefAccess != MA ? DefAccess : nullptr);
1160 } else {
1161 setMemoryAccessEquivTo(MA, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001162 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001163 markMemoryUsersTouched(MA);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001164 }
1165 }
Daniel Berlin32f8d562017-01-07 16:55:14 +00001166 } else if (StoreInst *SI = dyn_cast<StoreInst>(V)) {
1167 // There is, sadly, one complicating thing for stores. Stores do not
1168 // produce values, only consume them. However, in order to make loads and
1169 // stores value number the same, we ignore the value operand of the store.
1170 // But the value operand will still be the leader of our class, and thus, it
1171 // may change. Because the store is a use, the store will get reprocessed,
1172 // but nothing will change about it, and so nothing above will catch it
1173 // (since the class will not change). In order to make sure everything ends
1174 // up okay, we need to recheck the leader of the class. Since stores of
1175 // different values value number differently due to different memorydefs, we
1176 // are guaranteed the leader is always the same between stores in the same
1177 // class.
1178 DEBUG(dbgs() << "Checking store leader\n");
1179 auto ProperLeader =
1180 lookupOperandLeader(SI->getValueOperand(), SI, SI->getParent());
1181 if (EClass->RepLeader != ProperLeader) {
1182 DEBUG(dbgs() << "Store leader changed, fixing\n");
1183 EClass->RepLeader = ProperLeader;
1184 markLeaderChangeTouched(EClass);
1185 markMemoryUsersTouched(MSSA->getMemoryAccess(SI));
1186 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001187 }
1188}
1189
1190// Process the fact that Edge (from, to) is reachable, including marking
1191// any newly reachable blocks and instructions for processing.
1192void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1193 // Check if the Edge was reachable before.
1194 if (ReachableEdges.insert({From, To}).second) {
1195 // If this block wasn't reachable before, all instructions are touched.
1196 if (ReachableBlocks.insert(To).second) {
1197 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1198 const auto &InstRange = BlockInstRange.lookup(To);
1199 TouchedInstructions.set(InstRange.first, InstRange.second);
1200 } else {
1201 DEBUG(dbgs() << "Block " << getBlockName(To)
1202 << " was reachable, but new edge {" << getBlockName(From)
1203 << "," << getBlockName(To) << "} to it found\n");
1204
1205 // We've made an edge reachable to an existing block, which may
1206 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1207 // they are the only thing that depend on new edges. Anything using their
1208 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001209 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
1210 TouchedInstructions.set(InstrDFS[MemPhi]);
1211
Davide Italiano7e274e02016-12-22 16:03:48 +00001212 auto BI = To->begin();
1213 while (isa<PHINode>(BI)) {
1214 TouchedInstructions.set(InstrDFS[&*BI]);
1215 ++BI;
1216 }
1217 }
1218 }
1219}
1220
1221// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1222// see if we know some constant value for it already.
1223Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1224 auto Result = lookupOperandLeader(Cond, nullptr, B);
1225 if (isa<Constant>(Result))
1226 return Result;
1227 return nullptr;
1228}
1229
1230// Process the outgoing edges of a block for reachability.
1231void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1232 // Evaluate reachability of terminator instruction.
1233 BranchInst *BR;
1234 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1235 Value *Cond = BR->getCondition();
1236 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1237 if (!CondEvaluated) {
1238 if (auto *I = dyn_cast<Instruction>(Cond)) {
1239 const Expression *E = createExpression(I, B);
1240 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1241 CondEvaluated = CE->getConstantValue();
1242 }
1243 } else if (isa<ConstantInt>(Cond)) {
1244 CondEvaluated = Cond;
1245 }
1246 }
1247 ConstantInt *CI;
1248 BasicBlock *TrueSucc = BR->getSuccessor(0);
1249 BasicBlock *FalseSucc = BR->getSuccessor(1);
1250 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1251 if (CI->isOne()) {
1252 DEBUG(dbgs() << "Condition for Terminator " << *TI
1253 << " evaluated to true\n");
1254 updateReachableEdge(B, TrueSucc);
1255 } else if (CI->isZero()) {
1256 DEBUG(dbgs() << "Condition for Terminator " << *TI
1257 << " evaluated to false\n");
1258 updateReachableEdge(B, FalseSucc);
1259 }
1260 } else {
1261 updateReachableEdge(B, TrueSucc);
1262 updateReachableEdge(B, FalseSucc);
1263 }
1264 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1265 // For switches, propagate the case values into the case
1266 // destinations.
1267
1268 // Remember how many outgoing edges there are to every successor.
1269 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1270
Davide Italiano7e274e02016-12-22 16:03:48 +00001271 Value *SwitchCond = SI->getCondition();
1272 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1273 // See if we were able to turn this switch statement into a constant.
1274 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001275 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001276 // We should be able to get case value for this.
1277 auto CaseVal = SI->findCaseValue(CondVal);
1278 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1279 // We proved the value is outside of the range of the case.
1280 // We can't do anything other than mark the default dest as reachable,
1281 // and go home.
1282 updateReachableEdge(B, SI->getDefaultDest());
1283 return;
1284 }
1285 // Now get where it goes and mark it reachable.
1286 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1287 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001288 } else {
1289 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1290 BasicBlock *TargetBlock = SI->getSuccessor(i);
1291 ++SwitchEdges[TargetBlock];
1292 updateReachableEdge(B, TargetBlock);
1293 }
1294 }
1295 } else {
1296 // Otherwise this is either unconditional, or a type we have no
1297 // idea about. Just mark successors as reachable.
1298 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1299 BasicBlock *TargetBlock = TI->getSuccessor(i);
1300 updateReachableEdge(B, TargetBlock);
1301 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001302
1303 // This also may be a memory defining terminator, in which case, set it
1304 // equivalent to nothing.
1305 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1306 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001307 }
1308}
1309
Daniel Berlin85f91b02016-12-26 20:06:58 +00001310// The algorithm initially places the values of the routine in the INITIAL
1311// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001312// class. The leader of INITIAL is the undetermined value `TOP`.
1313// When the algorithm has finished, values still in INITIAL are unreachable.
1314void NewGVN::initializeCongruenceClasses(Function &F) {
1315 // FIXME now i can't remember why this is 2
1316 NextCongruenceNum = 2;
1317 // Initialize all other instructions to be in INITIAL class.
1318 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001319 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001320 for (auto &B : F) {
1321 if (auto *MP = MSSA->getMemoryAccess(&B))
1322 MemoryAccessEquiv.insert({MP, MSSA->getLiveOnEntryDef()});
1323
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001324 for (auto &I : B) {
1325 InitialValues.insert(&I);
1326 ValueToClass[&I] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001327 // All memory accesses are equivalent to live on entry to start. They must
1328 // be initialized to something so that initial changes are noticed. For
1329 // the maximal answer, we initialize them all to be the same as
1330 // liveOnEntry. Note that to save time, we only initialize the
1331 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1332 // other expression can generate a memory equivalence. If we start
1333 // handling memcpy/etc, we can expand this.
1334 if (isa<StoreInst>(&I))
1335 MemoryAccessEquiv.insert(
1336 {MSSA->getMemoryAccess(&I), MSSA->getLiveOnEntryDef()});
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001337 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001338 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001339 InitialClass->Members.swap(InitialValues);
1340
1341 // Initialize arguments to be in their own unique congruence classes
1342 for (auto &FA : F.args())
1343 createSingletonCongruenceClass(&FA);
1344}
1345
1346void NewGVN::cleanupTables() {
1347 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1348 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1349 << CongruenceClasses[i]->Members.size() << " members\n");
1350 // Make sure we delete the congruence class (probably worth switching to
1351 // a unique_ptr at some point.
1352 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001353 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001354 }
1355
1356 ValueToClass.clear();
1357 ArgRecycler.clear(ExpressionAllocator);
1358 ExpressionAllocator.Reset();
1359 CongruenceClasses.clear();
1360 ExpressionToClass.clear();
1361 ValueToExpression.clear();
1362 ReachableBlocks.clear();
1363 ReachableEdges.clear();
1364#ifndef NDEBUG
1365 ProcessedCount.clear();
1366#endif
1367 DFSDomMap.clear();
1368 InstrDFS.clear();
1369 InstructionsToErase.clear();
1370
1371 DFSToInstr.clear();
1372 BlockInstRange.clear();
1373 TouchedInstructions.clear();
1374 DominatedInstRange.clear();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001375 MemoryAccessEquiv.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001376}
1377
1378std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1379 unsigned Start) {
1380 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001381 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1382 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001383 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001384 }
1385
Davide Italiano7e274e02016-12-22 16:03:48 +00001386 for (auto &I : *B) {
1387 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001388 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001389 }
1390
1391 // All of the range functions taken half-open ranges (open on the end side).
1392 // So we do not subtract one from count, because at this point it is one
1393 // greater than the last instruction.
1394 return std::make_pair(Start, End);
1395}
1396
1397void NewGVN::updateProcessedCount(Value *V) {
1398#ifndef NDEBUG
1399 if (ProcessedCount.count(V) == 0) {
1400 ProcessedCount.insert({V, 1});
1401 } else {
1402 ProcessedCount[V] += 1;
1403 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001404 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001405 }
1406#endif
1407}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001408// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1409void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1410 // If all the arguments are the same, the MemoryPhi has the same value as the
1411 // argument.
1412 // Filter out unreachable blocks from our operands.
1413 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1414 return ReachableBlocks.count(MP->getIncomingBlock(U));
1415 });
1416
1417 assert(Filtered.begin() != Filtered.end() &&
1418 "We should not be processing a MemoryPhi in a completely "
1419 "unreachable block");
1420
1421 // Transform the remaining operands into operand leaders.
1422 // FIXME: mapped_iterator should have a range version.
1423 auto LookupFunc = [&](const Use &U) {
1424 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1425 };
1426 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1427 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1428
1429 // and now check if all the elements are equal.
1430 // Sadly, we can't use std::equals since these are random access iterators.
1431 MemoryAccess *AllSameValue = *MappedBegin;
1432 ++MappedBegin;
1433 bool AllEqual = std::all_of(
1434 MappedBegin, MappedEnd,
1435 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1436
1437 if (AllEqual)
1438 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1439 else
1440 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1441
1442 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr))
1443 markMemoryUsersTouched(MP);
1444}
1445
1446// Value number a single instruction, symbolically evaluating, performing
1447// congruence finding, and updating mappings.
1448void NewGVN::valueNumberInstruction(Instruction *I) {
1449 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001450 if (isInstructionTriviallyDead(I, TLI)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001451 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001452 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001453 return;
1454 }
1455 if (!I->isTerminator()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001456 const auto *Symbolized = performSymbolicEvaluation(I, I->getParent());
1457 // If we couldn't come up with a symbolic expression, use the unknown
1458 // expression
1459 if (Symbolized == nullptr)
1460 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001461 performCongruenceFinding(I, Symbolized);
1462 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001463 // Handle terminators that return values. All of them produce values we
1464 // don't currently understand.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001465 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001466 auto *Symbolized = createUnknownExpression(I);
1467 performCongruenceFinding(I, Symbolized);
1468 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001469 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1470 }
1471}
Davide Italiano7e274e02016-12-22 16:03:48 +00001472
Daniel Berlin589cecc2017-01-02 18:00:46 +00001473// Verify the that the memory equivalence table makes sense relative to the
1474// congruence classes.
1475void NewGVN::verifyMemoryCongruency() {
1476 // Anything equivalent in the memory access table should be in the same
1477 // congruence class.
1478
1479 // Filter out the unreachable and trivially dead entries, because they may
1480 // never have been updated if the instructions were not processed.
1481 auto ReachableAccessPred =
1482 [&](const std::pair<const MemoryAccess *, MemoryAccess *> Pair) {
1483 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1484 if (!Result)
1485 return false;
1486 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1487 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1488 return true;
1489 };
1490
1491 auto Filtered = make_filter_range(MemoryAccessEquiv, ReachableAccessPred);
1492 for (auto KV : Filtered) {
1493 assert(KV.first != KV.second &&
1494 "We added a useless equivalence to the memory equivalence table");
1495 // Unreachable instructions may not have changed because we never process
1496 // them.
1497 if (!ReachableBlocks.count(KV.first->getBlock()))
1498 continue;
1499 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
1500 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second);
Davide Italiano67ada752017-01-02 19:03:16 +00001501 if (FirstMUD && SecondMUD)
Daniel Berlin589cecc2017-01-02 18:00:46 +00001502 assert(
Davide Italiano67ada752017-01-02 19:03:16 +00001503 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1504 ValueToClass.lookup(SecondMUD->getMemoryInst()) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00001505 "The instructions for these memory operations should have been in "
1506 "the same congruence class");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001507 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1508
1509 // We can only sanely verify that MemoryDefs in the operand list all have
1510 // the same class.
1511 auto ReachableOperandPred = [&](const Use &U) {
1512 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1513 isa<MemoryDef>(U);
1514
1515 };
1516 // All arguments should in the same class, ignoring unreachable arguments
1517 auto FilteredPhiArgs =
1518 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1519 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1520 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1521 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1522 const MemoryDef *MD = cast<MemoryDef>(U);
1523 return ValueToClass.lookup(MD->getMemoryInst());
1524 });
1525 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1526 PhiOpClasses.begin()) &&
1527 "All MemoryPhi arguments should be in the same class");
1528 }
1529 }
1530}
1531
Daniel Berlin85f91b02016-12-26 20:06:58 +00001532// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001533bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001534 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1535 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001536 bool Changed = false;
1537 DT = _DT;
1538 AC = _AC;
1539 TLI = _TLI;
1540 AA = _AA;
1541 MSSA = _MSSA;
1542 DL = &F.getParent()->getDataLayout();
1543 MSSAWalker = MSSA->getWalker();
1544
1545 // Count number of instructions for sizing of hash tables, and come
1546 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001547 unsigned ICount = 1;
1548 // Add an empty instruction to account for the fact that we start at 1
1549 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001550 // Note: We want RPO traversal of the blocks, which is not quite the same as
1551 // dominator tree order, particularly with regard whether backedges get
1552 // visited first or second, given a block with multiple successors.
1553 // If we visit in the wrong order, we will end up performing N times as many
1554 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001555 // The dominator tree does guarantee that, for a given dom tree node, it's
1556 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1557 // the siblings.
1558 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001559 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001560 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001561 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001562 auto *Node = DT->getNode(B);
1563 assert(Node && "RPO and Dominator tree should have same reachability");
1564 RPOOrdering[Node] = ++Counter;
1565 }
1566 // Sort dominator tree children arrays into RPO.
1567 for (auto &B : RPOT) {
1568 auto *Node = DT->getNode(B);
1569 if (Node->getChildren().size() > 1)
1570 std::sort(Node->begin(), Node->end(),
1571 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1572 return RPOOrdering[A] < RPOOrdering[B];
1573 });
1574 }
1575
1576 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1577 auto DFI = df_begin(DT->getRootNode());
1578 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1579 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001580 const auto &BlockRange = assignDFSNumbers(B, ICount);
1581 BlockInstRange.insert({B, BlockRange});
1582 ICount += BlockRange.second - BlockRange.first;
1583 }
1584
1585 // Handle forward unreachable blocks and figure out which blocks
1586 // have single preds.
1587 for (auto &B : F) {
1588 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001589 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001590 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1591 BlockInstRange.insert({&B, BlockRange});
1592 ICount += BlockRange.second - BlockRange.first;
1593 }
1594 }
1595
Daniel Berline0bd37e2016-12-29 22:15:12 +00001596 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001597 DominatedInstRange.reserve(F.size());
1598 // Ensure we don't end up resizing the expressionToClass map, as
1599 // that can be quite expensive. At most, we have one expression per
1600 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001601 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001602
1603 // Initialize the touched instructions to include the entry block.
1604 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1605 TouchedInstructions.set(InstRange.first, InstRange.second);
1606 ReachableBlocks.insert(&F.getEntryBlock());
1607
1608 initializeCongruenceClasses(F);
1609
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001610 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001611 // We start out in the entry block.
1612 BasicBlock *LastBlock = &F.getEntryBlock();
1613 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001614 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00001615 // Walk through all the instructions in all the blocks in RPO.
1616 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1617 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Daniel Berline0bd37e2016-12-29 22:15:12 +00001618 assert(InstrNum != 0 && "Bit 0 should never be set, something touched an "
1619 "instruction not in the lookup table");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001620 Value *V = DFSToInstr[InstrNum];
1621 BasicBlock *CurrBlock = nullptr;
1622
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001623 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001624 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001625 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001626 CurrBlock = MP->getBlock();
1627 else
1628 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001629
1630 // If we hit a new block, do reachability processing.
1631 if (CurrBlock != LastBlock) {
1632 LastBlock = CurrBlock;
1633 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1634 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1635
1636 // If it's not reachable, erase any touched instructions and move on.
1637 if (!BlockReachable) {
1638 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1639 DEBUG(dbgs() << "Skipping instructions in block "
1640 << getBlockName(CurrBlock)
1641 << " because it is unreachable\n");
1642 continue;
1643 }
1644 updateProcessedCount(CurrBlock);
1645 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001646
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001647 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001648 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1649 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001650 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001651 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001652 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001653 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001654 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001655 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001656 // Reset after processing (because we may mark ourselves as touched when
1657 // we propagate equalities).
1658 TouchedInstructions.reset(InstrNum);
1659 }
1660 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001661 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001662#ifndef NDEBUG
1663 verifyMemoryCongruency();
1664#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001665 Changed |= eliminateInstructions(F);
1666
1667 // Delete all instructions marked for deletion.
1668 for (Instruction *ToErase : InstructionsToErase) {
1669 if (!ToErase->use_empty())
1670 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1671
1672 ToErase->eraseFromParent();
1673 }
1674
1675 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001676 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1677 return !ReachableBlocks.count(&BB);
1678 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001679
1680 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1681 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001682 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001683 deleteInstructionsInBlock(&BB);
1684 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001685 }
1686
1687 cleanupTables();
1688 return Changed;
1689}
1690
1691bool NewGVN::runOnFunction(Function &F) {
1692 if (skipFunction(F))
1693 return false;
1694 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1695 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1696 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1697 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1698 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1699}
1700
Daniel Berlin85f91b02016-12-26 20:06:58 +00001701PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001702 NewGVN Impl;
1703
1704 // Apparently the order in which we get these results matter for
1705 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1706 // the same order here, just in case.
1707 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1708 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1709 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1710 auto &AA = AM.getResult<AAManager>(F);
1711 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1712 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1713 if (!Changed)
1714 return PreservedAnalyses::all();
1715 PreservedAnalyses PA;
1716 PA.preserve<DominatorTreeAnalysis>();
1717 PA.preserve<GlobalsAA>();
1718 return PA;
1719}
1720
1721// Return true if V is a value that will always be available (IE can
1722// be placed anywhere) in the function. We don't do globals here
1723// because they are often worse to put in place.
1724// TODO: Separate cost from availability
1725static bool alwaysAvailable(Value *V) {
1726 return isa<Constant>(V) || isa<Argument>(V);
1727}
1728
1729// Get the basic block from an instruction/value.
1730static BasicBlock *getBlockForValue(Value *V) {
1731 if (auto *I = dyn_cast<Instruction>(V))
1732 return I->getParent();
1733 return nullptr;
1734}
1735
1736struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001737 int DFSIn = 0;
1738 int DFSOut = 0;
1739 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001740 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001741 Value *Val = nullptr;
1742 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001743
1744 bool operator<(const ValueDFS &Other) const {
1745 // It's not enough that any given field be less than - we have sets
1746 // of fields that need to be evaluated together to give a proper ordering.
1747 // For example, if you have;
1748 // DFS (1, 3)
1749 // Val 0
1750 // DFS (1, 2)
1751 // Val 50
1752 // We want the second to be less than the first, but if we just go field
1753 // by field, we will get to Val 0 < Val 50 and say the first is less than
1754 // the second. We only want it to be less than if the DFS orders are equal.
1755 //
1756 // Each LLVM instruction only produces one value, and thus the lowest-level
1757 // differentiator that really matters for the stack (and what we use as as a
1758 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001759 // Everything else in the structure is instruction level, and only affects
1760 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001761 //
1762 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1763 // the order of replacement of uses does not matter.
1764 // IE given,
1765 // a = 5
1766 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001767 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1768 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001769 // The .val will be the same as well.
1770 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001771 // You will replace both, and it does not matter what order you replace them
1772 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1773 // operand 2).
1774 // Similarly for the case of same dfsin, dfsout, localnum, but different
1775 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001776 // a = 5
1777 // b = 6
1778 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001779 // in c, we will a valuedfs for a, and one for b,with everything the same
1780 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001781 // It does not matter what order we replace these operands in.
1782 // You will always end up with the same IR, and this is guaranteed.
1783 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1784 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1785 Other.U);
1786 }
1787};
1788
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00001789void NewGVN::convertDenseToDFSOrdered(
1790 CongruenceClass::MemberSet &Dense,
1791 SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001792 for (auto D : Dense) {
1793 // First add the value.
1794 BasicBlock *BB = getBlockForValue(D);
1795 // Constants are handled prior to ever calling this function, so
1796 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001797 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001798 ValueDFS VD;
1799
1800 std::pair<int, int> DFSPair = DFSDomMap[BB];
1801 assert(DFSPair.first != -1 && DFSPair.second != -1 && "Invalid DFS Pair");
1802 VD.DFSIn = DFSPair.first;
1803 VD.DFSOut = DFSPair.second;
1804 VD.Val = D;
1805 // If it's an instruction, use the real local dfs number.
1806 if (auto *I = dyn_cast<Instruction>(D))
1807 VD.LocalNum = InstrDFS[I];
1808 else
1809 llvm_unreachable("Should have been an instruction");
1810
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001811 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001812
1813 // Now add the users.
1814 for (auto &U : D->uses()) {
1815 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1816 ValueDFS VD;
1817 // Put the phi node uses in the incoming block.
1818 BasicBlock *IBlock;
1819 if (auto *P = dyn_cast<PHINode>(I)) {
1820 IBlock = P->getIncomingBlock(U);
1821 // Make phi node users appear last in the incoming block
1822 // they are from.
1823 VD.LocalNum = InstrDFS.size() + 1;
1824 } else {
1825 IBlock = I->getParent();
1826 VD.LocalNum = InstrDFS[I];
1827 }
1828 std::pair<int, int> DFSPair = DFSDomMap[IBlock];
1829 VD.DFSIn = DFSPair.first;
1830 VD.DFSOut = DFSPair.second;
1831 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001832 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001833 }
1834 }
1835 }
1836}
1837
1838static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1839 // Patch the replacement so that it is not more restrictive than the value
1840 // being replaced.
1841 auto *Op = dyn_cast<BinaryOperator>(I);
1842 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
1843
1844 if (Op && ReplOp)
1845 ReplOp->andIRFlags(Op);
1846
1847 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
1848 // FIXME: If both the original and replacement value are part of the
1849 // same control-flow region (meaning that the execution of one
1850 // guarentees the executation of the other), then we can combine the
1851 // noalias scopes here and do better than the general conservative
1852 // answer used in combineMetadata().
1853
1854 // In general, GVN unifies expressions over different control-flow
1855 // regions, and so we need a conservative combination of the noalias
1856 // scopes.
1857 unsigned KnownIDs[] = {
1858 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1859 LLVMContext::MD_noalias, LLVMContext::MD_range,
1860 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1861 LLVMContext::MD_invariant_group};
1862 combineMetadata(ReplInst, I, KnownIDs);
1863 }
1864}
1865
1866static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1867 patchReplacementInstruction(I, Repl);
1868 I->replaceAllUsesWith(Repl);
1869}
1870
1871void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
1872 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1873 ++NumGVNBlocksDeleted;
1874
1875 // Check to see if there are non-terminating instructions to delete.
1876 if (isa<TerminatorInst>(BB->begin()))
1877 return;
1878
1879 // Delete the instructions backwards, as it has a reduced likelihood of having
1880 // to update as many def-use and use-def chains. Start after the terminator.
1881 auto StartPoint = BB->rbegin();
1882 ++StartPoint;
1883 // Note that we explicitly recalculate BB->rend() on each iteration,
1884 // as it may change when we remove the first instruction.
1885 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
1886 Instruction &Inst = *I++;
1887 if (!Inst.use_empty())
1888 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
1889 if (isa<LandingPadInst>(Inst))
1890 continue;
1891
1892 Inst.eraseFromParent();
1893 ++NumGVNInstrDeleted;
1894 }
1895}
1896
1897void NewGVN::markInstructionForDeletion(Instruction *I) {
1898 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
1899 InstructionsToErase.insert(I);
1900}
1901
1902void NewGVN::replaceInstruction(Instruction *I, Value *V) {
1903
1904 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
1905 patchAndReplaceAllUsesWith(I, V);
1906 // We save the actual erasing to avoid invalidating memory
1907 // dependencies until we are done with everything.
1908 markInstructionForDeletion(I);
1909}
1910
1911namespace {
1912
1913// This is a stack that contains both the value and dfs info of where
1914// that value is valid.
1915class ValueDFSStack {
1916public:
1917 Value *back() const { return ValueStack.back(); }
1918 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
1919
1920 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001921 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001922 DFSStack.emplace_back(DFSIn, DFSOut);
1923 }
1924 bool empty() const { return DFSStack.empty(); }
1925 bool isInScope(int DFSIn, int DFSOut) const {
1926 if (empty())
1927 return false;
1928 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
1929 }
1930
1931 void popUntilDFSScope(int DFSIn, int DFSOut) {
1932
1933 // These two should always be in sync at this point.
1934 assert(ValueStack.size() == DFSStack.size() &&
1935 "Mismatch between ValueStack and DFSStack");
1936 while (
1937 !DFSStack.empty() &&
1938 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
1939 DFSStack.pop_back();
1940 ValueStack.pop_back();
1941 }
1942 }
1943
1944private:
1945 SmallVector<Value *, 8> ValueStack;
1946 SmallVector<std::pair<int, int>, 8> DFSStack;
1947};
1948}
Daniel Berlin04443432017-01-07 03:23:47 +00001949
Davide Italiano7e274e02016-12-22 16:03:48 +00001950bool NewGVN::eliminateInstructions(Function &F) {
1951 // This is a non-standard eliminator. The normal way to eliminate is
1952 // to walk the dominator tree in order, keeping track of available
1953 // values, and eliminating them. However, this is mildly
1954 // pointless. It requires doing lookups on every instruction,
1955 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001956 // instructions part of most singleton congruence classes, we know we
1957 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00001958
1959 // Instead, this eliminator looks at the congruence classes directly, sorts
1960 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001961 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001962 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001963 // last member. This is worst case O(E log E) where E = number of
1964 // instructions in a single congruence class. In theory, this is all
1965 // instructions. In practice, it is much faster, as most instructions are
1966 // either in singleton congruence classes or can't possibly be eliminated
1967 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00001968 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001969 // for elimination purposes.
1970 // TODO: If we wanted to be faster, We could remove any members with no
1971 // overlapping ranges while sorting, as we will never eliminate anything
1972 // with those members, as they don't dominate anything else in our set.
1973
Davide Italiano7e274e02016-12-22 16:03:48 +00001974 bool AnythingReplaced = false;
1975
1976 // Since we are going to walk the domtree anyway, and we can't guarantee the
1977 // DFS numbers are updated, we compute some ourselves.
1978 DT->updateDFSNumbers();
1979
1980 for (auto &B : F) {
1981 if (!ReachableBlocks.count(&B)) {
1982 for (const auto S : successors(&B)) {
1983 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001984 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00001985 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
1986 << getBlockName(&B)
1987 << " with undef due to it being unreachable\n");
1988 for (auto &Operand : Phi.incoming_values())
1989 if (Phi.getIncomingBlock(Operand) == &B)
1990 Operand.set(UndefValue::get(Phi.getType()));
1991 }
1992 }
1993 }
1994 DomTreeNode *Node = DT->getNode(&B);
1995 if (Node)
1996 DFSDomMap[&B] = {Node->getDFSNumIn(), Node->getDFSNumOut()};
1997 }
1998
1999 for (CongruenceClass *CC : CongruenceClasses) {
2000 // FIXME: We should eventually be able to replace everything still
2001 // in the initial class with undef, as they should be unreachable.
2002 // Right now, initial still contains some things we skip value
2003 // numbering of (UNREACHABLE's, for example).
2004 if (CC == InitialClass || CC->Dead)
2005 continue;
2006 assert(CC->RepLeader && "We should have had a leader");
2007
2008 // If this is a leader that is always available, and it's a
2009 // constant or has no equivalences, just replace everything with
2010 // it. We then update the congruence class with whatever members
2011 // are left.
2012 if (alwaysAvailable(CC->RepLeader)) {
2013 SmallPtrSet<Value *, 4> MembersLeft;
2014 for (auto M : CC->Members) {
2015
2016 Value *Member = M;
2017
2018 // Void things have no uses we can replace.
2019 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
2020 MembersLeft.insert(Member);
2021 continue;
2022 }
2023
2024 DEBUG(dbgs() << "Found replacement " << *(CC->RepLeader) << " for "
2025 << *Member << "\n");
2026 // Due to equality propagation, these may not always be
2027 // instructions, they may be real values. We don't really
2028 // care about trying to replace the non-instructions.
2029 if (auto *I = dyn_cast<Instruction>(Member)) {
2030 assert(CC->RepLeader != I &&
2031 "About to accidentally remove our leader");
2032 replaceInstruction(I, CC->RepLeader);
2033 AnythingReplaced = true;
2034
2035 continue;
2036 } else {
2037 MembersLeft.insert(I);
2038 }
2039 }
2040 CC->Members.swap(MembersLeft);
2041
2042 } else {
2043 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
2044 // If this is a singleton, we can skip it.
2045 if (CC->Members.size() != 1) {
2046
2047 // This is a stack because equality replacement/etc may place
2048 // constants in the middle of the member list, and we want to use
2049 // those constant values in preference to the current leader, over
2050 // the scope of those constants.
2051 ValueDFSStack EliminationStack;
2052
2053 // Convert the members to DFS ordered sets and then merge them.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002054 SmallVector<ValueDFS, 8> DFSOrderedSet;
Davide Italiano7e274e02016-12-22 16:03:48 +00002055 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
2056
2057 // Sort the whole thing.
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002058 std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
Davide Italiano7e274e02016-12-22 16:03:48 +00002059
Daniel Berlin2f1fbcc2017-01-09 05:34:19 +00002060 for (auto &VD : DFSOrderedSet) {
2061 int MemberDFSIn = VD.DFSIn;
2062 int MemberDFSOut = VD.DFSOut;
2063 Value *Member = VD.Val;
2064 Use *MemberUse = VD.U;
Davide Italiano7e274e02016-12-22 16:03:48 +00002065
Daniel Berlind92e7f92017-01-07 00:01:42 +00002066 if (Member) {
2067 // We ignore void things because we can't get a value from them.
2068 // FIXME: We could actually use this to kill dead stores that are
2069 // dominated by equivalent earlier stores.
2070 if (Member->getType()->isVoidTy())
2071 continue;
2072 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002073
2074 if (EliminationStack.empty()) {
2075 DEBUG(dbgs() << "Elimination Stack is empty\n");
2076 } else {
2077 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2078 << EliminationStack.dfs_back().first << ","
2079 << EliminationStack.dfs_back().second << ")\n");
2080 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002081
2082 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2083 << MemberDFSOut << ")\n");
2084 // First, we see if we are out of scope or empty. If so,
2085 // and there equivalences, we try to replace the top of
2086 // stack with equivalences (if it's on the stack, it must
2087 // not have been eliminated yet).
2088 // Then we synchronize to our current scope, by
2089 // popping until we are back within a DFS scope that
2090 // dominates the current member.
2091 // Then, what happens depends on a few factors
2092 // If the stack is now empty, we need to push
2093 // If we have a constant or a local equivalence we want to
2094 // start using, we also push.
2095 // Otherwise, we walk along, processing members who are
2096 // dominated by this scope, and eliminate them.
2097 bool ShouldPush =
2098 Member && (EliminationStack.empty() || isa<Constant>(Member));
2099 bool OutOfScope =
2100 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2101
2102 if (OutOfScope || ShouldPush) {
2103 // Sync to our current scope.
2104 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2105 ShouldPush |= Member && EliminationStack.empty();
2106 if (ShouldPush) {
2107 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2108 }
2109 }
2110
2111 // If we get to this point, and the stack is empty we must have a use
2112 // with nothing we can use to eliminate it, just skip it.
2113 if (EliminationStack.empty())
2114 continue;
2115
2116 // Skip the Value's, we only want to eliminate on their uses.
2117 if (Member)
2118 continue;
2119 Value *Result = EliminationStack.back();
2120
Daniel Berlind92e7f92017-01-07 00:01:42 +00002121 // Don't replace our existing users with ourselves.
2122 if (MemberUse->get() == Result)
Davide Italiano7e274e02016-12-22 16:03:48 +00002123 continue;
2124
2125 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2126 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2127 << "\n");
2128
2129 // If we replaced something in an instruction, handle the patching of
2130 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002131 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002132 patchReplacementInstruction(ReplacedInst, Result);
2133
2134 assert(isa<Instruction>(MemberUse->getUser()));
2135 MemberUse->set(Result);
2136 AnythingReplaced = true;
2137 }
2138 }
2139 }
2140
2141 // Cleanup the congruence class.
2142 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002143 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002144 if (Member->getType()->isVoidTy()) {
2145 MembersLeft.insert(Member);
2146 continue;
2147 }
2148
2149 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2150 if (isInstructionTriviallyDead(MemberInst)) {
2151 // TODO: Don't mark loads of undefs.
2152 markInstructionForDeletion(MemberInst);
2153 continue;
2154 }
2155 }
2156 MembersLeft.insert(Member);
2157 }
2158 CC->Members.swap(MembersLeft);
2159 }
2160
2161 return AnythingReplaced;
2162}