blob: 294b0e26fe87d2db295c51cd409b36c8f43cb48e [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);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000344 void verifyMemoryCongruency();
Davide Italiano7e274e02016-12-22 16:03:48 +0000345};
346
347char NewGVN::ID = 0;
348
349// createGVNPass - The public interface to this file.
350FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
351
Davide Italianob1114092016-12-28 13:37:17 +0000352template <typename T>
353static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
354 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000355 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000356 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000357 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000358 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000359 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000360 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000361 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000362 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000363 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000364 return true;
365}
366
Davide Italianob1114092016-12-28 13:37:17 +0000367bool LoadExpression::equals(const Expression &Other) const {
368 return equalsLoadStoreHelper(*this, Other);
369}
Davide Italiano7e274e02016-12-22 16:03:48 +0000370
Davide Italianob1114092016-12-28 13:37:17 +0000371bool StoreExpression::equals(const Expression &Other) const {
372 return equalsLoadStoreHelper(*this, Other);
Davide Italiano7e274e02016-12-22 16:03:48 +0000373}
374
375#ifndef NDEBUG
376static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000377 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000378}
379#endif
380
381INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
382INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
383INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
384INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
385INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
386INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
387INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
388INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
389
390PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
391 BasicBlock *PhiBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000392 auto *PN = cast<PHINode>(I);
393 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000394 PHIExpression(PN->getNumOperands(), I->getParent());
395
396 E->allocateOperands(ArgRecycler, ExpressionAllocator);
397 E->setType(I->getType());
398 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000399
400 auto ReachablePhiArg = [&](const Use &U) {
401 return ReachableBlocks.count(PN->getIncomingBlock(U));
402 };
403
404 // Filter out unreachable operands
405 auto Filtered = make_filter_range(PN->operands(), ReachablePhiArg);
406
407 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
408 [&](const Use &U) -> Value * {
409 // Don't try to transform self-defined phis
410 if (U == PN)
411 return PN;
412 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PhiBlock);
413 return lookupOperandLeader(U, I, BBE);
414 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000415 return E;
416}
417
418// Set basic expression info (Arguments, type, opcode) for Expression
419// E from Instruction I in block B.
420bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
421 const BasicBlock *B) {
422 bool AllConstant = true;
423 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
424 E->setType(GEP->getSourceElementType());
425 else
426 E->setType(I->getType());
427 E->setOpcode(I->getOpcode());
428 E->allocateOperands(ArgRecycler, ExpressionAllocator);
429
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000430 // Transform the operand array into an operand leader array, and keep track of
431 // whether all members are constant.
432 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000433 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000434 AllConstant &= isa<Constant>(Operand);
435 return Operand;
436 });
437
Davide Italiano7e274e02016-12-22 16:03:48 +0000438 return AllConstant;
439}
440
441const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
442 Value *Arg1, Value *Arg2,
443 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000444 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000445
446 E->setType(T);
447 E->setOpcode(Opcode);
448 E->allocateOperands(ArgRecycler, ExpressionAllocator);
449 if (Instruction::isCommutative(Opcode)) {
450 // Ensure that commutative instructions that only differ by a permutation
451 // of their operands get the same value number by sorting the operand value
452 // numbers. Since all commutative instructions have two operands it is more
453 // efficient to sort by hand rather than using, say, std::sort.
454 if (Arg1 > Arg2)
455 std::swap(Arg1, Arg2);
456 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000457 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
458 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000459
460 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
461 DT, AC);
462 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
463 return SimplifiedE;
464 return E;
465}
466
467// Take a Value returned by simplification of Expression E/Instruction
468// I, and see if it resulted in a simpler expression. If so, return
469// that expression.
470// TODO: Once finished, this should not take an Instruction, we only
471// use it for printing.
472const Expression *NewGVN::checkSimplificationResults(Expression *E,
473 Instruction *I, Value *V) {
474 if (!V)
475 return nullptr;
476 if (auto *C = dyn_cast<Constant>(V)) {
477 if (I)
478 DEBUG(dbgs() << "Simplified " << *I << " to "
479 << " constant " << *C << "\n");
480 NumGVNOpsSimplified++;
481 assert(isa<BasicExpression>(E) &&
482 "We should always have had a basic expression here");
483
484 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
485 ExpressionAllocator.Deallocate(E);
486 return createConstantExpression(C);
487 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
488 if (I)
489 DEBUG(dbgs() << "Simplified " << *I << " to "
490 << " variable " << *V << "\n");
491 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
492 ExpressionAllocator.Deallocate(E);
493 return createVariableExpression(V);
494 }
495
496 CongruenceClass *CC = ValueToClass.lookup(V);
497 if (CC && CC->DefiningExpr) {
498 if (I)
499 DEBUG(dbgs() << "Simplified " << *I << " to "
500 << " expression " << *V << "\n");
501 NumGVNOpsSimplified++;
502 assert(isa<BasicExpression>(E) &&
503 "We should always have had a basic expression here");
504 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
505 ExpressionAllocator.Deallocate(E);
506 return CC->DefiningExpr;
507 }
508 return nullptr;
509}
510
511const Expression *NewGVN::createExpression(Instruction *I,
512 const BasicBlock *B) {
513
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000514 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000515
516 bool AllConstant = setBasicExpressionInfo(I, E, B);
517
518 if (I->isCommutative()) {
519 // Ensure that commutative instructions that only differ by a permutation
520 // of their operands get the same value number by sorting the operand value
521 // numbers. Since all commutative instructions have two operands it is more
522 // efficient to sort by hand rather than using, say, std::sort.
523 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
524 if (E->getOperand(0) > E->getOperand(1))
525 E->swapOperands(0, 1);
526 }
527
528 // Perform simplificaiton
529 // TODO: Right now we only check to see if we get a constant result.
530 // We may get a less than constant, but still better, result for
531 // some operations.
532 // IE
533 // add 0, x -> x
534 // and x, x -> x
535 // We should handle this by simply rewriting the expression.
536 if (auto *CI = dyn_cast<CmpInst>(I)) {
537 // Sort the operand value numbers so x<y and y>x get the same value
538 // number.
539 CmpInst::Predicate Predicate = CI->getPredicate();
540 if (E->getOperand(0) > E->getOperand(1)) {
541 E->swapOperands(0, 1);
542 Predicate = CmpInst::getSwappedPredicate(Predicate);
543 }
544 E->setOpcode((CI->getOpcode() << 8) | Predicate);
545 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
546 // TODO: Since we noop bitcasts, we may need to check types before
547 // simplifying, so that we don't end up simplifying based on a wrong
548 // type assumption. We should clean this up so we can use constants of the
549 // wrong type
550
551 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
552 "Wrong types on cmp instruction");
553 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
554 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
555 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
556 *DL, TLI, DT, AC);
557 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
558 return SimplifiedE;
559 }
560 } else if (isa<SelectInst>(I)) {
561 if (isa<Constant>(E->getOperand(0)) ||
562 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
563 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
564 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
565 E->getOperand(2), *DL, TLI, DT, AC);
566 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
567 return SimplifiedE;
568 }
569 } else if (I->isBinaryOp()) {
570 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
571 *DL, TLI, DT, AC);
572 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
573 return SimplifiedE;
574 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
575 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
576 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
577 return SimplifiedE;
578 } else if (isa<GetElementPtrInst>(I)) {
579 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000580 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000581 *DL, TLI, DT, AC);
582 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
583 return SimplifiedE;
584 } else if (AllConstant) {
585 // We don't bother trying to simplify unless all of the operands
586 // were constant.
587 // TODO: There are a lot of Simplify*'s we could call here, if we
588 // wanted to. The original motivating case for this code was a
589 // zext i1 false to i8, which we don't have an interface to
590 // simplify (IE there is no SimplifyZExt).
591
592 SmallVector<Constant *, 8> C;
593 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000594 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000595
596 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
597 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
598 return SimplifiedE;
599 }
600 return E;
601}
602
603const AggregateValueExpression *
604NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
605 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000606 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000607 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
608 setBasicExpressionInfo(I, E, B);
609 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000610 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000611 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000612 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000613 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000614 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
615 setBasicExpressionInfo(EI, E, B);
616 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000617 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000618 return E;
619 }
620 llvm_unreachable("Unhandled type of aggregate value operation");
621}
622
Daniel Berlin85f91b02016-12-26 20:06:58 +0000623const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000624 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000625 E->setOpcode(V->getValueID());
626 return E;
627}
628
629const Expression *NewGVN::createVariableOrConstant(Value *V,
630 const BasicBlock *B) {
631 auto Leader = lookupOperandLeader(V, nullptr, B);
632 if (auto *C = dyn_cast<Constant>(Leader))
633 return createConstantExpression(C);
634 return createVariableExpression(Leader);
635}
636
Daniel Berlin85f91b02016-12-26 20:06:58 +0000637const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000638 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000639 E->setOpcode(C->getValueID());
640 return E;
641}
642
643const CallExpression *NewGVN::createCallExpression(CallInst *CI,
644 MemoryAccess *HV,
645 const BasicBlock *B) {
646 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000647 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000648 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
649 setBasicExpressionInfo(CI, E, B);
650 return E;
651}
652
653// See if we have a congruence class and leader for this operand, and if so,
654// return it. Otherwise, return the operand itself.
655template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000656Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000657 CongruenceClass *CC = ValueToClass.lookup(V);
658 if (CC && (CC != InitialClass))
659 return CC->RepLeader;
660 return V;
661}
662
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000663MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
664 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA);
665 return Result ? Result : MA;
666}
667
Davide Italiano7e274e02016-12-22 16:03:48 +0000668LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
669 LoadInst *LI, MemoryAccess *DA,
670 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000671 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000672 E->allocateOperands(ArgRecycler, ExpressionAllocator);
673 E->setType(LoadType);
674
675 // Give store and loads same opcode so they value number together.
676 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000677 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000678 if (LI)
679 E->setAlignment(LI->getAlignment());
680
681 // TODO: Value number heap versions. We may be able to discover
682 // things alias analysis can't on it's own (IE that a store and a
683 // load have the same value, and thus, it isn't clobbering the load).
684 return E;
685}
686
687const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
688 MemoryAccess *DA,
689 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000690 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000691 new (ExpressionAllocator) StoreExpression(SI->getNumOperands(), SI, DA);
692 E->allocateOperands(ArgRecycler, ExpressionAllocator);
693 E->setType(SI->getValueOperand()->getType());
694
695 // Give store and loads same opcode so they value number together.
696 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000697 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000698
699 // TODO: Value number heap versions. We may be able to discover
700 // things alias analysis can't on it's own (IE that a store and a
701 // load have the same value, and thus, it isn't clobbering the load).
702 return E;
703}
704
705const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
706 const BasicBlock *B) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000707 // Unlike loads, we never try to eliminate stores, so we do not check if they
708 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000709 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000710 // If this store's memorydef stores the same value as the last store, the
711 // memory accesses are equivalent.
712 // Get the expression, if any, for the RHS of the MemoryDef.
713 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
714 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
715 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
716 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
717 // See if this store expression already has a value, and it's the same as our
Daniel Berlin589cecc2017-01-02 18:00:46 +0000718 // current store. FIXME: Right now, we only do this for simple stores.
719 if (SI->isSimple()) {
720 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
721 if (CC && CC->DefiningExpr && isa<StoreExpression>(CC->DefiningExpr) &&
722 CC->RepLeader == lookupOperandLeader(SI->getValueOperand(), SI, B))
723 return createStoreExpression(SI, StoreRHS, B);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000724 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000725
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000726 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000727}
728
729const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
730 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000731 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000732
733 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000734 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000735 if (!LI->isSimple())
736 return nullptr;
737
Daniel Berlin85f91b02016-12-26 20:06:58 +0000738 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000739 // Load of undef is undef.
740 if (isa<UndefValue>(LoadAddressLeader))
741 return createConstantExpression(UndefValue::get(LI->getType()));
742
743 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
744
745 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
746 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
747 Instruction *DefiningInst = MD->getMemoryInst();
748 // If the defining instruction is not reachable, replace with undef.
749 if (!ReachableBlocks.count(DefiningInst->getParent()))
750 return createConstantExpression(UndefValue::get(LI->getType()));
751 }
752 }
753
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000754 const Expression *E =
755 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
756 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000757 return E;
758}
759
760// Evaluate read only and pure calls, and create an expression result.
761const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
762 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000763 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000764 if (AA->doesNotAccessMemory(CI))
765 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000766 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000767 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000768 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000769 }
770 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000771}
772
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000773// Update the memory access equivalence table to say that From is equal to To,
774// and return true if this is different from what already existed in the table.
775bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000776 DEBUG(dbgs() << "Setting " << *From << " equivalent to ");
777 if (!To)
778 DEBUG(dbgs() << "itself");
779 else
780 DEBUG(dbgs() << *To);
781 DEBUG(dbgs() << "\n");
782 auto LookupResult = MemoryAccessEquiv.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000783 bool Changed = false;
784 // If it's already in the table, see if the value changed.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000785 if (LookupResult != MemoryAccessEquiv.end()) {
786 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000787 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000788 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000789 Changed = true;
790 } else if (!To) {
791 // It used to be equivalent to something, and now it's not.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000792 MemoryAccessEquiv.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000793 Changed = true;
794 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000795 } else {
796 assert(!To &&
797 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000798 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000799
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000800 return Changed;
801}
Davide Italiano7e274e02016-12-22 16:03:48 +0000802// Evaluate PHI nodes symbolically, and create an expression result.
803const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
804 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000805 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000806 if (E->op_empty()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000807 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
808 << "\n");
809 E->deallocateOperands(ArgRecycler);
810 ExpressionAllocator.Deallocate(E);
811 return createConstantExpression(UndefValue::get(I->getType()));
812 }
813
814 Value *AllSameValue = E->getOperand(0);
815
816 // See if all arguments are the same, ignoring undef arguments, because we can
817 // choose a value that is the same for them.
818 for (const Value *Arg : E->operands())
819 if (Arg != AllSameValue && !isa<UndefValue>(Arg)) {
Davide Italiano0e714802016-12-28 14:00:11 +0000820 AllSameValue = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000821 break;
822 }
823
824 if (AllSameValue) {
825 // It's possible to have phi nodes with cycles (IE dependent on
826 // other phis that are .... dependent on the original phi node),
827 // especially in weird CFG's where some arguments are unreachable, or
828 // uninitialized along certain paths.
829 // This can cause infinite loops during evaluation (even if you disable
830 // the recursion below, you will simply ping-pong between congruence
831 // classes). If a phi node symbolically evaluates to another phi node,
832 // just leave it alone. If they are really the same, we will still
833 // eliminate them in favor of each other.
834 if (isa<PHINode>(AllSameValue))
835 return E;
836 NumGVNPhisAllSame++;
837 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
838 << "\n");
839 E->deallocateOperands(ArgRecycler);
840 ExpressionAllocator.Deallocate(E);
841 if (auto *C = dyn_cast<Constant>(AllSameValue))
842 return createConstantExpression(C);
843 return createVariableExpression(AllSameValue);
844 }
845 return E;
846}
847
848const Expression *
849NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
850 const BasicBlock *B) {
851 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
852 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
853 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
854 unsigned Opcode = 0;
855 // EI might be an extract from one of our recognised intrinsics. If it
856 // is we'll synthesize a semantically equivalent expression instead on
857 // an extract value expression.
858 switch (II->getIntrinsicID()) {
859 case Intrinsic::sadd_with_overflow:
860 case Intrinsic::uadd_with_overflow:
861 Opcode = Instruction::Add;
862 break;
863 case Intrinsic::ssub_with_overflow:
864 case Intrinsic::usub_with_overflow:
865 Opcode = Instruction::Sub;
866 break;
867 case Intrinsic::smul_with_overflow:
868 case Intrinsic::umul_with_overflow:
869 Opcode = Instruction::Mul;
870 break;
871 default:
872 break;
873 }
874
875 if (Opcode != 0) {
876 // Intrinsic recognized. Grab its args to finish building the
877 // expression.
878 assert(II->getNumArgOperands() == 2 &&
879 "Expect two args for recognised intrinsics.");
880 return createBinaryExpression(Opcode, EI->getType(),
881 II->getArgOperand(0),
882 II->getArgOperand(1), B);
883 }
884 }
885 }
886
887 return createAggregateValueExpression(I, B);
888}
889
890// Substitute and symbolize the value before value numbering.
891const Expression *NewGVN::performSymbolicEvaluation(Value *V,
892 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000893 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000894 if (auto *C = dyn_cast<Constant>(V))
895 E = createConstantExpression(C);
896 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
897 E = createVariableExpression(V);
898 } else {
899 // TODO: memory intrinsics.
900 // TODO: Some day, we should do the forward propagation and reassociation
901 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000902 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000903 switch (I->getOpcode()) {
904 case Instruction::ExtractValue:
905 case Instruction::InsertValue:
906 E = performSymbolicAggrValueEvaluation(I, B);
907 break;
908 case Instruction::PHI:
909 E = performSymbolicPHIEvaluation(I, B);
910 break;
911 case Instruction::Call:
912 E = performSymbolicCallEvaluation(I, B);
913 break;
914 case Instruction::Store:
915 E = performSymbolicStoreEvaluation(I, B);
916 break;
917 case Instruction::Load:
918 E = performSymbolicLoadEvaluation(I, B);
919 break;
920 case Instruction::BitCast: {
921 E = createExpression(I, B);
922 } break;
923
924 case Instruction::Add:
925 case Instruction::FAdd:
926 case Instruction::Sub:
927 case Instruction::FSub:
928 case Instruction::Mul:
929 case Instruction::FMul:
930 case Instruction::UDiv:
931 case Instruction::SDiv:
932 case Instruction::FDiv:
933 case Instruction::URem:
934 case Instruction::SRem:
935 case Instruction::FRem:
936 case Instruction::Shl:
937 case Instruction::LShr:
938 case Instruction::AShr:
939 case Instruction::And:
940 case Instruction::Or:
941 case Instruction::Xor:
942 case Instruction::ICmp:
943 case Instruction::FCmp:
944 case Instruction::Trunc:
945 case Instruction::ZExt:
946 case Instruction::SExt:
947 case Instruction::FPToUI:
948 case Instruction::FPToSI:
949 case Instruction::UIToFP:
950 case Instruction::SIToFP:
951 case Instruction::FPTrunc:
952 case Instruction::FPExt:
953 case Instruction::PtrToInt:
954 case Instruction::IntToPtr:
955 case Instruction::Select:
956 case Instruction::ExtractElement:
957 case Instruction::InsertElement:
958 case Instruction::ShuffleVector:
959 case Instruction::GetElementPtr:
960 E = createExpression(I, B);
961 break;
962 default:
963 return nullptr;
964 }
965 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000966 return E;
967}
968
969// There is an edge from 'Src' to 'Dst'. Return true if every path from
970// the entry block to 'Dst' passes via this edge. In particular 'Dst'
971// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000972bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000973
974 // While in theory it is interesting to consider the case in which Dst has
975 // more than one predecessor, because Dst might be part of a loop which is
976 // only reachable from Src, in practice it is pointless since at the time
977 // GVN runs all such loops have preheaders, which means that Dst will have
978 // been changed to have only one predecessor, namely Src.
979 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
980 const BasicBlock *Src = E.getStart();
981 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
982 (void)Src;
983 return Pred != nullptr;
984}
985
986void NewGVN::markUsersTouched(Value *V) {
987 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +0000988 for (auto *User : V->users()) {
989 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Davide Italiano7e274e02016-12-22 16:03:48 +0000990 TouchedInstructions.set(InstrDFS[User]);
991 }
992}
993
994void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
995 for (auto U : MA->users()) {
996 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
997 TouchedInstructions.set(InstrDFS[MUD->getMemoryInst()]);
998 else
Daniel Berline0bd37e2016-12-29 22:15:12 +0000999 TouchedInstructions.set(InstrDFS[U]);
Davide Italiano7e274e02016-12-22 16:03:48 +00001000 }
1001}
1002
1003// Perform congruence finding on a given value numbering expression.
1004void NewGVN::performCongruenceFinding(Value *V, const Expression *E) {
1005
1006 ValueToExpression[V] = E;
1007 // This is guaranteed to return something, since it will at least find
1008 // INITIAL.
1009 CongruenceClass *VClass = ValueToClass[V];
1010 assert(VClass && "Should have found a vclass");
1011 // Dead classes should have been eliminated from the mapping.
1012 assert(!VClass->Dead && "Found a dead class");
1013
1014 CongruenceClass *EClass;
1015 // Expressions we can't symbolize are always in their own unique
Daniel Berline0bd37e2016-12-29 22:15:12 +00001016 // congruence class. FIXME: This is hard to perfect. Long term, we should try
1017 // to create expressions for everything. We should add UnknownExpression(Inst)
1018 // or something to avoid wasting time creating real ones. Then the existing
1019 // logic will just work.
Davide Italiano0e714802016-12-28 14:00:11 +00001020 if (E == nullptr) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001021 // We may have already made a unique class.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001022 // Test whether we are still in the initial class, or we have found a class
1023 if (VClass == InitialClass || VClass->RepLeader != V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001024 CongruenceClass *NewClass = createCongruenceClass(V, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001025 // We should always be adding the member in the below code.
1026 EClass = NewClass;
1027 DEBUG(dbgs() << "Created new congruence class for " << *V
Davide Italiano0e714802016-12-28 14:00:11 +00001028 << " due to nullptr expression\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001029 } else {
1030 EClass = VClass;
1031 }
1032 } else if (const auto *VE = dyn_cast<VariableExpression>(E)) {
1033 EClass = ValueToClass[VE->getVariableValue()];
1034 } else {
1035 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1036
1037 // If it's not in the value table, create a new congruence class.
1038 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001039 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001040 auto place = lookupResult.first;
1041 place->second = NewClass;
1042
1043 // Constants and variables should always be made the leader.
1044 if (const auto *CE = dyn_cast<ConstantExpression>(E))
1045 NewClass->RepLeader = CE->getConstantValue();
1046 else if (const auto *VE = dyn_cast<VariableExpression>(E))
1047 NewClass->RepLeader = VE->getVariableValue();
1048 else if (const auto *SE = dyn_cast<StoreExpression>(E))
1049 NewClass->RepLeader = SE->getStoreInst()->getValueOperand();
1050 else
1051 NewClass->RepLeader = V;
1052
1053 EClass = NewClass;
1054 DEBUG(dbgs() << "Created new congruence class for " << *V
1055 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin589cecc2017-01-02 18:00:46 +00001056 << " and leader " << *(NewClass->RepLeader) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001057 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1058 } else {
1059 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001060 if (isa<ConstantExpression>(E))
1061 assert(isa<Constant>(EClass->RepLeader) &&
1062 "Any class with a constant expression should have a "
1063 "constant leader");
1064
Davide Italiano7e274e02016-12-22 16:03:48 +00001065 assert(EClass && "Somehow don't have an eclass");
1066
1067 assert(!EClass->Dead && "We accidentally looked up a dead class");
1068 }
1069 }
1070 bool WasInChanged = ChangedValues.erase(V);
1071 if (VClass != EClass || WasInChanged) {
1072 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1073 << "\n");
1074
1075 if (VClass != EClass) {
1076 DEBUG(dbgs() << "New congruence class for " << V << " is " << EClass->ID
1077 << "\n");
1078
1079 VClass->Members.erase(V);
1080 EClass->Members.insert(V);
1081 ValueToClass[V] = EClass;
1082 // See if we destroyed the class or need to swap leaders.
1083 if (VClass->Members.empty() && VClass != InitialClass) {
1084 if (VClass->DefiningExpr) {
1085 VClass->Dead = true;
1086 DEBUG(dbgs() << "Erasing expression " << *E << " from table\n");
1087 ExpressionToClass.erase(VClass->DefiningExpr);
1088 }
1089 } else if (VClass->RepLeader == V) {
1090 // FIXME: When the leader changes, the value numbering of
1091 // everything may change, so we need to reprocess.
1092 VClass->RepLeader = *(VClass->Members.begin());
1093 for (auto M : VClass->Members) {
1094 if (auto *I = dyn_cast<Instruction>(M))
1095 TouchedInstructions.set(InstrDFS[I]);
1096 ChangedValues.insert(M);
1097 }
1098 }
1099 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001100
Davide Italiano7e274e02016-12-22 16:03:48 +00001101 markUsersTouched(V);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001102 if (auto *I = dyn_cast<Instruction>(V)) {
1103 if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
1104 // If this is a MemoryDef, we need to update the equivalence table. If
1105 // we
1106 // determined the expression is congruent to a different memory state,
1107 // use that different memory state. If we determined it didn't, we
1108 // update
1109 // that as well. Note that currently, we do not guarantee the
1110 // "different" memory state dominates us. The goal is to make things
1111 // that are congruent look congruent, not ensure we can eliminate one in
1112 // favor of the other.
1113 // Right now, the only way they can be equivalent is for store
1114 // expresions.
1115 if (!isa<MemoryUse>(MA)) {
1116 if (E && isa<StoreExpression>(E) && EClass->Members.size() != 1) {
1117 auto *DefAccess = cast<StoreExpression>(E)->getDefiningAccess();
1118 setMemoryAccessEquivTo(MA, DefAccess != MA ? DefAccess : nullptr);
1119 } else {
1120 setMemoryAccessEquivTo(MA, nullptr);
1121 }
1122 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001123 markMemoryUsersTouched(MA);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001124 }
1125 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001126 }
1127}
1128
1129// Process the fact that Edge (from, to) is reachable, including marking
1130// any newly reachable blocks and instructions for processing.
1131void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1132 // Check if the Edge was reachable before.
1133 if (ReachableEdges.insert({From, To}).second) {
1134 // If this block wasn't reachable before, all instructions are touched.
1135 if (ReachableBlocks.insert(To).second) {
1136 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1137 const auto &InstRange = BlockInstRange.lookup(To);
1138 TouchedInstructions.set(InstRange.first, InstRange.second);
1139 } else {
1140 DEBUG(dbgs() << "Block " << getBlockName(To)
1141 << " was reachable, but new edge {" << getBlockName(From)
1142 << "," << getBlockName(To) << "} to it found\n");
1143
1144 // We've made an edge reachable to an existing block, which may
1145 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1146 // they are the only thing that depend on new edges. Anything using their
1147 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001148 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
1149 TouchedInstructions.set(InstrDFS[MemPhi]);
1150
Davide Italiano7e274e02016-12-22 16:03:48 +00001151 auto BI = To->begin();
1152 while (isa<PHINode>(BI)) {
1153 TouchedInstructions.set(InstrDFS[&*BI]);
1154 ++BI;
1155 }
1156 }
1157 }
1158}
1159
1160// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1161// see if we know some constant value for it already.
1162Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1163 auto Result = lookupOperandLeader(Cond, nullptr, B);
1164 if (isa<Constant>(Result))
1165 return Result;
1166 return nullptr;
1167}
1168
1169// Process the outgoing edges of a block for reachability.
1170void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1171 // Evaluate reachability of terminator instruction.
1172 BranchInst *BR;
1173 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1174 Value *Cond = BR->getCondition();
1175 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1176 if (!CondEvaluated) {
1177 if (auto *I = dyn_cast<Instruction>(Cond)) {
1178 const Expression *E = createExpression(I, B);
1179 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1180 CondEvaluated = CE->getConstantValue();
1181 }
1182 } else if (isa<ConstantInt>(Cond)) {
1183 CondEvaluated = Cond;
1184 }
1185 }
1186 ConstantInt *CI;
1187 BasicBlock *TrueSucc = BR->getSuccessor(0);
1188 BasicBlock *FalseSucc = BR->getSuccessor(1);
1189 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1190 if (CI->isOne()) {
1191 DEBUG(dbgs() << "Condition for Terminator " << *TI
1192 << " evaluated to true\n");
1193 updateReachableEdge(B, TrueSucc);
1194 } else if (CI->isZero()) {
1195 DEBUG(dbgs() << "Condition for Terminator " << *TI
1196 << " evaluated to false\n");
1197 updateReachableEdge(B, FalseSucc);
1198 }
1199 } else {
1200 updateReachableEdge(B, TrueSucc);
1201 updateReachableEdge(B, FalseSucc);
1202 }
1203 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1204 // For switches, propagate the case values into the case
1205 // destinations.
1206
1207 // Remember how many outgoing edges there are to every successor.
1208 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1209
Davide Italiano7e274e02016-12-22 16:03:48 +00001210 Value *SwitchCond = SI->getCondition();
1211 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1212 // See if we were able to turn this switch statement into a constant.
1213 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001214 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001215 // We should be able to get case value for this.
1216 auto CaseVal = SI->findCaseValue(CondVal);
1217 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1218 // We proved the value is outside of the range of the case.
1219 // We can't do anything other than mark the default dest as reachable,
1220 // and go home.
1221 updateReachableEdge(B, SI->getDefaultDest());
1222 return;
1223 }
1224 // Now get where it goes and mark it reachable.
1225 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1226 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001227 } else {
1228 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1229 BasicBlock *TargetBlock = SI->getSuccessor(i);
1230 ++SwitchEdges[TargetBlock];
1231 updateReachableEdge(B, TargetBlock);
1232 }
1233 }
1234 } else {
1235 // Otherwise this is either unconditional, or a type we have no
1236 // idea about. Just mark successors as reachable.
1237 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1238 BasicBlock *TargetBlock = TI->getSuccessor(i);
1239 updateReachableEdge(B, TargetBlock);
1240 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001241
1242 // This also may be a memory defining terminator, in which case, set it
1243 // equivalent to nothing.
1244 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1245 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001246 }
1247}
1248
Daniel Berlin85f91b02016-12-26 20:06:58 +00001249// The algorithm initially places the values of the routine in the INITIAL
1250// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001251// class. The leader of INITIAL is the undetermined value `TOP`.
1252// When the algorithm has finished, values still in INITIAL are unreachable.
1253void NewGVN::initializeCongruenceClasses(Function &F) {
1254 // FIXME now i can't remember why this is 2
1255 NextCongruenceNum = 2;
1256 // Initialize all other instructions to be in INITIAL class.
1257 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001258 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001259 for (auto &B : F) {
1260 if (auto *MP = MSSA->getMemoryAccess(&B))
1261 MemoryAccessEquiv.insert({MP, MSSA->getLiveOnEntryDef()});
1262
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001263 for (auto &I : B) {
1264 InitialValues.insert(&I);
1265 ValueToClass[&I] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001266 // All memory accesses are equivalent to live on entry to start. They must
1267 // be initialized to something so that initial changes are noticed. For
1268 // the maximal answer, we initialize them all to be the same as
1269 // liveOnEntry. Note that to save time, we only initialize the
1270 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1271 // other expression can generate a memory equivalence. If we start
1272 // handling memcpy/etc, we can expand this.
1273 if (isa<StoreInst>(&I))
1274 MemoryAccessEquiv.insert(
1275 {MSSA->getMemoryAccess(&I), MSSA->getLiveOnEntryDef()});
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001276 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001277 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001278 InitialClass->Members.swap(InitialValues);
1279
1280 // Initialize arguments to be in their own unique congruence classes
1281 for (auto &FA : F.args())
1282 createSingletonCongruenceClass(&FA);
1283}
1284
1285void NewGVN::cleanupTables() {
1286 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1287 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1288 << CongruenceClasses[i]->Members.size() << " members\n");
1289 // Make sure we delete the congruence class (probably worth switching to
1290 // a unique_ptr at some point.
1291 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001292 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001293 }
1294
1295 ValueToClass.clear();
1296 ArgRecycler.clear(ExpressionAllocator);
1297 ExpressionAllocator.Reset();
1298 CongruenceClasses.clear();
1299 ExpressionToClass.clear();
1300 ValueToExpression.clear();
1301 ReachableBlocks.clear();
1302 ReachableEdges.clear();
1303#ifndef NDEBUG
1304 ProcessedCount.clear();
1305#endif
1306 DFSDomMap.clear();
1307 InstrDFS.clear();
1308 InstructionsToErase.clear();
1309
1310 DFSToInstr.clear();
1311 BlockInstRange.clear();
1312 TouchedInstructions.clear();
1313 DominatedInstRange.clear();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001314 MemoryAccessEquiv.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001315}
1316
1317std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1318 unsigned Start) {
1319 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001320 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1321 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001322 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001323 }
1324
Davide Italiano7e274e02016-12-22 16:03:48 +00001325 for (auto &I : *B) {
1326 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001327 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001328 }
1329
1330 // All of the range functions taken half-open ranges (open on the end side).
1331 // So we do not subtract one from count, because at this point it is one
1332 // greater than the last instruction.
1333 return std::make_pair(Start, End);
1334}
1335
1336void NewGVN::updateProcessedCount(Value *V) {
1337#ifndef NDEBUG
1338 if (ProcessedCount.count(V) == 0) {
1339 ProcessedCount.insert({V, 1});
1340 } else {
1341 ProcessedCount[V] += 1;
1342 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001343 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001344 }
1345#endif
1346}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001347// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1348void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1349 // If all the arguments are the same, the MemoryPhi has the same value as the
1350 // argument.
1351 // Filter out unreachable blocks from our operands.
1352 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1353 return ReachableBlocks.count(MP->getIncomingBlock(U));
1354 });
1355
1356 assert(Filtered.begin() != Filtered.end() &&
1357 "We should not be processing a MemoryPhi in a completely "
1358 "unreachable block");
1359
1360 // Transform the remaining operands into operand leaders.
1361 // FIXME: mapped_iterator should have a range version.
1362 auto LookupFunc = [&](const Use &U) {
1363 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1364 };
1365 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1366 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1367
1368 // and now check if all the elements are equal.
1369 // Sadly, we can't use std::equals since these are random access iterators.
1370 MemoryAccess *AllSameValue = *MappedBegin;
1371 ++MappedBegin;
1372 bool AllEqual = std::all_of(
1373 MappedBegin, MappedEnd,
1374 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1375
1376 if (AllEqual)
1377 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1378 else
1379 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1380
1381 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr))
1382 markMemoryUsersTouched(MP);
1383}
1384
1385// Value number a single instruction, symbolically evaluating, performing
1386// congruence finding, and updating mappings.
1387void NewGVN::valueNumberInstruction(Instruction *I) {
1388 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001389 if (isInstructionTriviallyDead(I, TLI)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001390 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001391 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001392 return;
1393 }
1394 if (!I->isTerminator()) {
1395 const Expression *Symbolized = performSymbolicEvaluation(I, I->getParent());
1396 performCongruenceFinding(I, Symbolized);
1397 } else {
1398 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1399 }
1400}
Davide Italiano7e274e02016-12-22 16:03:48 +00001401
Daniel Berlin589cecc2017-01-02 18:00:46 +00001402// Verify the that the memory equivalence table makes sense relative to the
1403// congruence classes.
1404void NewGVN::verifyMemoryCongruency() {
1405 // Anything equivalent in the memory access table should be in the same
1406 // congruence class.
1407
1408 // Filter out the unreachable and trivially dead entries, because they may
1409 // never have been updated if the instructions were not processed.
1410 auto ReachableAccessPred =
1411 [&](const std::pair<const MemoryAccess *, MemoryAccess *> Pair) {
1412 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1413 if (!Result)
1414 return false;
1415 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1416 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1417 return true;
1418 };
1419
1420 auto Filtered = make_filter_range(MemoryAccessEquiv, ReachableAccessPred);
1421 for (auto KV : Filtered) {
1422 assert(KV.first != KV.second &&
1423 "We added a useless equivalence to the memory equivalence table");
1424 // Unreachable instructions may not have changed because we never process
1425 // them.
1426 if (!ReachableBlocks.count(KV.first->getBlock()))
1427 continue;
1428 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
1429 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second);
1430 if (FirstMUD && SecondMUD) {
1431 auto *FirstInst = FirstMUD->getMemoryInst();
1432 auto *SecondInst = SecondMUD->getMemoryInst();
1433 assert(
1434 ValueToClass.lookup(FirstInst) == ValueToClass.lookup(SecondInst) &&
1435 "The instructions for these memory operations should have been in "
1436 "the same congruence class");
1437 }
1438 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1439
1440 // We can only sanely verify that MemoryDefs in the operand list all have
1441 // the same class.
1442 auto ReachableOperandPred = [&](const Use &U) {
1443 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1444 isa<MemoryDef>(U);
1445
1446 };
1447 // All arguments should in the same class, ignoring unreachable arguments
1448 auto FilteredPhiArgs =
1449 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1450 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1451 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1452 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1453 const MemoryDef *MD = cast<MemoryDef>(U);
1454 return ValueToClass.lookup(MD->getMemoryInst());
1455 });
1456 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1457 PhiOpClasses.begin()) &&
1458 "All MemoryPhi arguments should be in the same class");
1459 }
1460 }
1461}
1462
Daniel Berlin85f91b02016-12-26 20:06:58 +00001463// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001464bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001465 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1466 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001467 bool Changed = false;
1468 DT = _DT;
1469 AC = _AC;
1470 TLI = _TLI;
1471 AA = _AA;
1472 MSSA = _MSSA;
1473 DL = &F.getParent()->getDataLayout();
1474 MSSAWalker = MSSA->getWalker();
1475
1476 // Count number of instructions for sizing of hash tables, and come
1477 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001478 unsigned ICount = 1;
1479 // Add an empty instruction to account for the fact that we start at 1
1480 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001481 // Note: We want RPO traversal of the blocks, which is not quite the same as
1482 // dominator tree order, particularly with regard whether backedges get
1483 // visited first or second, given a block with multiple successors.
1484 // If we visit in the wrong order, we will end up performing N times as many
1485 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001486 // The dominator tree does guarantee that, for a given dom tree node, it's
1487 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1488 // the siblings.
1489 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001490 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001491 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001492 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001493 auto *Node = DT->getNode(B);
1494 assert(Node && "RPO and Dominator tree should have same reachability");
1495 RPOOrdering[Node] = ++Counter;
1496 }
1497 // Sort dominator tree children arrays into RPO.
1498 for (auto &B : RPOT) {
1499 auto *Node = DT->getNode(B);
1500 if (Node->getChildren().size() > 1)
1501 std::sort(Node->begin(), Node->end(),
1502 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1503 return RPOOrdering[A] < RPOOrdering[B];
1504 });
1505 }
1506
1507 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1508 auto DFI = df_begin(DT->getRootNode());
1509 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1510 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001511 const auto &BlockRange = assignDFSNumbers(B, ICount);
1512 BlockInstRange.insert({B, BlockRange});
1513 ICount += BlockRange.second - BlockRange.first;
1514 }
1515
1516 // Handle forward unreachable blocks and figure out which blocks
1517 // have single preds.
1518 for (auto &B : F) {
1519 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001520 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001521 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1522 BlockInstRange.insert({&B, BlockRange});
1523 ICount += BlockRange.second - BlockRange.first;
1524 }
1525 }
1526
Daniel Berline0bd37e2016-12-29 22:15:12 +00001527 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001528 DominatedInstRange.reserve(F.size());
1529 // Ensure we don't end up resizing the expressionToClass map, as
1530 // that can be quite expensive. At most, we have one expression per
1531 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001532 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001533
1534 // Initialize the touched instructions to include the entry block.
1535 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1536 TouchedInstructions.set(InstRange.first, InstRange.second);
1537 ReachableBlocks.insert(&F.getEntryBlock());
1538
1539 initializeCongruenceClasses(F);
1540
1541 // We start out in the entry block.
1542 BasicBlock *LastBlock = &F.getEntryBlock();
1543 while (TouchedInstructions.any()) {
1544 // Walk through all the instructions in all the blocks in RPO.
1545 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1546 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Daniel Berline0bd37e2016-12-29 22:15:12 +00001547 assert(InstrNum != 0 && "Bit 0 should never be set, something touched an "
1548 "instruction not in the lookup table");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001549 Value *V = DFSToInstr[InstrNum];
1550 BasicBlock *CurrBlock = nullptr;
1551
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001552 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001553 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001554 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001555 CurrBlock = MP->getBlock();
1556 else
1557 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001558
1559 // If we hit a new block, do reachability processing.
1560 if (CurrBlock != LastBlock) {
1561 LastBlock = CurrBlock;
1562 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1563 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1564
1565 // If it's not reachable, erase any touched instructions and move on.
1566 if (!BlockReachable) {
1567 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1568 DEBUG(dbgs() << "Skipping instructions in block "
1569 << getBlockName(CurrBlock)
1570 << " because it is unreachable\n");
1571 continue;
1572 }
1573 updateProcessedCount(CurrBlock);
1574 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001575
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001576 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001577 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1578 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001579 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001580 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001581 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001582 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001583 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001584 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001585 // Reset after processing (because we may mark ourselves as touched when
1586 // we propagate equalities).
1587 TouchedInstructions.reset(InstrNum);
1588 }
1589 }
1590
Daniel Berlin589cecc2017-01-02 18:00:46 +00001591// FIXME: Move this to expensive checks when we are satisfied with NewGVN
1592#ifndef NDEBUG
1593 verifyMemoryCongruency();
1594#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001595 Changed |= eliminateInstructions(F);
1596
1597 // Delete all instructions marked for deletion.
1598 for (Instruction *ToErase : InstructionsToErase) {
1599 if (!ToErase->use_empty())
1600 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1601
1602 ToErase->eraseFromParent();
1603 }
1604
1605 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001606 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1607 return !ReachableBlocks.count(&BB);
1608 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001609
1610 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1611 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001612 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001613 deleteInstructionsInBlock(&BB);
1614 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001615 }
1616
1617 cleanupTables();
1618 return Changed;
1619}
1620
1621bool NewGVN::runOnFunction(Function &F) {
1622 if (skipFunction(F))
1623 return false;
1624 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1625 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1626 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1627 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1628 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1629}
1630
Daniel Berlin85f91b02016-12-26 20:06:58 +00001631PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001632 NewGVN Impl;
1633
1634 // Apparently the order in which we get these results matter for
1635 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1636 // the same order here, just in case.
1637 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1638 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1639 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1640 auto &AA = AM.getResult<AAManager>(F);
1641 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1642 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1643 if (!Changed)
1644 return PreservedAnalyses::all();
1645 PreservedAnalyses PA;
1646 PA.preserve<DominatorTreeAnalysis>();
1647 PA.preserve<GlobalsAA>();
1648 return PA;
1649}
1650
1651// Return true if V is a value that will always be available (IE can
1652// be placed anywhere) in the function. We don't do globals here
1653// because they are often worse to put in place.
1654// TODO: Separate cost from availability
1655static bool alwaysAvailable(Value *V) {
1656 return isa<Constant>(V) || isa<Argument>(V);
1657}
1658
1659// Get the basic block from an instruction/value.
1660static BasicBlock *getBlockForValue(Value *V) {
1661 if (auto *I = dyn_cast<Instruction>(V))
1662 return I->getParent();
1663 return nullptr;
1664}
1665
1666struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001667 int DFSIn = 0;
1668 int DFSOut = 0;
1669 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001670 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001671 Value *Val = nullptr;
1672 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001673
1674 bool operator<(const ValueDFS &Other) const {
1675 // It's not enough that any given field be less than - we have sets
1676 // of fields that need to be evaluated together to give a proper ordering.
1677 // For example, if you have;
1678 // DFS (1, 3)
1679 // Val 0
1680 // DFS (1, 2)
1681 // Val 50
1682 // We want the second to be less than the first, but if we just go field
1683 // by field, we will get to Val 0 < Val 50 and say the first is less than
1684 // the second. We only want it to be less than if the DFS orders are equal.
1685 //
1686 // Each LLVM instruction only produces one value, and thus the lowest-level
1687 // differentiator that really matters for the stack (and what we use as as a
1688 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001689 // Everything else in the structure is instruction level, and only affects
1690 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001691 //
1692 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1693 // the order of replacement of uses does not matter.
1694 // IE given,
1695 // a = 5
1696 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001697 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1698 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001699 // The .val will be the same as well.
1700 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001701 // You will replace both, and it does not matter what order you replace them
1702 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1703 // operand 2).
1704 // Similarly for the case of same dfsin, dfsout, localnum, but different
1705 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001706 // a = 5
1707 // b = 6
1708 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001709 // in c, we will a valuedfs for a, and one for b,with everything the same
1710 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001711 // It does not matter what order we replace these operands in.
1712 // You will always end up with the same IR, and this is guaranteed.
1713 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1714 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1715 Other.U);
1716 }
1717};
1718
1719void NewGVN::convertDenseToDFSOrdered(CongruenceClass::MemberSet &Dense,
1720 std::vector<ValueDFS> &DFSOrderedSet) {
1721 for (auto D : Dense) {
1722 // First add the value.
1723 BasicBlock *BB = getBlockForValue(D);
1724 // Constants are handled prior to ever calling this function, so
1725 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001726 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001727 ValueDFS VD;
1728
1729 std::pair<int, int> DFSPair = DFSDomMap[BB];
1730 assert(DFSPair.first != -1 && DFSPair.second != -1 && "Invalid DFS Pair");
1731 VD.DFSIn = DFSPair.first;
1732 VD.DFSOut = DFSPair.second;
1733 VD.Val = D;
1734 // If it's an instruction, use the real local dfs number.
1735 if (auto *I = dyn_cast<Instruction>(D))
1736 VD.LocalNum = InstrDFS[I];
1737 else
1738 llvm_unreachable("Should have been an instruction");
1739
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001740 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001741
1742 // Now add the users.
1743 for (auto &U : D->uses()) {
1744 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1745 ValueDFS VD;
1746 // Put the phi node uses in the incoming block.
1747 BasicBlock *IBlock;
1748 if (auto *P = dyn_cast<PHINode>(I)) {
1749 IBlock = P->getIncomingBlock(U);
1750 // Make phi node users appear last in the incoming block
1751 // they are from.
1752 VD.LocalNum = InstrDFS.size() + 1;
1753 } else {
1754 IBlock = I->getParent();
1755 VD.LocalNum = InstrDFS[I];
1756 }
1757 std::pair<int, int> DFSPair = DFSDomMap[IBlock];
1758 VD.DFSIn = DFSPair.first;
1759 VD.DFSOut = DFSPair.second;
1760 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001761 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001762 }
1763 }
1764 }
1765}
1766
1767static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1768 // Patch the replacement so that it is not more restrictive than the value
1769 // being replaced.
1770 auto *Op = dyn_cast<BinaryOperator>(I);
1771 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
1772
1773 if (Op && ReplOp)
1774 ReplOp->andIRFlags(Op);
1775
1776 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
1777 // FIXME: If both the original and replacement value are part of the
1778 // same control-flow region (meaning that the execution of one
1779 // guarentees the executation of the other), then we can combine the
1780 // noalias scopes here and do better than the general conservative
1781 // answer used in combineMetadata().
1782
1783 // In general, GVN unifies expressions over different control-flow
1784 // regions, and so we need a conservative combination of the noalias
1785 // scopes.
1786 unsigned KnownIDs[] = {
1787 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1788 LLVMContext::MD_noalias, LLVMContext::MD_range,
1789 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1790 LLVMContext::MD_invariant_group};
1791 combineMetadata(ReplInst, I, KnownIDs);
1792 }
1793}
1794
1795static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1796 patchReplacementInstruction(I, Repl);
1797 I->replaceAllUsesWith(Repl);
1798}
1799
1800void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
1801 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1802 ++NumGVNBlocksDeleted;
1803
1804 // Check to see if there are non-terminating instructions to delete.
1805 if (isa<TerminatorInst>(BB->begin()))
1806 return;
1807
1808 // Delete the instructions backwards, as it has a reduced likelihood of having
1809 // to update as many def-use and use-def chains. Start after the terminator.
1810 auto StartPoint = BB->rbegin();
1811 ++StartPoint;
1812 // Note that we explicitly recalculate BB->rend() on each iteration,
1813 // as it may change when we remove the first instruction.
1814 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
1815 Instruction &Inst = *I++;
1816 if (!Inst.use_empty())
1817 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
1818 if (isa<LandingPadInst>(Inst))
1819 continue;
1820
1821 Inst.eraseFromParent();
1822 ++NumGVNInstrDeleted;
1823 }
1824}
1825
1826void NewGVN::markInstructionForDeletion(Instruction *I) {
1827 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
1828 InstructionsToErase.insert(I);
1829}
1830
1831void NewGVN::replaceInstruction(Instruction *I, Value *V) {
1832
1833 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
1834 patchAndReplaceAllUsesWith(I, V);
1835 // We save the actual erasing to avoid invalidating memory
1836 // dependencies until we are done with everything.
1837 markInstructionForDeletion(I);
1838}
1839
1840namespace {
1841
1842// This is a stack that contains both the value and dfs info of where
1843// that value is valid.
1844class ValueDFSStack {
1845public:
1846 Value *back() const { return ValueStack.back(); }
1847 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
1848
1849 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001850 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001851 DFSStack.emplace_back(DFSIn, DFSOut);
1852 }
1853 bool empty() const { return DFSStack.empty(); }
1854 bool isInScope(int DFSIn, int DFSOut) const {
1855 if (empty())
1856 return false;
1857 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
1858 }
1859
1860 void popUntilDFSScope(int DFSIn, int DFSOut) {
1861
1862 // These two should always be in sync at this point.
1863 assert(ValueStack.size() == DFSStack.size() &&
1864 "Mismatch between ValueStack and DFSStack");
1865 while (
1866 !DFSStack.empty() &&
1867 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
1868 DFSStack.pop_back();
1869 ValueStack.pop_back();
1870 }
1871 }
1872
1873private:
1874 SmallVector<Value *, 8> ValueStack;
1875 SmallVector<std::pair<int, int>, 8> DFSStack;
1876};
1877}
1878
1879bool NewGVN::eliminateInstructions(Function &F) {
1880 // This is a non-standard eliminator. The normal way to eliminate is
1881 // to walk the dominator tree in order, keeping track of available
1882 // values, and eliminating them. However, this is mildly
1883 // pointless. It requires doing lookups on every instruction,
1884 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001885 // instructions part of most singleton congruence classes, we know we
1886 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00001887
1888 // Instead, this eliminator looks at the congruence classes directly, sorts
1889 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001890 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001891 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001892 // last member. This is worst case O(E log E) where E = number of
1893 // instructions in a single congruence class. In theory, this is all
1894 // instructions. In practice, it is much faster, as most instructions are
1895 // either in singleton congruence classes or can't possibly be eliminated
1896 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00001897 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001898 // for elimination purposes.
1899 // TODO: If we wanted to be faster, We could remove any members with no
1900 // overlapping ranges while sorting, as we will never eliminate anything
1901 // with those members, as they don't dominate anything else in our set.
1902
Davide Italiano7e274e02016-12-22 16:03:48 +00001903 bool AnythingReplaced = false;
1904
1905 // Since we are going to walk the domtree anyway, and we can't guarantee the
1906 // DFS numbers are updated, we compute some ourselves.
1907 DT->updateDFSNumbers();
1908
1909 for (auto &B : F) {
1910 if (!ReachableBlocks.count(&B)) {
1911 for (const auto S : successors(&B)) {
1912 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001913 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00001914 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
1915 << getBlockName(&B)
1916 << " with undef due to it being unreachable\n");
1917 for (auto &Operand : Phi.incoming_values())
1918 if (Phi.getIncomingBlock(Operand) == &B)
1919 Operand.set(UndefValue::get(Phi.getType()));
1920 }
1921 }
1922 }
1923 DomTreeNode *Node = DT->getNode(&B);
1924 if (Node)
1925 DFSDomMap[&B] = {Node->getDFSNumIn(), Node->getDFSNumOut()};
1926 }
1927
1928 for (CongruenceClass *CC : CongruenceClasses) {
1929 // FIXME: We should eventually be able to replace everything still
1930 // in the initial class with undef, as they should be unreachable.
1931 // Right now, initial still contains some things we skip value
1932 // numbering of (UNREACHABLE's, for example).
1933 if (CC == InitialClass || CC->Dead)
1934 continue;
1935 assert(CC->RepLeader && "We should have had a leader");
1936
1937 // If this is a leader that is always available, and it's a
1938 // constant or has no equivalences, just replace everything with
1939 // it. We then update the congruence class with whatever members
1940 // are left.
1941 if (alwaysAvailable(CC->RepLeader)) {
1942 SmallPtrSet<Value *, 4> MembersLeft;
1943 for (auto M : CC->Members) {
1944
1945 Value *Member = M;
1946
1947 // Void things have no uses we can replace.
1948 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
1949 MembersLeft.insert(Member);
1950 continue;
1951 }
1952
1953 DEBUG(dbgs() << "Found replacement " << *(CC->RepLeader) << " for "
1954 << *Member << "\n");
1955 // Due to equality propagation, these may not always be
1956 // instructions, they may be real values. We don't really
1957 // care about trying to replace the non-instructions.
1958 if (auto *I = dyn_cast<Instruction>(Member)) {
1959 assert(CC->RepLeader != I &&
1960 "About to accidentally remove our leader");
1961 replaceInstruction(I, CC->RepLeader);
1962 AnythingReplaced = true;
1963
1964 continue;
1965 } else {
1966 MembersLeft.insert(I);
1967 }
1968 }
1969 CC->Members.swap(MembersLeft);
1970
1971 } else {
1972 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
1973 // If this is a singleton, we can skip it.
1974 if (CC->Members.size() != 1) {
1975
1976 // This is a stack because equality replacement/etc may place
1977 // constants in the middle of the member list, and we want to use
1978 // those constant values in preference to the current leader, over
1979 // the scope of those constants.
1980 ValueDFSStack EliminationStack;
1981
1982 // Convert the members to DFS ordered sets and then merge them.
1983 std::vector<ValueDFS> DFSOrderedSet;
1984 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
1985
1986 // Sort the whole thing.
1987 sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
1988
1989 for (auto &C : DFSOrderedSet) {
1990 int MemberDFSIn = C.DFSIn;
1991 int MemberDFSOut = C.DFSOut;
1992 Value *Member = C.Val;
1993 Use *MemberUse = C.U;
1994
1995 // We ignore void things because we can't get a value from them.
1996 if (Member && Member->getType()->isVoidTy())
1997 continue;
1998
1999 if (EliminationStack.empty()) {
2000 DEBUG(dbgs() << "Elimination Stack is empty\n");
2001 } else {
2002 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2003 << EliminationStack.dfs_back().first << ","
2004 << EliminationStack.dfs_back().second << ")\n");
2005 }
2006 if (Member && isa<Constant>(Member))
2007 assert(isa<Constant>(CC->RepLeader));
2008
2009 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2010 << MemberDFSOut << ")\n");
2011 // First, we see if we are out of scope or empty. If so,
2012 // and there equivalences, we try to replace the top of
2013 // stack with equivalences (if it's on the stack, it must
2014 // not have been eliminated yet).
2015 // Then we synchronize to our current scope, by
2016 // popping until we are back within a DFS scope that
2017 // dominates the current member.
2018 // Then, what happens depends on a few factors
2019 // If the stack is now empty, we need to push
2020 // If we have a constant or a local equivalence we want to
2021 // start using, we also push.
2022 // Otherwise, we walk along, processing members who are
2023 // dominated by this scope, and eliminate them.
2024 bool ShouldPush =
2025 Member && (EliminationStack.empty() || isa<Constant>(Member));
2026 bool OutOfScope =
2027 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2028
2029 if (OutOfScope || ShouldPush) {
2030 // Sync to our current scope.
2031 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2032 ShouldPush |= Member && EliminationStack.empty();
2033 if (ShouldPush) {
2034 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2035 }
2036 }
2037
2038 // If we get to this point, and the stack is empty we must have a use
2039 // with nothing we can use to eliminate it, just skip it.
2040 if (EliminationStack.empty())
2041 continue;
2042
2043 // Skip the Value's, we only want to eliminate on their uses.
2044 if (Member)
2045 continue;
2046 Value *Result = EliminationStack.back();
2047
Daniel Berline0bd37e2016-12-29 22:15:12 +00002048 // Don't replace our existing users with ourselves, and don't replace
2049 // phi node arguments with the result of the same phi node.
2050 // IE tmp = phi(tmp11, undef); tmp11 = foo -> tmp = phi(tmp, undef)
2051 if (MemberUse->get() == Result ||
2052 (isa<PHINode>(Result) && MemberUse->getUser() == Result))
Davide Italiano7e274e02016-12-22 16:03:48 +00002053 continue;
2054
2055 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2056 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2057 << "\n");
2058
2059 // If we replaced something in an instruction, handle the patching of
2060 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002061 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002062 patchReplacementInstruction(ReplacedInst, Result);
2063
2064 assert(isa<Instruction>(MemberUse->getUser()));
2065 MemberUse->set(Result);
2066 AnythingReplaced = true;
2067 }
2068 }
2069 }
2070
2071 // Cleanup the congruence class.
2072 SmallPtrSet<Value *, 4> MembersLeft;
Piotr Padlewski26dada72016-12-28 19:42:49 +00002073 for (Value * Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002074 if (Member->getType()->isVoidTy()) {
2075 MembersLeft.insert(Member);
2076 continue;
2077 }
2078
2079 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2080 if (isInstructionTriviallyDead(MemberInst)) {
2081 // TODO: Don't mark loads of undefs.
2082 markInstructionForDeletion(MemberInst);
2083 continue;
2084 }
2085 }
2086 MembersLeft.insert(Member);
2087 }
2088 CC->Members.swap(MembersLeft);
2089 }
2090
2091 return AnythingReplaced;
2092}