blob: 790dd6ed72212c3fffddacf15e7a1793b4f495c5 [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");
82
83//===----------------------------------------------------------------------===//
84// GVN Pass
85//===----------------------------------------------------------------------===//
86
87// Anchor methods.
88namespace llvm {
89namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +000090Expression::~Expression() = default;
91BasicExpression::~BasicExpression() = default;
92CallExpression::~CallExpression() = default;
93LoadExpression::~LoadExpression() = default;
94StoreExpression::~StoreExpression() = default;
95AggregateValueExpression::~AggregateValueExpression() = default;
96PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +000097}
98}
99
100// Congruence classes represent the set of expressions/instructions
101// that are all the same *during some scope in the function*.
102// That is, because of the way we perform equality propagation, and
103// because of memory value numbering, it is not correct to assume
104// you can willy-nilly replace any member with any other at any
105// point in the function.
106//
107// For any Value in the Member set, it is valid to replace any dominated member
108// with that Value.
109//
110// Every congruence class has a leader, and the leader is used to
111// symbolize instructions in a canonical way (IE every operand of an
112// instruction that is a member of the same congruence class will
113// always be replaced with leader during symbolization).
114// To simplify symbolization, we keep the leader as a constant if class can be
115// proved to be a constant value.
116// Otherwise, the leader is a randomly chosen member of the value set, it does
117// not matter which one is chosen.
118// Each congruence class also has a defining expression,
119// though the expression may be null. If it exists, it can be used for forward
120// propagation and reassociation of values.
121//
122struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000123 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000124 unsigned ID;
125 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000126 Value *RepLeader = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000127 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000128 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000129 // Actual members of this class.
130 MemberSet Members;
131
132 // True if this class has no members left. This is mainly used for assertion
133 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000134 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000135
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000136 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000137 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000138 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000139};
140
141namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000142template <> struct DenseMapInfo<const Expression *> {
143 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000144 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000145 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
146 return reinterpret_cast<const Expression *>(Val);
147 }
148 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000149 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000150 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
151 return reinterpret_cast<const Expression *>(Val);
152 }
153 static unsigned getHashValue(const Expression *V) {
154 return static_cast<unsigned>(V->getHashValue());
155 }
156 static bool isEqual(const Expression *LHS, const Expression *RHS) {
157 if (LHS == RHS)
158 return true;
159 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
160 LHS == getEmptyKey() || RHS == getEmptyKey())
161 return false;
162 return *LHS == *RHS;
163 }
164};
Davide Italiano7e274e02016-12-22 16:03:48 +0000165} // end namespace llvm
166
167class NewGVN : public FunctionPass {
168 DominatorTree *DT;
169 const DataLayout *DL;
170 const TargetLibraryInfo *TLI;
171 AssumptionCache *AC;
172 AliasAnalysis *AA;
173 MemorySSA *MSSA;
174 MemorySSAWalker *MSSAWalker;
175 BumpPtrAllocator ExpressionAllocator;
176 ArrayRecycler<Value *> ArgRecycler;
177
178 // Congruence class info.
179 CongruenceClass *InitialClass;
180 std::vector<CongruenceClass *> CongruenceClasses;
181 unsigned NextCongruenceNum;
182
183 // Value Mappings.
184 DenseMap<Value *, CongruenceClass *> ValueToClass;
185 DenseMap<Value *, const Expression *> ValueToExpression;
186
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000187 // A table storing which memorydefs/phis represent a memory state provably
188 // equivalent to another memory state.
189 // We could use the congruence class machinery, but the MemoryAccess's are
190 // abstract memory states, so they can only ever be equivalent to each other,
191 // and not to constants, etc.
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000192 DenseMap<const MemoryAccess *, MemoryAccess *> MemoryAccessEquiv;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000193
Davide Italiano7e274e02016-12-22 16:03:48 +0000194 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000195 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000196 ExpressionClassMap ExpressionToClass;
197
198 // Which values have changed as a result of leader changes.
199 SmallPtrSet<Value *, 8> ChangedValues;
200
201 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000202 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000203 DenseSet<BlockEdge> ReachableEdges;
204 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
205
206 // This is a bitvector because, on larger functions, we may have
207 // thousands of touched instructions at once (entire blocks,
208 // instructions with hundreds of uses, etc). Even with optimization
209 // for when we mark whole blocks as touched, when this was a
210 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
211 // the time in GVN just managing this list. The bitvector, on the
212 // other hand, efficiently supports test/set/clear of both
213 // individual and ranges, as well as "find next element" This
214 // enables us to use it as a worklist with essentially 0 cost.
215 BitVector TouchedInstructions;
216
217 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
218 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
219 DominatedInstRange;
220
221#ifndef NDEBUG
222 // Debugging for how many times each block and instruction got processed.
223 DenseMap<const Value *, unsigned> ProcessedCount;
224#endif
225
226 // DFS info.
227 DenseMap<const BasicBlock *, std::pair<int, int>> DFSDomMap;
228 DenseMap<const Value *, unsigned> InstrDFS;
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000229 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000230
231 // Deletion info.
232 SmallPtrSet<Instruction *, 8> InstructionsToErase;
233
234public:
235 static char ID; // Pass identification, replacement for typeid.
236 NewGVN() : FunctionPass(ID) {
237 initializeNewGVNPass(*PassRegistry::getPassRegistry());
238 }
239
240 bool runOnFunction(Function &F) override;
241 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000242 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000243
244private:
245 // This transformation requires dominator postdominator info.
246 void getAnalysisUsage(AnalysisUsage &AU) const override {
247 AU.addRequired<AssumptionCacheTracker>();
248 AU.addRequired<DominatorTreeWrapperPass>();
249 AU.addRequired<TargetLibraryInfoWrapperPass>();
250 AU.addRequired<MemorySSAWrapperPass>();
251 AU.addRequired<AAResultsWrapperPass>();
252
253 AU.addPreserved<DominatorTreeWrapperPass>();
254 AU.addPreserved<GlobalsAAWrapperPass>();
255 }
256
257 // Expression handling.
258 const Expression *createExpression(Instruction *, const BasicBlock *);
259 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
260 const BasicBlock *);
261 PHIExpression *createPHIExpression(Instruction *);
262 const VariableExpression *createVariableExpression(Value *);
263 const ConstantExpression *createConstantExpression(Constant *);
264 const Expression *createVariableOrConstant(Value *V, const BasicBlock *B);
265 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
266 const BasicBlock *);
267 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
268 MemoryAccess *, const BasicBlock *);
269
270 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
271 const BasicBlock *);
272 const AggregateValueExpression *
273 createAggregateValueExpression(Instruction *, const BasicBlock *);
274 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
275 const BasicBlock *);
276
277 // Congruence class handling.
278 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000279 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000280 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000281 return result;
282 }
283
284 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000285 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000286 CClass->Members.insert(Member);
287 ValueToClass[Member] = CClass;
288 return CClass;
289 }
290 void initializeCongruenceClasses(Function &F);
291
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000292 // Value number an Instruction or MemoryPhi.
293 void valueNumberMemoryPhi(MemoryPhi *);
294 void valueNumberInstruction(Instruction *);
295
Davide Italiano7e274e02016-12-22 16:03:48 +0000296 // Symbolic evaluation.
297 const Expression *checkSimplificationResults(Expression *, Instruction *,
298 Value *);
299 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
300 const Expression *performSymbolicLoadEvaluation(Instruction *,
301 const BasicBlock *);
302 const Expression *performSymbolicStoreEvaluation(Instruction *,
303 const BasicBlock *);
304 const Expression *performSymbolicCallEvaluation(Instruction *,
305 const BasicBlock *);
306 const Expression *performSymbolicPHIEvaluation(Instruction *,
307 const BasicBlock *);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000308 bool setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To);
Davide Italiano7e274e02016-12-22 16:03:48 +0000309 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
310 const BasicBlock *);
311
312 // Congruence finding.
313 // Templated to allow them to work both on BB's and BB-edges.
314 template <class T>
315 Value *lookupOperandLeader(Value *, const User *, const T &) const;
316 void performCongruenceFinding(Value *, const Expression *);
317
318 // Reachability handling.
319 void updateReachableEdge(BasicBlock *, BasicBlock *);
320 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000321 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000322 Value *findConditionEquivalence(Value *, BasicBlock *) const;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000323 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000324
325 // Elimination.
326 struct ValueDFS;
327 void convertDenseToDFSOrdered(CongruenceClass::MemberSet &,
328 std::vector<ValueDFS> &);
329
330 bool eliminateInstructions(Function &);
331 void replaceInstruction(Instruction *, Value *);
332 void markInstructionForDeletion(Instruction *);
333 void deleteInstructionsInBlock(BasicBlock *);
334
335 // New instruction creation.
336 void handleNewInstruction(Instruction *){};
337 void markUsersTouched(Value *);
338 void markMemoryUsersTouched(MemoryAccess *);
339
340 // Utilities.
341 void cleanupTables();
342 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
343 void updateProcessedCount(Value *V);
344};
345
346char NewGVN::ID = 0;
347
348// createGVNPass - The public interface to this file.
349FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
350
Davide Italianob1114092016-12-28 13:37:17 +0000351template <typename T>
352static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
353 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000354 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000355 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000356 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000357 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000358 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000359 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000360 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000361 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000362 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000363 return true;
364}
365
Davide Italianob1114092016-12-28 13:37:17 +0000366bool LoadExpression::equals(const Expression &Other) const {
367 return equalsLoadStoreHelper(*this, Other);
368}
Davide Italiano7e274e02016-12-22 16:03:48 +0000369
Davide Italianob1114092016-12-28 13:37:17 +0000370bool StoreExpression::equals(const Expression &Other) const {
371 return equalsLoadStoreHelper(*this, Other);
Davide Italiano7e274e02016-12-22 16:03:48 +0000372}
373
374#ifndef NDEBUG
375static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000376 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000377}
378#endif
379
380INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
381INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
382INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
383INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
384INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
385INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
386INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
387INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
388
389PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
390 BasicBlock *PhiBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000391 auto *PN = cast<PHINode>(I);
392 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000393 PHIExpression(PN->getNumOperands(), I->getParent());
394
395 E->allocateOperands(ArgRecycler, ExpressionAllocator);
396 E->setType(I->getType());
397 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000398
399 auto ReachablePhiArg = [&](const Use &U) {
400 return ReachableBlocks.count(PN->getIncomingBlock(U));
401 };
402
403 // Filter out unreachable operands
404 auto Filtered = make_filter_range(PN->operands(), ReachablePhiArg);
405
406 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
407 [&](const Use &U) -> Value * {
408 // Don't try to transform self-defined phis
409 if (U == PN)
410 return PN;
411 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PhiBlock);
412 return lookupOperandLeader(U, I, BBE);
413 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000414 return E;
415}
416
417// Set basic expression info (Arguments, type, opcode) for Expression
418// E from Instruction I in block B.
419bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
420 const BasicBlock *B) {
421 bool AllConstant = true;
422 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
423 E->setType(GEP->getSourceElementType());
424 else
425 E->setType(I->getType());
426 E->setOpcode(I->getOpcode());
427 E->allocateOperands(ArgRecycler, ExpressionAllocator);
428
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000429 // Transform the operand array into an operand leader array, and keep track of
430 // whether all members are constant.
431 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000432 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000433 AllConstant &= isa<Constant>(Operand);
434 return Operand;
435 });
436
Davide Italiano7e274e02016-12-22 16:03:48 +0000437 return AllConstant;
438}
439
440const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
441 Value *Arg1, Value *Arg2,
442 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000443 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000444
445 E->setType(T);
446 E->setOpcode(Opcode);
447 E->allocateOperands(ArgRecycler, ExpressionAllocator);
448 if (Instruction::isCommutative(Opcode)) {
449 // Ensure that commutative instructions that only differ by a permutation
450 // of their operands get the same value number by sorting the operand value
451 // numbers. Since all commutative instructions have two operands it is more
452 // efficient to sort by hand rather than using, say, std::sort.
453 if (Arg1 > Arg2)
454 std::swap(Arg1, Arg2);
455 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000456 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
457 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000458
459 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
460 DT, AC);
461 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
462 return SimplifiedE;
463 return E;
464}
465
466// Take a Value returned by simplification of Expression E/Instruction
467// I, and see if it resulted in a simpler expression. If so, return
468// that expression.
469// TODO: Once finished, this should not take an Instruction, we only
470// use it for printing.
471const Expression *NewGVN::checkSimplificationResults(Expression *E,
472 Instruction *I, Value *V) {
473 if (!V)
474 return nullptr;
475 if (auto *C = dyn_cast<Constant>(V)) {
476 if (I)
477 DEBUG(dbgs() << "Simplified " << *I << " to "
478 << " constant " << *C << "\n");
479 NumGVNOpsSimplified++;
480 assert(isa<BasicExpression>(E) &&
481 "We should always have had a basic expression here");
482
483 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
484 ExpressionAllocator.Deallocate(E);
485 return createConstantExpression(C);
486 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
487 if (I)
488 DEBUG(dbgs() << "Simplified " << *I << " to "
489 << " variable " << *V << "\n");
490 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
491 ExpressionAllocator.Deallocate(E);
492 return createVariableExpression(V);
493 }
494
495 CongruenceClass *CC = ValueToClass.lookup(V);
496 if (CC && CC->DefiningExpr) {
497 if (I)
498 DEBUG(dbgs() << "Simplified " << *I << " to "
499 << " expression " << *V << "\n");
500 NumGVNOpsSimplified++;
501 assert(isa<BasicExpression>(E) &&
502 "We should always have had a basic expression here");
503 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
504 ExpressionAllocator.Deallocate(E);
505 return CC->DefiningExpr;
506 }
507 return nullptr;
508}
509
510const Expression *NewGVN::createExpression(Instruction *I,
511 const BasicBlock *B) {
512
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000513 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000514
515 bool AllConstant = setBasicExpressionInfo(I, E, B);
516
517 if (I->isCommutative()) {
518 // Ensure that commutative instructions that only differ by a permutation
519 // of their operands get the same value number by sorting the operand value
520 // numbers. Since all commutative instructions have two operands it is more
521 // efficient to sort by hand rather than using, say, std::sort.
522 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
523 if (E->getOperand(0) > E->getOperand(1))
524 E->swapOperands(0, 1);
525 }
526
527 // Perform simplificaiton
528 // TODO: Right now we only check to see if we get a constant result.
529 // We may get a less than constant, but still better, result for
530 // some operations.
531 // IE
532 // add 0, x -> x
533 // and x, x -> x
534 // We should handle this by simply rewriting the expression.
535 if (auto *CI = dyn_cast<CmpInst>(I)) {
536 // Sort the operand value numbers so x<y and y>x get the same value
537 // number.
538 CmpInst::Predicate Predicate = CI->getPredicate();
539 if (E->getOperand(0) > E->getOperand(1)) {
540 E->swapOperands(0, 1);
541 Predicate = CmpInst::getSwappedPredicate(Predicate);
542 }
543 E->setOpcode((CI->getOpcode() << 8) | Predicate);
544 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
545 // TODO: Since we noop bitcasts, we may need to check types before
546 // simplifying, so that we don't end up simplifying based on a wrong
547 // type assumption. We should clean this up so we can use constants of the
548 // wrong type
549
550 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
551 "Wrong types on cmp instruction");
552 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
553 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
554 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
555 *DL, TLI, DT, AC);
556 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
557 return SimplifiedE;
558 }
559 } else if (isa<SelectInst>(I)) {
560 if (isa<Constant>(E->getOperand(0)) ||
561 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
562 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
563 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
564 E->getOperand(2), *DL, TLI, DT, AC);
565 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
566 return SimplifiedE;
567 }
568 } else if (I->isBinaryOp()) {
569 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
570 *DL, TLI, DT, AC);
571 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
572 return SimplifiedE;
573 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
574 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
575 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
576 return SimplifiedE;
577 } else if (isa<GetElementPtrInst>(I)) {
578 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000579 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000580 *DL, TLI, DT, AC);
581 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
582 return SimplifiedE;
583 } else if (AllConstant) {
584 // We don't bother trying to simplify unless all of the operands
585 // were constant.
586 // TODO: There are a lot of Simplify*'s we could call here, if we
587 // wanted to. The original motivating case for this code was a
588 // zext i1 false to i8, which we don't have an interface to
589 // simplify (IE there is no SimplifyZExt).
590
591 SmallVector<Constant *, 8> C;
592 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000593 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000594
595 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
596 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
597 return SimplifiedE;
598 }
599 return E;
600}
601
602const AggregateValueExpression *
603NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
604 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000605 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000606 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
607 setBasicExpressionInfo(I, E, B);
608 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000609 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000610 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000611 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000612 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000613 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
614 setBasicExpressionInfo(EI, E, B);
615 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000616 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000617 return E;
618 }
619 llvm_unreachable("Unhandled type of aggregate value operation");
620}
621
Daniel Berlin85f91b02016-12-26 20:06:58 +0000622const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000623 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000624 E->setOpcode(V->getValueID());
625 return E;
626}
627
628const Expression *NewGVN::createVariableOrConstant(Value *V,
629 const BasicBlock *B) {
630 auto Leader = lookupOperandLeader(V, nullptr, B);
631 if (auto *C = dyn_cast<Constant>(Leader))
632 return createConstantExpression(C);
633 return createVariableExpression(Leader);
634}
635
Daniel Berlin85f91b02016-12-26 20:06:58 +0000636const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000637 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000638 E->setOpcode(C->getValueID());
639 return E;
640}
641
642const CallExpression *NewGVN::createCallExpression(CallInst *CI,
643 MemoryAccess *HV,
644 const BasicBlock *B) {
645 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000646 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000647 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
648 setBasicExpressionInfo(CI, E, B);
649 return E;
650}
651
652// See if we have a congruence class and leader for this operand, and if so,
653// return it. Otherwise, return the operand itself.
654template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000655Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000656 CongruenceClass *CC = ValueToClass.lookup(V);
657 if (CC && (CC != InitialClass))
658 return CC->RepLeader;
659 return V;
660}
661
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000662MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
663 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA);
664 return Result ? Result : MA;
665}
666
Davide Italiano7e274e02016-12-22 16:03:48 +0000667LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
668 LoadInst *LI, MemoryAccess *DA,
669 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000670 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000671 E->allocateOperands(ArgRecycler, ExpressionAllocator);
672 E->setType(LoadType);
673
674 // Give store and loads same opcode so they value number together.
675 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000676 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000677 if (LI)
678 E->setAlignment(LI->getAlignment());
679
680 // TODO: Value number heap versions. We may be able to discover
681 // things alias analysis can't on it's own (IE that a store and a
682 // load have the same value, and thus, it isn't clobbering the load).
683 return E;
684}
685
686const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
687 MemoryAccess *DA,
688 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000689 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000690 new (ExpressionAllocator) StoreExpression(SI->getNumOperands(), SI, DA);
691 E->allocateOperands(ArgRecycler, ExpressionAllocator);
692 E->setType(SI->getValueOperand()->getType());
693
694 // Give store and loads same opcode so they value number together.
695 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000696 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000697
698 // TODO: Value number heap versions. We may be able to discover
699 // things alias analysis can't on it's own (IE that a store and a
700 // load have the same value, and thus, it isn't clobbering the load).
701 return E;
702}
703
704const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
705 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000706 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000707 // If this store's memorydef stores the same value as the last store, the
708 // memory accesses are equivalent.
709 // Get the expression, if any, for the RHS of the MemoryDef.
710 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
711 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
712 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
713 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
714 // See if this store expression already has a value, and it's the same as our
715 // current store.
716 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
717 if (CC &&
718 CC->RepLeader == lookupOperandLeader(SI->getValueOperand(), SI, B)) {
719 setMemoryAccessEquivTo(StoreAccess, StoreRHS);
720 return OldStore;
721 }
722 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000723}
724
725const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
726 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000727 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000728
729 // We can eliminate in favor of non-simple loads, but we won't be able to
730 // eliminate them.
731 if (!LI->isSimple())
732 return nullptr;
733
Daniel Berlin85f91b02016-12-26 20:06:58 +0000734 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000735 // Load of undef is undef.
736 if (isa<UndefValue>(LoadAddressLeader))
737 return createConstantExpression(UndefValue::get(LI->getType()));
738
739 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
740
741 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
742 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
743 Instruction *DefiningInst = MD->getMemoryInst();
744 // If the defining instruction is not reachable, replace with undef.
745 if (!ReachableBlocks.count(DefiningInst->getParent()))
746 return createConstantExpression(UndefValue::get(LI->getType()));
747 }
748 }
749
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000750 const Expression *E =
751 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
752 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000753 return E;
754}
755
756// Evaluate read only and pure calls, and create an expression result.
757const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
758 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000759 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000760 if (AA->doesNotAccessMemory(CI))
761 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000762 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000763 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000764 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000765 }
766 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000767}
768
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000769// Update the memory access equivalence table to say that From is equal to To,
770// and return true if this is different from what already existed in the table.
771bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To) {
772 auto LookupResult = MemoryAccessEquiv.insert({From, nullptr});
773 bool Changed = false;
774 // If it's already in the table, see if the value changed.
775 if (LookupResult.second) {
776 if (To && LookupResult.first->second != To) {
777 // It wasn't equivalent before, and now it is.
778 LookupResult.first->second = To;
779 Changed = true;
780 } else if (!To) {
781 // It used to be equivalent to something, and now it's not.
782 MemoryAccessEquiv.erase(LookupResult.first);
783 Changed = true;
784 }
785 } else if (To) {
786 // It wasn't in the table, but is equivalent to something.
787 LookupResult.first->second = To;
788 Changed = true;
789 }
790 return Changed;
791}
Davide Italiano7e274e02016-12-22 16:03:48 +0000792// Evaluate PHI nodes symbolically, and create an expression result.
793const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
794 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000795 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000796 if (E->op_empty()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000797 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
798 << "\n");
799 E->deallocateOperands(ArgRecycler);
800 ExpressionAllocator.Deallocate(E);
801 return createConstantExpression(UndefValue::get(I->getType()));
802 }
803
804 Value *AllSameValue = E->getOperand(0);
805
806 // See if all arguments are the same, ignoring undef arguments, because we can
807 // choose a value that is the same for them.
808 for (const Value *Arg : E->operands())
809 if (Arg != AllSameValue && !isa<UndefValue>(Arg)) {
Davide Italiano0e714802016-12-28 14:00:11 +0000810 AllSameValue = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000811 break;
812 }
813
814 if (AllSameValue) {
815 // It's possible to have phi nodes with cycles (IE dependent on
816 // other phis that are .... dependent on the original phi node),
817 // especially in weird CFG's where some arguments are unreachable, or
818 // uninitialized along certain paths.
819 // This can cause infinite loops during evaluation (even if you disable
820 // the recursion below, you will simply ping-pong between congruence
821 // classes). If a phi node symbolically evaluates to another phi node,
822 // just leave it alone. If they are really the same, we will still
823 // eliminate them in favor of each other.
824 if (isa<PHINode>(AllSameValue))
825 return E;
826 NumGVNPhisAllSame++;
827 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
828 << "\n");
829 E->deallocateOperands(ArgRecycler);
830 ExpressionAllocator.Deallocate(E);
831 if (auto *C = dyn_cast<Constant>(AllSameValue))
832 return createConstantExpression(C);
833 return createVariableExpression(AllSameValue);
834 }
835 return E;
836}
837
838const Expression *
839NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
840 const BasicBlock *B) {
841 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
842 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
843 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
844 unsigned Opcode = 0;
845 // EI might be an extract from one of our recognised intrinsics. If it
846 // is we'll synthesize a semantically equivalent expression instead on
847 // an extract value expression.
848 switch (II->getIntrinsicID()) {
849 case Intrinsic::sadd_with_overflow:
850 case Intrinsic::uadd_with_overflow:
851 Opcode = Instruction::Add;
852 break;
853 case Intrinsic::ssub_with_overflow:
854 case Intrinsic::usub_with_overflow:
855 Opcode = Instruction::Sub;
856 break;
857 case Intrinsic::smul_with_overflow:
858 case Intrinsic::umul_with_overflow:
859 Opcode = Instruction::Mul;
860 break;
861 default:
862 break;
863 }
864
865 if (Opcode != 0) {
866 // Intrinsic recognized. Grab its args to finish building the
867 // expression.
868 assert(II->getNumArgOperands() == 2 &&
869 "Expect two args for recognised intrinsics.");
870 return createBinaryExpression(Opcode, EI->getType(),
871 II->getArgOperand(0),
872 II->getArgOperand(1), B);
873 }
874 }
875 }
876
877 return createAggregateValueExpression(I, B);
878}
879
880// Substitute and symbolize the value before value numbering.
881const Expression *NewGVN::performSymbolicEvaluation(Value *V,
882 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000883 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000884 if (auto *C = dyn_cast<Constant>(V))
885 E = createConstantExpression(C);
886 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
887 E = createVariableExpression(V);
888 } else {
889 // TODO: memory intrinsics.
890 // TODO: Some day, we should do the forward propagation and reassociation
891 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000892 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000893 switch (I->getOpcode()) {
894 case Instruction::ExtractValue:
895 case Instruction::InsertValue:
896 E = performSymbolicAggrValueEvaluation(I, B);
897 break;
898 case Instruction::PHI:
899 E = performSymbolicPHIEvaluation(I, B);
900 break;
901 case Instruction::Call:
902 E = performSymbolicCallEvaluation(I, B);
903 break;
904 case Instruction::Store:
905 E = performSymbolicStoreEvaluation(I, B);
906 break;
907 case Instruction::Load:
908 E = performSymbolicLoadEvaluation(I, B);
909 break;
910 case Instruction::BitCast: {
911 E = createExpression(I, B);
912 } break;
913
914 case Instruction::Add:
915 case Instruction::FAdd:
916 case Instruction::Sub:
917 case Instruction::FSub:
918 case Instruction::Mul:
919 case Instruction::FMul:
920 case Instruction::UDiv:
921 case Instruction::SDiv:
922 case Instruction::FDiv:
923 case Instruction::URem:
924 case Instruction::SRem:
925 case Instruction::FRem:
926 case Instruction::Shl:
927 case Instruction::LShr:
928 case Instruction::AShr:
929 case Instruction::And:
930 case Instruction::Or:
931 case Instruction::Xor:
932 case Instruction::ICmp:
933 case Instruction::FCmp:
934 case Instruction::Trunc:
935 case Instruction::ZExt:
936 case Instruction::SExt:
937 case Instruction::FPToUI:
938 case Instruction::FPToSI:
939 case Instruction::UIToFP:
940 case Instruction::SIToFP:
941 case Instruction::FPTrunc:
942 case Instruction::FPExt:
943 case Instruction::PtrToInt:
944 case Instruction::IntToPtr:
945 case Instruction::Select:
946 case Instruction::ExtractElement:
947 case Instruction::InsertElement:
948 case Instruction::ShuffleVector:
949 case Instruction::GetElementPtr:
950 E = createExpression(I, B);
951 break;
952 default:
953 return nullptr;
954 }
955 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000956 return E;
957}
958
959// There is an edge from 'Src' to 'Dst'. Return true if every path from
960// the entry block to 'Dst' passes via this edge. In particular 'Dst'
961// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000962bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000963
964 // While in theory it is interesting to consider the case in which Dst has
965 // more than one predecessor, because Dst might be part of a loop which is
966 // only reachable from Src, in practice it is pointless since at the time
967 // GVN runs all such loops have preheaders, which means that Dst will have
968 // been changed to have only one predecessor, namely Src.
969 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
970 const BasicBlock *Src = E.getStart();
971 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
972 (void)Src;
973 return Pred != nullptr;
974}
975
976void NewGVN::markUsersTouched(Value *V) {
977 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +0000978 for (auto *User : V->users()) {
979 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Davide Italiano7e274e02016-12-22 16:03:48 +0000980 TouchedInstructions.set(InstrDFS[User]);
981 }
982}
983
984void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
985 for (auto U : MA->users()) {
986 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
987 TouchedInstructions.set(InstrDFS[MUD->getMemoryInst()]);
988 else
Daniel Berline0bd37e2016-12-29 22:15:12 +0000989 TouchedInstructions.set(InstrDFS[U]);
Davide Italiano7e274e02016-12-22 16:03:48 +0000990 }
991}
992
993// Perform congruence finding on a given value numbering expression.
994void NewGVN::performCongruenceFinding(Value *V, const Expression *E) {
995
996 ValueToExpression[V] = E;
997 // This is guaranteed to return something, since it will at least find
998 // INITIAL.
999 CongruenceClass *VClass = ValueToClass[V];
1000 assert(VClass && "Should have found a vclass");
1001 // Dead classes should have been eliminated from the mapping.
1002 assert(!VClass->Dead && "Found a dead class");
1003
1004 CongruenceClass *EClass;
1005 // Expressions we can't symbolize are always in their own unique
Daniel Berline0bd37e2016-12-29 22:15:12 +00001006 // congruence class. FIXME: This is hard to perfect. Long term, we should try
1007 // to create expressions for everything. We should add UnknownExpression(Inst)
1008 // or something to avoid wasting time creating real ones. Then the existing
1009 // logic will just work.
Davide Italiano0e714802016-12-28 14:00:11 +00001010 if (E == nullptr) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001011 // We may have already made a unique class.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001012 // Test whether we are still in the initial class, or we have found a class
1013 if (VClass == InitialClass || VClass->RepLeader != V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001014 CongruenceClass *NewClass = createCongruenceClass(V, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001015 // We should always be adding the member in the below code.
1016 EClass = NewClass;
1017 DEBUG(dbgs() << "Created new congruence class for " << *V
Davide Italiano0e714802016-12-28 14:00:11 +00001018 << " due to nullptr expression\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001019 } else {
1020 EClass = VClass;
1021 }
1022 } else if (const auto *VE = dyn_cast<VariableExpression>(E)) {
1023 EClass = ValueToClass[VE->getVariableValue()];
1024 } else {
1025 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1026
1027 // If it's not in the value table, create a new congruence class.
1028 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001029 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001030 auto place = lookupResult.first;
1031 place->second = NewClass;
1032
1033 // Constants and variables should always be made the leader.
1034 if (const auto *CE = dyn_cast<ConstantExpression>(E))
1035 NewClass->RepLeader = CE->getConstantValue();
1036 else if (const auto *VE = dyn_cast<VariableExpression>(E))
1037 NewClass->RepLeader = VE->getVariableValue();
1038 else if (const auto *SE = dyn_cast<StoreExpression>(E))
1039 NewClass->RepLeader = SE->getStoreInst()->getValueOperand();
1040 else
1041 NewClass->RepLeader = V;
1042
1043 EClass = NewClass;
1044 DEBUG(dbgs() << "Created new congruence class for " << *V
1045 << " using expression " << *E << " at " << NewClass->ID
1046 << "\n");
1047 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1048 } else {
1049 EClass = lookupResult.first->second;
1050 assert(EClass && "Somehow don't have an eclass");
1051
1052 assert(!EClass->Dead && "We accidentally looked up a dead class");
1053 }
1054 }
1055 bool WasInChanged = ChangedValues.erase(V);
1056 if (VClass != EClass || WasInChanged) {
1057 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1058 << "\n");
1059
1060 if (VClass != EClass) {
1061 DEBUG(dbgs() << "New congruence class for " << V << " is " << EClass->ID
1062 << "\n");
1063
1064 VClass->Members.erase(V);
1065 EClass->Members.insert(V);
1066 ValueToClass[V] = EClass;
1067 // See if we destroyed the class or need to swap leaders.
1068 if (VClass->Members.empty() && VClass != InitialClass) {
1069 if (VClass->DefiningExpr) {
1070 VClass->Dead = true;
1071 DEBUG(dbgs() << "Erasing expression " << *E << " from table\n");
1072 ExpressionToClass.erase(VClass->DefiningExpr);
1073 }
1074 } else if (VClass->RepLeader == V) {
1075 // FIXME: When the leader changes, the value numbering of
1076 // everything may change, so we need to reprocess.
1077 VClass->RepLeader = *(VClass->Members.begin());
1078 for (auto M : VClass->Members) {
1079 if (auto *I = dyn_cast<Instruction>(M))
1080 TouchedInstructions.set(InstrDFS[I]);
1081 ChangedValues.insert(M);
1082 }
1083 }
1084 }
1085 markUsersTouched(V);
Davide Italiano463c32e2016-12-24 17:17:21 +00001086 if (auto *I = dyn_cast<Instruction>(V))
Davide Italiano7e274e02016-12-22 16:03:48 +00001087 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
1088 markMemoryUsersTouched(MA);
1089 }
1090}
1091
1092// Process the fact that Edge (from, to) is reachable, including marking
1093// any newly reachable blocks and instructions for processing.
1094void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1095 // Check if the Edge was reachable before.
1096 if (ReachableEdges.insert({From, To}).second) {
1097 // If this block wasn't reachable before, all instructions are touched.
1098 if (ReachableBlocks.insert(To).second) {
1099 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1100 const auto &InstRange = BlockInstRange.lookup(To);
1101 TouchedInstructions.set(InstRange.first, InstRange.second);
1102 } else {
1103 DEBUG(dbgs() << "Block " << getBlockName(To)
1104 << " was reachable, but new edge {" << getBlockName(From)
1105 << "," << getBlockName(To) << "} to it found\n");
1106
1107 // We've made an edge reachable to an existing block, which may
1108 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1109 // they are the only thing that depend on new edges. Anything using their
1110 // values will get propagated to if necessary.
1111 auto BI = To->begin();
1112 while (isa<PHINode>(BI)) {
1113 TouchedInstructions.set(InstrDFS[&*BI]);
1114 ++BI;
1115 }
1116 }
1117 }
1118}
1119
1120// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1121// see if we know some constant value for it already.
1122Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1123 auto Result = lookupOperandLeader(Cond, nullptr, B);
1124 if (isa<Constant>(Result))
1125 return Result;
1126 return nullptr;
1127}
1128
1129// Process the outgoing edges of a block for reachability.
1130void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1131 // Evaluate reachability of terminator instruction.
1132 BranchInst *BR;
1133 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1134 Value *Cond = BR->getCondition();
1135 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1136 if (!CondEvaluated) {
1137 if (auto *I = dyn_cast<Instruction>(Cond)) {
1138 const Expression *E = createExpression(I, B);
1139 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1140 CondEvaluated = CE->getConstantValue();
1141 }
1142 } else if (isa<ConstantInt>(Cond)) {
1143 CondEvaluated = Cond;
1144 }
1145 }
1146 ConstantInt *CI;
1147 BasicBlock *TrueSucc = BR->getSuccessor(0);
1148 BasicBlock *FalseSucc = BR->getSuccessor(1);
1149 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1150 if (CI->isOne()) {
1151 DEBUG(dbgs() << "Condition for Terminator " << *TI
1152 << " evaluated to true\n");
1153 updateReachableEdge(B, TrueSucc);
1154 } else if (CI->isZero()) {
1155 DEBUG(dbgs() << "Condition for Terminator " << *TI
1156 << " evaluated to false\n");
1157 updateReachableEdge(B, FalseSucc);
1158 }
1159 } else {
1160 updateReachableEdge(B, TrueSucc);
1161 updateReachableEdge(B, FalseSucc);
1162 }
1163 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1164 // For switches, propagate the case values into the case
1165 // destinations.
1166
1167 // Remember how many outgoing edges there are to every successor.
1168 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1169
Davide Italiano7e274e02016-12-22 16:03:48 +00001170 Value *SwitchCond = SI->getCondition();
1171 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1172 // See if we were able to turn this switch statement into a constant.
1173 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001174 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001175 // We should be able to get case value for this.
1176 auto CaseVal = SI->findCaseValue(CondVal);
1177 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1178 // We proved the value is outside of the range of the case.
1179 // We can't do anything other than mark the default dest as reachable,
1180 // and go home.
1181 updateReachableEdge(B, SI->getDefaultDest());
1182 return;
1183 }
1184 // Now get where it goes and mark it reachable.
1185 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1186 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001187 } else {
1188 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1189 BasicBlock *TargetBlock = SI->getSuccessor(i);
1190 ++SwitchEdges[TargetBlock];
1191 updateReachableEdge(B, TargetBlock);
1192 }
1193 }
1194 } else {
1195 // Otherwise this is either unconditional, or a type we have no
1196 // idea about. Just mark successors as reachable.
1197 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1198 BasicBlock *TargetBlock = TI->getSuccessor(i);
1199 updateReachableEdge(B, TargetBlock);
1200 }
1201 }
1202}
1203
Daniel Berlin85f91b02016-12-26 20:06:58 +00001204// The algorithm initially places the values of the routine in the INITIAL
1205// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001206// class. The leader of INITIAL is the undetermined value `TOP`.
1207// When the algorithm has finished, values still in INITIAL are unreachable.
1208void NewGVN::initializeCongruenceClasses(Function &F) {
1209 // FIXME now i can't remember why this is 2
1210 NextCongruenceNum = 2;
1211 // Initialize all other instructions to be in INITIAL class.
1212 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001213 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001214 for (auto &B : F)
1215 for (auto &I : B) {
1216 InitialValues.insert(&I);
1217 ValueToClass[&I] = InitialClass;
1218 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001219 InitialClass->Members.swap(InitialValues);
1220
1221 // Initialize arguments to be in their own unique congruence classes
1222 for (auto &FA : F.args())
1223 createSingletonCongruenceClass(&FA);
1224}
1225
1226void NewGVN::cleanupTables() {
1227 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1228 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1229 << CongruenceClasses[i]->Members.size() << " members\n");
1230 // Make sure we delete the congruence class (probably worth switching to
1231 // a unique_ptr at some point.
1232 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001233 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001234 }
1235
1236 ValueToClass.clear();
1237 ArgRecycler.clear(ExpressionAllocator);
1238 ExpressionAllocator.Reset();
1239 CongruenceClasses.clear();
1240 ExpressionToClass.clear();
1241 ValueToExpression.clear();
1242 ReachableBlocks.clear();
1243 ReachableEdges.clear();
1244#ifndef NDEBUG
1245 ProcessedCount.clear();
1246#endif
1247 DFSDomMap.clear();
1248 InstrDFS.clear();
1249 InstructionsToErase.clear();
1250
1251 DFSToInstr.clear();
1252 BlockInstRange.clear();
1253 TouchedInstructions.clear();
1254 DominatedInstRange.clear();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001255 MemoryAccessEquiv.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001256}
1257
1258std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1259 unsigned Start) {
1260 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001261 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1262 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001263 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001264 }
1265
Davide Italiano7e274e02016-12-22 16:03:48 +00001266 for (auto &I : *B) {
1267 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001268 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001269 }
1270
1271 // All of the range functions taken half-open ranges (open on the end side).
1272 // So we do not subtract one from count, because at this point it is one
1273 // greater than the last instruction.
1274 return std::make_pair(Start, End);
1275}
1276
1277void NewGVN::updateProcessedCount(Value *V) {
1278#ifndef NDEBUG
1279 if (ProcessedCount.count(V) == 0) {
1280 ProcessedCount.insert({V, 1});
1281 } else {
1282 ProcessedCount[V] += 1;
1283 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001284 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001285 }
1286#endif
1287}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001288// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1289void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1290 // If all the arguments are the same, the MemoryPhi has the same value as the
1291 // argument.
1292 // Filter out unreachable blocks from our operands.
1293 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1294 return ReachableBlocks.count(MP->getIncomingBlock(U));
1295 });
1296
1297 assert(Filtered.begin() != Filtered.end() &&
1298 "We should not be processing a MemoryPhi in a completely "
1299 "unreachable block");
1300
1301 // Transform the remaining operands into operand leaders.
1302 // FIXME: mapped_iterator should have a range version.
1303 auto LookupFunc = [&](const Use &U) {
1304 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1305 };
1306 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1307 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1308
1309 // and now check if all the elements are equal.
1310 // Sadly, we can't use std::equals since these are random access iterators.
1311 MemoryAccess *AllSameValue = *MappedBegin;
1312 ++MappedBegin;
1313 bool AllEqual = std::all_of(
1314 MappedBegin, MappedEnd,
1315 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1316
1317 if (AllEqual)
1318 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1319 else
1320 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1321
1322 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr))
1323 markMemoryUsersTouched(MP);
1324}
1325
1326// Value number a single instruction, symbolically evaluating, performing
1327// congruence finding, and updating mappings.
1328void NewGVN::valueNumberInstruction(Instruction *I) {
1329 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001330 if (isInstructionTriviallyDead(I, TLI)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001331 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001332 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001333 return;
1334 }
1335 if (!I->isTerminator()) {
1336 const Expression *Symbolized = performSymbolicEvaluation(I, I->getParent());
1337 performCongruenceFinding(I, Symbolized);
1338 } else {
1339 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1340 }
1341}
Davide Italiano7e274e02016-12-22 16:03:48 +00001342
Daniel Berlin85f91b02016-12-26 20:06:58 +00001343// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001344bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001345 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1346 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001347 bool Changed = false;
1348 DT = _DT;
1349 AC = _AC;
1350 TLI = _TLI;
1351 AA = _AA;
1352 MSSA = _MSSA;
1353 DL = &F.getParent()->getDataLayout();
1354 MSSAWalker = MSSA->getWalker();
1355
1356 // Count number of instructions for sizing of hash tables, and come
1357 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001358 unsigned ICount = 1;
1359 // Add an empty instruction to account for the fact that we start at 1
1360 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001361 // Note: We want RPO traversal of the blocks, which is not quite the same as
1362 // dominator tree order, particularly with regard whether backedges get
1363 // visited first or second, given a block with multiple successors.
1364 // If we visit in the wrong order, we will end up performing N times as many
1365 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001366 // The dominator tree does guarantee that, for a given dom tree node, it's
1367 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1368 // the siblings.
1369 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001370 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001371 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001372 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001373 auto *Node = DT->getNode(B);
1374 assert(Node && "RPO and Dominator tree should have same reachability");
1375 RPOOrdering[Node] = ++Counter;
1376 }
1377 // Sort dominator tree children arrays into RPO.
1378 for (auto &B : RPOT) {
1379 auto *Node = DT->getNode(B);
1380 if (Node->getChildren().size() > 1)
1381 std::sort(Node->begin(), Node->end(),
1382 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1383 return RPOOrdering[A] < RPOOrdering[B];
1384 });
1385 }
1386
1387 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1388 auto DFI = df_begin(DT->getRootNode());
1389 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1390 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001391 const auto &BlockRange = assignDFSNumbers(B, ICount);
1392 BlockInstRange.insert({B, BlockRange});
1393 ICount += BlockRange.second - BlockRange.first;
1394 }
1395
1396 // Handle forward unreachable blocks and figure out which blocks
1397 // have single preds.
1398 for (auto &B : F) {
1399 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001400 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001401 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1402 BlockInstRange.insert({&B, BlockRange});
1403 ICount += BlockRange.second - BlockRange.first;
1404 }
1405 }
1406
Daniel Berline0bd37e2016-12-29 22:15:12 +00001407 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001408 DominatedInstRange.reserve(F.size());
1409 // Ensure we don't end up resizing the expressionToClass map, as
1410 // that can be quite expensive. At most, we have one expression per
1411 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001412 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001413
1414 // Initialize the touched instructions to include the entry block.
1415 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1416 TouchedInstructions.set(InstRange.first, InstRange.second);
1417 ReachableBlocks.insert(&F.getEntryBlock());
1418
1419 initializeCongruenceClasses(F);
1420
1421 // We start out in the entry block.
1422 BasicBlock *LastBlock = &F.getEntryBlock();
1423 while (TouchedInstructions.any()) {
1424 // Walk through all the instructions in all the blocks in RPO.
1425 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1426 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Daniel Berline0bd37e2016-12-29 22:15:12 +00001427 assert(InstrNum != 0 && "Bit 0 should never be set, something touched an "
1428 "instruction not in the lookup table");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001429 Value *V = DFSToInstr[InstrNum];
1430 BasicBlock *CurrBlock = nullptr;
1431
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001432 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001433 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001434 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001435 CurrBlock = MP->getBlock();
1436 else
1437 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001438
1439 // If we hit a new block, do reachability processing.
1440 if (CurrBlock != LastBlock) {
1441 LastBlock = CurrBlock;
1442 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1443 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1444
1445 // If it's not reachable, erase any touched instructions and move on.
1446 if (!BlockReachable) {
1447 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1448 DEBUG(dbgs() << "Skipping instructions in block "
1449 << getBlockName(CurrBlock)
1450 << " because it is unreachable\n");
1451 continue;
1452 }
1453 updateProcessedCount(CurrBlock);
1454 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001455
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001456 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001457 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1458 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001459 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001460 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001461 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001462 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001463 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001464 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001465 // Reset after processing (because we may mark ourselves as touched when
1466 // we propagate equalities).
1467 TouchedInstructions.reset(InstrNum);
1468 }
1469 }
1470
1471 Changed |= eliminateInstructions(F);
1472
1473 // Delete all instructions marked for deletion.
1474 for (Instruction *ToErase : InstructionsToErase) {
1475 if (!ToErase->use_empty())
1476 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1477
1478 ToErase->eraseFromParent();
1479 }
1480
1481 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001482 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1483 return !ReachableBlocks.count(&BB);
1484 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001485
1486 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1487 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001488 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001489 deleteInstructionsInBlock(&BB);
1490 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001491 }
1492
1493 cleanupTables();
1494 return Changed;
1495}
1496
1497bool NewGVN::runOnFunction(Function &F) {
1498 if (skipFunction(F))
1499 return false;
1500 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1501 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1502 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1503 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1504 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1505}
1506
Daniel Berlin85f91b02016-12-26 20:06:58 +00001507PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001508 NewGVN Impl;
1509
1510 // Apparently the order in which we get these results matter for
1511 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1512 // the same order here, just in case.
1513 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1514 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1515 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1516 auto &AA = AM.getResult<AAManager>(F);
1517 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1518 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1519 if (!Changed)
1520 return PreservedAnalyses::all();
1521 PreservedAnalyses PA;
1522 PA.preserve<DominatorTreeAnalysis>();
1523 PA.preserve<GlobalsAA>();
1524 return PA;
1525}
1526
1527// Return true if V is a value that will always be available (IE can
1528// be placed anywhere) in the function. We don't do globals here
1529// because they are often worse to put in place.
1530// TODO: Separate cost from availability
1531static bool alwaysAvailable(Value *V) {
1532 return isa<Constant>(V) || isa<Argument>(V);
1533}
1534
1535// Get the basic block from an instruction/value.
1536static BasicBlock *getBlockForValue(Value *V) {
1537 if (auto *I = dyn_cast<Instruction>(V))
1538 return I->getParent();
1539 return nullptr;
1540}
1541
1542struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001543 int DFSIn = 0;
1544 int DFSOut = 0;
1545 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001546 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001547 Value *Val = nullptr;
1548 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001549
1550 bool operator<(const ValueDFS &Other) const {
1551 // It's not enough that any given field be less than - we have sets
1552 // of fields that need to be evaluated together to give a proper ordering.
1553 // For example, if you have;
1554 // DFS (1, 3)
1555 // Val 0
1556 // DFS (1, 2)
1557 // Val 50
1558 // We want the second to be less than the first, but if we just go field
1559 // by field, we will get to Val 0 < Val 50 and say the first is less than
1560 // the second. We only want it to be less than if the DFS orders are equal.
1561 //
1562 // Each LLVM instruction only produces one value, and thus the lowest-level
1563 // differentiator that really matters for the stack (and what we use as as a
1564 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001565 // Everything else in the structure is instruction level, and only affects
1566 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001567 //
1568 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1569 // the order of replacement of uses does not matter.
1570 // IE given,
1571 // a = 5
1572 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001573 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1574 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001575 // The .val will be the same as well.
1576 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001577 // You will replace both, and it does not matter what order you replace them
1578 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1579 // operand 2).
1580 // Similarly for the case of same dfsin, dfsout, localnum, but different
1581 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001582 // a = 5
1583 // b = 6
1584 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001585 // in c, we will a valuedfs for a, and one for b,with everything the same
1586 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001587 // It does not matter what order we replace these operands in.
1588 // You will always end up with the same IR, and this is guaranteed.
1589 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1590 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1591 Other.U);
1592 }
1593};
1594
1595void NewGVN::convertDenseToDFSOrdered(CongruenceClass::MemberSet &Dense,
1596 std::vector<ValueDFS> &DFSOrderedSet) {
1597 for (auto D : Dense) {
1598 // First add the value.
1599 BasicBlock *BB = getBlockForValue(D);
1600 // Constants are handled prior to ever calling this function, so
1601 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001602 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001603 ValueDFS VD;
1604
1605 std::pair<int, int> DFSPair = DFSDomMap[BB];
1606 assert(DFSPair.first != -1 && DFSPair.second != -1 && "Invalid DFS Pair");
1607 VD.DFSIn = DFSPair.first;
1608 VD.DFSOut = DFSPair.second;
1609 VD.Val = D;
1610 // If it's an instruction, use the real local dfs number.
1611 if (auto *I = dyn_cast<Instruction>(D))
1612 VD.LocalNum = InstrDFS[I];
1613 else
1614 llvm_unreachable("Should have been an instruction");
1615
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001616 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001617
1618 // Now add the users.
1619 for (auto &U : D->uses()) {
1620 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1621 ValueDFS VD;
1622 // Put the phi node uses in the incoming block.
1623 BasicBlock *IBlock;
1624 if (auto *P = dyn_cast<PHINode>(I)) {
1625 IBlock = P->getIncomingBlock(U);
1626 // Make phi node users appear last in the incoming block
1627 // they are from.
1628 VD.LocalNum = InstrDFS.size() + 1;
1629 } else {
1630 IBlock = I->getParent();
1631 VD.LocalNum = InstrDFS[I];
1632 }
1633 std::pair<int, int> DFSPair = DFSDomMap[IBlock];
1634 VD.DFSIn = DFSPair.first;
1635 VD.DFSOut = DFSPair.second;
1636 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001637 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001638 }
1639 }
1640 }
1641}
1642
1643static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1644 // Patch the replacement so that it is not more restrictive than the value
1645 // being replaced.
1646 auto *Op = dyn_cast<BinaryOperator>(I);
1647 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
1648
1649 if (Op && ReplOp)
1650 ReplOp->andIRFlags(Op);
1651
1652 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
1653 // FIXME: If both the original and replacement value are part of the
1654 // same control-flow region (meaning that the execution of one
1655 // guarentees the executation of the other), then we can combine the
1656 // noalias scopes here and do better than the general conservative
1657 // answer used in combineMetadata().
1658
1659 // In general, GVN unifies expressions over different control-flow
1660 // regions, and so we need a conservative combination of the noalias
1661 // scopes.
1662 unsigned KnownIDs[] = {
1663 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1664 LLVMContext::MD_noalias, LLVMContext::MD_range,
1665 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1666 LLVMContext::MD_invariant_group};
1667 combineMetadata(ReplInst, I, KnownIDs);
1668 }
1669}
1670
1671static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1672 patchReplacementInstruction(I, Repl);
1673 I->replaceAllUsesWith(Repl);
1674}
1675
1676void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
1677 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1678 ++NumGVNBlocksDeleted;
1679
1680 // Check to see if there are non-terminating instructions to delete.
1681 if (isa<TerminatorInst>(BB->begin()))
1682 return;
1683
1684 // Delete the instructions backwards, as it has a reduced likelihood of having
1685 // to update as many def-use and use-def chains. Start after the terminator.
1686 auto StartPoint = BB->rbegin();
1687 ++StartPoint;
1688 // Note that we explicitly recalculate BB->rend() on each iteration,
1689 // as it may change when we remove the first instruction.
1690 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
1691 Instruction &Inst = *I++;
1692 if (!Inst.use_empty())
1693 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
1694 if (isa<LandingPadInst>(Inst))
1695 continue;
1696
1697 Inst.eraseFromParent();
1698 ++NumGVNInstrDeleted;
1699 }
1700}
1701
1702void NewGVN::markInstructionForDeletion(Instruction *I) {
1703 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
1704 InstructionsToErase.insert(I);
1705}
1706
1707void NewGVN::replaceInstruction(Instruction *I, Value *V) {
1708
1709 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
1710 patchAndReplaceAllUsesWith(I, V);
1711 // We save the actual erasing to avoid invalidating memory
1712 // dependencies until we are done with everything.
1713 markInstructionForDeletion(I);
1714}
1715
1716namespace {
1717
1718// This is a stack that contains both the value and dfs info of where
1719// that value is valid.
1720class ValueDFSStack {
1721public:
1722 Value *back() const { return ValueStack.back(); }
1723 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
1724
1725 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001726 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001727 DFSStack.emplace_back(DFSIn, DFSOut);
1728 }
1729 bool empty() const { return DFSStack.empty(); }
1730 bool isInScope(int DFSIn, int DFSOut) const {
1731 if (empty())
1732 return false;
1733 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
1734 }
1735
1736 void popUntilDFSScope(int DFSIn, int DFSOut) {
1737
1738 // These two should always be in sync at this point.
1739 assert(ValueStack.size() == DFSStack.size() &&
1740 "Mismatch between ValueStack and DFSStack");
1741 while (
1742 !DFSStack.empty() &&
1743 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
1744 DFSStack.pop_back();
1745 ValueStack.pop_back();
1746 }
1747 }
1748
1749private:
1750 SmallVector<Value *, 8> ValueStack;
1751 SmallVector<std::pair<int, int>, 8> DFSStack;
1752};
1753}
1754
1755bool NewGVN::eliminateInstructions(Function &F) {
1756 // This is a non-standard eliminator. The normal way to eliminate is
1757 // to walk the dominator tree in order, keeping track of available
1758 // values, and eliminating them. However, this is mildly
1759 // pointless. It requires doing lookups on every instruction,
1760 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001761 // instructions part of most singleton congruence classes, we know we
1762 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00001763
1764 // Instead, this eliminator looks at the congruence classes directly, sorts
1765 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001766 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001767 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001768 // last member. This is worst case O(E log E) where E = number of
1769 // instructions in a single congruence class. In theory, this is all
1770 // instructions. In practice, it is much faster, as most instructions are
1771 // either in singleton congruence classes or can't possibly be eliminated
1772 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00001773 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001774 // for elimination purposes.
1775 // TODO: If we wanted to be faster, We could remove any members with no
1776 // overlapping ranges while sorting, as we will never eliminate anything
1777 // with those members, as they don't dominate anything else in our set.
1778
Davide Italiano7e274e02016-12-22 16:03:48 +00001779 bool AnythingReplaced = false;
1780
1781 // Since we are going to walk the domtree anyway, and we can't guarantee the
1782 // DFS numbers are updated, we compute some ourselves.
1783 DT->updateDFSNumbers();
1784
1785 for (auto &B : F) {
1786 if (!ReachableBlocks.count(&B)) {
1787 for (const auto S : successors(&B)) {
1788 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001789 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00001790 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
1791 << getBlockName(&B)
1792 << " with undef due to it being unreachable\n");
1793 for (auto &Operand : Phi.incoming_values())
1794 if (Phi.getIncomingBlock(Operand) == &B)
1795 Operand.set(UndefValue::get(Phi.getType()));
1796 }
1797 }
1798 }
1799 DomTreeNode *Node = DT->getNode(&B);
1800 if (Node)
1801 DFSDomMap[&B] = {Node->getDFSNumIn(), Node->getDFSNumOut()};
1802 }
1803
1804 for (CongruenceClass *CC : CongruenceClasses) {
1805 // FIXME: We should eventually be able to replace everything still
1806 // in the initial class with undef, as they should be unreachable.
1807 // Right now, initial still contains some things we skip value
1808 // numbering of (UNREACHABLE's, for example).
1809 if (CC == InitialClass || CC->Dead)
1810 continue;
1811 assert(CC->RepLeader && "We should have had a leader");
1812
1813 // If this is a leader that is always available, and it's a
1814 // constant or has no equivalences, just replace everything with
1815 // it. We then update the congruence class with whatever members
1816 // are left.
1817 if (alwaysAvailable(CC->RepLeader)) {
1818 SmallPtrSet<Value *, 4> MembersLeft;
1819 for (auto M : CC->Members) {
1820
1821 Value *Member = M;
1822
1823 // Void things have no uses we can replace.
1824 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
1825 MembersLeft.insert(Member);
1826 continue;
1827 }
1828
1829 DEBUG(dbgs() << "Found replacement " << *(CC->RepLeader) << " for "
1830 << *Member << "\n");
1831 // Due to equality propagation, these may not always be
1832 // instructions, they may be real values. We don't really
1833 // care about trying to replace the non-instructions.
1834 if (auto *I = dyn_cast<Instruction>(Member)) {
1835 assert(CC->RepLeader != I &&
1836 "About to accidentally remove our leader");
1837 replaceInstruction(I, CC->RepLeader);
1838 AnythingReplaced = true;
1839
1840 continue;
1841 } else {
1842 MembersLeft.insert(I);
1843 }
1844 }
1845 CC->Members.swap(MembersLeft);
1846
1847 } else {
1848 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
1849 // If this is a singleton, we can skip it.
1850 if (CC->Members.size() != 1) {
1851
1852 // This is a stack because equality replacement/etc may place
1853 // constants in the middle of the member list, and we want to use
1854 // those constant values in preference to the current leader, over
1855 // the scope of those constants.
1856 ValueDFSStack EliminationStack;
1857
1858 // Convert the members to DFS ordered sets and then merge them.
1859 std::vector<ValueDFS> DFSOrderedSet;
1860 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
1861
1862 // Sort the whole thing.
1863 sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
1864
1865 for (auto &C : DFSOrderedSet) {
1866 int MemberDFSIn = C.DFSIn;
1867 int MemberDFSOut = C.DFSOut;
1868 Value *Member = C.Val;
1869 Use *MemberUse = C.U;
1870
1871 // We ignore void things because we can't get a value from them.
1872 if (Member && Member->getType()->isVoidTy())
1873 continue;
1874
1875 if (EliminationStack.empty()) {
1876 DEBUG(dbgs() << "Elimination Stack is empty\n");
1877 } else {
1878 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
1879 << EliminationStack.dfs_back().first << ","
1880 << EliminationStack.dfs_back().second << ")\n");
1881 }
1882 if (Member && isa<Constant>(Member))
1883 assert(isa<Constant>(CC->RepLeader));
1884
1885 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
1886 << MemberDFSOut << ")\n");
1887 // First, we see if we are out of scope or empty. If so,
1888 // and there equivalences, we try to replace the top of
1889 // stack with equivalences (if it's on the stack, it must
1890 // not have been eliminated yet).
1891 // Then we synchronize to our current scope, by
1892 // popping until we are back within a DFS scope that
1893 // dominates the current member.
1894 // Then, what happens depends on a few factors
1895 // If the stack is now empty, we need to push
1896 // If we have a constant or a local equivalence we want to
1897 // start using, we also push.
1898 // Otherwise, we walk along, processing members who are
1899 // dominated by this scope, and eliminate them.
1900 bool ShouldPush =
1901 Member && (EliminationStack.empty() || isa<Constant>(Member));
1902 bool OutOfScope =
1903 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
1904
1905 if (OutOfScope || ShouldPush) {
1906 // Sync to our current scope.
1907 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
1908 ShouldPush |= Member && EliminationStack.empty();
1909 if (ShouldPush) {
1910 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
1911 }
1912 }
1913
1914 // If we get to this point, and the stack is empty we must have a use
1915 // with nothing we can use to eliminate it, just skip it.
1916 if (EliminationStack.empty())
1917 continue;
1918
1919 // Skip the Value's, we only want to eliminate on their uses.
1920 if (Member)
1921 continue;
1922 Value *Result = EliminationStack.back();
1923
Daniel Berline0bd37e2016-12-29 22:15:12 +00001924 // Don't replace our existing users with ourselves, and don't replace
1925 // phi node arguments with the result of the same phi node.
1926 // IE tmp = phi(tmp11, undef); tmp11 = foo -> tmp = phi(tmp, undef)
1927 if (MemberUse->get() == Result ||
1928 (isa<PHINode>(Result) && MemberUse->getUser() == Result))
Davide Italiano7e274e02016-12-22 16:03:48 +00001929 continue;
1930
1931 DEBUG(dbgs() << "Found replacement " << *Result << " for "
1932 << *MemberUse->get() << " in " << *(MemberUse->getUser())
1933 << "\n");
1934
1935 // If we replaced something in an instruction, handle the patching of
1936 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001937 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00001938 patchReplacementInstruction(ReplacedInst, Result);
1939
1940 assert(isa<Instruction>(MemberUse->getUser()));
1941 MemberUse->set(Result);
1942 AnythingReplaced = true;
1943 }
1944 }
1945 }
1946
1947 // Cleanup the congruence class.
1948 SmallPtrSet<Value *, 4> MembersLeft;
Piotr Padlewski26dada72016-12-28 19:42:49 +00001949 for (Value * Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001950 if (Member->getType()->isVoidTy()) {
1951 MembersLeft.insert(Member);
1952 continue;
1953 }
1954
1955 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
1956 if (isInstructionTriviallyDead(MemberInst)) {
1957 // TODO: Don't mark loads of undefs.
1958 markInstructionForDeletion(MemberInst);
1959 continue;
1960 }
1961 }
1962 MembersLeft.insert(Member);
1963 }
1964 CC->Members.swap(MembersLeft);
1965 }
1966
1967 return AnythingReplaced;
1968}