blob: 54c0a4bc21d80048dd45bbbf289f21eee47642a3 [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.
192 DenseMap<MemoryAccess *, MemoryAccess *> MemoryAccessEquiv;
193
Davide Italiano7e274e02016-12-22 16:03:48 +0000194 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000195 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000196 ExpressionClassMap ExpressionToClass;
197
198 // Which values have changed as a result of leader changes.
199 SmallPtrSet<Value *, 8> ChangedValues;
200
201 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000202 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000203 DenseSet<BlockEdge> ReachableEdges;
204 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
205
206 // This is a bitvector because, on larger functions, we may have
207 // thousands of touched instructions at once (entire blocks,
208 // instructions with hundreds of uses, etc). Even with optimization
209 // for when we mark whole blocks as touched, when this was a
210 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
211 // the time in GVN just managing this list. The bitvector, on the
212 // other hand, efficiently supports test/set/clear of both
213 // individual and ranges, as well as "find next element" This
214 // enables us to use it as a worklist with essentially 0 cost.
215 BitVector TouchedInstructions;
216
217 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
218 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
219 DominatedInstRange;
220
221#ifndef NDEBUG
222 // Debugging for how many times each block and instruction got processed.
223 DenseMap<const Value *, unsigned> ProcessedCount;
224#endif
225
226 // DFS info.
227 DenseMap<const BasicBlock *, std::pair<int, int>> DFSDomMap;
228 DenseMap<const Value *, unsigned> InstrDFS;
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000229 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000230
231 // Deletion info.
232 SmallPtrSet<Instruction *, 8> InstructionsToErase;
233
234public:
235 static char ID; // Pass identification, replacement for typeid.
236 NewGVN() : FunctionPass(ID) {
237 initializeNewGVNPass(*PassRegistry::getPassRegistry());
238 }
239
240 bool runOnFunction(Function &F) override;
241 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000242 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000243
244private:
245 // This transformation requires dominator postdominator info.
246 void getAnalysisUsage(AnalysisUsage &AU) const override {
247 AU.addRequired<AssumptionCacheTracker>();
248 AU.addRequired<DominatorTreeWrapperPass>();
249 AU.addRequired<TargetLibraryInfoWrapperPass>();
250 AU.addRequired<MemorySSAWrapperPass>();
251 AU.addRequired<AAResultsWrapperPass>();
252
253 AU.addPreserved<DominatorTreeWrapperPass>();
254 AU.addPreserved<GlobalsAAWrapperPass>();
255 }
256
257 // Expression handling.
258 const Expression *createExpression(Instruction *, const BasicBlock *);
259 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
260 const BasicBlock *);
261 PHIExpression *createPHIExpression(Instruction *);
262 const VariableExpression *createVariableExpression(Value *);
263 const ConstantExpression *createConstantExpression(Constant *);
264 const Expression *createVariableOrConstant(Value *V, const BasicBlock *B);
265 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
266 const BasicBlock *);
267 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
268 MemoryAccess *, const BasicBlock *);
269
270 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
271 const BasicBlock *);
272 const AggregateValueExpression *
273 createAggregateValueExpression(Instruction *, const BasicBlock *);
274 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
275 const BasicBlock *);
276
277 // Congruence class handling.
278 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000279 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000280 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000281 return result;
282 }
283
284 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000285 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000286 CClass->Members.insert(Member);
287 ValueToClass[Member] = CClass;
288 return CClass;
289 }
290 void initializeCongruenceClasses(Function &F);
291
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000292 // Value number an Instruction or MemoryPhi.
293 void valueNumberMemoryPhi(MemoryPhi *);
294 void valueNumberInstruction(Instruction *);
295
Davide Italiano7e274e02016-12-22 16:03:48 +0000296 // Symbolic evaluation.
297 const Expression *checkSimplificationResults(Expression *, Instruction *,
298 Value *);
299 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
300 const Expression *performSymbolicLoadEvaluation(Instruction *,
301 const BasicBlock *);
302 const Expression *performSymbolicStoreEvaluation(Instruction *,
303 const BasicBlock *);
304 const Expression *performSymbolicCallEvaluation(Instruction *,
305 const BasicBlock *);
306 const Expression *performSymbolicPHIEvaluation(Instruction *,
307 const BasicBlock *);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000308 bool setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To);
Davide Italiano7e274e02016-12-22 16:03:48 +0000309 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
310 const BasicBlock *);
311
312 // Congruence finding.
313 // Templated to allow them to work both on BB's and BB-edges.
314 template <class T>
315 Value *lookupOperandLeader(Value *, const User *, const T &) const;
316 void performCongruenceFinding(Value *, const Expression *);
317
318 // Reachability handling.
319 void updateReachableEdge(BasicBlock *, BasicBlock *);
320 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000321 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000322 Value *findConditionEquivalence(Value *, BasicBlock *) const;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000323 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000324
325 // Elimination.
326 struct ValueDFS;
327 void convertDenseToDFSOrdered(CongruenceClass::MemberSet &,
328 std::vector<ValueDFS> &);
329
330 bool eliminateInstructions(Function &);
331 void replaceInstruction(Instruction *, Value *);
332 void markInstructionForDeletion(Instruction *);
333 void deleteInstructionsInBlock(BasicBlock *);
334
335 // New instruction creation.
336 void handleNewInstruction(Instruction *){};
337 void markUsersTouched(Value *);
338 void markMemoryUsersTouched(MemoryAccess *);
339
340 // Utilities.
341 void cleanupTables();
342 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
343 void updateProcessedCount(Value *V);
344};
345
346char NewGVN::ID = 0;
347
348// createGVNPass - The public interface to this file.
349FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
350
Davide Italianob1114092016-12-28 13:37:17 +0000351template <typename T>
352static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
353 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
354 !LHS.BasicExpression::equals(RHS))
Davide Italiano7e274e02016-12-22 16:03:48 +0000355 return false;
Davide Italianob1114092016-12-28 13:37:17 +0000356 if (const auto *L = dyn_cast<LoadExpression>(&RHS))
357 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000358 return false;
Davide Italianob1114092016-12-28 13:37:17 +0000359 if (const auto *S = dyn_cast<StoreExpression>(&RHS))
360 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000361 return false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000362 return true;
363}
364
Davide Italianob1114092016-12-28 13:37:17 +0000365bool LoadExpression::equals(const Expression &Other) const {
366 return equalsLoadStoreHelper(*this, Other);
367}
Davide Italiano7e274e02016-12-22 16:03:48 +0000368
Davide Italianob1114092016-12-28 13:37:17 +0000369bool StoreExpression::equals(const Expression &Other) const {
370 return equalsLoadStoreHelper(*this, Other);
Davide Italiano7e274e02016-12-22 16:03:48 +0000371}
372
373#ifndef NDEBUG
374static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000375 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000376}
377#endif
378
379INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
380INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
381INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
382INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
383INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
384INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
385INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
386INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
387
388PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
389 BasicBlock *PhiBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000390 auto *PN = cast<PHINode>(I);
391 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000392 PHIExpression(PN->getNumOperands(), I->getParent());
393
394 E->allocateOperands(ArgRecycler, ExpressionAllocator);
395 E->setType(I->getType());
396 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000397
398 auto ReachablePhiArg = [&](const Use &U) {
399 return ReachableBlocks.count(PN->getIncomingBlock(U));
400 };
401
402 // Filter out unreachable operands
403 auto Filtered = make_filter_range(PN->operands(), ReachablePhiArg);
404
405 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
406 [&](const Use &U) -> Value * {
407 // Don't try to transform self-defined phis
408 if (U == PN)
409 return PN;
410 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PhiBlock);
411 return lookupOperandLeader(U, I, BBE);
412 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000413 return E;
414}
415
416// Set basic expression info (Arguments, type, opcode) for Expression
417// E from Instruction I in block B.
418bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
419 const BasicBlock *B) {
420 bool AllConstant = true;
421 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
422 E->setType(GEP->getSourceElementType());
423 else
424 E->setType(I->getType());
425 E->setOpcode(I->getOpcode());
426 E->allocateOperands(ArgRecycler, ExpressionAllocator);
427
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000428 // Transform the operand array into an operand leader array, and keep track of
429 // whether all members are constant.
430 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000431 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000432 AllConstant &= isa<Constant>(Operand);
433 return Operand;
434 });
435
Davide Italiano7e274e02016-12-22 16:03:48 +0000436 return AllConstant;
437}
438
439const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
440 Value *Arg1, Value *Arg2,
441 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000442 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000443
444 E->setType(T);
445 E->setOpcode(Opcode);
446 E->allocateOperands(ArgRecycler, ExpressionAllocator);
447 if (Instruction::isCommutative(Opcode)) {
448 // Ensure that commutative instructions that only differ by a permutation
449 // of their operands get the same value number by sorting the operand value
450 // numbers. Since all commutative instructions have two operands it is more
451 // efficient to sort by hand rather than using, say, std::sort.
452 if (Arg1 > Arg2)
453 std::swap(Arg1, Arg2);
454 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000455 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
456 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000457
458 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
459 DT, AC);
460 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
461 return SimplifiedE;
462 return E;
463}
464
465// Take a Value returned by simplification of Expression E/Instruction
466// I, and see if it resulted in a simpler expression. If so, return
467// that expression.
468// TODO: Once finished, this should not take an Instruction, we only
469// use it for printing.
470const Expression *NewGVN::checkSimplificationResults(Expression *E,
471 Instruction *I, Value *V) {
472 if (!V)
473 return nullptr;
474 if (auto *C = dyn_cast<Constant>(V)) {
475 if (I)
476 DEBUG(dbgs() << "Simplified " << *I << " to "
477 << " constant " << *C << "\n");
478 NumGVNOpsSimplified++;
479 assert(isa<BasicExpression>(E) &&
480 "We should always have had a basic expression here");
481
482 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
483 ExpressionAllocator.Deallocate(E);
484 return createConstantExpression(C);
485 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
486 if (I)
487 DEBUG(dbgs() << "Simplified " << *I << " to "
488 << " variable " << *V << "\n");
489 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
490 ExpressionAllocator.Deallocate(E);
491 return createVariableExpression(V);
492 }
493
494 CongruenceClass *CC = ValueToClass.lookup(V);
495 if (CC && CC->DefiningExpr) {
496 if (I)
497 DEBUG(dbgs() << "Simplified " << *I << " to "
498 << " expression " << *V << "\n");
499 NumGVNOpsSimplified++;
500 assert(isa<BasicExpression>(E) &&
501 "We should always have had a basic expression here");
502 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
503 ExpressionAllocator.Deallocate(E);
504 return CC->DefiningExpr;
505 }
506 return nullptr;
507}
508
509const Expression *NewGVN::createExpression(Instruction *I,
510 const BasicBlock *B) {
511
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000512 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000513
514 bool AllConstant = setBasicExpressionInfo(I, E, B);
515
516 if (I->isCommutative()) {
517 // Ensure that commutative instructions that only differ by a permutation
518 // of their operands get the same value number by sorting the operand value
519 // numbers. Since all commutative instructions have two operands it is more
520 // efficient to sort by hand rather than using, say, std::sort.
521 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
522 if (E->getOperand(0) > E->getOperand(1))
523 E->swapOperands(0, 1);
524 }
525
526 // Perform simplificaiton
527 // TODO: Right now we only check to see if we get a constant result.
528 // We may get a less than constant, but still better, result for
529 // some operations.
530 // IE
531 // add 0, x -> x
532 // and x, x -> x
533 // We should handle this by simply rewriting the expression.
534 if (auto *CI = dyn_cast<CmpInst>(I)) {
535 // Sort the operand value numbers so x<y and y>x get the same value
536 // number.
537 CmpInst::Predicate Predicate = CI->getPredicate();
538 if (E->getOperand(0) > E->getOperand(1)) {
539 E->swapOperands(0, 1);
540 Predicate = CmpInst::getSwappedPredicate(Predicate);
541 }
542 E->setOpcode((CI->getOpcode() << 8) | Predicate);
543 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
544 // TODO: Since we noop bitcasts, we may need to check types before
545 // simplifying, so that we don't end up simplifying based on a wrong
546 // type assumption. We should clean this up so we can use constants of the
547 // wrong type
548
549 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
550 "Wrong types on cmp instruction");
551 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
552 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
553 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
554 *DL, TLI, DT, AC);
555 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
556 return SimplifiedE;
557 }
558 } else if (isa<SelectInst>(I)) {
559 if (isa<Constant>(E->getOperand(0)) ||
560 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
561 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
562 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
563 E->getOperand(2), *DL, TLI, DT, AC);
564 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
565 return SimplifiedE;
566 }
567 } else if (I->isBinaryOp()) {
568 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
569 *DL, TLI, DT, AC);
570 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
571 return SimplifiedE;
572 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
573 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
574 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
575 return SimplifiedE;
576 } else if (isa<GetElementPtrInst>(I)) {
577 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000578 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000579 *DL, TLI, DT, AC);
580 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
581 return SimplifiedE;
582 } else if (AllConstant) {
583 // We don't bother trying to simplify unless all of the operands
584 // were constant.
585 // TODO: There are a lot of Simplify*'s we could call here, if we
586 // wanted to. The original motivating case for this code was a
587 // zext i1 false to i8, which we don't have an interface to
588 // simplify (IE there is no SimplifyZExt).
589
590 SmallVector<Constant *, 8> C;
591 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000592 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000593
594 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
595 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
596 return SimplifiedE;
597 }
598 return E;
599}
600
601const AggregateValueExpression *
602NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
603 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000604 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000605 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
606 setBasicExpressionInfo(I, E, B);
607 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000608 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000609 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000610 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000611 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000612 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
613 setBasicExpressionInfo(EI, E, B);
614 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000615 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000616 return E;
617 }
618 llvm_unreachable("Unhandled type of aggregate value operation");
619}
620
Daniel Berlin85f91b02016-12-26 20:06:58 +0000621const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000622 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000623 E->setOpcode(V->getValueID());
624 return E;
625}
626
627const Expression *NewGVN::createVariableOrConstant(Value *V,
628 const BasicBlock *B) {
629 auto Leader = lookupOperandLeader(V, nullptr, B);
630 if (auto *C = dyn_cast<Constant>(Leader))
631 return createConstantExpression(C);
632 return createVariableExpression(Leader);
633}
634
Daniel Berlin85f91b02016-12-26 20:06:58 +0000635const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000636 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000637 E->setOpcode(C->getValueID());
638 return E;
639}
640
641const CallExpression *NewGVN::createCallExpression(CallInst *CI,
642 MemoryAccess *HV,
643 const BasicBlock *B) {
644 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000645 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000646 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
647 setBasicExpressionInfo(CI, E, B);
648 return E;
649}
650
651// See if we have a congruence class and leader for this operand, and if so,
652// return it. Otherwise, return the operand itself.
653template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000654Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000655 CongruenceClass *CC = ValueToClass.lookup(V);
656 if (CC && (CC != InitialClass))
657 return CC->RepLeader;
658 return V;
659}
660
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000661MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
662 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA);
663 return Result ? Result : MA;
664}
665
Davide Italiano7e274e02016-12-22 16:03:48 +0000666LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
667 LoadInst *LI, MemoryAccess *DA,
668 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000669 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000670 E->allocateOperands(ArgRecycler, ExpressionAllocator);
671 E->setType(LoadType);
672
673 // Give store and loads same opcode so they value number together.
674 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000675 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000676 if (LI)
677 E->setAlignment(LI->getAlignment());
678
679 // TODO: Value number heap versions. We may be able to discover
680 // things alias analysis can't on it's own (IE that a store and a
681 // load have the same value, and thus, it isn't clobbering the load).
682 return E;
683}
684
685const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
686 MemoryAccess *DA,
687 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000688 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000689 new (ExpressionAllocator) StoreExpression(SI->getNumOperands(), SI, DA);
690 E->allocateOperands(ArgRecycler, ExpressionAllocator);
691 E->setType(SI->getValueOperand()->getType());
692
693 // Give store and loads same opcode so they value number together.
694 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000695 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000696
697 // TODO: Value number heap versions. We may be able to discover
698 // things alias analysis can't on it's own (IE that a store and a
699 // load have the same value, and thus, it isn't clobbering the load).
700 return E;
701}
702
703const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
704 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000705 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000706 // If this store's memorydef stores the same value as the last store, the
707 // memory accesses are equivalent.
708 // Get the expression, if any, for the RHS of the MemoryDef.
709 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
710 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
711 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
712 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
713 // See if this store expression already has a value, and it's the same as our
714 // current store.
715 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
716 if (CC &&
717 CC->RepLeader == lookupOperandLeader(SI->getValueOperand(), SI, B)) {
718 setMemoryAccessEquivTo(StoreAccess, StoreRHS);
719 return OldStore;
720 }
721 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000722}
723
724const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
725 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000726 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000727
728 // We can eliminate in favor of non-simple loads, but we won't be able to
729 // eliminate them.
730 if (!LI->isSimple())
731 return nullptr;
732
Daniel Berlin85f91b02016-12-26 20:06:58 +0000733 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000734 // Load of undef is undef.
735 if (isa<UndefValue>(LoadAddressLeader))
736 return createConstantExpression(UndefValue::get(LI->getType()));
737
738 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
739
740 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
741 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
742 Instruction *DefiningInst = MD->getMemoryInst();
743 // If the defining instruction is not reachable, replace with undef.
744 if (!ReachableBlocks.count(DefiningInst->getParent()))
745 return createConstantExpression(UndefValue::get(LI->getType()));
746 }
747 }
748
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000749 const Expression *E =
750 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
751 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000752 return E;
753}
754
755// Evaluate read only and pure calls, and create an expression result.
756const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
757 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000758 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000759 if (AA->doesNotAccessMemory(CI))
760 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000761 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000762 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000763 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000764 }
765 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000766}
767
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000768// Update the memory access equivalence table to say that From is equal to To,
769// and return true if this is different from what already existed in the table.
770bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To) {
771 auto LookupResult = MemoryAccessEquiv.insert({From, nullptr});
772 bool Changed = false;
773 // If it's already in the table, see if the value changed.
774 if (LookupResult.second) {
775 if (To && LookupResult.first->second != To) {
776 // It wasn't equivalent before, and now it is.
777 LookupResult.first->second = To;
778 Changed = true;
779 } else if (!To) {
780 // It used to be equivalent to something, and now it's not.
781 MemoryAccessEquiv.erase(LookupResult.first);
782 Changed = true;
783 }
784 } else if (To) {
785 // It wasn't in the table, but is equivalent to something.
786 LookupResult.first->second = To;
787 Changed = true;
788 }
789 return Changed;
790}
Davide Italiano7e274e02016-12-22 16:03:48 +0000791// Evaluate PHI nodes symbolically, and create an expression result.
792const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
793 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000794 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000795 if (E->op_empty()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000796 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
797 << "\n");
798 E->deallocateOperands(ArgRecycler);
799 ExpressionAllocator.Deallocate(E);
800 return createConstantExpression(UndefValue::get(I->getType()));
801 }
802
803 Value *AllSameValue = E->getOperand(0);
804
805 // See if all arguments are the same, ignoring undef arguments, because we can
806 // choose a value that is the same for them.
807 for (const Value *Arg : E->operands())
808 if (Arg != AllSameValue && !isa<UndefValue>(Arg)) {
Davide Italiano0e714802016-12-28 14:00:11 +0000809 AllSameValue = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000810 break;
811 }
812
813 if (AllSameValue) {
814 // It's possible to have phi nodes with cycles (IE dependent on
815 // other phis that are .... dependent on the original phi node),
816 // especially in weird CFG's where some arguments are unreachable, or
817 // uninitialized along certain paths.
818 // This can cause infinite loops during evaluation (even if you disable
819 // the recursion below, you will simply ping-pong between congruence
820 // classes). If a phi node symbolically evaluates to another phi node,
821 // just leave it alone. If they are really the same, we will still
822 // eliminate them in favor of each other.
823 if (isa<PHINode>(AllSameValue))
824 return E;
825 NumGVNPhisAllSame++;
826 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
827 << "\n");
828 E->deallocateOperands(ArgRecycler);
829 ExpressionAllocator.Deallocate(E);
830 if (auto *C = dyn_cast<Constant>(AllSameValue))
831 return createConstantExpression(C);
832 return createVariableExpression(AllSameValue);
833 }
834 return E;
835}
836
837const Expression *
838NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
839 const BasicBlock *B) {
840 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
841 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
842 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
843 unsigned Opcode = 0;
844 // EI might be an extract from one of our recognised intrinsics. If it
845 // is we'll synthesize a semantically equivalent expression instead on
846 // an extract value expression.
847 switch (II->getIntrinsicID()) {
848 case Intrinsic::sadd_with_overflow:
849 case Intrinsic::uadd_with_overflow:
850 Opcode = Instruction::Add;
851 break;
852 case Intrinsic::ssub_with_overflow:
853 case Intrinsic::usub_with_overflow:
854 Opcode = Instruction::Sub;
855 break;
856 case Intrinsic::smul_with_overflow:
857 case Intrinsic::umul_with_overflow:
858 Opcode = Instruction::Mul;
859 break;
860 default:
861 break;
862 }
863
864 if (Opcode != 0) {
865 // Intrinsic recognized. Grab its args to finish building the
866 // expression.
867 assert(II->getNumArgOperands() == 2 &&
868 "Expect two args for recognised intrinsics.");
869 return createBinaryExpression(Opcode, EI->getType(),
870 II->getArgOperand(0),
871 II->getArgOperand(1), B);
872 }
873 }
874 }
875
876 return createAggregateValueExpression(I, B);
877}
878
879// Substitute and symbolize the value before value numbering.
880const Expression *NewGVN::performSymbolicEvaluation(Value *V,
881 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000882 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000883 if (auto *C = dyn_cast<Constant>(V))
884 E = createConstantExpression(C);
885 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
886 E = createVariableExpression(V);
887 } else {
888 // TODO: memory intrinsics.
889 // TODO: Some day, we should do the forward propagation and reassociation
890 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000891 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000892 switch (I->getOpcode()) {
893 case Instruction::ExtractValue:
894 case Instruction::InsertValue:
895 E = performSymbolicAggrValueEvaluation(I, B);
896 break;
897 case Instruction::PHI:
898 E = performSymbolicPHIEvaluation(I, B);
899 break;
900 case Instruction::Call:
901 E = performSymbolicCallEvaluation(I, B);
902 break;
903 case Instruction::Store:
904 E = performSymbolicStoreEvaluation(I, B);
905 break;
906 case Instruction::Load:
907 E = performSymbolicLoadEvaluation(I, B);
908 break;
909 case Instruction::BitCast: {
910 E = createExpression(I, B);
911 } break;
912
913 case Instruction::Add:
914 case Instruction::FAdd:
915 case Instruction::Sub:
916 case Instruction::FSub:
917 case Instruction::Mul:
918 case Instruction::FMul:
919 case Instruction::UDiv:
920 case Instruction::SDiv:
921 case Instruction::FDiv:
922 case Instruction::URem:
923 case Instruction::SRem:
924 case Instruction::FRem:
925 case Instruction::Shl:
926 case Instruction::LShr:
927 case Instruction::AShr:
928 case Instruction::And:
929 case Instruction::Or:
930 case Instruction::Xor:
931 case Instruction::ICmp:
932 case Instruction::FCmp:
933 case Instruction::Trunc:
934 case Instruction::ZExt:
935 case Instruction::SExt:
936 case Instruction::FPToUI:
937 case Instruction::FPToSI:
938 case Instruction::UIToFP:
939 case Instruction::SIToFP:
940 case Instruction::FPTrunc:
941 case Instruction::FPExt:
942 case Instruction::PtrToInt:
943 case Instruction::IntToPtr:
944 case Instruction::Select:
945 case Instruction::ExtractElement:
946 case Instruction::InsertElement:
947 case Instruction::ShuffleVector:
948 case Instruction::GetElementPtr:
949 E = createExpression(I, B);
950 break;
951 default:
952 return nullptr;
953 }
954 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000955 return E;
956}
957
958// There is an edge from 'Src' to 'Dst'. Return true if every path from
959// the entry block to 'Dst' passes via this edge. In particular 'Dst'
960// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000961bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000962
963 // While in theory it is interesting to consider the case in which Dst has
964 // more than one predecessor, because Dst might be part of a loop which is
965 // only reachable from Src, in practice it is pointless since at the time
966 // GVN runs all such loops have preheaders, which means that Dst will have
967 // been changed to have only one predecessor, namely Src.
968 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
969 const BasicBlock *Src = E.getStart();
970 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
971 (void)Src;
972 return Pred != nullptr;
973}
974
975void NewGVN::markUsersTouched(Value *V) {
976 // Now mark the users as touched.
977 for (auto &U : V->uses()) {
978 auto *User = dyn_cast<Instruction>(U.getUser());
979 assert(User && "Use of value not within an instruction?");
980 TouchedInstructions.set(InstrDFS[User]);
981 }
982}
983
984void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
985 for (auto U : MA->users()) {
986 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
987 TouchedInstructions.set(InstrDFS[MUD->getMemoryInst()]);
988 else
989 TouchedInstructions.set(InstrDFS[MA]);
990 }
991}
992
993// Perform congruence finding on a given value numbering expression.
994void NewGVN::performCongruenceFinding(Value *V, const Expression *E) {
995
996 ValueToExpression[V] = E;
997 // This is guaranteed to return something, since it will at least find
998 // INITIAL.
999 CongruenceClass *VClass = ValueToClass[V];
1000 assert(VClass && "Should have found a vclass");
1001 // Dead classes should have been eliminated from the mapping.
1002 assert(!VClass->Dead && "Found a dead class");
1003
1004 CongruenceClass *EClass;
1005 // Expressions we can't symbolize are always in their own unique
1006 // congruence class.
Davide Italiano0e714802016-12-28 14:00:11 +00001007 if (E == nullptr) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001008 // We may have already made a unique class.
1009 if (VClass->Members.size() != 1 || VClass->RepLeader != V) {
Davide Italiano0e714802016-12-28 14:00:11 +00001010 CongruenceClass *NewClass = createCongruenceClass(V, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001011 // We should always be adding the member in the below code.
1012 EClass = NewClass;
1013 DEBUG(dbgs() << "Created new congruence class for " << *V
Davide Italiano0e714802016-12-28 14:00:11 +00001014 << " due to nullptr expression\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001015 } else {
1016 EClass = VClass;
1017 }
1018 } else if (const auto *VE = dyn_cast<VariableExpression>(E)) {
1019 EClass = ValueToClass[VE->getVariableValue()];
1020 } else {
1021 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1022
1023 // If it's not in the value table, create a new congruence class.
1024 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001025 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001026 auto place = lookupResult.first;
1027 place->second = NewClass;
1028
1029 // Constants and variables should always be made the leader.
1030 if (const auto *CE = dyn_cast<ConstantExpression>(E))
1031 NewClass->RepLeader = CE->getConstantValue();
1032 else if (const auto *VE = dyn_cast<VariableExpression>(E))
1033 NewClass->RepLeader = VE->getVariableValue();
1034 else if (const auto *SE = dyn_cast<StoreExpression>(E))
1035 NewClass->RepLeader = SE->getStoreInst()->getValueOperand();
1036 else
1037 NewClass->RepLeader = V;
1038
1039 EClass = NewClass;
1040 DEBUG(dbgs() << "Created new congruence class for " << *V
1041 << " using expression " << *E << " at " << NewClass->ID
1042 << "\n");
1043 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1044 } else {
1045 EClass = lookupResult.first->second;
1046 assert(EClass && "Somehow don't have an eclass");
1047
1048 assert(!EClass->Dead && "We accidentally looked up a dead class");
1049 }
1050 }
1051 bool WasInChanged = ChangedValues.erase(V);
1052 if (VClass != EClass || WasInChanged) {
1053 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1054 << "\n");
1055
1056 if (VClass != EClass) {
1057 DEBUG(dbgs() << "New congruence class for " << V << " is " << EClass->ID
1058 << "\n");
1059
1060 VClass->Members.erase(V);
1061 EClass->Members.insert(V);
1062 ValueToClass[V] = EClass;
1063 // See if we destroyed the class or need to swap leaders.
1064 if (VClass->Members.empty() && VClass != InitialClass) {
1065 if (VClass->DefiningExpr) {
1066 VClass->Dead = true;
1067 DEBUG(dbgs() << "Erasing expression " << *E << " from table\n");
1068 ExpressionToClass.erase(VClass->DefiningExpr);
1069 }
1070 } else if (VClass->RepLeader == V) {
1071 // FIXME: When the leader changes, the value numbering of
1072 // everything may change, so we need to reprocess.
1073 VClass->RepLeader = *(VClass->Members.begin());
1074 for (auto M : VClass->Members) {
1075 if (auto *I = dyn_cast<Instruction>(M))
1076 TouchedInstructions.set(InstrDFS[I]);
1077 ChangedValues.insert(M);
1078 }
1079 }
1080 }
1081 markUsersTouched(V);
Davide Italiano463c32e2016-12-24 17:17:21 +00001082 if (auto *I = dyn_cast<Instruction>(V))
Davide Italiano7e274e02016-12-22 16:03:48 +00001083 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
1084 markMemoryUsersTouched(MA);
1085 }
1086}
1087
1088// Process the fact that Edge (from, to) is reachable, including marking
1089// any newly reachable blocks and instructions for processing.
1090void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1091 // Check if the Edge was reachable before.
1092 if (ReachableEdges.insert({From, To}).second) {
1093 // If this block wasn't reachable before, all instructions are touched.
1094 if (ReachableBlocks.insert(To).second) {
1095 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1096 const auto &InstRange = BlockInstRange.lookup(To);
1097 TouchedInstructions.set(InstRange.first, InstRange.second);
1098 } else {
1099 DEBUG(dbgs() << "Block " << getBlockName(To)
1100 << " was reachable, but new edge {" << getBlockName(From)
1101 << "," << getBlockName(To) << "} to it found\n");
1102
1103 // We've made an edge reachable to an existing block, which may
1104 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1105 // they are the only thing that depend on new edges. Anything using their
1106 // values will get propagated to if necessary.
1107 auto BI = To->begin();
1108 while (isa<PHINode>(BI)) {
1109 TouchedInstructions.set(InstrDFS[&*BI]);
1110 ++BI;
1111 }
1112 }
1113 }
1114}
1115
1116// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1117// see if we know some constant value for it already.
1118Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1119 auto Result = lookupOperandLeader(Cond, nullptr, B);
1120 if (isa<Constant>(Result))
1121 return Result;
1122 return nullptr;
1123}
1124
1125// Process the outgoing edges of a block for reachability.
1126void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1127 // Evaluate reachability of terminator instruction.
1128 BranchInst *BR;
1129 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1130 Value *Cond = BR->getCondition();
1131 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1132 if (!CondEvaluated) {
1133 if (auto *I = dyn_cast<Instruction>(Cond)) {
1134 const Expression *E = createExpression(I, B);
1135 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1136 CondEvaluated = CE->getConstantValue();
1137 }
1138 } else if (isa<ConstantInt>(Cond)) {
1139 CondEvaluated = Cond;
1140 }
1141 }
1142 ConstantInt *CI;
1143 BasicBlock *TrueSucc = BR->getSuccessor(0);
1144 BasicBlock *FalseSucc = BR->getSuccessor(1);
1145 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1146 if (CI->isOne()) {
1147 DEBUG(dbgs() << "Condition for Terminator " << *TI
1148 << " evaluated to true\n");
1149 updateReachableEdge(B, TrueSucc);
1150 } else if (CI->isZero()) {
1151 DEBUG(dbgs() << "Condition for Terminator " << *TI
1152 << " evaluated to false\n");
1153 updateReachableEdge(B, FalseSucc);
1154 }
1155 } else {
1156 updateReachableEdge(B, TrueSucc);
1157 updateReachableEdge(B, FalseSucc);
1158 }
1159 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1160 // For switches, propagate the case values into the case
1161 // destinations.
1162
1163 // Remember how many outgoing edges there are to every successor.
1164 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1165
Davide Italiano7e274e02016-12-22 16:03:48 +00001166 Value *SwitchCond = SI->getCondition();
1167 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1168 // See if we were able to turn this switch statement into a constant.
1169 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001170 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001171 // We should be able to get case value for this.
1172 auto CaseVal = SI->findCaseValue(CondVal);
1173 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1174 // We proved the value is outside of the range of the case.
1175 // We can't do anything other than mark the default dest as reachable,
1176 // and go home.
1177 updateReachableEdge(B, SI->getDefaultDest());
1178 return;
1179 }
1180 // Now get where it goes and mark it reachable.
1181 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1182 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001183 } else {
1184 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1185 BasicBlock *TargetBlock = SI->getSuccessor(i);
1186 ++SwitchEdges[TargetBlock];
1187 updateReachableEdge(B, TargetBlock);
1188 }
1189 }
1190 } else {
1191 // Otherwise this is either unconditional, or a type we have no
1192 // idea about. Just mark successors as reachable.
1193 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1194 BasicBlock *TargetBlock = TI->getSuccessor(i);
1195 updateReachableEdge(B, TargetBlock);
1196 }
1197 }
1198}
1199
Daniel Berlin85f91b02016-12-26 20:06:58 +00001200// The algorithm initially places the values of the routine in the INITIAL
1201// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001202// class. The leader of INITIAL is the undetermined value `TOP`.
1203// When the algorithm has finished, values still in INITIAL are unreachable.
1204void NewGVN::initializeCongruenceClasses(Function &F) {
1205 // FIXME now i can't remember why this is 2
1206 NextCongruenceNum = 2;
1207 // Initialize all other instructions to be in INITIAL class.
1208 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001209 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001210 for (auto &B : F)
1211 for (auto &I : B) {
1212 InitialValues.insert(&I);
1213 ValueToClass[&I] = InitialClass;
1214 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001215 InitialClass->Members.swap(InitialValues);
1216
1217 // Initialize arguments to be in their own unique congruence classes
1218 for (auto &FA : F.args())
1219 createSingletonCongruenceClass(&FA);
1220}
1221
1222void NewGVN::cleanupTables() {
1223 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1224 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1225 << CongruenceClasses[i]->Members.size() << " members\n");
1226 // Make sure we delete the congruence class (probably worth switching to
1227 // a unique_ptr at some point.
1228 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001229 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001230 }
1231
1232 ValueToClass.clear();
1233 ArgRecycler.clear(ExpressionAllocator);
1234 ExpressionAllocator.Reset();
1235 CongruenceClasses.clear();
1236 ExpressionToClass.clear();
1237 ValueToExpression.clear();
1238 ReachableBlocks.clear();
1239 ReachableEdges.clear();
1240#ifndef NDEBUG
1241 ProcessedCount.clear();
1242#endif
1243 DFSDomMap.clear();
1244 InstrDFS.clear();
1245 InstructionsToErase.clear();
1246
1247 DFSToInstr.clear();
1248 BlockInstRange.clear();
1249 TouchedInstructions.clear();
1250 DominatedInstRange.clear();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001251 MemoryAccessEquiv.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001252}
1253
1254std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1255 unsigned Start) {
1256 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001257 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1258 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001259 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001260 }
1261
Davide Italiano7e274e02016-12-22 16:03:48 +00001262 for (auto &I : *B) {
1263 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001264 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001265 }
1266
1267 // All of the range functions taken half-open ranges (open on the end side).
1268 // So we do not subtract one from count, because at this point it is one
1269 // greater than the last instruction.
1270 return std::make_pair(Start, End);
1271}
1272
1273void NewGVN::updateProcessedCount(Value *V) {
1274#ifndef NDEBUG
1275 if (ProcessedCount.count(V) == 0) {
1276 ProcessedCount.insert({V, 1});
1277 } else {
1278 ProcessedCount[V] += 1;
1279 assert(ProcessedCount[V] < 100 &&
1280 "Seem to have processed the same Value a lot\n");
1281 }
1282#endif
1283}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001284// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1285void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1286 // If all the arguments are the same, the MemoryPhi has the same value as the
1287 // argument.
1288 // Filter out unreachable blocks from our operands.
1289 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1290 return ReachableBlocks.count(MP->getIncomingBlock(U));
1291 });
1292
1293 assert(Filtered.begin() != Filtered.end() &&
1294 "We should not be processing a MemoryPhi in a completely "
1295 "unreachable block");
1296
1297 // Transform the remaining operands into operand leaders.
1298 // FIXME: mapped_iterator should have a range version.
1299 auto LookupFunc = [&](const Use &U) {
1300 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1301 };
1302 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1303 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1304
1305 // and now check if all the elements are equal.
1306 // Sadly, we can't use std::equals since these are random access iterators.
1307 MemoryAccess *AllSameValue = *MappedBegin;
1308 ++MappedBegin;
1309 bool AllEqual = std::all_of(
1310 MappedBegin, MappedEnd,
1311 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1312
1313 if (AllEqual)
1314 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1315 else
1316 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1317
1318 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr))
1319 markMemoryUsersTouched(MP);
1320}
1321
1322// Value number a single instruction, symbolically evaluating, performing
1323// congruence finding, and updating mappings.
1324void NewGVN::valueNumberInstruction(Instruction *I) {
1325 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001326 if (isInstructionTriviallyDead(I, TLI)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001327 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001328 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001329 return;
1330 }
1331 if (!I->isTerminator()) {
1332 const Expression *Symbolized = performSymbolicEvaluation(I, I->getParent());
1333 performCongruenceFinding(I, Symbolized);
1334 } else {
1335 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1336 }
1337}
Davide Italiano7e274e02016-12-22 16:03:48 +00001338
Daniel Berlin85f91b02016-12-26 20:06:58 +00001339// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001340bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001341 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1342 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001343 bool Changed = false;
1344 DT = _DT;
1345 AC = _AC;
1346 TLI = _TLI;
1347 AA = _AA;
1348 MSSA = _MSSA;
1349 DL = &F.getParent()->getDataLayout();
1350 MSSAWalker = MSSA->getWalker();
1351
1352 // Count number of instructions for sizing of hash tables, and come
1353 // up with a global dfs numbering for instructions.
1354 unsigned ICount = 0;
1355 SmallPtrSet<BasicBlock *, 16> VisitedBlocks;
1356
1357 // Note: We want RPO traversal of the blocks, which is not quite the same as
1358 // dominator tree order, particularly with regard whether backedges get
1359 // visited first or second, given a block with multiple successors.
1360 // If we visit in the wrong order, we will end up performing N times as many
1361 // iterations.
1362 ReversePostOrderTraversal<Function *> RPOT(&F);
1363 for (auto &B : RPOT) {
1364 VisitedBlocks.insert(B);
1365 const auto &BlockRange = assignDFSNumbers(B, ICount);
1366 BlockInstRange.insert({B, BlockRange});
1367 ICount += BlockRange.second - BlockRange.first;
1368 }
1369
1370 // Handle forward unreachable blocks and figure out which blocks
1371 // have single preds.
1372 for (auto &B : F) {
1373 // Assign numbers to unreachable blocks.
1374 if (!VisitedBlocks.count(&B)) {
1375 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1376 BlockInstRange.insert({&B, BlockRange});
1377 ICount += BlockRange.second - BlockRange.first;
1378 }
1379 }
1380
1381 TouchedInstructions.resize(ICount + 1);
1382 DominatedInstRange.reserve(F.size());
1383 // Ensure we don't end up resizing the expressionToClass map, as
1384 // that can be quite expensive. At most, we have one expression per
1385 // instruction.
1386 ExpressionToClass.reserve(ICount + 1);
1387
1388 // Initialize the touched instructions to include the entry block.
1389 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1390 TouchedInstructions.set(InstRange.first, InstRange.second);
1391 ReachableBlocks.insert(&F.getEntryBlock());
1392
1393 initializeCongruenceClasses(F);
1394
1395 // We start out in the entry block.
1396 BasicBlock *LastBlock = &F.getEntryBlock();
1397 while (TouchedInstructions.any()) {
1398 // Walk through all the instructions in all the blocks in RPO.
1399 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1400 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001401 Value *V = DFSToInstr[InstrNum];
1402 BasicBlock *CurrBlock = nullptr;
1403
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001404 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001405 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001406 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001407 CurrBlock = MP->getBlock();
1408 else
1409 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001410
1411 // If we hit a new block, do reachability processing.
1412 if (CurrBlock != LastBlock) {
1413 LastBlock = CurrBlock;
1414 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1415 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1416
1417 // If it's not reachable, erase any touched instructions and move on.
1418 if (!BlockReachable) {
1419 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1420 DEBUG(dbgs() << "Skipping instructions in block "
1421 << getBlockName(CurrBlock)
1422 << " because it is unreachable\n");
1423 continue;
1424 }
1425 updateProcessedCount(CurrBlock);
1426 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001427
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001428 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001429 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1430 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001431 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001432 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001433 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001434 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001435 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001436 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001437 // Reset after processing (because we may mark ourselves as touched when
1438 // we propagate equalities).
1439 TouchedInstructions.reset(InstrNum);
1440 }
1441 }
1442
1443 Changed |= eliminateInstructions(F);
1444
1445 // Delete all instructions marked for deletion.
1446 for (Instruction *ToErase : InstructionsToErase) {
1447 if (!ToErase->use_empty())
1448 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1449
1450 ToErase->eraseFromParent();
1451 }
1452
1453 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001454 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1455 return !ReachableBlocks.count(&BB);
1456 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001457
1458 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1459 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001460 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001461 deleteInstructionsInBlock(&BB);
1462 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001463 }
1464
1465 cleanupTables();
1466 return Changed;
1467}
1468
1469bool NewGVN::runOnFunction(Function &F) {
1470 if (skipFunction(F))
1471 return false;
1472 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1473 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1474 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1475 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1476 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1477}
1478
Daniel Berlin85f91b02016-12-26 20:06:58 +00001479PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001480 NewGVN Impl;
1481
1482 // Apparently the order in which we get these results matter for
1483 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1484 // the same order here, just in case.
1485 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1486 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1487 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1488 auto &AA = AM.getResult<AAManager>(F);
1489 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1490 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1491 if (!Changed)
1492 return PreservedAnalyses::all();
1493 PreservedAnalyses PA;
1494 PA.preserve<DominatorTreeAnalysis>();
1495 PA.preserve<GlobalsAA>();
1496 return PA;
1497}
1498
1499// Return true if V is a value that will always be available (IE can
1500// be placed anywhere) in the function. We don't do globals here
1501// because they are often worse to put in place.
1502// TODO: Separate cost from availability
1503static bool alwaysAvailable(Value *V) {
1504 return isa<Constant>(V) || isa<Argument>(V);
1505}
1506
1507// Get the basic block from an instruction/value.
1508static BasicBlock *getBlockForValue(Value *V) {
1509 if (auto *I = dyn_cast<Instruction>(V))
1510 return I->getParent();
1511 return nullptr;
1512}
1513
1514struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001515 int DFSIn = 0;
1516 int DFSOut = 0;
1517 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001518 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001519 Value *Val = nullptr;
1520 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001521
1522 bool operator<(const ValueDFS &Other) const {
1523 // It's not enough that any given field be less than - we have sets
1524 // of fields that need to be evaluated together to give a proper ordering.
1525 // For example, if you have;
1526 // DFS (1, 3)
1527 // Val 0
1528 // DFS (1, 2)
1529 // Val 50
1530 // We want the second to be less than the first, but if we just go field
1531 // by field, we will get to Val 0 < Val 50 and say the first is less than
1532 // the second. We only want it to be less than if the DFS orders are equal.
1533 //
1534 // Each LLVM instruction only produces one value, and thus the lowest-level
1535 // differentiator that really matters for the stack (and what we use as as a
1536 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001537 // Everything else in the structure is instruction level, and only affects
1538 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001539 //
1540 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1541 // the order of replacement of uses does not matter.
1542 // IE given,
1543 // a = 5
1544 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001545 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1546 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001547 // The .val will be the same as well.
1548 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001549 // You will replace both, and it does not matter what order you replace them
1550 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1551 // operand 2).
1552 // Similarly for the case of same dfsin, dfsout, localnum, but different
1553 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001554 // a = 5
1555 // b = 6
1556 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001557 // in c, we will a valuedfs for a, and one for b,with everything the same
1558 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001559 // It does not matter what order we replace these operands in.
1560 // You will always end up with the same IR, and this is guaranteed.
1561 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1562 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1563 Other.U);
1564 }
1565};
1566
1567void NewGVN::convertDenseToDFSOrdered(CongruenceClass::MemberSet &Dense,
1568 std::vector<ValueDFS> &DFSOrderedSet) {
1569 for (auto D : Dense) {
1570 // First add the value.
1571 BasicBlock *BB = getBlockForValue(D);
1572 // Constants are handled prior to ever calling this function, so
1573 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001574 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001575 ValueDFS VD;
1576
1577 std::pair<int, int> DFSPair = DFSDomMap[BB];
1578 assert(DFSPair.first != -1 && DFSPair.second != -1 && "Invalid DFS Pair");
1579 VD.DFSIn = DFSPair.first;
1580 VD.DFSOut = DFSPair.second;
1581 VD.Val = D;
1582 // If it's an instruction, use the real local dfs number.
1583 if (auto *I = dyn_cast<Instruction>(D))
1584 VD.LocalNum = InstrDFS[I];
1585 else
1586 llvm_unreachable("Should have been an instruction");
1587
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001588 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001589
1590 // Now add the users.
1591 for (auto &U : D->uses()) {
1592 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1593 ValueDFS VD;
1594 // Put the phi node uses in the incoming block.
1595 BasicBlock *IBlock;
1596 if (auto *P = dyn_cast<PHINode>(I)) {
1597 IBlock = P->getIncomingBlock(U);
1598 // Make phi node users appear last in the incoming block
1599 // they are from.
1600 VD.LocalNum = InstrDFS.size() + 1;
1601 } else {
1602 IBlock = I->getParent();
1603 VD.LocalNum = InstrDFS[I];
1604 }
1605 std::pair<int, int> DFSPair = DFSDomMap[IBlock];
1606 VD.DFSIn = DFSPair.first;
1607 VD.DFSOut = DFSPair.second;
1608 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001609 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001610 }
1611 }
1612 }
1613}
1614
1615static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1616 // Patch the replacement so that it is not more restrictive than the value
1617 // being replaced.
1618 auto *Op = dyn_cast<BinaryOperator>(I);
1619 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
1620
1621 if (Op && ReplOp)
1622 ReplOp->andIRFlags(Op);
1623
1624 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
1625 // FIXME: If both the original and replacement value are part of the
1626 // same control-flow region (meaning that the execution of one
1627 // guarentees the executation of the other), then we can combine the
1628 // noalias scopes here and do better than the general conservative
1629 // answer used in combineMetadata().
1630
1631 // In general, GVN unifies expressions over different control-flow
1632 // regions, and so we need a conservative combination of the noalias
1633 // scopes.
1634 unsigned KnownIDs[] = {
1635 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1636 LLVMContext::MD_noalias, LLVMContext::MD_range,
1637 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1638 LLVMContext::MD_invariant_group};
1639 combineMetadata(ReplInst, I, KnownIDs);
1640 }
1641}
1642
1643static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1644 patchReplacementInstruction(I, Repl);
1645 I->replaceAllUsesWith(Repl);
1646}
1647
1648void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
1649 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1650 ++NumGVNBlocksDeleted;
1651
1652 // Check to see if there are non-terminating instructions to delete.
1653 if (isa<TerminatorInst>(BB->begin()))
1654 return;
1655
1656 // Delete the instructions backwards, as it has a reduced likelihood of having
1657 // to update as many def-use and use-def chains. Start after the terminator.
1658 auto StartPoint = BB->rbegin();
1659 ++StartPoint;
1660 // Note that we explicitly recalculate BB->rend() on each iteration,
1661 // as it may change when we remove the first instruction.
1662 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
1663 Instruction &Inst = *I++;
1664 if (!Inst.use_empty())
1665 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
1666 if (isa<LandingPadInst>(Inst))
1667 continue;
1668
1669 Inst.eraseFromParent();
1670 ++NumGVNInstrDeleted;
1671 }
1672}
1673
1674void NewGVN::markInstructionForDeletion(Instruction *I) {
1675 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
1676 InstructionsToErase.insert(I);
1677}
1678
1679void NewGVN::replaceInstruction(Instruction *I, Value *V) {
1680
1681 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
1682 patchAndReplaceAllUsesWith(I, V);
1683 // We save the actual erasing to avoid invalidating memory
1684 // dependencies until we are done with everything.
1685 markInstructionForDeletion(I);
1686}
1687
1688namespace {
1689
1690// This is a stack that contains both the value and dfs info of where
1691// that value is valid.
1692class ValueDFSStack {
1693public:
1694 Value *back() const { return ValueStack.back(); }
1695 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
1696
1697 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001698 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001699 DFSStack.emplace_back(DFSIn, DFSOut);
1700 }
1701 bool empty() const { return DFSStack.empty(); }
1702 bool isInScope(int DFSIn, int DFSOut) const {
1703 if (empty())
1704 return false;
1705 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
1706 }
1707
1708 void popUntilDFSScope(int DFSIn, int DFSOut) {
1709
1710 // These two should always be in sync at this point.
1711 assert(ValueStack.size() == DFSStack.size() &&
1712 "Mismatch between ValueStack and DFSStack");
1713 while (
1714 !DFSStack.empty() &&
1715 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
1716 DFSStack.pop_back();
1717 ValueStack.pop_back();
1718 }
1719 }
1720
1721private:
1722 SmallVector<Value *, 8> ValueStack;
1723 SmallVector<std::pair<int, int>, 8> DFSStack;
1724};
1725}
1726
1727bool NewGVN::eliminateInstructions(Function &F) {
1728 // This is a non-standard eliminator. The normal way to eliminate is
1729 // to walk the dominator tree in order, keeping track of available
1730 // values, and eliminating them. However, this is mildly
1731 // pointless. It requires doing lookups on every instruction,
1732 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001733 // instructions part of most singleton congruence classes, we know we
1734 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00001735
1736 // Instead, this eliminator looks at the congruence classes directly, sorts
1737 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001738 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001739 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001740 // last member. This is worst case O(E log E) where E = number of
1741 // instructions in a single congruence class. In theory, this is all
1742 // instructions. In practice, it is much faster, as most instructions are
1743 // either in singleton congruence classes or can't possibly be eliminated
1744 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00001745 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001746 // for elimination purposes.
1747 // TODO: If we wanted to be faster, We could remove any members with no
1748 // overlapping ranges while sorting, as we will never eliminate anything
1749 // with those members, as they don't dominate anything else in our set.
1750
Davide Italiano7e274e02016-12-22 16:03:48 +00001751 bool AnythingReplaced = false;
1752
1753 // Since we are going to walk the domtree anyway, and we can't guarantee the
1754 // DFS numbers are updated, we compute some ourselves.
1755 DT->updateDFSNumbers();
1756
1757 for (auto &B : F) {
1758 if (!ReachableBlocks.count(&B)) {
1759 for (const auto S : successors(&B)) {
1760 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001761 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00001762 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
1763 << getBlockName(&B)
1764 << " with undef due to it being unreachable\n");
1765 for (auto &Operand : Phi.incoming_values())
1766 if (Phi.getIncomingBlock(Operand) == &B)
1767 Operand.set(UndefValue::get(Phi.getType()));
1768 }
1769 }
1770 }
1771 DomTreeNode *Node = DT->getNode(&B);
1772 if (Node)
1773 DFSDomMap[&B] = {Node->getDFSNumIn(), Node->getDFSNumOut()};
1774 }
1775
1776 for (CongruenceClass *CC : CongruenceClasses) {
1777 // FIXME: We should eventually be able to replace everything still
1778 // in the initial class with undef, as they should be unreachable.
1779 // Right now, initial still contains some things we skip value
1780 // numbering of (UNREACHABLE's, for example).
1781 if (CC == InitialClass || CC->Dead)
1782 continue;
1783 assert(CC->RepLeader && "We should have had a leader");
1784
1785 // If this is a leader that is always available, and it's a
1786 // constant or has no equivalences, just replace everything with
1787 // it. We then update the congruence class with whatever members
1788 // are left.
1789 if (alwaysAvailable(CC->RepLeader)) {
1790 SmallPtrSet<Value *, 4> MembersLeft;
1791 for (auto M : CC->Members) {
1792
1793 Value *Member = M;
1794
1795 // Void things have no uses we can replace.
1796 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
1797 MembersLeft.insert(Member);
1798 continue;
1799 }
1800
1801 DEBUG(dbgs() << "Found replacement " << *(CC->RepLeader) << " for "
1802 << *Member << "\n");
1803 // Due to equality propagation, these may not always be
1804 // instructions, they may be real values. We don't really
1805 // care about trying to replace the non-instructions.
1806 if (auto *I = dyn_cast<Instruction>(Member)) {
1807 assert(CC->RepLeader != I &&
1808 "About to accidentally remove our leader");
1809 replaceInstruction(I, CC->RepLeader);
1810 AnythingReplaced = true;
1811
1812 continue;
1813 } else {
1814 MembersLeft.insert(I);
1815 }
1816 }
1817 CC->Members.swap(MembersLeft);
1818
1819 } else {
1820 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
1821 // If this is a singleton, we can skip it.
1822 if (CC->Members.size() != 1) {
1823
1824 // This is a stack because equality replacement/etc may place
1825 // constants in the middle of the member list, and we want to use
1826 // those constant values in preference to the current leader, over
1827 // the scope of those constants.
1828 ValueDFSStack EliminationStack;
1829
1830 // Convert the members to DFS ordered sets and then merge them.
1831 std::vector<ValueDFS> DFSOrderedSet;
1832 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
1833
1834 // Sort the whole thing.
1835 sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
1836
1837 for (auto &C : DFSOrderedSet) {
1838 int MemberDFSIn = C.DFSIn;
1839 int MemberDFSOut = C.DFSOut;
1840 Value *Member = C.Val;
1841 Use *MemberUse = C.U;
1842
1843 // We ignore void things because we can't get a value from them.
1844 if (Member && Member->getType()->isVoidTy())
1845 continue;
1846
1847 if (EliminationStack.empty()) {
1848 DEBUG(dbgs() << "Elimination Stack is empty\n");
1849 } else {
1850 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
1851 << EliminationStack.dfs_back().first << ","
1852 << EliminationStack.dfs_back().second << ")\n");
1853 }
1854 if (Member && isa<Constant>(Member))
1855 assert(isa<Constant>(CC->RepLeader));
1856
1857 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
1858 << MemberDFSOut << ")\n");
1859 // First, we see if we are out of scope or empty. If so,
1860 // and there equivalences, we try to replace the top of
1861 // stack with equivalences (if it's on the stack, it must
1862 // not have been eliminated yet).
1863 // Then we synchronize to our current scope, by
1864 // popping until we are back within a DFS scope that
1865 // dominates the current member.
1866 // Then, what happens depends on a few factors
1867 // If the stack is now empty, we need to push
1868 // If we have a constant or a local equivalence we want to
1869 // start using, we also push.
1870 // Otherwise, we walk along, processing members who are
1871 // dominated by this scope, and eliminate them.
1872 bool ShouldPush =
1873 Member && (EliminationStack.empty() || isa<Constant>(Member));
1874 bool OutOfScope =
1875 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
1876
1877 if (OutOfScope || ShouldPush) {
1878 // Sync to our current scope.
1879 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
1880 ShouldPush |= Member && EliminationStack.empty();
1881 if (ShouldPush) {
1882 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
1883 }
1884 }
1885
1886 // If we get to this point, and the stack is empty we must have a use
1887 // with nothing we can use to eliminate it, just skip it.
1888 if (EliminationStack.empty())
1889 continue;
1890
1891 // Skip the Value's, we only want to eliminate on their uses.
1892 if (Member)
1893 continue;
1894 Value *Result = EliminationStack.back();
1895
1896 // Don't replace our existing users with ourselves.
1897 if (MemberUse->get() == Result)
1898 continue;
1899
1900 DEBUG(dbgs() << "Found replacement " << *Result << " for "
1901 << *MemberUse->get() << " in " << *(MemberUse->getUser())
1902 << "\n");
1903
1904 // If we replaced something in an instruction, handle the patching of
1905 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001906 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00001907 patchReplacementInstruction(ReplacedInst, Result);
1908
1909 assert(isa<Instruction>(MemberUse->getUser()));
1910 MemberUse->set(Result);
1911 AnythingReplaced = true;
1912 }
1913 }
1914 }
1915
1916 // Cleanup the congruence class.
1917 SmallPtrSet<Value *, 4> MembersLeft;
Piotr Padlewski26dada72016-12-28 19:42:49 +00001918 for (Value * Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001919 if (Member->getType()->isVoidTy()) {
1920 MembersLeft.insert(Member);
1921 continue;
1922 }
1923
1924 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
1925 if (isInstructionTriviallyDead(MemberInst)) {
1926 // TODO: Don't mark loads of undefs.
1927 markInstructionForDeletion(MemberInst);
1928 continue;
1929 }
1930 }
1931 MembersLeft.insert(Member);
1932 }
1933 CC->Members.swap(MembersLeft);
1934 }
1935
1936 return AnythingReplaced;
1937}