blob: b22c6b4ded5ee54990216b4c3bf0bdff6c10bb4c [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);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000265 const UnknownExpression *createUnknownExpression(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000266 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
267 const BasicBlock *);
268 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
269 MemoryAccess *, const BasicBlock *);
270
271 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
272 const BasicBlock *);
273 const AggregateValueExpression *
274 createAggregateValueExpression(Instruction *, const BasicBlock *);
275 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
276 const BasicBlock *);
277
278 // Congruence class handling.
279 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000280 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000281 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000282 return result;
283 }
284
285 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000286 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000287 CClass->Members.insert(Member);
288 ValueToClass[Member] = CClass;
289 return CClass;
290 }
291 void initializeCongruenceClasses(Function &F);
292
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000293 // Value number an Instruction or MemoryPhi.
294 void valueNumberMemoryPhi(MemoryPhi *);
295 void valueNumberInstruction(Instruction *);
296
Davide Italiano7e274e02016-12-22 16:03:48 +0000297 // Symbolic evaluation.
298 const Expression *checkSimplificationResults(Expression *, Instruction *,
299 Value *);
300 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
301 const Expression *performSymbolicLoadEvaluation(Instruction *,
302 const BasicBlock *);
303 const Expression *performSymbolicStoreEvaluation(Instruction *,
304 const BasicBlock *);
305 const Expression *performSymbolicCallEvaluation(Instruction *,
306 const BasicBlock *);
307 const Expression *performSymbolicPHIEvaluation(Instruction *,
308 const BasicBlock *);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000309 bool setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To);
Davide Italiano7e274e02016-12-22 16:03:48 +0000310 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
311 const BasicBlock *);
312
313 // Congruence finding.
314 // Templated to allow them to work both on BB's and BB-edges.
315 template <class T>
316 Value *lookupOperandLeader(Value *, const User *, const T &) const;
317 void performCongruenceFinding(Value *, const Expression *);
318
319 // Reachability handling.
320 void updateReachableEdge(BasicBlock *, BasicBlock *);
321 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000322 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000323 Value *findConditionEquivalence(Value *, BasicBlock *) const;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000324 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000325
326 // Elimination.
327 struct ValueDFS;
328 void convertDenseToDFSOrdered(CongruenceClass::MemberSet &,
329 std::vector<ValueDFS> &);
330
331 bool eliminateInstructions(Function &);
332 void replaceInstruction(Instruction *, Value *);
333 void markInstructionForDeletion(Instruction *);
334 void deleteInstructionsInBlock(BasicBlock *);
335
336 // New instruction creation.
337 void handleNewInstruction(Instruction *){};
338 void markUsersTouched(Value *);
339 void markMemoryUsersTouched(MemoryAccess *);
340
341 // Utilities.
342 void cleanupTables();
343 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
344 void updateProcessedCount(Value *V);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000345 void verifyMemoryCongruency();
Davide Italiano7e274e02016-12-22 16:03:48 +0000346};
347
348char NewGVN::ID = 0;
349
350// createGVNPass - The public interface to this file.
351FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
352
Davide Italianob1114092016-12-28 13:37:17 +0000353template <typename T>
354static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
355 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000356 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000357 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000358 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000359 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000360 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000361 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000362 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000363 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000364 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000365 return true;
366}
367
Davide Italianob1114092016-12-28 13:37:17 +0000368bool LoadExpression::equals(const Expression &Other) const {
369 return equalsLoadStoreHelper(*this, Other);
370}
Davide Italiano7e274e02016-12-22 16:03:48 +0000371
Davide Italianob1114092016-12-28 13:37:17 +0000372bool StoreExpression::equals(const Expression &Other) const {
373 return equalsLoadStoreHelper(*this, Other);
Davide Italiano7e274e02016-12-22 16:03:48 +0000374}
375
376#ifndef NDEBUG
377static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000378 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000379}
380#endif
381
382INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
383INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
384INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
385INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
386INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
387INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
388INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
389INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
390
391PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
392 BasicBlock *PhiBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000393 auto *PN = cast<PHINode>(I);
394 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000395 PHIExpression(PN->getNumOperands(), I->getParent());
396
397 E->allocateOperands(ArgRecycler, ExpressionAllocator);
398 E->setType(I->getType());
399 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000400
401 auto ReachablePhiArg = [&](const Use &U) {
402 return ReachableBlocks.count(PN->getIncomingBlock(U));
403 };
404
405 // Filter out unreachable operands
406 auto Filtered = make_filter_range(PN->operands(), ReachablePhiArg);
407
408 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
409 [&](const Use &U) -> Value * {
410 // Don't try to transform self-defined phis
411 if (U == PN)
412 return PN;
413 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PhiBlock);
414 return lookupOperandLeader(U, I, BBE);
415 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000416 return E;
417}
418
419// Set basic expression info (Arguments, type, opcode) for Expression
420// E from Instruction I in block B.
421bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
422 const BasicBlock *B) {
423 bool AllConstant = true;
424 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
425 E->setType(GEP->getSourceElementType());
426 else
427 E->setType(I->getType());
428 E->setOpcode(I->getOpcode());
429 E->allocateOperands(ArgRecycler, ExpressionAllocator);
430
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000431 // Transform the operand array into an operand leader array, and keep track of
432 // whether all members are constant.
433 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000434 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000435 AllConstant &= isa<Constant>(Operand);
436 return Operand;
437 });
438
Davide Italiano7e274e02016-12-22 16:03:48 +0000439 return AllConstant;
440}
441
442const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
443 Value *Arg1, Value *Arg2,
444 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000445 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000446
447 E->setType(T);
448 E->setOpcode(Opcode);
449 E->allocateOperands(ArgRecycler, ExpressionAllocator);
450 if (Instruction::isCommutative(Opcode)) {
451 // Ensure that commutative instructions that only differ by a permutation
452 // of their operands get the same value number by sorting the operand value
453 // numbers. Since all commutative instructions have two operands it is more
454 // efficient to sort by hand rather than using, say, std::sort.
455 if (Arg1 > Arg2)
456 std::swap(Arg1, Arg2);
457 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000458 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
459 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000460
461 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
462 DT, AC);
463 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
464 return SimplifiedE;
465 return E;
466}
467
468// Take a Value returned by simplification of Expression E/Instruction
469// I, and see if it resulted in a simpler expression. If so, return
470// that expression.
471// TODO: Once finished, this should not take an Instruction, we only
472// use it for printing.
473const Expression *NewGVN::checkSimplificationResults(Expression *E,
474 Instruction *I, Value *V) {
475 if (!V)
476 return nullptr;
477 if (auto *C = dyn_cast<Constant>(V)) {
478 if (I)
479 DEBUG(dbgs() << "Simplified " << *I << " to "
480 << " constant " << *C << "\n");
481 NumGVNOpsSimplified++;
482 assert(isa<BasicExpression>(E) &&
483 "We should always have had a basic expression here");
484
485 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
486 ExpressionAllocator.Deallocate(E);
487 return createConstantExpression(C);
488 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
489 if (I)
490 DEBUG(dbgs() << "Simplified " << *I << " to "
491 << " variable " << *V << "\n");
492 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
493 ExpressionAllocator.Deallocate(E);
494 return createVariableExpression(V);
495 }
496
497 CongruenceClass *CC = ValueToClass.lookup(V);
498 if (CC && CC->DefiningExpr) {
499 if (I)
500 DEBUG(dbgs() << "Simplified " << *I << " to "
501 << " expression " << *V << "\n");
502 NumGVNOpsSimplified++;
503 assert(isa<BasicExpression>(E) &&
504 "We should always have had a basic expression here");
505 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
506 ExpressionAllocator.Deallocate(E);
507 return CC->DefiningExpr;
508 }
509 return nullptr;
510}
511
512const Expression *NewGVN::createExpression(Instruction *I,
513 const BasicBlock *B) {
514
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000515 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000516
517 bool AllConstant = setBasicExpressionInfo(I, E, B);
518
519 if (I->isCommutative()) {
520 // Ensure that commutative instructions that only differ by a permutation
521 // of their operands get the same value number by sorting the operand value
522 // numbers. Since all commutative instructions have two operands it is more
523 // efficient to sort by hand rather than using, say, std::sort.
524 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
525 if (E->getOperand(0) > E->getOperand(1))
526 E->swapOperands(0, 1);
527 }
528
529 // Perform simplificaiton
530 // TODO: Right now we only check to see if we get a constant result.
531 // We may get a less than constant, but still better, result for
532 // some operations.
533 // IE
534 // add 0, x -> x
535 // and x, x -> x
536 // We should handle this by simply rewriting the expression.
537 if (auto *CI = dyn_cast<CmpInst>(I)) {
538 // Sort the operand value numbers so x<y and y>x get the same value
539 // number.
540 CmpInst::Predicate Predicate = CI->getPredicate();
541 if (E->getOperand(0) > E->getOperand(1)) {
542 E->swapOperands(0, 1);
543 Predicate = CmpInst::getSwappedPredicate(Predicate);
544 }
545 E->setOpcode((CI->getOpcode() << 8) | Predicate);
546 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
547 // TODO: Since we noop bitcasts, we may need to check types before
548 // simplifying, so that we don't end up simplifying based on a wrong
549 // type assumption. We should clean this up so we can use constants of the
550 // wrong type
551
552 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
553 "Wrong types on cmp instruction");
554 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
555 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
556 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
557 *DL, TLI, DT, AC);
558 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
559 return SimplifiedE;
560 }
561 } else if (isa<SelectInst>(I)) {
562 if (isa<Constant>(E->getOperand(0)) ||
563 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
564 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
565 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
566 E->getOperand(2), *DL, TLI, DT, AC);
567 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
568 return SimplifiedE;
569 }
570 } else if (I->isBinaryOp()) {
571 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
572 *DL, TLI, DT, AC);
573 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
574 return SimplifiedE;
575 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
576 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
577 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
578 return SimplifiedE;
579 } else if (isa<GetElementPtrInst>(I)) {
580 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000581 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000582 *DL, TLI, DT, AC);
583 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
584 return SimplifiedE;
585 } else if (AllConstant) {
586 // We don't bother trying to simplify unless all of the operands
587 // were constant.
588 // TODO: There are a lot of Simplify*'s we could call here, if we
589 // wanted to. The original motivating case for this code was a
590 // zext i1 false to i8, which we don't have an interface to
591 // simplify (IE there is no SimplifyZExt).
592
593 SmallVector<Constant *, 8> C;
594 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000595 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000596
597 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
598 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
599 return SimplifiedE;
600 }
601 return E;
602}
603
604const AggregateValueExpression *
605NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
606 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000607 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000608 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
609 setBasicExpressionInfo(I, E, B);
610 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000611 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000612 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000613 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000614 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000615 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
616 setBasicExpressionInfo(EI, E, B);
617 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000618 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000619 return E;
620 }
621 llvm_unreachable("Unhandled type of aggregate value operation");
622}
623
Daniel Berlin85f91b02016-12-26 20:06:58 +0000624const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000625 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000626 E->setOpcode(V->getValueID());
627 return E;
628}
629
630const Expression *NewGVN::createVariableOrConstant(Value *V,
631 const BasicBlock *B) {
632 auto Leader = lookupOperandLeader(V, nullptr, B);
633 if (auto *C = dyn_cast<Constant>(Leader))
634 return createConstantExpression(C);
635 return createVariableExpression(Leader);
636}
637
Daniel Berlin85f91b02016-12-26 20:06:58 +0000638const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000639 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000640 E->setOpcode(C->getValueID());
641 return E;
642}
643
Daniel Berlin02c6b172017-01-02 18:00:53 +0000644const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
645 auto *E = new (ExpressionAllocator) UnknownExpression(I);
646 E->setOpcode(I->getOpcode());
647 return E;
648}
649
Davide Italiano7e274e02016-12-22 16:03:48 +0000650const CallExpression *NewGVN::createCallExpression(CallInst *CI,
651 MemoryAccess *HV,
652 const BasicBlock *B) {
653 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000654 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000655 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
656 setBasicExpressionInfo(CI, E, B);
657 return E;
658}
659
660// See if we have a congruence class and leader for this operand, and if so,
661// return it. Otherwise, return the operand itself.
662template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000663Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000664 CongruenceClass *CC = ValueToClass.lookup(V);
665 if (CC && (CC != InitialClass))
666 return CC->RepLeader;
667 return V;
668}
669
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000670MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
671 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA);
672 return Result ? Result : MA;
673}
674
Davide Italiano7e274e02016-12-22 16:03:48 +0000675LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
676 LoadInst *LI, MemoryAccess *DA,
677 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000678 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000679 E->allocateOperands(ArgRecycler, ExpressionAllocator);
680 E->setType(LoadType);
681
682 // Give store and loads same opcode so they value number together.
683 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000684 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000685 if (LI)
686 E->setAlignment(LI->getAlignment());
687
688 // TODO: Value number heap versions. We may be able to discover
689 // things alias analysis can't on it's own (IE that a store and a
690 // load have the same value, and thus, it isn't clobbering the load).
691 return E;
692}
693
694const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
695 MemoryAccess *DA,
696 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000697 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000698 new (ExpressionAllocator) StoreExpression(SI->getNumOperands(), SI, DA);
699 E->allocateOperands(ArgRecycler, ExpressionAllocator);
700 E->setType(SI->getValueOperand()->getType());
701
702 // Give store and loads same opcode so they value number together.
703 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000704 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000705
706 // TODO: Value number heap versions. We may be able to discover
707 // things alias analysis can't on it's own (IE that a store and a
708 // load have the same value, and thus, it isn't clobbering the load).
709 return E;
710}
711
712const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
713 const BasicBlock *B) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000714 // Unlike loads, we never try to eliminate stores, so we do not check if they
715 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000716 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000717 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinde43ef92017-01-02 19:49:17 +0000718 // See if we are defined by a previous store expression, it already has a
719 // value, and it's the same value as our current store. FIXME: Right now, we
720 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000721 if (SI->isSimple()) {
Daniel Berlinde43ef92017-01-02 19:49:17 +0000722 // Get the expression, if any, for the RHS of the MemoryDef.
723 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
724 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
725 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000726 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
727 if (CC && CC->DefiningExpr && isa<StoreExpression>(CC->DefiningExpr) &&
728 CC->RepLeader == lookupOperandLeader(SI->getValueOperand(), SI, B))
729 return createStoreExpression(SI, StoreRHS, B);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000730 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000731
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000732 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000733}
734
735const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
736 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000737 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000738
739 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000740 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000741 if (!LI->isSimple())
742 return nullptr;
743
Daniel Berlin85f91b02016-12-26 20:06:58 +0000744 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000745 // Load of undef is undef.
746 if (isa<UndefValue>(LoadAddressLeader))
747 return createConstantExpression(UndefValue::get(LI->getType()));
748
749 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
750
751 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
752 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
753 Instruction *DefiningInst = MD->getMemoryInst();
754 // If the defining instruction is not reachable, replace with undef.
755 if (!ReachableBlocks.count(DefiningInst->getParent()))
756 return createConstantExpression(UndefValue::get(LI->getType()));
757 }
758 }
759
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000760 const Expression *E =
761 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
762 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000763 return E;
764}
765
766// Evaluate read only and pure calls, and create an expression result.
767const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
768 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000769 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000770 if (AA->doesNotAccessMemory(CI))
771 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000772 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000773 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000774 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000775 }
776 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000777}
778
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000779// Update the memory access equivalence table to say that From is equal to To,
780// and return true if this is different from what already existed in the table.
781bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To) {
Davide Italiano84126162017-01-02 18:41:34 +0000782 DEBUG(dbgs() << "Setting " << *From << " equivalent to ");
783 if (!To)
784 DEBUG(dbgs() << "itself");
785 else
786 DEBUG(dbgs() << *To);
787 DEBUG(dbgs() << "\n");
Daniel Berlin589cecc2017-01-02 18:00:46 +0000788 auto LookupResult = MemoryAccessEquiv.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000789 bool Changed = false;
790 // If it's already in the table, see if the value changed.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000791 if (LookupResult != MemoryAccessEquiv.end()) {
792 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000793 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000794 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000795 Changed = true;
796 } else if (!To) {
797 // It used to be equivalent to something, and now it's not.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000798 MemoryAccessEquiv.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000799 Changed = true;
800 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000801 } else {
802 assert(!To &&
803 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000804 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000805
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000806 return Changed;
807}
Davide Italiano7e274e02016-12-22 16:03:48 +0000808// Evaluate PHI nodes symbolically, and create an expression result.
809const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
810 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000811 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000812 if (E->op_empty()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000813 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
814 << "\n");
815 E->deallocateOperands(ArgRecycler);
816 ExpressionAllocator.Deallocate(E);
817 return createConstantExpression(UndefValue::get(I->getType()));
818 }
819
820 Value *AllSameValue = E->getOperand(0);
821
822 // See if all arguments are the same, ignoring undef arguments, because we can
823 // choose a value that is the same for them.
824 for (const Value *Arg : E->operands())
825 if (Arg != AllSameValue && !isa<UndefValue>(Arg)) {
Davide Italiano0e714802016-12-28 14:00:11 +0000826 AllSameValue = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000827 break;
828 }
829
830 if (AllSameValue) {
831 // It's possible to have phi nodes with cycles (IE dependent on
832 // other phis that are .... dependent on the original phi node),
833 // especially in weird CFG's where some arguments are unreachable, or
834 // uninitialized along certain paths.
835 // This can cause infinite loops during evaluation (even if you disable
836 // the recursion below, you will simply ping-pong between congruence
837 // classes). If a phi node symbolically evaluates to another phi node,
838 // just leave it alone. If they are really the same, we will still
839 // eliminate them in favor of each other.
840 if (isa<PHINode>(AllSameValue))
841 return E;
842 NumGVNPhisAllSame++;
843 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
844 << "\n");
845 E->deallocateOperands(ArgRecycler);
846 ExpressionAllocator.Deallocate(E);
847 if (auto *C = dyn_cast<Constant>(AllSameValue))
848 return createConstantExpression(C);
849 return createVariableExpression(AllSameValue);
850 }
851 return E;
852}
853
854const Expression *
855NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
856 const BasicBlock *B) {
857 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
858 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
859 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
860 unsigned Opcode = 0;
861 // EI might be an extract from one of our recognised intrinsics. If it
862 // is we'll synthesize a semantically equivalent expression instead on
863 // an extract value expression.
864 switch (II->getIntrinsicID()) {
865 case Intrinsic::sadd_with_overflow:
866 case Intrinsic::uadd_with_overflow:
867 Opcode = Instruction::Add;
868 break;
869 case Intrinsic::ssub_with_overflow:
870 case Intrinsic::usub_with_overflow:
871 Opcode = Instruction::Sub;
872 break;
873 case Intrinsic::smul_with_overflow:
874 case Intrinsic::umul_with_overflow:
875 Opcode = Instruction::Mul;
876 break;
877 default:
878 break;
879 }
880
881 if (Opcode != 0) {
882 // Intrinsic recognized. Grab its args to finish building the
883 // expression.
884 assert(II->getNumArgOperands() == 2 &&
885 "Expect two args for recognised intrinsics.");
886 return createBinaryExpression(Opcode, EI->getType(),
887 II->getArgOperand(0),
888 II->getArgOperand(1), B);
889 }
890 }
891 }
892
893 return createAggregateValueExpression(I, B);
894}
895
896// Substitute and symbolize the value before value numbering.
897const Expression *NewGVN::performSymbolicEvaluation(Value *V,
898 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000899 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000900 if (auto *C = dyn_cast<Constant>(V))
901 E = createConstantExpression(C);
902 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
903 E = createVariableExpression(V);
904 } else {
905 // TODO: memory intrinsics.
906 // TODO: Some day, we should do the forward propagation and reassociation
907 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000908 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000909 switch (I->getOpcode()) {
910 case Instruction::ExtractValue:
911 case Instruction::InsertValue:
912 E = performSymbolicAggrValueEvaluation(I, B);
913 break;
914 case Instruction::PHI:
915 E = performSymbolicPHIEvaluation(I, B);
916 break;
917 case Instruction::Call:
918 E = performSymbolicCallEvaluation(I, B);
919 break;
920 case Instruction::Store:
921 E = performSymbolicStoreEvaluation(I, B);
922 break;
923 case Instruction::Load:
924 E = performSymbolicLoadEvaluation(I, B);
925 break;
926 case Instruction::BitCast: {
927 E = createExpression(I, B);
928 } break;
929
930 case Instruction::Add:
931 case Instruction::FAdd:
932 case Instruction::Sub:
933 case Instruction::FSub:
934 case Instruction::Mul:
935 case Instruction::FMul:
936 case Instruction::UDiv:
937 case Instruction::SDiv:
938 case Instruction::FDiv:
939 case Instruction::URem:
940 case Instruction::SRem:
941 case Instruction::FRem:
942 case Instruction::Shl:
943 case Instruction::LShr:
944 case Instruction::AShr:
945 case Instruction::And:
946 case Instruction::Or:
947 case Instruction::Xor:
948 case Instruction::ICmp:
949 case Instruction::FCmp:
950 case Instruction::Trunc:
951 case Instruction::ZExt:
952 case Instruction::SExt:
953 case Instruction::FPToUI:
954 case Instruction::FPToSI:
955 case Instruction::UIToFP:
956 case Instruction::SIToFP:
957 case Instruction::FPTrunc:
958 case Instruction::FPExt:
959 case Instruction::PtrToInt:
960 case Instruction::IntToPtr:
961 case Instruction::Select:
962 case Instruction::ExtractElement:
963 case Instruction::InsertElement:
964 case Instruction::ShuffleVector:
965 case Instruction::GetElementPtr:
966 E = createExpression(I, B);
967 break;
968 default:
969 return nullptr;
970 }
971 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000972 return E;
973}
974
975// There is an edge from 'Src' to 'Dst'. Return true if every path from
976// the entry block to 'Dst' passes via this edge. In particular 'Dst'
977// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000978bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000979
980 // While in theory it is interesting to consider the case in which Dst has
981 // more than one predecessor, because Dst might be part of a loop which is
982 // only reachable from Src, in practice it is pointless since at the time
983 // GVN runs all such loops have preheaders, which means that Dst will have
984 // been changed to have only one predecessor, namely Src.
985 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
986 const BasicBlock *Src = E.getStart();
987 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
988 (void)Src;
989 return Pred != nullptr;
990}
991
992void NewGVN::markUsersTouched(Value *V) {
993 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +0000994 for (auto *User : V->users()) {
995 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Davide Italiano7e274e02016-12-22 16:03:48 +0000996 TouchedInstructions.set(InstrDFS[User]);
997 }
998}
999
1000void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1001 for (auto U : MA->users()) {
1002 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
1003 TouchedInstructions.set(InstrDFS[MUD->getMemoryInst()]);
1004 else
Daniel Berline0bd37e2016-12-29 22:15:12 +00001005 TouchedInstructions.set(InstrDFS[U]);
Davide Italiano7e274e02016-12-22 16:03:48 +00001006 }
1007}
1008
1009// Perform congruence finding on a given value numbering expression.
1010void NewGVN::performCongruenceFinding(Value *V, const Expression *E) {
1011
1012 ValueToExpression[V] = E;
1013 // This is guaranteed to return something, since it will at least find
1014 // INITIAL.
1015 CongruenceClass *VClass = ValueToClass[V];
1016 assert(VClass && "Should have found a vclass");
1017 // Dead classes should have been eliminated from the mapping.
1018 assert(!VClass->Dead && "Found a dead class");
1019
1020 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001021 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001022 EClass = ValueToClass[VE->getVariableValue()];
1023 } else {
1024 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1025
1026 // If it's not in the value table, create a new congruence class.
1027 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001028 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001029 auto place = lookupResult.first;
1030 place->second = NewClass;
1031
1032 // Constants and variables should always be made the leader.
1033 if (const auto *CE = dyn_cast<ConstantExpression>(E))
1034 NewClass->RepLeader = CE->getConstantValue();
1035 else if (const auto *VE = dyn_cast<VariableExpression>(E))
1036 NewClass->RepLeader = VE->getVariableValue();
1037 else if (const auto *SE = dyn_cast<StoreExpression>(E))
1038 NewClass->RepLeader = SE->getStoreInst()->getValueOperand();
1039 else
1040 NewClass->RepLeader = V;
1041
1042 EClass = NewClass;
1043 DEBUG(dbgs() << "Created new congruence class for " << *V
1044 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin589cecc2017-01-02 18:00:46 +00001045 << " and leader " << *(NewClass->RepLeader) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001046 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1047 } else {
1048 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001049 if (isa<ConstantExpression>(E))
1050 assert(isa<Constant>(EClass->RepLeader) &&
1051 "Any class with a constant expression should have a "
1052 "constant leader");
1053
Davide Italiano7e274e02016-12-22 16:03:48 +00001054 assert(EClass && "Somehow don't have an eclass");
1055
1056 assert(!EClass->Dead && "We accidentally looked up a dead class");
1057 }
1058 }
1059 bool WasInChanged = ChangedValues.erase(V);
1060 if (VClass != EClass || WasInChanged) {
1061 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1062 << "\n");
1063
1064 if (VClass != EClass) {
1065 DEBUG(dbgs() << "New congruence class for " << V << " is " << EClass->ID
1066 << "\n");
1067
1068 VClass->Members.erase(V);
1069 EClass->Members.insert(V);
1070 ValueToClass[V] = EClass;
1071 // See if we destroyed the class or need to swap leaders.
1072 if (VClass->Members.empty() && VClass != InitialClass) {
1073 if (VClass->DefiningExpr) {
1074 VClass->Dead = true;
1075 DEBUG(dbgs() << "Erasing expression " << *E << " from table\n");
1076 ExpressionToClass.erase(VClass->DefiningExpr);
1077 }
1078 } else if (VClass->RepLeader == V) {
1079 // FIXME: When the leader changes, the value numbering of
1080 // everything may change, so we need to reprocess.
1081 VClass->RepLeader = *(VClass->Members.begin());
1082 for (auto M : VClass->Members) {
1083 if (auto *I = dyn_cast<Instruction>(M))
1084 TouchedInstructions.set(InstrDFS[I]);
1085 ChangedValues.insert(M);
1086 }
1087 }
1088 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001089
Davide Italiano7e274e02016-12-22 16:03:48 +00001090 markUsersTouched(V);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001091 if (auto *I = dyn_cast<Instruction>(V)) {
1092 if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
1093 // If this is a MemoryDef, we need to update the equivalence table. If
Daniel Berlin25f05b02017-01-02 18:22:38 +00001094 // we determined the expression is congruent to a different memory
1095 // state, use that different memory state. If we determined it didn't,
Daniel Berlinde43ef92017-01-02 19:49:17 +00001096 // we update that as well. Right now, we only support store
Daniel Berlin25f05b02017-01-02 18:22:38 +00001097 // expressions.
Daniel Berlinde43ef92017-01-02 19:49:17 +00001098 if (!isa<MemoryUse>(MA) && isa<StoreExpression>(E) &&
1099 EClass->Members.size() != 1) {
1100 auto *DefAccess = cast<StoreExpression>(E)->getDefiningAccess();
1101 setMemoryAccessEquivTo(MA, DefAccess != MA ? DefAccess : nullptr);
1102 } else {
1103 setMemoryAccessEquivTo(MA, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001104 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001105 markMemoryUsersTouched(MA);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001106 }
1107 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001108 }
1109}
1110
1111// Process the fact that Edge (from, to) is reachable, including marking
1112// any newly reachable blocks and instructions for processing.
1113void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1114 // Check if the Edge was reachable before.
1115 if (ReachableEdges.insert({From, To}).second) {
1116 // If this block wasn't reachable before, all instructions are touched.
1117 if (ReachableBlocks.insert(To).second) {
1118 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1119 const auto &InstRange = BlockInstRange.lookup(To);
1120 TouchedInstructions.set(InstRange.first, InstRange.second);
1121 } else {
1122 DEBUG(dbgs() << "Block " << getBlockName(To)
1123 << " was reachable, but new edge {" << getBlockName(From)
1124 << "," << getBlockName(To) << "} to it found\n");
1125
1126 // We've made an edge reachable to an existing block, which may
1127 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1128 // they are the only thing that depend on new edges. Anything using their
1129 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001130 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
1131 TouchedInstructions.set(InstrDFS[MemPhi]);
1132
Davide Italiano7e274e02016-12-22 16:03:48 +00001133 auto BI = To->begin();
1134 while (isa<PHINode>(BI)) {
1135 TouchedInstructions.set(InstrDFS[&*BI]);
1136 ++BI;
1137 }
1138 }
1139 }
1140}
1141
1142// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1143// see if we know some constant value for it already.
1144Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1145 auto Result = lookupOperandLeader(Cond, nullptr, B);
1146 if (isa<Constant>(Result))
1147 return Result;
1148 return nullptr;
1149}
1150
1151// Process the outgoing edges of a block for reachability.
1152void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1153 // Evaluate reachability of terminator instruction.
1154 BranchInst *BR;
1155 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1156 Value *Cond = BR->getCondition();
1157 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1158 if (!CondEvaluated) {
1159 if (auto *I = dyn_cast<Instruction>(Cond)) {
1160 const Expression *E = createExpression(I, B);
1161 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1162 CondEvaluated = CE->getConstantValue();
1163 }
1164 } else if (isa<ConstantInt>(Cond)) {
1165 CondEvaluated = Cond;
1166 }
1167 }
1168 ConstantInt *CI;
1169 BasicBlock *TrueSucc = BR->getSuccessor(0);
1170 BasicBlock *FalseSucc = BR->getSuccessor(1);
1171 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1172 if (CI->isOne()) {
1173 DEBUG(dbgs() << "Condition for Terminator " << *TI
1174 << " evaluated to true\n");
1175 updateReachableEdge(B, TrueSucc);
1176 } else if (CI->isZero()) {
1177 DEBUG(dbgs() << "Condition for Terminator " << *TI
1178 << " evaluated to false\n");
1179 updateReachableEdge(B, FalseSucc);
1180 }
1181 } else {
1182 updateReachableEdge(B, TrueSucc);
1183 updateReachableEdge(B, FalseSucc);
1184 }
1185 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1186 // For switches, propagate the case values into the case
1187 // destinations.
1188
1189 // Remember how many outgoing edges there are to every successor.
1190 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1191
Davide Italiano7e274e02016-12-22 16:03:48 +00001192 Value *SwitchCond = SI->getCondition();
1193 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1194 // See if we were able to turn this switch statement into a constant.
1195 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001196 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001197 // We should be able to get case value for this.
1198 auto CaseVal = SI->findCaseValue(CondVal);
1199 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1200 // We proved the value is outside of the range of the case.
1201 // We can't do anything other than mark the default dest as reachable,
1202 // and go home.
1203 updateReachableEdge(B, SI->getDefaultDest());
1204 return;
1205 }
1206 // Now get where it goes and mark it reachable.
1207 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1208 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001209 } else {
1210 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1211 BasicBlock *TargetBlock = SI->getSuccessor(i);
1212 ++SwitchEdges[TargetBlock];
1213 updateReachableEdge(B, TargetBlock);
1214 }
1215 }
1216 } else {
1217 // Otherwise this is either unconditional, or a type we have no
1218 // idea about. Just mark successors as reachable.
1219 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1220 BasicBlock *TargetBlock = TI->getSuccessor(i);
1221 updateReachableEdge(B, TargetBlock);
1222 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001223
1224 // This also may be a memory defining terminator, in which case, set it
1225 // equivalent to nothing.
1226 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1227 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001228 }
1229}
1230
Daniel Berlin85f91b02016-12-26 20:06:58 +00001231// The algorithm initially places the values of the routine in the INITIAL
1232// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001233// class. The leader of INITIAL is the undetermined value `TOP`.
1234// When the algorithm has finished, values still in INITIAL are unreachable.
1235void NewGVN::initializeCongruenceClasses(Function &F) {
1236 // FIXME now i can't remember why this is 2
1237 NextCongruenceNum = 2;
1238 // Initialize all other instructions to be in INITIAL class.
1239 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001240 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001241 for (auto &B : F) {
1242 if (auto *MP = MSSA->getMemoryAccess(&B))
1243 MemoryAccessEquiv.insert({MP, MSSA->getLiveOnEntryDef()});
1244
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001245 for (auto &I : B) {
1246 InitialValues.insert(&I);
1247 ValueToClass[&I] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001248 // All memory accesses are equivalent to live on entry to start. They must
1249 // be initialized to something so that initial changes are noticed. For
1250 // the maximal answer, we initialize them all to be the same as
1251 // liveOnEntry. Note that to save time, we only initialize the
1252 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1253 // other expression can generate a memory equivalence. If we start
1254 // handling memcpy/etc, we can expand this.
1255 if (isa<StoreInst>(&I))
1256 MemoryAccessEquiv.insert(
1257 {MSSA->getMemoryAccess(&I), MSSA->getLiveOnEntryDef()});
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001258 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001259 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001260 InitialClass->Members.swap(InitialValues);
1261
1262 // Initialize arguments to be in their own unique congruence classes
1263 for (auto &FA : F.args())
1264 createSingletonCongruenceClass(&FA);
1265}
1266
1267void NewGVN::cleanupTables() {
1268 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1269 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1270 << CongruenceClasses[i]->Members.size() << " members\n");
1271 // Make sure we delete the congruence class (probably worth switching to
1272 // a unique_ptr at some point.
1273 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001274 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001275 }
1276
1277 ValueToClass.clear();
1278 ArgRecycler.clear(ExpressionAllocator);
1279 ExpressionAllocator.Reset();
1280 CongruenceClasses.clear();
1281 ExpressionToClass.clear();
1282 ValueToExpression.clear();
1283 ReachableBlocks.clear();
1284 ReachableEdges.clear();
1285#ifndef NDEBUG
1286 ProcessedCount.clear();
1287#endif
1288 DFSDomMap.clear();
1289 InstrDFS.clear();
1290 InstructionsToErase.clear();
1291
1292 DFSToInstr.clear();
1293 BlockInstRange.clear();
1294 TouchedInstructions.clear();
1295 DominatedInstRange.clear();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001296 MemoryAccessEquiv.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001297}
1298
1299std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1300 unsigned Start) {
1301 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001302 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1303 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001304 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001305 }
1306
Davide Italiano7e274e02016-12-22 16:03:48 +00001307 for (auto &I : *B) {
1308 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001309 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001310 }
1311
1312 // All of the range functions taken half-open ranges (open on the end side).
1313 // So we do not subtract one from count, because at this point it is one
1314 // greater than the last instruction.
1315 return std::make_pair(Start, End);
1316}
1317
1318void NewGVN::updateProcessedCount(Value *V) {
1319#ifndef NDEBUG
1320 if (ProcessedCount.count(V) == 0) {
1321 ProcessedCount.insert({V, 1});
1322 } else {
1323 ProcessedCount[V] += 1;
1324 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001325 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001326 }
1327#endif
1328}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001329// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1330void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1331 // If all the arguments are the same, the MemoryPhi has the same value as the
1332 // argument.
1333 // Filter out unreachable blocks from our operands.
1334 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1335 return ReachableBlocks.count(MP->getIncomingBlock(U));
1336 });
1337
1338 assert(Filtered.begin() != Filtered.end() &&
1339 "We should not be processing a MemoryPhi in a completely "
1340 "unreachable block");
1341
1342 // Transform the remaining operands into operand leaders.
1343 // FIXME: mapped_iterator should have a range version.
1344 auto LookupFunc = [&](const Use &U) {
1345 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1346 };
1347 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1348 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1349
1350 // and now check if all the elements are equal.
1351 // Sadly, we can't use std::equals since these are random access iterators.
1352 MemoryAccess *AllSameValue = *MappedBegin;
1353 ++MappedBegin;
1354 bool AllEqual = std::all_of(
1355 MappedBegin, MappedEnd,
1356 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1357
1358 if (AllEqual)
1359 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1360 else
1361 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1362
1363 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr))
1364 markMemoryUsersTouched(MP);
1365}
1366
1367// Value number a single instruction, symbolically evaluating, performing
1368// congruence finding, and updating mappings.
1369void NewGVN::valueNumberInstruction(Instruction *I) {
1370 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001371 if (isInstructionTriviallyDead(I, TLI)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001372 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001373 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001374 return;
1375 }
1376 if (!I->isTerminator()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001377 const auto *Symbolized = performSymbolicEvaluation(I, I->getParent());
1378 // If we couldn't come up with a symbolic expression, use the unknown
1379 // expression
1380 if (Symbolized == nullptr)
1381 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001382 performCongruenceFinding(I, Symbolized);
1383 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001384 // Handle terminators that return values. All of them produce values we
1385 // don't currently understand.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001386 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001387 auto *Symbolized = createUnknownExpression(I);
1388 performCongruenceFinding(I, Symbolized);
1389 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001390 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1391 }
1392}
Davide Italiano7e274e02016-12-22 16:03:48 +00001393
Daniel Berlin589cecc2017-01-02 18:00:46 +00001394// Verify the that the memory equivalence table makes sense relative to the
1395// congruence classes.
1396void NewGVN::verifyMemoryCongruency() {
1397 // Anything equivalent in the memory access table should be in the same
1398 // congruence class.
1399
1400 // Filter out the unreachable and trivially dead entries, because they may
1401 // never have been updated if the instructions were not processed.
1402 auto ReachableAccessPred =
1403 [&](const std::pair<const MemoryAccess *, MemoryAccess *> Pair) {
1404 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1405 if (!Result)
1406 return false;
1407 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1408 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1409 return true;
1410 };
1411
1412 auto Filtered = make_filter_range(MemoryAccessEquiv, ReachableAccessPred);
1413 for (auto KV : Filtered) {
1414 assert(KV.first != KV.second &&
1415 "We added a useless equivalence to the memory equivalence table");
1416 // Unreachable instructions may not have changed because we never process
1417 // them.
1418 if (!ReachableBlocks.count(KV.first->getBlock()))
1419 continue;
1420 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
1421 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second);
Davide Italiano67ada752017-01-02 19:03:16 +00001422 if (FirstMUD && SecondMUD)
Daniel Berlin589cecc2017-01-02 18:00:46 +00001423 assert(
Davide Italiano67ada752017-01-02 19:03:16 +00001424 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1425 ValueToClass.lookup(SecondMUD->getMemoryInst()) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00001426 "The instructions for these memory operations should have been in "
1427 "the same congruence class");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001428 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1429
1430 // We can only sanely verify that MemoryDefs in the operand list all have
1431 // the same class.
1432 auto ReachableOperandPred = [&](const Use &U) {
1433 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1434 isa<MemoryDef>(U);
1435
1436 };
1437 // All arguments should in the same class, ignoring unreachable arguments
1438 auto FilteredPhiArgs =
1439 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1440 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1441 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1442 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1443 const MemoryDef *MD = cast<MemoryDef>(U);
1444 return ValueToClass.lookup(MD->getMemoryInst());
1445 });
1446 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1447 PhiOpClasses.begin()) &&
1448 "All MemoryPhi arguments should be in the same class");
1449 }
1450 }
1451}
1452
Daniel Berlin85f91b02016-12-26 20:06:58 +00001453// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001454bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001455 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1456 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001457 bool Changed = false;
1458 DT = _DT;
1459 AC = _AC;
1460 TLI = _TLI;
1461 AA = _AA;
1462 MSSA = _MSSA;
1463 DL = &F.getParent()->getDataLayout();
1464 MSSAWalker = MSSA->getWalker();
1465
1466 // Count number of instructions for sizing of hash tables, and come
1467 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001468 unsigned ICount = 1;
1469 // Add an empty instruction to account for the fact that we start at 1
1470 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001471 // Note: We want RPO traversal of the blocks, which is not quite the same as
1472 // dominator tree order, particularly with regard whether backedges get
1473 // visited first or second, given a block with multiple successors.
1474 // If we visit in the wrong order, we will end up performing N times as many
1475 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001476 // The dominator tree does guarantee that, for a given dom tree node, it's
1477 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1478 // the siblings.
1479 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001480 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001481 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001482 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001483 auto *Node = DT->getNode(B);
1484 assert(Node && "RPO and Dominator tree should have same reachability");
1485 RPOOrdering[Node] = ++Counter;
1486 }
1487 // Sort dominator tree children arrays into RPO.
1488 for (auto &B : RPOT) {
1489 auto *Node = DT->getNode(B);
1490 if (Node->getChildren().size() > 1)
1491 std::sort(Node->begin(), Node->end(),
1492 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1493 return RPOOrdering[A] < RPOOrdering[B];
1494 });
1495 }
1496
1497 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1498 auto DFI = df_begin(DT->getRootNode());
1499 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1500 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001501 const auto &BlockRange = assignDFSNumbers(B, ICount);
1502 BlockInstRange.insert({B, BlockRange});
1503 ICount += BlockRange.second - BlockRange.first;
1504 }
1505
1506 // Handle forward unreachable blocks and figure out which blocks
1507 // have single preds.
1508 for (auto &B : F) {
1509 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001510 if (!DFI.nodeVisited(DT->getNode(&B))) {
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
Daniel Berline0bd37e2016-12-29 22:15:12 +00001517 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001518 DominatedInstRange.reserve(F.size());
1519 // Ensure we don't end up resizing the expressionToClass map, as
1520 // that can be quite expensive. At most, we have one expression per
1521 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001522 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001523
1524 // Initialize the touched instructions to include the entry block.
1525 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1526 TouchedInstructions.set(InstRange.first, InstRange.second);
1527 ReachableBlocks.insert(&F.getEntryBlock());
1528
1529 initializeCongruenceClasses(F);
1530
1531 // We start out in the entry block.
1532 BasicBlock *LastBlock = &F.getEntryBlock();
1533 while (TouchedInstructions.any()) {
1534 // Walk through all the instructions in all the blocks in RPO.
1535 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1536 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Daniel Berline0bd37e2016-12-29 22:15:12 +00001537 assert(InstrNum != 0 && "Bit 0 should never be set, something touched an "
1538 "instruction not in the lookup table");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001539 Value *V = DFSToInstr[InstrNum];
1540 BasicBlock *CurrBlock = nullptr;
1541
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001542 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001543 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001544 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001545 CurrBlock = MP->getBlock();
1546 else
1547 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001548
1549 // If we hit a new block, do reachability processing.
1550 if (CurrBlock != LastBlock) {
1551 LastBlock = CurrBlock;
1552 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1553 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1554
1555 // If it's not reachable, erase any touched instructions and move on.
1556 if (!BlockReachable) {
1557 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1558 DEBUG(dbgs() << "Skipping instructions in block "
1559 << getBlockName(CurrBlock)
1560 << " because it is unreachable\n");
1561 continue;
1562 }
1563 updateProcessedCount(CurrBlock);
1564 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001565
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001566 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001567 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1568 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001569 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001570 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001571 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001572 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001573 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001574 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001575 // Reset after processing (because we may mark ourselves as touched when
1576 // we propagate equalities).
1577 TouchedInstructions.reset(InstrNum);
1578 }
1579 }
1580
Daniel Berlin589cecc2017-01-02 18:00:46 +00001581#ifndef NDEBUG
1582 verifyMemoryCongruency();
1583#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001584 Changed |= eliminateInstructions(F);
1585
1586 // Delete all instructions marked for deletion.
1587 for (Instruction *ToErase : InstructionsToErase) {
1588 if (!ToErase->use_empty())
1589 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1590
1591 ToErase->eraseFromParent();
1592 }
1593
1594 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001595 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1596 return !ReachableBlocks.count(&BB);
1597 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001598
1599 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1600 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001601 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001602 deleteInstructionsInBlock(&BB);
1603 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001604 }
1605
1606 cleanupTables();
1607 return Changed;
1608}
1609
1610bool NewGVN::runOnFunction(Function &F) {
1611 if (skipFunction(F))
1612 return false;
1613 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1614 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1615 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1616 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1617 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1618}
1619
Daniel Berlin85f91b02016-12-26 20:06:58 +00001620PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001621 NewGVN Impl;
1622
1623 // Apparently the order in which we get these results matter for
1624 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1625 // the same order here, just in case.
1626 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1627 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1628 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1629 auto &AA = AM.getResult<AAManager>(F);
1630 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1631 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1632 if (!Changed)
1633 return PreservedAnalyses::all();
1634 PreservedAnalyses PA;
1635 PA.preserve<DominatorTreeAnalysis>();
1636 PA.preserve<GlobalsAA>();
1637 return PA;
1638}
1639
1640// Return true if V is a value that will always be available (IE can
1641// be placed anywhere) in the function. We don't do globals here
1642// because they are often worse to put in place.
1643// TODO: Separate cost from availability
1644static bool alwaysAvailable(Value *V) {
1645 return isa<Constant>(V) || isa<Argument>(V);
1646}
1647
1648// Get the basic block from an instruction/value.
1649static BasicBlock *getBlockForValue(Value *V) {
1650 if (auto *I = dyn_cast<Instruction>(V))
1651 return I->getParent();
1652 return nullptr;
1653}
1654
1655struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001656 int DFSIn = 0;
1657 int DFSOut = 0;
1658 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001659 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001660 Value *Val = nullptr;
1661 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001662
1663 bool operator<(const ValueDFS &Other) const {
1664 // It's not enough that any given field be less than - we have sets
1665 // of fields that need to be evaluated together to give a proper ordering.
1666 // For example, if you have;
1667 // DFS (1, 3)
1668 // Val 0
1669 // DFS (1, 2)
1670 // Val 50
1671 // We want the second to be less than the first, but if we just go field
1672 // by field, we will get to Val 0 < Val 50 and say the first is less than
1673 // the second. We only want it to be less than if the DFS orders are equal.
1674 //
1675 // Each LLVM instruction only produces one value, and thus the lowest-level
1676 // differentiator that really matters for the stack (and what we use as as a
1677 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001678 // Everything else in the structure is instruction level, and only affects
1679 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001680 //
1681 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1682 // the order of replacement of uses does not matter.
1683 // IE given,
1684 // a = 5
1685 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001686 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1687 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001688 // The .val will be the same as well.
1689 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001690 // You will replace both, and it does not matter what order you replace them
1691 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1692 // operand 2).
1693 // Similarly for the case of same dfsin, dfsout, localnum, but different
1694 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001695 // a = 5
1696 // b = 6
1697 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001698 // in c, we will a valuedfs for a, and one for b,with everything the same
1699 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001700 // It does not matter what order we replace these operands in.
1701 // You will always end up with the same IR, and this is guaranteed.
1702 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1703 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1704 Other.U);
1705 }
1706};
1707
1708void NewGVN::convertDenseToDFSOrdered(CongruenceClass::MemberSet &Dense,
1709 std::vector<ValueDFS> &DFSOrderedSet) {
1710 for (auto D : Dense) {
1711 // First add the value.
1712 BasicBlock *BB = getBlockForValue(D);
1713 // Constants are handled prior to ever calling this function, so
1714 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001715 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001716 ValueDFS VD;
1717
1718 std::pair<int, int> DFSPair = DFSDomMap[BB];
1719 assert(DFSPair.first != -1 && DFSPair.second != -1 && "Invalid DFS Pair");
1720 VD.DFSIn = DFSPair.first;
1721 VD.DFSOut = DFSPair.second;
1722 VD.Val = D;
1723 // If it's an instruction, use the real local dfs number.
1724 if (auto *I = dyn_cast<Instruction>(D))
1725 VD.LocalNum = InstrDFS[I];
1726 else
1727 llvm_unreachable("Should have been an instruction");
1728
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001729 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001730
1731 // Now add the users.
1732 for (auto &U : D->uses()) {
1733 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1734 ValueDFS VD;
1735 // Put the phi node uses in the incoming block.
1736 BasicBlock *IBlock;
1737 if (auto *P = dyn_cast<PHINode>(I)) {
1738 IBlock = P->getIncomingBlock(U);
1739 // Make phi node users appear last in the incoming block
1740 // they are from.
1741 VD.LocalNum = InstrDFS.size() + 1;
1742 } else {
1743 IBlock = I->getParent();
1744 VD.LocalNum = InstrDFS[I];
1745 }
1746 std::pair<int, int> DFSPair = DFSDomMap[IBlock];
1747 VD.DFSIn = DFSPair.first;
1748 VD.DFSOut = DFSPair.second;
1749 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001750 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001751 }
1752 }
1753 }
1754}
1755
1756static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1757 // Patch the replacement so that it is not more restrictive than the value
1758 // being replaced.
1759 auto *Op = dyn_cast<BinaryOperator>(I);
1760 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
1761
1762 if (Op && ReplOp)
1763 ReplOp->andIRFlags(Op);
1764
1765 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
1766 // FIXME: If both the original and replacement value are part of the
1767 // same control-flow region (meaning that the execution of one
1768 // guarentees the executation of the other), then we can combine the
1769 // noalias scopes here and do better than the general conservative
1770 // answer used in combineMetadata().
1771
1772 // In general, GVN unifies expressions over different control-flow
1773 // regions, and so we need a conservative combination of the noalias
1774 // scopes.
1775 unsigned KnownIDs[] = {
1776 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1777 LLVMContext::MD_noalias, LLVMContext::MD_range,
1778 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1779 LLVMContext::MD_invariant_group};
1780 combineMetadata(ReplInst, I, KnownIDs);
1781 }
1782}
1783
1784static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1785 patchReplacementInstruction(I, Repl);
1786 I->replaceAllUsesWith(Repl);
1787}
1788
1789void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
1790 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1791 ++NumGVNBlocksDeleted;
1792
1793 // Check to see if there are non-terminating instructions to delete.
1794 if (isa<TerminatorInst>(BB->begin()))
1795 return;
1796
1797 // Delete the instructions backwards, as it has a reduced likelihood of having
1798 // to update as many def-use and use-def chains. Start after the terminator.
1799 auto StartPoint = BB->rbegin();
1800 ++StartPoint;
1801 // Note that we explicitly recalculate BB->rend() on each iteration,
1802 // as it may change when we remove the first instruction.
1803 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
1804 Instruction &Inst = *I++;
1805 if (!Inst.use_empty())
1806 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
1807 if (isa<LandingPadInst>(Inst))
1808 continue;
1809
1810 Inst.eraseFromParent();
1811 ++NumGVNInstrDeleted;
1812 }
1813}
1814
1815void NewGVN::markInstructionForDeletion(Instruction *I) {
1816 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
1817 InstructionsToErase.insert(I);
1818}
1819
1820void NewGVN::replaceInstruction(Instruction *I, Value *V) {
1821
1822 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
1823 patchAndReplaceAllUsesWith(I, V);
1824 // We save the actual erasing to avoid invalidating memory
1825 // dependencies until we are done with everything.
1826 markInstructionForDeletion(I);
1827}
1828
1829namespace {
1830
1831// This is a stack that contains both the value and dfs info of where
1832// that value is valid.
1833class ValueDFSStack {
1834public:
1835 Value *back() const { return ValueStack.back(); }
1836 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
1837
1838 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001839 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001840 DFSStack.emplace_back(DFSIn, DFSOut);
1841 }
1842 bool empty() const { return DFSStack.empty(); }
1843 bool isInScope(int DFSIn, int DFSOut) const {
1844 if (empty())
1845 return false;
1846 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
1847 }
1848
1849 void popUntilDFSScope(int DFSIn, int DFSOut) {
1850
1851 // These two should always be in sync at this point.
1852 assert(ValueStack.size() == DFSStack.size() &&
1853 "Mismatch between ValueStack and DFSStack");
1854 while (
1855 !DFSStack.empty() &&
1856 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
1857 DFSStack.pop_back();
1858 ValueStack.pop_back();
1859 }
1860 }
1861
1862private:
1863 SmallVector<Value *, 8> ValueStack;
1864 SmallVector<std::pair<int, int>, 8> DFSStack;
1865};
1866}
1867
1868bool NewGVN::eliminateInstructions(Function &F) {
1869 // This is a non-standard eliminator. The normal way to eliminate is
1870 // to walk the dominator tree in order, keeping track of available
1871 // values, and eliminating them. However, this is mildly
1872 // pointless. It requires doing lookups on every instruction,
1873 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001874 // instructions part of most singleton congruence classes, we know we
1875 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00001876
1877 // Instead, this eliminator looks at the congruence classes directly, sorts
1878 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001879 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001880 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001881 // last member. This is worst case O(E log E) where E = number of
1882 // instructions in a single congruence class. In theory, this is all
1883 // instructions. In practice, it is much faster, as most instructions are
1884 // either in singleton congruence classes or can't possibly be eliminated
1885 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00001886 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001887 // for elimination purposes.
1888 // TODO: If we wanted to be faster, We could remove any members with no
1889 // overlapping ranges while sorting, as we will never eliminate anything
1890 // with those members, as they don't dominate anything else in our set.
1891
Davide Italiano7e274e02016-12-22 16:03:48 +00001892 bool AnythingReplaced = false;
1893
1894 // Since we are going to walk the domtree anyway, and we can't guarantee the
1895 // DFS numbers are updated, we compute some ourselves.
1896 DT->updateDFSNumbers();
1897
1898 for (auto &B : F) {
1899 if (!ReachableBlocks.count(&B)) {
1900 for (const auto S : successors(&B)) {
1901 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001902 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00001903 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
1904 << getBlockName(&B)
1905 << " with undef due to it being unreachable\n");
1906 for (auto &Operand : Phi.incoming_values())
1907 if (Phi.getIncomingBlock(Operand) == &B)
1908 Operand.set(UndefValue::get(Phi.getType()));
1909 }
1910 }
1911 }
1912 DomTreeNode *Node = DT->getNode(&B);
1913 if (Node)
1914 DFSDomMap[&B] = {Node->getDFSNumIn(), Node->getDFSNumOut()};
1915 }
1916
1917 for (CongruenceClass *CC : CongruenceClasses) {
1918 // FIXME: We should eventually be able to replace everything still
1919 // in the initial class with undef, as they should be unreachable.
1920 // Right now, initial still contains some things we skip value
1921 // numbering of (UNREACHABLE's, for example).
1922 if (CC == InitialClass || CC->Dead)
1923 continue;
1924 assert(CC->RepLeader && "We should have had a leader");
1925
1926 // If this is a leader that is always available, and it's a
1927 // constant or has no equivalences, just replace everything with
1928 // it. We then update the congruence class with whatever members
1929 // are left.
1930 if (alwaysAvailable(CC->RepLeader)) {
1931 SmallPtrSet<Value *, 4> MembersLeft;
1932 for (auto M : CC->Members) {
1933
1934 Value *Member = M;
1935
1936 // Void things have no uses we can replace.
1937 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
1938 MembersLeft.insert(Member);
1939 continue;
1940 }
1941
1942 DEBUG(dbgs() << "Found replacement " << *(CC->RepLeader) << " for "
1943 << *Member << "\n");
1944 // Due to equality propagation, these may not always be
1945 // instructions, they may be real values. We don't really
1946 // care about trying to replace the non-instructions.
1947 if (auto *I = dyn_cast<Instruction>(Member)) {
1948 assert(CC->RepLeader != I &&
1949 "About to accidentally remove our leader");
1950 replaceInstruction(I, CC->RepLeader);
1951 AnythingReplaced = true;
1952
1953 continue;
1954 } else {
1955 MembersLeft.insert(I);
1956 }
1957 }
1958 CC->Members.swap(MembersLeft);
1959
1960 } else {
1961 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
1962 // If this is a singleton, we can skip it.
1963 if (CC->Members.size() != 1) {
1964
1965 // This is a stack because equality replacement/etc may place
1966 // constants in the middle of the member list, and we want to use
1967 // those constant values in preference to the current leader, over
1968 // the scope of those constants.
1969 ValueDFSStack EliminationStack;
1970
1971 // Convert the members to DFS ordered sets and then merge them.
1972 std::vector<ValueDFS> DFSOrderedSet;
1973 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
1974
1975 // Sort the whole thing.
1976 sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
1977
1978 for (auto &C : DFSOrderedSet) {
1979 int MemberDFSIn = C.DFSIn;
1980 int MemberDFSOut = C.DFSOut;
1981 Value *Member = C.Val;
1982 Use *MemberUse = C.U;
1983
1984 // We ignore void things because we can't get a value from them.
1985 if (Member && Member->getType()->isVoidTy())
1986 continue;
1987
1988 if (EliminationStack.empty()) {
1989 DEBUG(dbgs() << "Elimination Stack is empty\n");
1990 } else {
1991 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
1992 << EliminationStack.dfs_back().first << ","
1993 << EliminationStack.dfs_back().second << ")\n");
1994 }
1995 if (Member && isa<Constant>(Member))
1996 assert(isa<Constant>(CC->RepLeader));
1997
1998 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
1999 << MemberDFSOut << ")\n");
2000 // First, we see if we are out of scope or empty. If so,
2001 // and there equivalences, we try to replace the top of
2002 // stack with equivalences (if it's on the stack, it must
2003 // not have been eliminated yet).
2004 // Then we synchronize to our current scope, by
2005 // popping until we are back within a DFS scope that
2006 // dominates the current member.
2007 // Then, what happens depends on a few factors
2008 // If the stack is now empty, we need to push
2009 // If we have a constant or a local equivalence we want to
2010 // start using, we also push.
2011 // Otherwise, we walk along, processing members who are
2012 // dominated by this scope, and eliminate them.
2013 bool ShouldPush =
2014 Member && (EliminationStack.empty() || isa<Constant>(Member));
2015 bool OutOfScope =
2016 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2017
2018 if (OutOfScope || ShouldPush) {
2019 // Sync to our current scope.
2020 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2021 ShouldPush |= Member && EliminationStack.empty();
2022 if (ShouldPush) {
2023 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2024 }
2025 }
2026
2027 // If we get to this point, and the stack is empty we must have a use
2028 // with nothing we can use to eliminate it, just skip it.
2029 if (EliminationStack.empty())
2030 continue;
2031
2032 // Skip the Value's, we only want to eliminate on their uses.
2033 if (Member)
2034 continue;
2035 Value *Result = EliminationStack.back();
2036
Daniel Berline0bd37e2016-12-29 22:15:12 +00002037 // Don't replace our existing users with ourselves, and don't replace
2038 // phi node arguments with the result of the same phi node.
2039 // IE tmp = phi(tmp11, undef); tmp11 = foo -> tmp = phi(tmp, undef)
2040 if (MemberUse->get() == Result ||
2041 (isa<PHINode>(Result) && MemberUse->getUser() == Result))
Davide Italiano7e274e02016-12-22 16:03:48 +00002042 continue;
2043
2044 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2045 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2046 << "\n");
2047
2048 // If we replaced something in an instruction, handle the patching of
2049 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002050 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002051 patchReplacementInstruction(ReplacedInst, Result);
2052
2053 assert(isa<Instruction>(MemberUse->getUser()));
2054 MemberUse->set(Result);
2055 AnythingReplaced = true;
2056 }
2057 }
2058 }
2059
2060 // Cleanup the congruence class.
2061 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002062 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002063 if (Member->getType()->isVoidTy()) {
2064 MembersLeft.insert(Member);
2065 continue;
2066 }
2067
2068 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2069 if (isInstructionTriviallyDead(MemberInst)) {
2070 // TODO: Don't mark loads of undefs.
2071 markInstructionForDeletion(MemberInst);
2072 continue;
2073 }
2074 }
2075 MembersLeft.insert(Member);
2076 }
2077 CC->Members.swap(MembersLeft);
2078 }
2079
2080 return AnythingReplaced;
2081}