blob: 0f782333a1a79e5fdf779f5b147e19f73a392f36 [file] [log] [blame]
Davide Italiano7e274e02016-12-22 16:03:48 +00001//===---- NewGVN.cpp - Global Value Numbering Pass --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file implements the new LLVM's Global Value Numbering pass.
11/// GVN partitions values computed by a function into congruence classes.
12/// Values ending up in the same congruence class are guaranteed to be the same
13/// for every execution of the program. In that respect, congruency is a
14/// compile-time approximation of equivalence of values at runtime.
15/// The algorithm implemented here uses a sparse formulation and it's based
16/// on the ideas described in the paper:
17/// "A Sparse Algorithm for Predicated Global Value Numbering" from
18/// Karthik Gargi.
19///
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar/NewGVN.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/DepthFirstIterator.h"
27#include "llvm/ADT/Hashing.h"
28#include "llvm/ADT/MapVector.h"
29#include "llvm/ADT/PostOrderIterator.h"
Daniel Berlind7c12ee2016-12-25 22:23:49 +000030#include "llvm/ADT/STLExtras.h"
Davide Italiano7e274e02016-12-22 16:03:48 +000031#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/SparseBitVector.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/TinyPtrVector.h"
36#include "llvm/Analysis/AliasAnalysis.h"
37#include "llvm/Analysis/AssumptionCache.h"
38#include "llvm/Analysis/CFG.h"
39#include "llvm/Analysis/CFGPrinter.h"
40#include "llvm/Analysis/ConstantFolding.h"
41#include "llvm/Analysis/GlobalsModRef.h"
42#include "llvm/Analysis/InstructionSimplify.h"
43#include "llvm/Analysis/Loads.h"
44#include "llvm/Analysis/MemoryBuiltins.h"
45#include "llvm/Analysis/MemoryDependenceAnalysis.h"
46#include "llvm/Analysis/MemoryLocation.h"
47#include "llvm/Analysis/PHITransAddr.h"
48#include "llvm/Analysis/TargetLibraryInfo.h"
49#include "llvm/Analysis/ValueTracking.h"
50#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/GlobalVariable.h"
53#include "llvm/IR/IRBuilder.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
57#include "llvm/IR/PatternMatch.h"
58#include "llvm/IR/PredIteratorCache.h"
59#include "llvm/IR/Type.h"
60#include "llvm/Support/Allocator.h"
61#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/Debug.h"
63#include "llvm/Transforms/Scalar.h"
64#include "llvm/Transforms/Scalar/GVNExpression.h"
65#include "llvm/Transforms/Utils/BasicBlockUtils.h"
66#include "llvm/Transforms/Utils/Local.h"
67#include "llvm/Transforms/Utils/MemorySSA.h"
68#include "llvm/Transforms/Utils/SSAUpdater.h"
69#include <unordered_map>
70#include <utility>
71#include <vector>
72using namespace llvm;
73using namespace PatternMatch;
74using namespace llvm::GVNExpression;
75
76#define DEBUG_TYPE "newgvn"
77
78STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
79STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
80STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
81STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
Daniel Berlin04443432017-01-07 03:23:47 +000082STATISTIC(NumGVNMaxIterations,
83 "Maximum Number of iterations it took to converge GVN");
Davide Italiano7e274e02016-12-22 16:03:48 +000084
85//===----------------------------------------------------------------------===//
86// GVN Pass
87//===----------------------------------------------------------------------===//
88
89// Anchor methods.
90namespace llvm {
91namespace GVNExpression {
Daniel Berlin85f91b02016-12-26 20:06:58 +000092Expression::~Expression() = default;
93BasicExpression::~BasicExpression() = default;
94CallExpression::~CallExpression() = default;
95LoadExpression::~LoadExpression() = default;
96StoreExpression::~StoreExpression() = default;
97AggregateValueExpression::~AggregateValueExpression() = default;
98PHIExpression::~PHIExpression() = default;
Davide Italiano7e274e02016-12-22 16:03:48 +000099}
100}
101
102// Congruence classes represent the set of expressions/instructions
103// that are all the same *during some scope in the function*.
104// That is, because of the way we perform equality propagation, and
105// because of memory value numbering, it is not correct to assume
106// you can willy-nilly replace any member with any other at any
107// point in the function.
108//
109// For any Value in the Member set, it is valid to replace any dominated member
110// with that Value.
111//
112// Every congruence class has a leader, and the leader is used to
113// symbolize instructions in a canonical way (IE every operand of an
114// instruction that is a member of the same congruence class will
115// always be replaced with leader during symbolization).
116// To simplify symbolization, we keep the leader as a constant if class can be
117// proved to be a constant value.
118// Otherwise, the leader is a randomly chosen member of the value set, it does
119// not matter which one is chosen.
120// Each congruence class also has a defining expression,
121// though the expression may be null. If it exists, it can be used for forward
122// propagation and reassociation of values.
123//
124struct CongruenceClass {
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000125 using MemberSet = SmallPtrSet<Value *, 4>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000126 unsigned ID;
127 // Representative leader.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000128 Value *RepLeader = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000129 // Defining Expression.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000130 const Expression *DefiningExpr = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000131 // Actual members of this class.
132 MemberSet Members;
133
134 // True if this class has no members left. This is mainly used for assertion
135 // purposes, and for skipping empty classes.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000136 bool Dead = false;
Davide Italiano7e274e02016-12-22 16:03:48 +0000137
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000138 explicit CongruenceClass(unsigned ID) : ID(ID) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000139 CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000140 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
Davide Italiano7e274e02016-12-22 16:03:48 +0000141};
142
143namespace llvm {
Daniel Berlin85f91b02016-12-26 20:06:58 +0000144template <> struct DenseMapInfo<const Expression *> {
145 static const Expression *getEmptyKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000146 auto Val = static_cast<uintptr_t>(-1);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000147 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
148 return reinterpret_cast<const Expression *>(Val);
149 }
150 static const Expression *getTombstoneKey() {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000151 auto Val = static_cast<uintptr_t>(~1U);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000152 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
153 return reinterpret_cast<const Expression *>(Val);
154 }
155 static unsigned getHashValue(const Expression *V) {
156 return static_cast<unsigned>(V->getHashValue());
157 }
158 static bool isEqual(const Expression *LHS, const Expression *RHS) {
159 if (LHS == RHS)
160 return true;
161 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
162 LHS == getEmptyKey() || RHS == getEmptyKey())
163 return false;
164 return *LHS == *RHS;
165 }
166};
Davide Italiano7e274e02016-12-22 16:03:48 +0000167} // end namespace llvm
168
169class NewGVN : public FunctionPass {
170 DominatorTree *DT;
171 const DataLayout *DL;
172 const TargetLibraryInfo *TLI;
173 AssumptionCache *AC;
174 AliasAnalysis *AA;
175 MemorySSA *MSSA;
176 MemorySSAWalker *MSSAWalker;
177 BumpPtrAllocator ExpressionAllocator;
178 ArrayRecycler<Value *> ArgRecycler;
179
180 // Congruence class info.
181 CongruenceClass *InitialClass;
182 std::vector<CongruenceClass *> CongruenceClasses;
183 unsigned NextCongruenceNum;
184
185 // Value Mappings.
186 DenseMap<Value *, CongruenceClass *> ValueToClass;
187 DenseMap<Value *, const Expression *> ValueToExpression;
188
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000189 // A table storing which memorydefs/phis represent a memory state provably
190 // equivalent to another memory state.
191 // We could use the congruence class machinery, but the MemoryAccess's are
192 // abstract memory states, so they can only ever be equivalent to each other,
193 // and not to constants, etc.
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000194 DenseMap<const MemoryAccess *, MemoryAccess *> MemoryAccessEquiv;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000195
Davide Italiano7e274e02016-12-22 16:03:48 +0000196 // Expression to class mapping.
Piotr Padlewskie4047b82016-12-28 19:29:26 +0000197 using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
Davide Italiano7e274e02016-12-22 16:03:48 +0000198 ExpressionClassMap ExpressionToClass;
199
200 // Which values have changed as a result of leader changes.
201 SmallPtrSet<Value *, 8> ChangedValues;
202
203 // Reachability info.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000204 using BlockEdge = BasicBlockEdge;
Davide Italiano7e274e02016-12-22 16:03:48 +0000205 DenseSet<BlockEdge> ReachableEdges;
206 SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
207
208 // This is a bitvector because, on larger functions, we may have
209 // thousands of touched instructions at once (entire blocks,
210 // instructions with hundreds of uses, etc). Even with optimization
211 // for when we mark whole blocks as touched, when this was a
212 // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
213 // the time in GVN just managing this list. The bitvector, on the
214 // other hand, efficiently supports test/set/clear of both
215 // individual and ranges, as well as "find next element" This
216 // enables us to use it as a worklist with essentially 0 cost.
217 BitVector TouchedInstructions;
218
219 DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
220 DenseMap<const DomTreeNode *, std::pair<unsigned, unsigned>>
221 DominatedInstRange;
222
223#ifndef NDEBUG
224 // Debugging for how many times each block and instruction got processed.
225 DenseMap<const Value *, unsigned> ProcessedCount;
226#endif
227
228 // DFS info.
229 DenseMap<const BasicBlock *, std::pair<int, int>> DFSDomMap;
230 DenseMap<const Value *, unsigned> InstrDFS;
Daniel Berlin1f31fe522016-12-27 09:20:36 +0000231 SmallVector<Value *, 32> DFSToInstr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000232
233 // Deletion info.
234 SmallPtrSet<Instruction *, 8> InstructionsToErase;
235
236public:
237 static char ID; // Pass identification, replacement for typeid.
238 NewGVN() : FunctionPass(ID) {
239 initializeNewGVNPass(*PassRegistry::getPassRegistry());
240 }
241
242 bool runOnFunction(Function &F) override;
243 bool runGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +0000244 TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000245
246private:
247 // This transformation requires dominator postdominator info.
248 void getAnalysisUsage(AnalysisUsage &AU) const override {
249 AU.addRequired<AssumptionCacheTracker>();
250 AU.addRequired<DominatorTreeWrapperPass>();
251 AU.addRequired<TargetLibraryInfoWrapperPass>();
252 AU.addRequired<MemorySSAWrapperPass>();
253 AU.addRequired<AAResultsWrapperPass>();
254
255 AU.addPreserved<DominatorTreeWrapperPass>();
256 AU.addPreserved<GlobalsAAWrapperPass>();
257 }
258
259 // Expression handling.
260 const Expression *createExpression(Instruction *, const BasicBlock *);
261 const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *,
262 const BasicBlock *);
263 PHIExpression *createPHIExpression(Instruction *);
264 const VariableExpression *createVariableExpression(Value *);
265 const ConstantExpression *createConstantExpression(Constant *);
266 const Expression *createVariableOrConstant(Value *V, const BasicBlock *B);
Daniel Berlin02c6b172017-01-02 18:00:53 +0000267 const UnknownExpression *createUnknownExpression(Instruction *);
Davide Italiano7e274e02016-12-22 16:03:48 +0000268 const StoreExpression *createStoreExpression(StoreInst *, MemoryAccess *,
269 const BasicBlock *);
270 LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
271 MemoryAccess *, const BasicBlock *);
272
273 const CallExpression *createCallExpression(CallInst *, MemoryAccess *,
274 const BasicBlock *);
275 const AggregateValueExpression *
276 createAggregateValueExpression(Instruction *, const BasicBlock *);
277 bool setBasicExpressionInfo(Instruction *, BasicExpression *,
278 const BasicBlock *);
279
280 // Congruence class handling.
281 CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000282 auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000283 CongruenceClasses.emplace_back(result);
Davide Italiano7e274e02016-12-22 16:03:48 +0000284 return result;
285 }
286
287 CongruenceClass *createSingletonCongruenceClass(Value *Member) {
Davide Italiano0e714802016-12-28 14:00:11 +0000288 CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000289 CClass->Members.insert(Member);
290 ValueToClass[Member] = CClass;
291 return CClass;
292 }
293 void initializeCongruenceClasses(Function &F);
294
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000295 // Value number an Instruction or MemoryPhi.
296 void valueNumberMemoryPhi(MemoryPhi *);
297 void valueNumberInstruction(Instruction *);
298
Davide Italiano7e274e02016-12-22 16:03:48 +0000299 // Symbolic evaluation.
300 const Expression *checkSimplificationResults(Expression *, Instruction *,
301 Value *);
302 const Expression *performSymbolicEvaluation(Value *, const BasicBlock *);
303 const Expression *performSymbolicLoadEvaluation(Instruction *,
304 const BasicBlock *);
305 const Expression *performSymbolicStoreEvaluation(Instruction *,
306 const BasicBlock *);
307 const Expression *performSymbolicCallEvaluation(Instruction *,
308 const BasicBlock *);
309 const Expression *performSymbolicPHIEvaluation(Instruction *,
310 const BasicBlock *);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000311 bool setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To);
Davide Italiano7e274e02016-12-22 16:03:48 +0000312 const Expression *performSymbolicAggrValueEvaluation(Instruction *,
313 const BasicBlock *);
314
315 // Congruence finding.
316 // Templated to allow them to work both on BB's and BB-edges.
317 template <class T>
318 Value *lookupOperandLeader(Value *, const User *, const T &) const;
319 void performCongruenceFinding(Value *, const Expression *);
320
321 // Reachability handling.
322 void updateReachableEdge(BasicBlock *, BasicBlock *);
323 void processOutgoingEdges(TerminatorInst *, BasicBlock *);
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000324 bool isOnlyReachableViaThisEdge(const BasicBlockEdge &) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000325 Value *findConditionEquivalence(Value *, BasicBlock *) const;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000326 MemoryAccess *lookupMemoryAccessEquiv(MemoryAccess *) const;
Davide Italiano7e274e02016-12-22 16:03:48 +0000327
328 // Elimination.
329 struct ValueDFS;
330 void convertDenseToDFSOrdered(CongruenceClass::MemberSet &,
331 std::vector<ValueDFS> &);
332
333 bool eliminateInstructions(Function &);
334 void replaceInstruction(Instruction *, Value *);
335 void markInstructionForDeletion(Instruction *);
336 void deleteInstructionsInBlock(BasicBlock *);
337
338 // New instruction creation.
339 void handleNewInstruction(Instruction *){};
340 void markUsersTouched(Value *);
341 void markMemoryUsersTouched(MemoryAccess *);
342
343 // Utilities.
344 void cleanupTables();
345 std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
346 void updateProcessedCount(Value *V);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000347 void verifyMemoryCongruency();
Davide Italiano7e274e02016-12-22 16:03:48 +0000348};
349
350char NewGVN::ID = 0;
351
352// createGVNPass - The public interface to this file.
353FunctionPass *llvm::createNewGVNPass() { return new NewGVN(); }
354
Davide Italianob1114092016-12-28 13:37:17 +0000355template <typename T>
356static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
357 if ((!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS)) ||
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000358 !LHS.BasicExpression::equals(RHS)) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000359 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000360 } else if (const auto *L = dyn_cast<LoadExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000361 if (LHS.getDefiningAccess() != L->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000362 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000363 } else if (const auto *S = dyn_cast<StoreExpression>(&RHS)) {
Davide Italianob1114092016-12-28 13:37:17 +0000364 if (LHS.getDefiningAccess() != S->getDefiningAccess())
Davide Italiano7e274e02016-12-22 16:03:48 +0000365 return false;
Daniel Berlin7ad1ea02016-12-29 00:49:32 +0000366 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000367 return true;
368}
369
Davide Italianob1114092016-12-28 13:37:17 +0000370bool LoadExpression::equals(const Expression &Other) const {
371 return equalsLoadStoreHelper(*this, Other);
372}
Davide Italiano7e274e02016-12-22 16:03:48 +0000373
Davide Italianob1114092016-12-28 13:37:17 +0000374bool StoreExpression::equals(const Expression &Other) const {
375 return equalsLoadStoreHelper(*this, Other);
Davide Italiano7e274e02016-12-22 16:03:48 +0000376}
377
378#ifndef NDEBUG
379static std::string getBlockName(const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000380 return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +0000381}
382#endif
383
384INITIALIZE_PASS_BEGIN(NewGVN, "newgvn", "Global Value Numbering", false, false)
385INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
386INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
387INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
388INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
389INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
390INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
391INITIALIZE_PASS_END(NewGVN, "newgvn", "Global Value Numbering", false, false)
392
393PHIExpression *NewGVN::createPHIExpression(Instruction *I) {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000394 BasicBlock *PHIBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000395 auto *PN = cast<PHINode>(I);
Daniel Berlind92e7f92017-01-07 00:01:42 +0000396 auto *E =
397 new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +0000398
399 E->allocateOperands(ArgRecycler, ExpressionAllocator);
400 E->setType(I->getType());
401 E->setOpcode(I->getOpcode());
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000402
403 auto ReachablePhiArg = [&](const Use &U) {
404 return ReachableBlocks.count(PN->getIncomingBlock(U));
405 };
406
407 // Filter out unreachable operands
408 auto Filtered = make_filter_range(PN->operands(), ReachablePhiArg);
409
410 std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
411 [&](const Use &U) -> Value * {
Daniel Berlind92e7f92017-01-07 00:01:42 +0000412 // Don't try to transform self-defined phis.
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000413 if (U == PN)
414 return PN;
Daniel Berlind92e7f92017-01-07 00:01:42 +0000415 const BasicBlockEdge BBE(PN->getIncomingBlock(U), PHIBlock);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000416 return lookupOperandLeader(U, I, BBE);
417 });
Davide Italiano7e274e02016-12-22 16:03:48 +0000418 return E;
419}
420
421// Set basic expression info (Arguments, type, opcode) for Expression
422// E from Instruction I in block B.
423bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E,
424 const BasicBlock *B) {
425 bool AllConstant = true;
426 if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
427 E->setType(GEP->getSourceElementType());
428 else
429 E->setType(I->getType());
430 E->setOpcode(I->getOpcode());
431 E->allocateOperands(ArgRecycler, ExpressionAllocator);
432
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000433 // Transform the operand array into an operand leader array, and keep track of
434 // whether all members are constant.
435 std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000436 auto Operand = lookupOperandLeader(O, I, B);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000437 AllConstant &= isa<Constant>(Operand);
438 return Operand;
439 });
440
Davide Italiano7e274e02016-12-22 16:03:48 +0000441 return AllConstant;
442}
443
444const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
445 Value *Arg1, Value *Arg2,
446 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000447 auto *E = new (ExpressionAllocator) BasicExpression(2);
Davide Italiano7e274e02016-12-22 16:03:48 +0000448
449 E->setType(T);
450 E->setOpcode(Opcode);
451 E->allocateOperands(ArgRecycler, ExpressionAllocator);
452 if (Instruction::isCommutative(Opcode)) {
453 // Ensure that commutative instructions that only differ by a permutation
454 // of their operands get the same value number by sorting the operand value
455 // numbers. Since all commutative instructions have two operands it is more
456 // efficient to sort by hand rather than using, say, std::sort.
457 if (Arg1 > Arg2)
458 std::swap(Arg1, Arg2);
459 }
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000460 E->op_push_back(lookupOperandLeader(Arg1, nullptr, B));
461 E->op_push_back(lookupOperandLeader(Arg2, nullptr, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000462
463 Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), *DL, TLI,
464 DT, AC);
465 if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
466 return SimplifiedE;
467 return E;
468}
469
470// Take a Value returned by simplification of Expression E/Instruction
471// I, and see if it resulted in a simpler expression. If so, return
472// that expression.
473// TODO: Once finished, this should not take an Instruction, we only
474// use it for printing.
475const Expression *NewGVN::checkSimplificationResults(Expression *E,
476 Instruction *I, Value *V) {
477 if (!V)
478 return nullptr;
479 if (auto *C = dyn_cast<Constant>(V)) {
480 if (I)
481 DEBUG(dbgs() << "Simplified " << *I << " to "
482 << " constant " << *C << "\n");
483 NumGVNOpsSimplified++;
484 assert(isa<BasicExpression>(E) &&
485 "We should always have had a basic expression here");
486
487 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
488 ExpressionAllocator.Deallocate(E);
489 return createConstantExpression(C);
490 } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
491 if (I)
492 DEBUG(dbgs() << "Simplified " << *I << " to "
493 << " variable " << *V << "\n");
494 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
495 ExpressionAllocator.Deallocate(E);
496 return createVariableExpression(V);
497 }
498
499 CongruenceClass *CC = ValueToClass.lookup(V);
500 if (CC && CC->DefiningExpr) {
501 if (I)
502 DEBUG(dbgs() << "Simplified " << *I << " to "
503 << " expression " << *V << "\n");
504 NumGVNOpsSimplified++;
505 assert(isa<BasicExpression>(E) &&
506 "We should always have had a basic expression here");
507 cast<BasicExpression>(E)->deallocateOperands(ArgRecycler);
508 ExpressionAllocator.Deallocate(E);
509 return CC->DefiningExpr;
510 }
511 return nullptr;
512}
513
514const Expression *NewGVN::createExpression(Instruction *I,
515 const BasicBlock *B) {
516
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000517 auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
Davide Italiano7e274e02016-12-22 16:03:48 +0000518
519 bool AllConstant = setBasicExpressionInfo(I, E, B);
520
521 if (I->isCommutative()) {
522 // Ensure that commutative instructions that only differ by a permutation
523 // of their operands get the same value number by sorting the operand value
524 // numbers. Since all commutative instructions have two operands it is more
525 // efficient to sort by hand rather than using, say, std::sort.
526 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
527 if (E->getOperand(0) > E->getOperand(1))
528 E->swapOperands(0, 1);
529 }
530
531 // Perform simplificaiton
532 // TODO: Right now we only check to see if we get a constant result.
533 // We may get a less than constant, but still better, result for
534 // some operations.
535 // IE
536 // add 0, x -> x
537 // and x, x -> x
538 // We should handle this by simply rewriting the expression.
539 if (auto *CI = dyn_cast<CmpInst>(I)) {
540 // Sort the operand value numbers so x<y and y>x get the same value
541 // number.
542 CmpInst::Predicate Predicate = CI->getPredicate();
543 if (E->getOperand(0) > E->getOperand(1)) {
544 E->swapOperands(0, 1);
545 Predicate = CmpInst::getSwappedPredicate(Predicate);
546 }
547 E->setOpcode((CI->getOpcode() << 8) | Predicate);
548 // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
549 // TODO: Since we noop bitcasts, we may need to check types before
550 // simplifying, so that we don't end up simplifying based on a wrong
551 // type assumption. We should clean this up so we can use constants of the
552 // wrong type
553
554 assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
555 "Wrong types on cmp instruction");
556 if ((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
557 E->getOperand(1)->getType() == I->getOperand(1)->getType())) {
558 Value *V = SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1),
559 *DL, TLI, DT, AC);
560 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
561 return SimplifiedE;
562 }
563 } else if (isa<SelectInst>(I)) {
564 if (isa<Constant>(E->getOperand(0)) ||
565 (E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
566 E->getOperand(2)->getType() == I->getOperand(2)->getType())) {
567 Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
568 E->getOperand(2), *DL, TLI, DT, AC);
569 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
570 return SimplifiedE;
571 }
572 } else if (I->isBinaryOp()) {
573 Value *V = SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1),
574 *DL, TLI, DT, AC);
575 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
576 return SimplifiedE;
577 } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
578 Value *V = SimplifyInstruction(BI, *DL, TLI, DT, AC);
579 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
580 return SimplifiedE;
581 } else if (isa<GetElementPtrInst>(I)) {
582 Value *V = SimplifyGEPInst(E->getType(),
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000583 ArrayRef<Value *>(E->op_begin(), E->op_end()),
Davide Italiano7e274e02016-12-22 16:03:48 +0000584 *DL, TLI, DT, AC);
585 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
586 return SimplifiedE;
587 } else if (AllConstant) {
588 // We don't bother trying to simplify unless all of the operands
589 // were constant.
590 // TODO: There are a lot of Simplify*'s we could call here, if we
591 // wanted to. The original motivating case for this code was a
592 // zext i1 false to i8, which we don't have an interface to
593 // simplify (IE there is no SimplifyZExt).
594
595 SmallVector<Constant *, 8> C;
596 for (Value *Arg : E->operands())
Piotr Padlewski6c37d292016-12-28 23:24:02 +0000597 C.emplace_back(cast<Constant>(Arg));
Davide Italiano7e274e02016-12-22 16:03:48 +0000598
599 if (Value *V = ConstantFoldInstOperands(I, C, *DL, TLI))
600 if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
601 return SimplifiedE;
602 }
603 return E;
604}
605
606const AggregateValueExpression *
607NewGVN::createAggregateValueExpression(Instruction *I, const BasicBlock *B) {
608 if (auto *II = dyn_cast<InsertValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000609 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000610 AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
611 setBasicExpressionInfo(I, E, B);
612 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000613 std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000614 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000615 } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000616 auto *E = new (ExpressionAllocator)
Davide Italiano7e274e02016-12-22 16:03:48 +0000617 AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
618 setBasicExpressionInfo(EI, E, B);
619 E->allocateIntOperands(ExpressionAllocator);
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000620 std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
Davide Italiano7e274e02016-12-22 16:03:48 +0000621 return E;
622 }
623 llvm_unreachable("Unhandled type of aggregate value operation");
624}
625
Daniel Berlin85f91b02016-12-26 20:06:58 +0000626const VariableExpression *NewGVN::createVariableExpression(Value *V) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000627 auto *E = new (ExpressionAllocator) VariableExpression(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000628 E->setOpcode(V->getValueID());
629 return E;
630}
631
632const Expression *NewGVN::createVariableOrConstant(Value *V,
633 const BasicBlock *B) {
634 auto Leader = lookupOperandLeader(V, nullptr, B);
635 if (auto *C = dyn_cast<Constant>(Leader))
636 return createConstantExpression(C);
637 return createVariableExpression(Leader);
638}
639
Daniel Berlin85f91b02016-12-26 20:06:58 +0000640const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000641 auto *E = new (ExpressionAllocator) ConstantExpression(C);
Davide Italiano7e274e02016-12-22 16:03:48 +0000642 E->setOpcode(C->getValueID());
643 return E;
644}
645
Daniel Berlin02c6b172017-01-02 18:00:53 +0000646const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
647 auto *E = new (ExpressionAllocator) UnknownExpression(I);
648 E->setOpcode(I->getOpcode());
649 return E;
650}
651
Davide Italiano7e274e02016-12-22 16:03:48 +0000652const CallExpression *NewGVN::createCallExpression(CallInst *CI,
653 MemoryAccess *HV,
654 const BasicBlock *B) {
655 // FIXME: Add operand bundles for calls.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000656 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000657 new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, HV);
658 setBasicExpressionInfo(CI, E, B);
659 return E;
660}
661
662// See if we have a congruence class and leader for this operand, and if so,
663// return it. Otherwise, return the operand itself.
664template <class T>
Daniel Berlin85f91b02016-12-26 20:06:58 +0000665Value *NewGVN::lookupOperandLeader(Value *V, const User *U, const T &B) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000666 CongruenceClass *CC = ValueToClass.lookup(V);
667 if (CC && (CC != InitialClass))
668 return CC->RepLeader;
669 return V;
670}
671
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000672MemoryAccess *NewGVN::lookupMemoryAccessEquiv(MemoryAccess *MA) const {
673 MemoryAccess *Result = MemoryAccessEquiv.lookup(MA);
674 return Result ? Result : MA;
675}
676
Davide Italiano7e274e02016-12-22 16:03:48 +0000677LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
678 LoadInst *LI, MemoryAccess *DA,
679 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000680 auto *E = new (ExpressionAllocator) LoadExpression(1, LI, DA);
Davide Italiano7e274e02016-12-22 16:03:48 +0000681 E->allocateOperands(ArgRecycler, ExpressionAllocator);
682 E->setType(LoadType);
683
684 // Give store and loads same opcode so they value number together.
685 E->setOpcode(0);
Davide Italianoa312ca82016-12-26 16:19:34 +0000686 E->op_push_back(lookupOperandLeader(PointerOp, LI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000687 if (LI)
688 E->setAlignment(LI->getAlignment());
689
690 // TODO: Value number heap versions. We may be able to discover
691 // things alias analysis can't on it's own (IE that a store and a
692 // load have the same value, and thus, it isn't clobbering the load).
693 return E;
694}
695
696const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
697 MemoryAccess *DA,
698 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000699 auto *E =
Davide Italiano7e274e02016-12-22 16:03:48 +0000700 new (ExpressionAllocator) StoreExpression(SI->getNumOperands(), SI, DA);
701 E->allocateOperands(ArgRecycler, ExpressionAllocator);
702 E->setType(SI->getValueOperand()->getType());
703
704 // Give store and loads same opcode so they value number together.
705 E->setOpcode(0);
Daniel Berlin65f5f0d2016-12-25 22:10:37 +0000706 E->op_push_back(lookupOperandLeader(SI->getPointerOperand(), SI, B));
Davide Italiano7e274e02016-12-22 16:03:48 +0000707
708 // TODO: Value number heap versions. We may be able to discover
709 // things alias analysis can't on it's own (IE that a store and a
710 // load have the same value, and thus, it isn't clobbering the load).
711 return E;
712}
713
714const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I,
715 const BasicBlock *B) {
Daniel Berlin589cecc2017-01-02 18:00:46 +0000716 // Unlike loads, we never try to eliminate stores, so we do not check if they
717 // are simple and avoid value numbering them.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000718 auto *SI = cast<StoreInst>(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000719 MemoryAccess *StoreAccess = MSSA->getMemoryAccess(SI);
Daniel Berlinde43ef92017-01-02 19:49:17 +0000720 // See if we are defined by a previous store expression, it already has a
721 // value, and it's the same value as our current store. FIXME: Right now, we
722 // only do this for simple stores, we should expand to cover memcpys, etc.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000723 if (SI->isSimple()) {
Daniel Berlinde43ef92017-01-02 19:49:17 +0000724 // Get the expression, if any, for the RHS of the MemoryDef.
725 MemoryAccess *StoreRHS = lookupMemoryAccessEquiv(
726 cast<MemoryDef>(StoreAccess)->getDefiningAccess());
727 const Expression *OldStore = createStoreExpression(SI, StoreRHS, B);
Daniel Berlin589cecc2017-01-02 18:00:46 +0000728 CongruenceClass *CC = ExpressionToClass.lookup(OldStore);
729 if (CC && CC->DefiningExpr && isa<StoreExpression>(CC->DefiningExpr) &&
730 CC->RepLeader == lookupOperandLeader(SI->getValueOperand(), SI, B))
731 return createStoreExpression(SI, StoreRHS, B);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000732 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000733
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000734 return createStoreExpression(SI, StoreAccess, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000735}
736
737const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I,
738 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000739 auto *LI = cast<LoadInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000740
741 // We can eliminate in favor of non-simple loads, but we won't be able to
Daniel Berlin589cecc2017-01-02 18:00:46 +0000742 // eliminate the loads themselves.
Davide Italiano7e274e02016-12-22 16:03:48 +0000743 if (!LI->isSimple())
744 return nullptr;
745
Daniel Berlin85f91b02016-12-26 20:06:58 +0000746 Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand(), I, B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000747 // Load of undef is undef.
748 if (isa<UndefValue>(LoadAddressLeader))
749 return createConstantExpression(UndefValue::get(LI->getType()));
750
751 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
752
753 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
754 if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
755 Instruction *DefiningInst = MD->getMemoryInst();
756 // If the defining instruction is not reachable, replace with undef.
757 if (!ReachableBlocks.count(DefiningInst->getParent()))
758 return createConstantExpression(UndefValue::get(LI->getType()));
759 }
760 }
761
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000762 const Expression *E =
763 createLoadExpression(LI->getType(), LI->getPointerOperand(), LI,
764 lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italiano7e274e02016-12-22 16:03:48 +0000765 return E;
766}
767
768// Evaluate read only and pure calls, and create an expression result.
769const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I,
770 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000771 auto *CI = cast<CallInst>(I);
Davide Italiano7e274e02016-12-22 16:03:48 +0000772 if (AA->doesNotAccessMemory(CI))
773 return createCallExpression(CI, nullptr, B);
Davide Italianob2225492016-12-27 18:15:39 +0000774 if (AA->onlyReadsMemory(CI)) {
Daniel Berlin85cbc8c2016-12-26 19:57:25 +0000775 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
Daniel Berlin85f91b02016-12-26 20:06:58 +0000776 return createCallExpression(CI, lookupMemoryAccessEquiv(DefiningAccess), B);
Davide Italianob2225492016-12-27 18:15:39 +0000777 }
778 return nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000779}
780
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000781// Update the memory access equivalence table to say that From is equal to To,
782// and return true if this is different from what already existed in the table.
783bool NewGVN::setMemoryAccessEquivTo(MemoryAccess *From, MemoryAccess *To) {
Davide Italiano84126162017-01-02 18:41:34 +0000784 DEBUG(dbgs() << "Setting " << *From << " equivalent to ");
785 if (!To)
786 DEBUG(dbgs() << "itself");
787 else
788 DEBUG(dbgs() << *To);
789 DEBUG(dbgs() << "\n");
Daniel Berlin589cecc2017-01-02 18:00:46 +0000790 auto LookupResult = MemoryAccessEquiv.find(From);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000791 bool Changed = false;
792 // If it's already in the table, see if the value changed.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000793 if (LookupResult != MemoryAccessEquiv.end()) {
794 if (To && LookupResult->second != To) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000795 // It wasn't equivalent before, and now it is.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000796 LookupResult->second = To;
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000797 Changed = true;
798 } else if (!To) {
799 // It used to be equivalent to something, and now it's not.
Daniel Berlin589cecc2017-01-02 18:00:46 +0000800 MemoryAccessEquiv.erase(LookupResult);
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000801 Changed = true;
802 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000803 } else {
804 assert(!To &&
805 "Memory equivalence should never change from nothing to something");
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000806 }
Daniel Berlin589cecc2017-01-02 18:00:46 +0000807
Daniel Berlind7c12ee2016-12-25 22:23:49 +0000808 return Changed;
809}
Davide Italiano7e274e02016-12-22 16:03:48 +0000810// Evaluate PHI nodes symbolically, and create an expression result.
811const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I,
812 const BasicBlock *B) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000813 auto *E = cast<PHIExpression>(createPHIExpression(I));
Daniel Berlind92e7f92017-01-07 00:01:42 +0000814 // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
815
816 // See if all arguaments are the same.
817 // We track if any were undef because they need special handling.
818 bool HasUndef = false;
819 auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
820 if (Arg == I)
821 return false;
822 if (isa<UndefValue>(Arg)) {
823 HasUndef = true;
824 return false;
825 }
826 return true;
827 });
828 // If we are left with no operands, it's undef
829 if (Filtered.begin() == Filtered.end()) {
Davide Italiano7e274e02016-12-22 16:03:48 +0000830 DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
831 << "\n");
832 E->deallocateOperands(ArgRecycler);
833 ExpressionAllocator.Deallocate(E);
834 return createConstantExpression(UndefValue::get(I->getType()));
835 }
Daniel Berlind92e7f92017-01-07 00:01:42 +0000836 Value *AllSameValue = *(Filtered.begin());
837 ++Filtered.begin();
838 // Can't use std::equal here, sadly, because filter.begin moves.
839 if (llvm::all_of(Filtered, [AllSameValue](const Value *V) {
840 return V == AllSameValue;
841 })) {
842 // In LLVM's non-standard representation of phi nodes, it's possible to have
843 // phi nodes with cycles (IE dependent on other phis that are .... dependent
844 // on the original phi node), especially in weird CFG's where some arguments
845 // are unreachable, or uninitialized along certain paths. This can cause
846 // infinite loops during evaluation. We work around this by not trying to
847 // really evaluate them independently, but instead using a variable
848 // expression to say if one is equivalent to the other.
849 // We also special case undef, so that if we have an undef, we can't use the
850 // common value unless it dominates the phi block.
851 if (HasUndef) {
852 // Only have to check for instructions
Davide Italiano1b97fc32017-01-07 02:05:50 +0000853 if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
Daniel Berlind92e7f92017-01-07 00:01:42 +0000854 if (!DT->dominates(AllSameInst, I))
855 return E;
Davide Italiano7e274e02016-12-22 16:03:48 +0000856 }
857
Davide Italiano7e274e02016-12-22 16:03:48 +0000858 NumGVNPhisAllSame++;
859 DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
860 << "\n");
861 E->deallocateOperands(ArgRecycler);
862 ExpressionAllocator.Deallocate(E);
863 if (auto *C = dyn_cast<Constant>(AllSameValue))
864 return createConstantExpression(C);
865 return createVariableExpression(AllSameValue);
866 }
867 return E;
868}
869
870const Expression *
871NewGVN::performSymbolicAggrValueEvaluation(Instruction *I,
872 const BasicBlock *B) {
873 if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
874 auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
875 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
876 unsigned Opcode = 0;
877 // EI might be an extract from one of our recognised intrinsics. If it
878 // is we'll synthesize a semantically equivalent expression instead on
879 // an extract value expression.
880 switch (II->getIntrinsicID()) {
881 case Intrinsic::sadd_with_overflow:
882 case Intrinsic::uadd_with_overflow:
883 Opcode = Instruction::Add;
884 break;
885 case Intrinsic::ssub_with_overflow:
886 case Intrinsic::usub_with_overflow:
887 Opcode = Instruction::Sub;
888 break;
889 case Intrinsic::smul_with_overflow:
890 case Intrinsic::umul_with_overflow:
891 Opcode = Instruction::Mul;
892 break;
893 default:
894 break;
895 }
896
897 if (Opcode != 0) {
898 // Intrinsic recognized. Grab its args to finish building the
899 // expression.
900 assert(II->getNumArgOperands() == 2 &&
901 "Expect two args for recognised intrinsics.");
902 return createBinaryExpression(Opcode, EI->getType(),
903 II->getArgOperand(0),
904 II->getArgOperand(1), B);
905 }
906 }
907 }
908
909 return createAggregateValueExpression(I, B);
910}
911
912// Substitute and symbolize the value before value numbering.
913const Expression *NewGVN::performSymbolicEvaluation(Value *V,
914 const BasicBlock *B) {
Davide Italiano0e714802016-12-28 14:00:11 +0000915 const Expression *E = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +0000916 if (auto *C = dyn_cast<Constant>(V))
917 E = createConstantExpression(C);
918 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
919 E = createVariableExpression(V);
920 } else {
921 // TODO: memory intrinsics.
922 // TODO: Some day, we should do the forward propagation and reassociation
923 // parts of the algorithm.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +0000924 auto *I = cast<Instruction>(V);
Davide Italiano7e274e02016-12-22 16:03:48 +0000925 switch (I->getOpcode()) {
926 case Instruction::ExtractValue:
927 case Instruction::InsertValue:
928 E = performSymbolicAggrValueEvaluation(I, B);
929 break;
930 case Instruction::PHI:
931 E = performSymbolicPHIEvaluation(I, B);
932 break;
933 case Instruction::Call:
934 E = performSymbolicCallEvaluation(I, B);
935 break;
936 case Instruction::Store:
937 E = performSymbolicStoreEvaluation(I, B);
938 break;
939 case Instruction::Load:
940 E = performSymbolicLoadEvaluation(I, B);
941 break;
942 case Instruction::BitCast: {
943 E = createExpression(I, B);
944 } break;
945
946 case Instruction::Add:
947 case Instruction::FAdd:
948 case Instruction::Sub:
949 case Instruction::FSub:
950 case Instruction::Mul:
951 case Instruction::FMul:
952 case Instruction::UDiv:
953 case Instruction::SDiv:
954 case Instruction::FDiv:
955 case Instruction::URem:
956 case Instruction::SRem:
957 case Instruction::FRem:
958 case Instruction::Shl:
959 case Instruction::LShr:
960 case Instruction::AShr:
961 case Instruction::And:
962 case Instruction::Or:
963 case Instruction::Xor:
964 case Instruction::ICmp:
965 case Instruction::FCmp:
966 case Instruction::Trunc:
967 case Instruction::ZExt:
968 case Instruction::SExt:
969 case Instruction::FPToUI:
970 case Instruction::FPToSI:
971 case Instruction::UIToFP:
972 case Instruction::SIToFP:
973 case Instruction::FPTrunc:
974 case Instruction::FPExt:
975 case Instruction::PtrToInt:
976 case Instruction::IntToPtr:
977 case Instruction::Select:
978 case Instruction::ExtractElement:
979 case Instruction::InsertElement:
980 case Instruction::ShuffleVector:
981 case Instruction::GetElementPtr:
982 E = createExpression(I, B);
983 break;
984 default:
985 return nullptr;
986 }
987 }
Davide Italiano7e274e02016-12-22 16:03:48 +0000988 return E;
989}
990
991// There is an edge from 'Src' to 'Dst'. Return true if every path from
992// the entry block to 'Dst' passes via this edge. In particular 'Dst'
993// must not be reachable via another edge from 'Src'.
Daniel Berlin8a6a8612016-12-24 00:04:07 +0000994bool NewGVN::isOnlyReachableViaThisEdge(const BasicBlockEdge &E) const {
Davide Italiano7e274e02016-12-22 16:03:48 +0000995
996 // While in theory it is interesting to consider the case in which Dst has
997 // more than one predecessor, because Dst might be part of a loop which is
998 // only reachable from Src, in practice it is pointless since at the time
999 // GVN runs all such loops have preheaders, which means that Dst will have
1000 // been changed to have only one predecessor, namely Src.
1001 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1002 const BasicBlock *Src = E.getStart();
1003 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
1004 (void)Src;
1005 return Pred != nullptr;
1006}
1007
1008void NewGVN::markUsersTouched(Value *V) {
1009 // Now mark the users as touched.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001010 for (auto *User : V->users()) {
1011 assert(isa<Instruction>(User) && "Use of value not within an instruction?");
Davide Italiano7e274e02016-12-22 16:03:48 +00001012 TouchedInstructions.set(InstrDFS[User]);
1013 }
1014}
1015
1016void NewGVN::markMemoryUsersTouched(MemoryAccess *MA) {
1017 for (auto U : MA->users()) {
1018 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U))
1019 TouchedInstructions.set(InstrDFS[MUD->getMemoryInst()]);
1020 else
Daniel Berline0bd37e2016-12-29 22:15:12 +00001021 TouchedInstructions.set(InstrDFS[U]);
Davide Italiano7e274e02016-12-22 16:03:48 +00001022 }
1023}
1024
1025// Perform congruence finding on a given value numbering expression.
1026void NewGVN::performCongruenceFinding(Value *V, const Expression *E) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001027 ValueToExpression[V] = E;
1028 // This is guaranteed to return something, since it will at least find
1029 // INITIAL.
1030 CongruenceClass *VClass = ValueToClass[V];
1031 assert(VClass && "Should have found a vclass");
1032 // Dead classes should have been eliminated from the mapping.
1033 assert(!VClass->Dead && "Found a dead class");
1034
1035 CongruenceClass *EClass;
Daniel Berlin02c6b172017-01-02 18:00:53 +00001036 if (const auto *VE = dyn_cast<VariableExpression>(E)) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001037 EClass = ValueToClass[VE->getVariableValue()];
1038 } else {
1039 auto lookupResult = ExpressionToClass.insert({E, nullptr});
1040
1041 // If it's not in the value table, create a new congruence class.
1042 if (lookupResult.second) {
Davide Italiano0e714802016-12-28 14:00:11 +00001043 CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
Davide Italiano7e274e02016-12-22 16:03:48 +00001044 auto place = lookupResult.first;
1045 place->second = NewClass;
1046
1047 // Constants and variables should always be made the leader.
1048 if (const auto *CE = dyn_cast<ConstantExpression>(E))
1049 NewClass->RepLeader = CE->getConstantValue();
1050 else if (const auto *VE = dyn_cast<VariableExpression>(E))
1051 NewClass->RepLeader = VE->getVariableValue();
1052 else if (const auto *SE = dyn_cast<StoreExpression>(E))
1053 NewClass->RepLeader = SE->getStoreInst()->getValueOperand();
1054 else
1055 NewClass->RepLeader = V;
1056
1057 EClass = NewClass;
1058 DEBUG(dbgs() << "Created new congruence class for " << *V
1059 << " using expression " << *E << " at " << NewClass->ID
Daniel Berlin589cecc2017-01-02 18:00:46 +00001060 << " and leader " << *(NewClass->RepLeader) << "\n");
Davide Italiano7e274e02016-12-22 16:03:48 +00001061 DEBUG(dbgs() << "Hash value was " << E->getHashValue() << "\n");
1062 } else {
1063 EClass = lookupResult.first->second;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001064 if (isa<ConstantExpression>(E))
1065 assert(isa<Constant>(EClass->RepLeader) &&
1066 "Any class with a constant expression should have a "
1067 "constant leader");
1068
Davide Italiano7e274e02016-12-22 16:03:48 +00001069 assert(EClass && "Somehow don't have an eclass");
1070
1071 assert(!EClass->Dead && "We accidentally looked up a dead class");
1072 }
1073 }
1074 bool WasInChanged = ChangedValues.erase(V);
1075 if (VClass != EClass || WasInChanged) {
1076 DEBUG(dbgs() << "Found class " << EClass->ID << " for expression " << E
1077 << "\n");
1078
1079 if (VClass != EClass) {
1080 DEBUG(dbgs() << "New congruence class for " << V << " is " << EClass->ID
1081 << "\n");
1082
1083 VClass->Members.erase(V);
1084 EClass->Members.insert(V);
1085 ValueToClass[V] = EClass;
1086 // See if we destroyed the class or need to swap leaders.
1087 if (VClass->Members.empty() && VClass != InitialClass) {
1088 if (VClass->DefiningExpr) {
1089 VClass->Dead = true;
1090 DEBUG(dbgs() << "Erasing expression " << *E << " from table\n");
1091 ExpressionToClass.erase(VClass->DefiningExpr);
1092 }
1093 } else if (VClass->RepLeader == V) {
1094 // FIXME: When the leader changes, the value numbering of
1095 // everything may change, so we need to reprocess.
1096 VClass->RepLeader = *(VClass->Members.begin());
1097 for (auto M : VClass->Members) {
1098 if (auto *I = dyn_cast<Instruction>(M))
1099 TouchedInstructions.set(InstrDFS[I]);
1100 ChangedValues.insert(M);
1101 }
1102 }
1103 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001104
Davide Italiano7e274e02016-12-22 16:03:48 +00001105 markUsersTouched(V);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001106 if (auto *I = dyn_cast<Instruction>(V)) {
1107 if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
1108 // If this is a MemoryDef, we need to update the equivalence table. If
Daniel Berlin25f05b02017-01-02 18:22:38 +00001109 // we determined the expression is congruent to a different memory
1110 // state, use that different memory state. If we determined it didn't,
Daniel Berlinde43ef92017-01-02 19:49:17 +00001111 // we update that as well. Right now, we only support store
Daniel Berlin25f05b02017-01-02 18:22:38 +00001112 // expressions.
Daniel Berlinde43ef92017-01-02 19:49:17 +00001113 if (!isa<MemoryUse>(MA) && isa<StoreExpression>(E) &&
1114 EClass->Members.size() != 1) {
1115 auto *DefAccess = cast<StoreExpression>(E)->getDefiningAccess();
1116 setMemoryAccessEquivTo(MA, DefAccess != MA ? DefAccess : nullptr);
1117 } else {
1118 setMemoryAccessEquivTo(MA, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001119 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001120 markMemoryUsersTouched(MA);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001121 }
1122 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001123 }
1124}
1125
1126// Process the fact that Edge (from, to) is reachable, including marking
1127// any newly reachable blocks and instructions for processing.
1128void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
1129 // Check if the Edge was reachable before.
1130 if (ReachableEdges.insert({From, To}).second) {
1131 // If this block wasn't reachable before, all instructions are touched.
1132 if (ReachableBlocks.insert(To).second) {
1133 DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
1134 const auto &InstRange = BlockInstRange.lookup(To);
1135 TouchedInstructions.set(InstRange.first, InstRange.second);
1136 } else {
1137 DEBUG(dbgs() << "Block " << getBlockName(To)
1138 << " was reachable, but new edge {" << getBlockName(From)
1139 << "," << getBlockName(To) << "} to it found\n");
1140
1141 // We've made an edge reachable to an existing block, which may
1142 // impact predicates. Otherwise, only mark the phi nodes as touched, as
1143 // they are the only thing that depend on new edges. Anything using their
1144 // values will get propagated to if necessary.
Daniel Berlin589cecc2017-01-02 18:00:46 +00001145 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
1146 TouchedInstructions.set(InstrDFS[MemPhi]);
1147
Davide Italiano7e274e02016-12-22 16:03:48 +00001148 auto BI = To->begin();
1149 while (isa<PHINode>(BI)) {
1150 TouchedInstructions.set(InstrDFS[&*BI]);
1151 ++BI;
1152 }
1153 }
1154 }
1155}
1156
1157// Given a predicate condition (from a switch, cmp, or whatever) and a block,
1158// see if we know some constant value for it already.
1159Value *NewGVN::findConditionEquivalence(Value *Cond, BasicBlock *B) const {
1160 auto Result = lookupOperandLeader(Cond, nullptr, B);
1161 if (isa<Constant>(Result))
1162 return Result;
1163 return nullptr;
1164}
1165
1166// Process the outgoing edges of a block for reachability.
1167void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
1168 // Evaluate reachability of terminator instruction.
1169 BranchInst *BR;
1170 if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
1171 Value *Cond = BR->getCondition();
1172 Value *CondEvaluated = findConditionEquivalence(Cond, B);
1173 if (!CondEvaluated) {
1174 if (auto *I = dyn_cast<Instruction>(Cond)) {
1175 const Expression *E = createExpression(I, B);
1176 if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
1177 CondEvaluated = CE->getConstantValue();
1178 }
1179 } else if (isa<ConstantInt>(Cond)) {
1180 CondEvaluated = Cond;
1181 }
1182 }
1183 ConstantInt *CI;
1184 BasicBlock *TrueSucc = BR->getSuccessor(0);
1185 BasicBlock *FalseSucc = BR->getSuccessor(1);
1186 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
1187 if (CI->isOne()) {
1188 DEBUG(dbgs() << "Condition for Terminator " << *TI
1189 << " evaluated to true\n");
1190 updateReachableEdge(B, TrueSucc);
1191 } else if (CI->isZero()) {
1192 DEBUG(dbgs() << "Condition for Terminator " << *TI
1193 << " evaluated to false\n");
1194 updateReachableEdge(B, FalseSucc);
1195 }
1196 } else {
1197 updateReachableEdge(B, TrueSucc);
1198 updateReachableEdge(B, FalseSucc);
1199 }
1200 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1201 // For switches, propagate the case values into the case
1202 // destinations.
1203
1204 // Remember how many outgoing edges there are to every successor.
1205 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1206
Davide Italiano7e274e02016-12-22 16:03:48 +00001207 Value *SwitchCond = SI->getCondition();
1208 Value *CondEvaluated = findConditionEquivalence(SwitchCond, B);
1209 // See if we were able to turn this switch statement into a constant.
1210 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001211 auto *CondVal = cast<ConstantInt>(CondEvaluated);
Davide Italiano7e274e02016-12-22 16:03:48 +00001212 // We should be able to get case value for this.
1213 auto CaseVal = SI->findCaseValue(CondVal);
1214 if (CaseVal.getCaseSuccessor() == SI->getDefaultDest()) {
1215 // We proved the value is outside of the range of the case.
1216 // We can't do anything other than mark the default dest as reachable,
1217 // and go home.
1218 updateReachableEdge(B, SI->getDefaultDest());
1219 return;
1220 }
1221 // Now get where it goes and mark it reachable.
1222 BasicBlock *TargetBlock = CaseVal.getCaseSuccessor();
1223 updateReachableEdge(B, TargetBlock);
Davide Italiano7e274e02016-12-22 16:03:48 +00001224 } else {
1225 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
1226 BasicBlock *TargetBlock = SI->getSuccessor(i);
1227 ++SwitchEdges[TargetBlock];
1228 updateReachableEdge(B, TargetBlock);
1229 }
1230 }
1231 } else {
1232 // Otherwise this is either unconditional, or a type we have no
1233 // idea about. Just mark successors as reachable.
1234 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1235 BasicBlock *TargetBlock = TI->getSuccessor(i);
1236 updateReachableEdge(B, TargetBlock);
1237 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001238
1239 // This also may be a memory defining terminator, in which case, set it
1240 // equivalent to nothing.
1241 if (MemoryAccess *MA = MSSA->getMemoryAccess(TI))
1242 setMemoryAccessEquivTo(MA, nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001243 }
1244}
1245
Daniel Berlin85f91b02016-12-26 20:06:58 +00001246// The algorithm initially places the values of the routine in the INITIAL
1247// congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001248// class. The leader of INITIAL is the undetermined value `TOP`.
1249// When the algorithm has finished, values still in INITIAL are unreachable.
1250void NewGVN::initializeCongruenceClasses(Function &F) {
1251 // FIXME now i can't remember why this is 2
1252 NextCongruenceNum = 2;
1253 // Initialize all other instructions to be in INITIAL class.
1254 CongruenceClass::MemberSet InitialValues;
Davide Italiano0e714802016-12-28 14:00:11 +00001255 InitialClass = createCongruenceClass(nullptr, nullptr);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001256 for (auto &B : F) {
1257 if (auto *MP = MSSA->getMemoryAccess(&B))
1258 MemoryAccessEquiv.insert({MP, MSSA->getLiveOnEntryDef()});
1259
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001260 for (auto &I : B) {
1261 InitialValues.insert(&I);
1262 ValueToClass[&I] = InitialClass;
Daniel Berlin589cecc2017-01-02 18:00:46 +00001263 // All memory accesses are equivalent to live on entry to start. They must
1264 // be initialized to something so that initial changes are noticed. For
1265 // the maximal answer, we initialize them all to be the same as
1266 // liveOnEntry. Note that to save time, we only initialize the
1267 // MemoryDef's for stores and all MemoryPhis to be equal. Right now, no
1268 // other expression can generate a memory equivalence. If we start
1269 // handling memcpy/etc, we can expand this.
1270 if (isa<StoreInst>(&I))
1271 MemoryAccessEquiv.insert(
1272 {MSSA->getMemoryAccess(&I), MSSA->getLiveOnEntryDef()});
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001273 }
Daniel Berlin589cecc2017-01-02 18:00:46 +00001274 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001275 InitialClass->Members.swap(InitialValues);
1276
1277 // Initialize arguments to be in their own unique congruence classes
1278 for (auto &FA : F.args())
1279 createSingletonCongruenceClass(&FA);
1280}
1281
1282void NewGVN::cleanupTables() {
1283 for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
1284 DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->ID << " has "
1285 << CongruenceClasses[i]->Members.size() << " members\n");
1286 // Make sure we delete the congruence class (probably worth switching to
1287 // a unique_ptr at some point.
1288 delete CongruenceClasses[i];
Davide Italiano0e714802016-12-28 14:00:11 +00001289 CongruenceClasses[i] = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001290 }
1291
1292 ValueToClass.clear();
1293 ArgRecycler.clear(ExpressionAllocator);
1294 ExpressionAllocator.Reset();
1295 CongruenceClasses.clear();
1296 ExpressionToClass.clear();
1297 ValueToExpression.clear();
1298 ReachableBlocks.clear();
1299 ReachableEdges.clear();
1300#ifndef NDEBUG
1301 ProcessedCount.clear();
1302#endif
1303 DFSDomMap.clear();
1304 InstrDFS.clear();
1305 InstructionsToErase.clear();
1306
1307 DFSToInstr.clear();
1308 BlockInstRange.clear();
1309 TouchedInstructions.clear();
1310 DominatedInstRange.clear();
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001311 MemoryAccessEquiv.clear();
Davide Italiano7e274e02016-12-22 16:03:48 +00001312}
1313
1314std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
1315 unsigned Start) {
1316 unsigned End = Start;
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001317 if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
1318 InstrDFS[MemPhi] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001319 DFSToInstr.emplace_back(MemPhi);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001320 }
1321
Davide Italiano7e274e02016-12-22 16:03:48 +00001322 for (auto &I : *B) {
1323 InstrDFS[&I] = End++;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001324 DFSToInstr.emplace_back(&I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001325 }
1326
1327 // All of the range functions taken half-open ranges (open on the end side).
1328 // So we do not subtract one from count, because at this point it is one
1329 // greater than the last instruction.
1330 return std::make_pair(Start, End);
1331}
1332
1333void NewGVN::updateProcessedCount(Value *V) {
1334#ifndef NDEBUG
1335 if (ProcessedCount.count(V) == 0) {
1336 ProcessedCount.insert({V, 1});
1337 } else {
1338 ProcessedCount[V] += 1;
1339 assert(ProcessedCount[V] < 100 &&
Davide Italiano75e39f92016-12-30 15:01:17 +00001340 "Seem to have processed the same Value a lot");
Davide Italiano7e274e02016-12-22 16:03:48 +00001341 }
1342#endif
1343}
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001344// Evaluate MemoryPhi nodes symbolically, just like PHI nodes
1345void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
1346 // If all the arguments are the same, the MemoryPhi has the same value as the
1347 // argument.
1348 // Filter out unreachable blocks from our operands.
1349 auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
1350 return ReachableBlocks.count(MP->getIncomingBlock(U));
1351 });
1352
1353 assert(Filtered.begin() != Filtered.end() &&
1354 "We should not be processing a MemoryPhi in a completely "
1355 "unreachable block");
1356
1357 // Transform the remaining operands into operand leaders.
1358 // FIXME: mapped_iterator should have a range version.
1359 auto LookupFunc = [&](const Use &U) {
1360 return lookupMemoryAccessEquiv(cast<MemoryAccess>(U));
1361 };
1362 auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
1363 auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
1364
1365 // and now check if all the elements are equal.
1366 // Sadly, we can't use std::equals since these are random access iterators.
1367 MemoryAccess *AllSameValue = *MappedBegin;
1368 ++MappedBegin;
1369 bool AllEqual = std::all_of(
1370 MappedBegin, MappedEnd,
1371 [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
1372
1373 if (AllEqual)
1374 DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
1375 else
1376 DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
1377
1378 if (setMemoryAccessEquivTo(MP, AllEqual ? AllSameValue : nullptr))
1379 markMemoryUsersTouched(MP);
1380}
1381
1382// Value number a single instruction, symbolically evaluating, performing
1383// congruence finding, and updating mappings.
1384void NewGVN::valueNumberInstruction(Instruction *I) {
1385 DEBUG(dbgs() << "Processing instruction " << *I << "\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001386 if (isInstructionTriviallyDead(I, TLI)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001387 DEBUG(dbgs() << "Skipping unused instruction\n");
Daniel Berlind59e8012016-12-26 18:44:36 +00001388 markInstructionForDeletion(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001389 return;
1390 }
1391 if (!I->isTerminator()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001392 const auto *Symbolized = performSymbolicEvaluation(I, I->getParent());
1393 // If we couldn't come up with a symbolic expression, use the unknown
1394 // expression
1395 if (Symbolized == nullptr)
1396 Symbolized = createUnknownExpression(I);
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001397 performCongruenceFinding(I, Symbolized);
1398 } else {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001399 // Handle terminators that return values. All of them produce values we
1400 // don't currently understand.
Daniel Berlin25f05b02017-01-02 18:22:38 +00001401 if (!I->getType()->isVoidTy()) {
Daniel Berlin02c6b172017-01-02 18:00:53 +00001402 auto *Symbolized = createUnknownExpression(I);
1403 performCongruenceFinding(I, Symbolized);
1404 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001405 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
1406 }
1407}
Davide Italiano7e274e02016-12-22 16:03:48 +00001408
Daniel Berlin589cecc2017-01-02 18:00:46 +00001409// Verify the that the memory equivalence table makes sense relative to the
1410// congruence classes.
1411void NewGVN::verifyMemoryCongruency() {
1412 // Anything equivalent in the memory access table should be in the same
1413 // congruence class.
1414
1415 // Filter out the unreachable and trivially dead entries, because they may
1416 // never have been updated if the instructions were not processed.
1417 auto ReachableAccessPred =
1418 [&](const std::pair<const MemoryAccess *, MemoryAccess *> Pair) {
1419 bool Result = ReachableBlocks.count(Pair.first->getBlock());
1420 if (!Result)
1421 return false;
1422 if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
1423 return !isInstructionTriviallyDead(MemDef->getMemoryInst());
1424 return true;
1425 };
1426
1427 auto Filtered = make_filter_range(MemoryAccessEquiv, ReachableAccessPred);
1428 for (auto KV : Filtered) {
1429 assert(KV.first != KV.second &&
1430 "We added a useless equivalence to the memory equivalence table");
1431 // Unreachable instructions may not have changed because we never process
1432 // them.
1433 if (!ReachableBlocks.count(KV.first->getBlock()))
1434 continue;
1435 if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
1436 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second);
Davide Italiano67ada752017-01-02 19:03:16 +00001437 if (FirstMUD && SecondMUD)
Daniel Berlin589cecc2017-01-02 18:00:46 +00001438 assert(
Davide Italiano67ada752017-01-02 19:03:16 +00001439 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
1440 ValueToClass.lookup(SecondMUD->getMemoryInst()) &&
Daniel Berlin589cecc2017-01-02 18:00:46 +00001441 "The instructions for these memory operations should have been in "
1442 "the same congruence class");
Daniel Berlin589cecc2017-01-02 18:00:46 +00001443 } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
1444
1445 // We can only sanely verify that MemoryDefs in the operand list all have
1446 // the same class.
1447 auto ReachableOperandPred = [&](const Use &U) {
1448 return ReachableBlocks.count(FirstMP->getIncomingBlock(U)) &&
1449 isa<MemoryDef>(U);
1450
1451 };
1452 // All arguments should in the same class, ignoring unreachable arguments
1453 auto FilteredPhiArgs =
1454 make_filter_range(FirstMP->operands(), ReachableOperandPred);
1455 SmallVector<const CongruenceClass *, 16> PhiOpClasses;
1456 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
1457 std::back_inserter(PhiOpClasses), [&](const Use &U) {
1458 const MemoryDef *MD = cast<MemoryDef>(U);
1459 return ValueToClass.lookup(MD->getMemoryInst());
1460 });
1461 assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
1462 PhiOpClasses.begin()) &&
1463 "All MemoryPhi arguments should be in the same class");
1464 }
1465 }
1466}
1467
Daniel Berlin85f91b02016-12-26 20:06:58 +00001468// This is the main transformation entry point.
Davide Italiano7e274e02016-12-22 16:03:48 +00001469bool NewGVN::runGVN(Function &F, DominatorTree *_DT, AssumptionCache *_AC,
Daniel Berlin85f91b02016-12-26 20:06:58 +00001470 TargetLibraryInfo *_TLI, AliasAnalysis *_AA,
1471 MemorySSA *_MSSA) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001472 bool Changed = false;
1473 DT = _DT;
1474 AC = _AC;
1475 TLI = _TLI;
1476 AA = _AA;
1477 MSSA = _MSSA;
1478 DL = &F.getParent()->getDataLayout();
1479 MSSAWalker = MSSA->getWalker();
1480
1481 // Count number of instructions for sizing of hash tables, and come
1482 // up with a global dfs numbering for instructions.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001483 unsigned ICount = 1;
1484 // Add an empty instruction to account for the fact that we start at 1
1485 DFSToInstr.emplace_back(nullptr);
Davide Italiano7e274e02016-12-22 16:03:48 +00001486 // Note: We want RPO traversal of the blocks, which is not quite the same as
1487 // dominator tree order, particularly with regard whether backedges get
1488 // visited first or second, given a block with multiple successors.
1489 // If we visit in the wrong order, we will end up performing N times as many
1490 // iterations.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001491 // The dominator tree does guarantee that, for a given dom tree node, it's
1492 // parent must occur before it in the RPO ordering. Thus, we only need to sort
1493 // the siblings.
1494 DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
Davide Italiano7e274e02016-12-22 16:03:48 +00001495 ReversePostOrderTraversal<Function *> RPOT(&F);
Daniel Berlin6658cc92016-12-29 01:12:36 +00001496 unsigned Counter = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001497 for (auto &B : RPOT) {
Daniel Berlin6658cc92016-12-29 01:12:36 +00001498 auto *Node = DT->getNode(B);
1499 assert(Node && "RPO and Dominator tree should have same reachability");
1500 RPOOrdering[Node] = ++Counter;
1501 }
1502 // Sort dominator tree children arrays into RPO.
1503 for (auto &B : RPOT) {
1504 auto *Node = DT->getNode(B);
1505 if (Node->getChildren().size() > 1)
1506 std::sort(Node->begin(), Node->end(),
1507 [&RPOOrdering](const DomTreeNode *A, const DomTreeNode *B) {
1508 return RPOOrdering[A] < RPOOrdering[B];
1509 });
1510 }
1511
1512 // Now a standard depth first ordering of the domtree is equivalent to RPO.
1513 auto DFI = df_begin(DT->getRootNode());
1514 for (auto DFE = df_end(DT->getRootNode()); DFI != DFE; ++DFI) {
1515 BasicBlock *B = DFI->getBlock();
Davide Italiano7e274e02016-12-22 16:03:48 +00001516 const auto &BlockRange = assignDFSNumbers(B, ICount);
1517 BlockInstRange.insert({B, BlockRange});
1518 ICount += BlockRange.second - BlockRange.first;
1519 }
1520
1521 // Handle forward unreachable blocks and figure out which blocks
1522 // have single preds.
1523 for (auto &B : F) {
1524 // Assign numbers to unreachable blocks.
Daniel Berlin6658cc92016-12-29 01:12:36 +00001525 if (!DFI.nodeVisited(DT->getNode(&B))) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001526 const auto &BlockRange = assignDFSNumbers(&B, ICount);
1527 BlockInstRange.insert({&B, BlockRange});
1528 ICount += BlockRange.second - BlockRange.first;
1529 }
1530 }
1531
Daniel Berline0bd37e2016-12-29 22:15:12 +00001532 TouchedInstructions.resize(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001533 DominatedInstRange.reserve(F.size());
1534 // Ensure we don't end up resizing the expressionToClass map, as
1535 // that can be quite expensive. At most, we have one expression per
1536 // instruction.
Daniel Berline0bd37e2016-12-29 22:15:12 +00001537 ExpressionToClass.reserve(ICount);
Davide Italiano7e274e02016-12-22 16:03:48 +00001538
1539 // Initialize the touched instructions to include the entry block.
1540 const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
1541 TouchedInstructions.set(InstRange.first, InstRange.second);
1542 ReachableBlocks.insert(&F.getEntryBlock());
1543
1544 initializeCongruenceClasses(F);
1545
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001546 unsigned int Iterations = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001547 // We start out in the entry block.
1548 BasicBlock *LastBlock = &F.getEntryBlock();
1549 while (TouchedInstructions.any()) {
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001550 ++Iterations;
Davide Italiano7e274e02016-12-22 16:03:48 +00001551 // Walk through all the instructions in all the blocks in RPO.
1552 for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
1553 InstrNum = TouchedInstructions.find_next(InstrNum)) {
Daniel Berline0bd37e2016-12-29 22:15:12 +00001554 assert(InstrNum != 0 && "Bit 0 should never be set, something touched an "
1555 "instruction not in the lookup table");
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001556 Value *V = DFSToInstr[InstrNum];
1557 BasicBlock *CurrBlock = nullptr;
1558
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001559 if (auto *I = dyn_cast<Instruction>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001560 CurrBlock = I->getParent();
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001561 else if (auto *MP = dyn_cast<MemoryPhi>(V))
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001562 CurrBlock = MP->getBlock();
1563 else
1564 llvm_unreachable("DFSToInstr gave us an unknown type of instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001565
1566 // If we hit a new block, do reachability processing.
1567 if (CurrBlock != LastBlock) {
1568 LastBlock = CurrBlock;
1569 bool BlockReachable = ReachableBlocks.count(CurrBlock);
1570 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
1571
1572 // If it's not reachable, erase any touched instructions and move on.
1573 if (!BlockReachable) {
1574 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
1575 DEBUG(dbgs() << "Skipping instructions in block "
1576 << getBlockName(CurrBlock)
1577 << " because it is unreachable\n");
1578 continue;
1579 }
1580 updateProcessedCount(CurrBlock);
1581 }
Davide Italiano7e274e02016-12-22 16:03:48 +00001582
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001583 if (auto *MP = dyn_cast<MemoryPhi>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001584 DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
1585 valueNumberMemoryPhi(MP);
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001586 } else if (auto *I = dyn_cast<Instruction>(V)) {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001587 valueNumberInstruction(I);
Davide Italiano7e274e02016-12-22 16:03:48 +00001588 } else {
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001589 llvm_unreachable("Should have been a MemoryPhi or Instruction");
Davide Italiano7e274e02016-12-22 16:03:48 +00001590 }
Daniel Berlind7c12ee2016-12-25 22:23:49 +00001591 updateProcessedCount(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001592 // Reset after processing (because we may mark ourselves as touched when
1593 // we propagate equalities).
1594 TouchedInstructions.reset(InstrNum);
1595 }
1596 }
Daniel Berlin6cc5e442017-01-04 21:01:02 +00001597 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
Daniel Berlin589cecc2017-01-02 18:00:46 +00001598#ifndef NDEBUG
1599 verifyMemoryCongruency();
1600#endif
Davide Italiano7e274e02016-12-22 16:03:48 +00001601 Changed |= eliminateInstructions(F);
1602
1603 // Delete all instructions marked for deletion.
1604 for (Instruction *ToErase : InstructionsToErase) {
1605 if (!ToErase->use_empty())
1606 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
1607
1608 ToErase->eraseFromParent();
1609 }
1610
1611 // Delete all unreachable blocks.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001612 auto UnreachableBlockPred = [&](const BasicBlock &BB) {
1613 return !ReachableBlocks.count(&BB);
1614 };
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001615
1616 for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
1617 DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
Daniel Berlin85f91b02016-12-26 20:06:58 +00001618 << " is unreachable\n");
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001619 deleteInstructionsInBlock(&BB);
1620 Changed = true;
Davide Italiano7e274e02016-12-22 16:03:48 +00001621 }
1622
1623 cleanupTables();
1624 return Changed;
1625}
1626
1627bool NewGVN::runOnFunction(Function &F) {
1628 if (skipFunction(F))
1629 return false;
1630 return runGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
1631 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
1632 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1633 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1634 &getAnalysis<MemorySSAWrapperPass>().getMSSA());
1635}
1636
Daniel Berlin85f91b02016-12-26 20:06:58 +00001637PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
Davide Italiano7e274e02016-12-22 16:03:48 +00001638 NewGVN Impl;
1639
1640 // Apparently the order in which we get these results matter for
1641 // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
1642 // the same order here, just in case.
1643 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1644 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1645 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1646 auto &AA = AM.getResult<AAManager>(F);
1647 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1648 bool Changed = Impl.runGVN(F, &DT, &AC, &TLI, &AA, &MSSA);
1649 if (!Changed)
1650 return PreservedAnalyses::all();
1651 PreservedAnalyses PA;
1652 PA.preserve<DominatorTreeAnalysis>();
1653 PA.preserve<GlobalsAA>();
1654 return PA;
1655}
1656
1657// Return true if V is a value that will always be available (IE can
1658// be placed anywhere) in the function. We don't do globals here
1659// because they are often worse to put in place.
1660// TODO: Separate cost from availability
1661static bool alwaysAvailable(Value *V) {
1662 return isa<Constant>(V) || isa<Argument>(V);
1663}
1664
1665// Get the basic block from an instruction/value.
1666static BasicBlock *getBlockForValue(Value *V) {
1667 if (auto *I = dyn_cast<Instruction>(V))
1668 return I->getParent();
1669 return nullptr;
1670}
1671
1672struct NewGVN::ValueDFS {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001673 int DFSIn = 0;
1674 int DFSOut = 0;
1675 int LocalNum = 0;
Davide Italiano7e274e02016-12-22 16:03:48 +00001676 // Only one of these will be set.
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001677 Value *Val = nullptr;
1678 Use *U = nullptr;
Davide Italiano7e274e02016-12-22 16:03:48 +00001679
1680 bool operator<(const ValueDFS &Other) const {
1681 // It's not enough that any given field be less than - we have sets
1682 // of fields that need to be evaluated together to give a proper ordering.
1683 // For example, if you have;
1684 // DFS (1, 3)
1685 // Val 0
1686 // DFS (1, 2)
1687 // Val 50
1688 // We want the second to be less than the first, but if we just go field
1689 // by field, we will get to Val 0 < Val 50 and say the first is less than
1690 // the second. We only want it to be less than if the DFS orders are equal.
1691 //
1692 // Each LLVM instruction only produces one value, and thus the lowest-level
1693 // differentiator that really matters for the stack (and what we use as as a
1694 // replacement) is the local dfs number.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001695 // Everything else in the structure is instruction level, and only affects
1696 // the order in which we will replace operands of a given instruction.
Davide Italiano7e274e02016-12-22 16:03:48 +00001697 //
1698 // For a given instruction (IE things with equal dfsin, dfsout, localnum),
1699 // the order of replacement of uses does not matter.
1700 // IE given,
1701 // a = 5
1702 // b = a + a
Daniel Berlin85f91b02016-12-26 20:06:58 +00001703 // When you hit b, you will have two valuedfs with the same dfsin, out, and
1704 // localnum.
Davide Italiano7e274e02016-12-22 16:03:48 +00001705 // The .val will be the same as well.
1706 // The .u's will be different.
Daniel Berlin85f91b02016-12-26 20:06:58 +00001707 // You will replace both, and it does not matter what order you replace them
1708 // in (IE whether you replace operand 2, then operand 1, or operand 1, then
1709 // operand 2).
1710 // Similarly for the case of same dfsin, dfsout, localnum, but different
1711 // .val's
Davide Italiano7e274e02016-12-22 16:03:48 +00001712 // a = 5
1713 // b = 6
1714 // c = a + b
Daniel Berlin85f91b02016-12-26 20:06:58 +00001715 // in c, we will a valuedfs for a, and one for b,with everything the same
1716 // but .val and .u.
Davide Italiano7e274e02016-12-22 16:03:48 +00001717 // It does not matter what order we replace these operands in.
1718 // You will always end up with the same IR, and this is guaranteed.
1719 return std::tie(DFSIn, DFSOut, LocalNum, Val, U) <
1720 std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Val,
1721 Other.U);
1722 }
1723};
1724
1725void NewGVN::convertDenseToDFSOrdered(CongruenceClass::MemberSet &Dense,
1726 std::vector<ValueDFS> &DFSOrderedSet) {
1727 for (auto D : Dense) {
1728 // First add the value.
1729 BasicBlock *BB = getBlockForValue(D);
1730 // Constants are handled prior to ever calling this function, so
1731 // we should only be left with instructions as members.
Chandler Carruthee086762016-12-23 01:38:06 +00001732 assert(BB && "Should have figured out a basic block for value");
Davide Italiano7e274e02016-12-22 16:03:48 +00001733 ValueDFS VD;
1734
1735 std::pair<int, int> DFSPair = DFSDomMap[BB];
1736 assert(DFSPair.first != -1 && DFSPair.second != -1 && "Invalid DFS Pair");
1737 VD.DFSIn = DFSPair.first;
1738 VD.DFSOut = DFSPair.second;
1739 VD.Val = D;
1740 // If it's an instruction, use the real local dfs number.
1741 if (auto *I = dyn_cast<Instruction>(D))
1742 VD.LocalNum = InstrDFS[I];
1743 else
1744 llvm_unreachable("Should have been an instruction");
1745
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001746 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001747
1748 // Now add the users.
1749 for (auto &U : D->uses()) {
1750 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
1751 ValueDFS VD;
1752 // Put the phi node uses in the incoming block.
1753 BasicBlock *IBlock;
1754 if (auto *P = dyn_cast<PHINode>(I)) {
1755 IBlock = P->getIncomingBlock(U);
1756 // Make phi node users appear last in the incoming block
1757 // they are from.
1758 VD.LocalNum = InstrDFS.size() + 1;
1759 } else {
1760 IBlock = I->getParent();
1761 VD.LocalNum = InstrDFS[I];
1762 }
1763 std::pair<int, int> DFSPair = DFSDomMap[IBlock];
1764 VD.DFSIn = DFSPair.first;
1765 VD.DFSOut = DFSPair.second;
1766 VD.U = &U;
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001767 DFSOrderedSet.emplace_back(VD);
Davide Italiano7e274e02016-12-22 16:03:48 +00001768 }
1769 }
1770 }
1771}
1772
1773static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1774 // Patch the replacement so that it is not more restrictive than the value
1775 // being replaced.
1776 auto *Op = dyn_cast<BinaryOperator>(I);
1777 auto *ReplOp = dyn_cast<BinaryOperator>(Repl);
1778
1779 if (Op && ReplOp)
1780 ReplOp->andIRFlags(Op);
1781
1782 if (auto *ReplInst = dyn_cast<Instruction>(Repl)) {
1783 // FIXME: If both the original and replacement value are part of the
1784 // same control-flow region (meaning that the execution of one
1785 // guarentees the executation of the other), then we can combine the
1786 // noalias scopes here and do better than the general conservative
1787 // answer used in combineMetadata().
1788
1789 // In general, GVN unifies expressions over different control-flow
1790 // regions, and so we need a conservative combination of the noalias
1791 // scopes.
1792 unsigned KnownIDs[] = {
1793 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1794 LLVMContext::MD_noalias, LLVMContext::MD_range,
1795 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1796 LLVMContext::MD_invariant_group};
1797 combineMetadata(ReplInst, I, KnownIDs);
1798 }
1799}
1800
1801static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1802 patchReplacementInstruction(I, Repl);
1803 I->replaceAllUsesWith(Repl);
1804}
1805
1806void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
1807 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1808 ++NumGVNBlocksDeleted;
1809
1810 // Check to see if there are non-terminating instructions to delete.
1811 if (isa<TerminatorInst>(BB->begin()))
1812 return;
1813
1814 // Delete the instructions backwards, as it has a reduced likelihood of having
1815 // to update as many def-use and use-def chains. Start after the terminator.
1816 auto StartPoint = BB->rbegin();
1817 ++StartPoint;
1818 // Note that we explicitly recalculate BB->rend() on each iteration,
1819 // as it may change when we remove the first instruction.
1820 for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
1821 Instruction &Inst = *I++;
1822 if (!Inst.use_empty())
1823 Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
1824 if (isa<LandingPadInst>(Inst))
1825 continue;
1826
1827 Inst.eraseFromParent();
1828 ++NumGVNInstrDeleted;
1829 }
1830}
1831
1832void NewGVN::markInstructionForDeletion(Instruction *I) {
1833 DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
1834 InstructionsToErase.insert(I);
1835}
1836
1837void NewGVN::replaceInstruction(Instruction *I, Value *V) {
1838
1839 DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
1840 patchAndReplaceAllUsesWith(I, V);
1841 // We save the actual erasing to avoid invalidating memory
1842 // dependencies until we are done with everything.
1843 markInstructionForDeletion(I);
1844}
1845
1846namespace {
1847
1848// This is a stack that contains both the value and dfs info of where
1849// that value is valid.
1850class ValueDFSStack {
1851public:
1852 Value *back() const { return ValueStack.back(); }
1853 std::pair<int, int> dfs_back() const { return DFSStack.back(); }
1854
1855 void push_back(Value *V, int DFSIn, int DFSOut) {
Piotr Padlewski6c37d292016-12-28 23:24:02 +00001856 ValueStack.emplace_back(V);
Davide Italiano7e274e02016-12-22 16:03:48 +00001857 DFSStack.emplace_back(DFSIn, DFSOut);
1858 }
1859 bool empty() const { return DFSStack.empty(); }
1860 bool isInScope(int DFSIn, int DFSOut) const {
1861 if (empty())
1862 return false;
1863 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
1864 }
1865
1866 void popUntilDFSScope(int DFSIn, int DFSOut) {
1867
1868 // These two should always be in sync at this point.
1869 assert(ValueStack.size() == DFSStack.size() &&
1870 "Mismatch between ValueStack and DFSStack");
1871 while (
1872 !DFSStack.empty() &&
1873 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
1874 DFSStack.pop_back();
1875 ValueStack.pop_back();
1876 }
1877 }
1878
1879private:
1880 SmallVector<Value *, 8> ValueStack;
1881 SmallVector<std::pair<int, int>, 8> DFSStack;
1882};
1883}
Daniel Berlin04443432017-01-07 03:23:47 +00001884
Davide Italiano7e274e02016-12-22 16:03:48 +00001885bool NewGVN::eliminateInstructions(Function &F) {
1886 // This is a non-standard eliminator. The normal way to eliminate is
1887 // to walk the dominator tree in order, keeping track of available
1888 // values, and eliminating them. However, this is mildly
1889 // pointless. It requires doing lookups on every instruction,
1890 // regardless of whether we will ever eliminate it. For
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001891 // instructions part of most singleton congruence classes, we know we
1892 // will never eliminate them.
Davide Italiano7e274e02016-12-22 16:03:48 +00001893
1894 // Instead, this eliminator looks at the congruence classes directly, sorts
1895 // them into a DFS ordering of the dominator tree, and then we just
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001896 // perform elimination straight on the sets by walking the congruence
Davide Italiano7e274e02016-12-22 16:03:48 +00001897 // class member uses in order, and eliminate the ones dominated by the
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001898 // last member. This is worst case O(E log E) where E = number of
1899 // instructions in a single congruence class. In theory, this is all
1900 // instructions. In practice, it is much faster, as most instructions are
1901 // either in singleton congruence classes or can't possibly be eliminated
1902 // anyway (if there are no overlapping DFS ranges in class).
Davide Italiano7e274e02016-12-22 16:03:48 +00001903 // When we find something not dominated, it becomes the new leader
Daniel Berlin85cbc8c2016-12-26 19:57:25 +00001904 // for elimination purposes.
1905 // TODO: If we wanted to be faster, We could remove any members with no
1906 // overlapping ranges while sorting, as we will never eliminate anything
1907 // with those members, as they don't dominate anything else in our set.
1908
Davide Italiano7e274e02016-12-22 16:03:48 +00001909 bool AnythingReplaced = false;
1910
1911 // Since we are going to walk the domtree anyway, and we can't guarantee the
1912 // DFS numbers are updated, we compute some ourselves.
1913 DT->updateDFSNumbers();
1914
1915 for (auto &B : F) {
1916 if (!ReachableBlocks.count(&B)) {
1917 for (const auto S : successors(&B)) {
1918 for (auto II = S->begin(); isa<PHINode>(II); ++II) {
Piotr Padlewskifc5727b2016-12-28 19:17:17 +00001919 auto &Phi = cast<PHINode>(*II);
Davide Italiano7e274e02016-12-22 16:03:48 +00001920 DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
1921 << getBlockName(&B)
1922 << " with undef due to it being unreachable\n");
1923 for (auto &Operand : Phi.incoming_values())
1924 if (Phi.getIncomingBlock(Operand) == &B)
1925 Operand.set(UndefValue::get(Phi.getType()));
1926 }
1927 }
1928 }
1929 DomTreeNode *Node = DT->getNode(&B);
1930 if (Node)
1931 DFSDomMap[&B] = {Node->getDFSNumIn(), Node->getDFSNumOut()};
1932 }
1933
1934 for (CongruenceClass *CC : CongruenceClasses) {
1935 // FIXME: We should eventually be able to replace everything still
1936 // in the initial class with undef, as they should be unreachable.
1937 // Right now, initial still contains some things we skip value
1938 // numbering of (UNREACHABLE's, for example).
1939 if (CC == InitialClass || CC->Dead)
1940 continue;
1941 assert(CC->RepLeader && "We should have had a leader");
1942
1943 // If this is a leader that is always available, and it's a
1944 // constant or has no equivalences, just replace everything with
1945 // it. We then update the congruence class with whatever members
1946 // are left.
1947 if (alwaysAvailable(CC->RepLeader)) {
1948 SmallPtrSet<Value *, 4> MembersLeft;
1949 for (auto M : CC->Members) {
1950
1951 Value *Member = M;
1952
1953 // Void things have no uses we can replace.
1954 if (Member == CC->RepLeader || Member->getType()->isVoidTy()) {
1955 MembersLeft.insert(Member);
1956 continue;
1957 }
1958
1959 DEBUG(dbgs() << "Found replacement " << *(CC->RepLeader) << " for "
1960 << *Member << "\n");
1961 // Due to equality propagation, these may not always be
1962 // instructions, they may be real values. We don't really
1963 // care about trying to replace the non-instructions.
1964 if (auto *I = dyn_cast<Instruction>(Member)) {
1965 assert(CC->RepLeader != I &&
1966 "About to accidentally remove our leader");
1967 replaceInstruction(I, CC->RepLeader);
1968 AnythingReplaced = true;
1969
1970 continue;
1971 } else {
1972 MembersLeft.insert(I);
1973 }
1974 }
1975 CC->Members.swap(MembersLeft);
1976
1977 } else {
1978 DEBUG(dbgs() << "Eliminating in congruence class " << CC->ID << "\n");
1979 // If this is a singleton, we can skip it.
1980 if (CC->Members.size() != 1) {
1981
1982 // This is a stack because equality replacement/etc may place
1983 // constants in the middle of the member list, and we want to use
1984 // those constant values in preference to the current leader, over
1985 // the scope of those constants.
1986 ValueDFSStack EliminationStack;
1987
1988 // Convert the members to DFS ordered sets and then merge them.
1989 std::vector<ValueDFS> DFSOrderedSet;
1990 convertDenseToDFSOrdered(CC->Members, DFSOrderedSet);
1991
1992 // Sort the whole thing.
1993 sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
1994
1995 for (auto &C : DFSOrderedSet) {
1996 int MemberDFSIn = C.DFSIn;
1997 int MemberDFSOut = C.DFSOut;
1998 Value *Member = C.Val;
1999 Use *MemberUse = C.U;
2000
Daniel Berlind92e7f92017-01-07 00:01:42 +00002001 if (Member) {
2002 // We ignore void things because we can't get a value from them.
2003 // FIXME: We could actually use this to kill dead stores that are
2004 // dominated by equivalent earlier stores.
2005 if (Member->getType()->isVoidTy())
2006 continue;
2007 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002008
2009 if (EliminationStack.empty()) {
2010 DEBUG(dbgs() << "Elimination Stack is empty\n");
2011 } else {
2012 DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
2013 << EliminationStack.dfs_back().first << ","
2014 << EliminationStack.dfs_back().second << ")\n");
2015 }
Davide Italiano7e274e02016-12-22 16:03:48 +00002016
2017 DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
2018 << MemberDFSOut << ")\n");
2019 // First, we see if we are out of scope or empty. If so,
2020 // and there equivalences, we try to replace the top of
2021 // stack with equivalences (if it's on the stack, it must
2022 // not have been eliminated yet).
2023 // Then we synchronize to our current scope, by
2024 // popping until we are back within a DFS scope that
2025 // dominates the current member.
2026 // Then, what happens depends on a few factors
2027 // If the stack is now empty, we need to push
2028 // If we have a constant or a local equivalence we want to
2029 // start using, we also push.
2030 // Otherwise, we walk along, processing members who are
2031 // dominated by this scope, and eliminate them.
2032 bool ShouldPush =
2033 Member && (EliminationStack.empty() || isa<Constant>(Member));
2034 bool OutOfScope =
2035 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
2036
2037 if (OutOfScope || ShouldPush) {
2038 // Sync to our current scope.
2039 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
2040 ShouldPush |= Member && EliminationStack.empty();
2041 if (ShouldPush) {
2042 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
2043 }
2044 }
2045
2046 // If we get to this point, and the stack is empty we must have a use
2047 // with nothing we can use to eliminate it, just skip it.
2048 if (EliminationStack.empty())
2049 continue;
2050
2051 // Skip the Value's, we only want to eliminate on their uses.
2052 if (Member)
2053 continue;
2054 Value *Result = EliminationStack.back();
2055
Daniel Berlind92e7f92017-01-07 00:01:42 +00002056 // Don't replace our existing users with ourselves.
2057 if (MemberUse->get() == Result)
Davide Italiano7e274e02016-12-22 16:03:48 +00002058 continue;
2059
2060 DEBUG(dbgs() << "Found replacement " << *Result << " for "
2061 << *MemberUse->get() << " in " << *(MemberUse->getUser())
2062 << "\n");
2063
2064 // If we replaced something in an instruction, handle the patching of
2065 // metadata.
Daniel Berlin85f91b02016-12-26 20:06:58 +00002066 if (auto *ReplacedInst = dyn_cast<Instruction>(MemberUse->get()))
Davide Italiano7e274e02016-12-22 16:03:48 +00002067 patchReplacementInstruction(ReplacedInst, Result);
2068
2069 assert(isa<Instruction>(MemberUse->getUser()));
2070 MemberUse->set(Result);
2071 AnythingReplaced = true;
2072 }
2073 }
2074 }
2075
2076 // Cleanup the congruence class.
2077 SmallPtrSet<Value *, 4> MembersLeft;
Daniel Berlin25f05b02017-01-02 18:22:38 +00002078 for (Value *Member : CC->Members) {
Davide Italiano7e274e02016-12-22 16:03:48 +00002079 if (Member->getType()->isVoidTy()) {
2080 MembersLeft.insert(Member);
2081 continue;
2082 }
2083
2084 if (auto *MemberInst = dyn_cast<Instruction>(Member)) {
2085 if (isInstructionTriviallyDead(MemberInst)) {
2086 // TODO: Don't mark loads of undefs.
2087 markInstructionForDeletion(MemberInst);
2088 continue;
2089 }
2090 }
2091 MembersLeft.insert(Member);
2092 }
2093 CC->Members.swap(MembersLeft);
2094 }
2095
2096 return AnythingReplaced;
2097}