blob: 0317ddbc914042487363137ee04e0067b9c9697a [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- LoadValueNumbering.cpp - Load Value #'ing Implementation -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a value numbering pass that value numbers load and call
11// instructions. To do this, it finds lexically identical load instructions,
12// and uses alias analysis to determine which loads are guaranteed to produce
13// the same value. To value number call instructions, it looks for calls to
14// functions that do not write to memory which do not have intervening
15// instructions that clobber the memory that is read from.
16//
17// This pass builds off of another value numbering pass to implement value
18// numbering for non-load and non-call instructions. It uses Alias Analysis so
19// that it can disambiguate the load instructions. The more powerful these base
20// analyses are, the more powerful the resultant value numbering will be.
21//
22//===----------------------------------------------------------------------===//
23
24#include "llvm/Analysis/LoadValueNumbering.h"
25#include "llvm/Constants.h"
26#include "llvm/Function.h"
27#include "llvm/Instructions.h"
28#include "llvm/Pass.h"
29#include "llvm/Type.h"
30#include "llvm/Analysis/ValueNumbering.h"
31#include "llvm/Analysis/AliasAnalysis.h"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Support/CFG.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Target/TargetData.h"
36#include <set>
37#include <algorithm>
38using namespace llvm;
39
40namespace {
41 // FIXME: This should not be a FunctionPass.
42 struct VISIBILITY_HIDDEN LoadVN : public FunctionPass, public ValueNumbering {
43 static char ID; // Class identification, replacement for typeinfo
Devang Patel3aab76e2008-03-19 21:56:59 +000044 LoadVN() : FunctionPass((intptr_t)&ID) {}
Devang Patel2b4fa682008-03-18 00:39:19 +000045
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046 /// Pass Implementation stuff. This doesn't do any analysis.
47 ///
48 bool runOnFunction(Function &) { return false; }
49
50 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering
51 /// and Alias Analysis.
52 ///
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
54
55 /// getEqualNumberNodes - Return nodes with the same value number as the
56 /// specified Value. This fills in the argument vector with any equal
57 /// values.
58 ///
59 virtual void getEqualNumberNodes(Value *V1,
60 std::vector<Value*> &RetVals) const;
61
62 /// deleteValue - This method should be called whenever an LLVM Value is
63 /// deleted from the program, for example when an instruction is found to be
64 /// redundant and is eliminated.
65 ///
66 virtual void deleteValue(Value *V) {
67 getAnalysis<AliasAnalysis>().deleteValue(V);
68 }
69
70 /// copyValue - This method should be used whenever a preexisting value in
71 /// the program is copied or cloned, introducing a new value. Note that
72 /// analysis implementations should tolerate clients that use this method to
73 /// introduce the same value multiple times: if the analysis already knows
74 /// about a value, it should ignore the request.
75 ///
76 virtual void copyValue(Value *From, Value *To) {
77 getAnalysis<AliasAnalysis>().copyValue(From, To);
78 }
79
80 /// getCallEqualNumberNodes - Given a call instruction, find other calls
81 /// that have the same value number.
82 void getCallEqualNumberNodes(CallInst *CI,
83 std::vector<Value*> &RetVals) const;
84 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085}
86
Dan Gohman089efff2008-05-13 00:00:25 +000087char LoadVN::ID = 0;
88// Register this pass...
89static RegisterPass<LoadVN>
90X("load-vn", "Load Value Numbering", false, true);
91
92// Declare that we implement the ValueNumbering interface
93static RegisterAnalysisGroup<ValueNumbering> Y(X);
94
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095FunctionPass *llvm::createLoadValueNumberingPass() { return new LoadVN(); }
96
97
98/// getAnalysisUsage - Does not modify anything. It uses Value Numbering and
99/// Alias Analysis.
100///
101void LoadVN::getAnalysisUsage(AnalysisUsage &AU) const {
102 AU.setPreservesAll();
103 AU.addRequiredTransitive<AliasAnalysis>();
104 AU.addRequired<ValueNumbering>();
105 AU.addRequiredTransitive<DominatorTree>();
106 AU.addRequiredTransitive<TargetData>();
107}
108
109static bool isPathTransparentTo(BasicBlock *CurBlock, BasicBlock *Dom,
110 Value *Ptr, unsigned Size, AliasAnalysis &AA,
111 std::set<BasicBlock*> &Visited,
112 std::map<BasicBlock*, bool> &TransparentBlocks){
113 // If we have already checked out this path, or if we reached our destination,
114 // stop searching, returning success.
115 if (CurBlock == Dom || !Visited.insert(CurBlock).second)
116 return true;
117
118 // Check whether this block is known transparent or not.
119 std::map<BasicBlock*, bool>::iterator TBI =
120 TransparentBlocks.lower_bound(CurBlock);
121
122 if (TBI == TransparentBlocks.end() || TBI->first != CurBlock) {
123 // If this basic block can modify the memory location, then the path is not
124 // transparent!
125 if (AA.canBasicBlockModify(*CurBlock, Ptr, Size)) {
126 TransparentBlocks.insert(TBI, std::make_pair(CurBlock, false));
127 return false;
128 }
129 TransparentBlocks.insert(TBI, std::make_pair(CurBlock, true));
130 } else if (!TBI->second)
131 // This block is known non-transparent, so that path can't be either.
132 return false;
133
134 // The current block is known to be transparent. The entire path is
135 // transparent if all of the predecessors paths to the parent is also
136 // transparent to the memory location.
137 for (pred_iterator PI = pred_begin(CurBlock), E = pred_end(CurBlock);
138 PI != E; ++PI)
139 if (!isPathTransparentTo(*PI, Dom, Ptr, Size, AA, Visited,
140 TransparentBlocks))
141 return false;
142 return true;
143}
144
145/// getCallEqualNumberNodes - Given a call instruction, find other calls that
146/// have the same value number.
147void LoadVN::getCallEqualNumberNodes(CallInst *CI,
148 std::vector<Value*> &RetVals) const {
149 Function *CF = CI->getCalledFunction();
150 if (CF == 0) return; // Indirect call.
151 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Duncan Sands00b24b52007-12-01 07:51:45 +0000152 AliasAnalysis::ModRefBehavior MRB = AA.getModRefBehavior(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 if (MRB != AliasAnalysis::DoesNotAccessMemory &&
154 MRB != AliasAnalysis::OnlyReadsMemory)
155 return; // Nothing we can do for now.
156
157 // Scan all of the arguments of the function, looking for one that is not
158 // global. In particular, we would prefer to have an argument or instruction
159 // operand to chase the def-use chains of.
160 Value *Op = CF;
161 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
162 if (isa<Argument>(CI->getOperand(i)) ||
163 isa<Instruction>(CI->getOperand(i))) {
164 Op = CI->getOperand(i);
165 break;
166 }
167
168 // Identify all lexically identical calls in this function.
169 std::vector<CallInst*> IdenticalCalls;
170
171 Function *CIFunc = CI->getParent()->getParent();
172 for (Value::use_iterator UI = Op->use_begin(), E = Op->use_end(); UI != E;
173 ++UI)
174 if (CallInst *C = dyn_cast<CallInst>(*UI))
175 if (C->getNumOperands() == CI->getNumOperands() &&
176 C->getOperand(0) == CI->getOperand(0) &&
177 C->getParent()->getParent() == CIFunc && C != CI) {
178 bool AllOperandsEqual = true;
179 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
180 if (C->getOperand(i) != CI->getOperand(i)) {
181 AllOperandsEqual = false;
182 break;
183 }
184
185 if (AllOperandsEqual)
186 IdenticalCalls.push_back(C);
187 }
188
189 if (IdenticalCalls.empty()) return;
190
191 // Eliminate duplicates, which could occur if we chose a value that is passed
192 // into a call site multiple times.
193 std::sort(IdenticalCalls.begin(), IdenticalCalls.end());
194 IdenticalCalls.erase(std::unique(IdenticalCalls.begin(),IdenticalCalls.end()),
195 IdenticalCalls.end());
196
197 // If the call reads memory, we must make sure that there are no stores
198 // between the calls in question.
199 //
200 // FIXME: This should use mod/ref information. What we really care about it
201 // whether an intervening instruction could modify memory that is read, not
202 // ANY memory.
203 //
204 if (MRB == AliasAnalysis::OnlyReadsMemory) {
205 DominatorTree &DT = getAnalysis<DominatorTree>();
206 BasicBlock *CIBB = CI->getParent();
207 for (unsigned i = 0; i != IdenticalCalls.size(); ++i) {
208 CallInst *C = IdenticalCalls[i];
209 bool CantEqual = false;
210
211 if (DT.dominates(CIBB, C->getParent())) {
212 // FIXME: we currently only handle the case where both calls are in the
213 // same basic block.
214 if (CIBB != C->getParent()) {
215 CantEqual = true;
216 } else {
217 Instruction *First = CI, *Second = C;
218 if (!DT.dominates(CI, C))
219 std::swap(First, Second);
220
221 // Scan the instructions between the calls, checking for stores or
222 // calls to dangerous functions.
223 BasicBlock::iterator I = First;
224 for (++First; I != BasicBlock::iterator(Second); ++I) {
225 if (isa<StoreInst>(I)) {
226 // FIXME: We could use mod/ref information to make this much
227 // better!
228 CantEqual = true;
229 break;
230 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
Duncan Sands00b24b52007-12-01 07:51:45 +0000231 if (!AA.onlyReadsMemory(CI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 CantEqual = true;
233 break;
234 }
235 } else if (I->mayWriteToMemory()) {
236 CantEqual = true;
237 break;
238 }
239 }
240 }
241
242 } else if (DT.dominates(C->getParent(), CIBB)) {
243 // FIXME: We could implement this, but we don't for now.
244 CantEqual = true;
245 } else {
246 // FIXME: if one doesn't dominate the other, we can't tell yet.
247 CantEqual = true;
248 }
249
250
251 if (CantEqual) {
252 // This call does not produce the same value as the one in the query.
253 std::swap(IdenticalCalls[i--], IdenticalCalls.back());
254 IdenticalCalls.pop_back();
255 }
256 }
257 }
258
259 // Any calls that are identical and not destroyed will produce equal values!
260 for (unsigned i = 0, e = IdenticalCalls.size(); i != e; ++i)
261 RetVals.push_back(IdenticalCalls[i]);
262}
263
264// getEqualNumberNodes - Return nodes with the same value number as the
265// specified Value. This fills in the argument vector with any equal values.
266//
267void LoadVN::getEqualNumberNodes(Value *V,
268 std::vector<Value*> &RetVals) const {
269 // If the alias analysis has any must alias information to share with us, we
270 // can definitely use it.
271 if (isa<PointerType>(V->getType()))
272 getAnalysis<AliasAnalysis>().getMustAliases(V, RetVals);
273
274 if (!isa<LoadInst>(V)) {
275 if (CallInst *CI = dyn_cast<CallInst>(V))
276 getCallEqualNumberNodes(CI, RetVals);
277
278 // Not a load instruction? Just chain to the base value numbering
279 // implementation to satisfy the request...
280 assert(&getAnalysis<ValueNumbering>() != (ValueNumbering*)this &&
281 "getAnalysis() returned this!");
282
283 return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
284 }
285
286 // Volatile loads cannot be replaced with the value of other loads.
287 LoadInst *LI = cast<LoadInst>(V);
288 if (LI->isVolatile())
289 return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
290
291 Value *LoadPtr = LI->getOperand(0);
292 BasicBlock *LoadBB = LI->getParent();
293 Function *F = LoadBB->getParent();
294
295 // Find out how many bytes of memory are loaded by the load instruction...
Duncan Sandsf99fdc62007-11-01 20:53:16 +0000296 unsigned LoadSize = getAnalysis<TargetData>().getTypeStoreSize(LI->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
298
299 // Figure out if the load is invalidated from the entry of the block it is in
300 // until the actual instruction. This scans the block backwards from LI. If
301 // we see any candidate load or store instructions, then we know that the
302 // candidates have the same value # as LI.
303 bool LoadInvalidatedInBBBefore = false;
304 for (BasicBlock::iterator I = LI; I != LoadBB->begin(); ) {
305 --I;
306 if (I == LoadPtr) {
307 // If we run into an allocation of the value being loaded, then the
308 // contents are not initialized.
309 if (isa<AllocationInst>(I))
310 RetVals.push_back(UndefValue::get(LI->getType()));
311
312 // Otherwise, since this is the definition of what we are loading, this
313 // loaded value cannot occur before this block.
314 LoadInvalidatedInBBBefore = true;
315 break;
316 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
317 // If this instruction is a candidate load before LI, we know there are no
318 // invalidating instructions between it and LI, so they have the same
319 // value number.
320 if (LI->getOperand(0) == LoadPtr && !LI->isVolatile())
321 RetVals.push_back(I);
322 }
323
324 if (AA.getModRefInfo(I, LoadPtr, LoadSize) & AliasAnalysis::Mod) {
325 // If the invalidating instruction is a store, and its in our candidate
326 // set, then we can do store-load forwarding: the load has the same value
327 // # as the stored value.
328 if (StoreInst *SI = dyn_cast<StoreInst>(I))
329 if (SI->getOperand(1) == LoadPtr)
330 RetVals.push_back(I->getOperand(0));
331
332 LoadInvalidatedInBBBefore = true;
333 break;
334 }
335 }
336
337 // Figure out if the load is invalidated between the load and the exit of the
338 // block it is defined in. While we are scanning the current basic block, if
339 // we see any candidate loads, then we know they have the same value # as LI.
340 //
341 bool LoadInvalidatedInBBAfter = false;
342 {
343 BasicBlock::iterator I = LI;
344 for (++I; I != LoadBB->end(); ++I) {
345 // If this instruction is a load, then this instruction returns the same
346 // value as LI.
347 if (isa<LoadInst>(I) && cast<LoadInst>(I)->getOperand(0) == LoadPtr)
348 RetVals.push_back(I);
349
350 if (AA.getModRefInfo(I, LoadPtr, LoadSize) & AliasAnalysis::Mod) {
351 LoadInvalidatedInBBAfter = true;
352 break;
353 }
354 }
355 }
356
357 // If the pointer is clobbered on entry and on exit to the function, there is
358 // no need to do any global analysis at all.
359 if (LoadInvalidatedInBBBefore && LoadInvalidatedInBBAfter)
360 return;
361
362 // Now that we know the value is not neccesarily killed on entry or exit to
363 // the BB, find out how many load and store instructions (to this location)
364 // live in each BB in the function.
365 //
366 std::map<BasicBlock*, unsigned> CandidateLoads;
367 std::set<BasicBlock*> CandidateStores;
368
369 for (Value::use_iterator UI = LoadPtr->use_begin(), UE = LoadPtr->use_end();
370 UI != UE; ++UI)
371 if (LoadInst *Cand = dyn_cast<LoadInst>(*UI)) {// Is a load of source?
372 if (Cand->getParent()->getParent() == F && // In the same function?
373 // Not in LI's block?
374 Cand->getParent() != LoadBB && !Cand->isVolatile())
375 ++CandidateLoads[Cand->getParent()]; // Got one.
376 } else if (StoreInst *Cand = dyn_cast<StoreInst>(*UI)) {
377 if (Cand->getParent()->getParent() == F && !Cand->isVolatile() &&
378 Cand->getOperand(1) == LoadPtr) // It's a store THROUGH the ptr.
379 CandidateStores.insert(Cand->getParent());
380 }
381
382 // Get dominators.
383 DominatorTree &DT = getAnalysis<DominatorTree>();
384
385 // TransparentBlocks - For each basic block the load/store is alive across,
386 // figure out if the pointer is invalidated or not. If it is invalidated, the
387 // boolean is set to false, if it's not it is set to true. If we don't know
388 // yet, the entry is not in the map.
389 std::map<BasicBlock*, bool> TransparentBlocks;
390
391 // Loop over all of the basic blocks that also load the value. If the value
392 // is live across the CFG from the source to destination blocks, and if the
393 // value is not invalidated in either the source or destination blocks, add it
394 // to the equivalence sets.
395 for (std::map<BasicBlock*, unsigned>::iterator
396 I = CandidateLoads.begin(), E = CandidateLoads.end(); I != E; ++I) {
397 bool CantEqual = false;
398
399 // Right now we only can handle cases where one load dominates the other.
400 // FIXME: generalize this!
401 BasicBlock *BB1 = I->first, *BB2 = LoadBB;
402 if (DT.dominates(BB1, BB2)) {
403 // The other load dominates LI. If the loaded value is killed entering
404 // the LoadBB block, we know the load is not live.
405 if (LoadInvalidatedInBBBefore)
406 CantEqual = true;
407 } else if (DT.dominates(BB2, BB1)) {
408 std::swap(BB1, BB2); // Canonicalize
409 // LI dominates the other load. If the loaded value is killed exiting
410 // the LoadBB block, we know the load is not live.
411 if (LoadInvalidatedInBBAfter)
412 CantEqual = true;
413 } else {
414 // None of these loads can VN the same.
415 CantEqual = true;
416 }
417
418 if (!CantEqual) {
419 // Ok, at this point, we know that BB1 dominates BB2, and that there is
420 // nothing in the LI block that kills the loaded value. Check to see if
421 // the value is live across the CFG.
422 std::set<BasicBlock*> Visited;
423 for (pred_iterator PI = pred_begin(BB2), E = pred_end(BB2); PI!=E; ++PI)
424 if (!isPathTransparentTo(*PI, BB1, LoadPtr, LoadSize, AA,
425 Visited, TransparentBlocks)) {
426 // None of these loads can VN the same.
427 CantEqual = true;
428 break;
429 }
430 }
431
432 // If the loads can equal so far, scan the basic block that contains the
433 // loads under consideration to see if they are invalidated in the block.
434 // For any loads that are not invalidated, add them to the equivalence
435 // set!
436 if (!CantEqual) {
437 unsigned NumLoads = I->second;
438 if (BB1 == LoadBB) {
439 // If LI dominates the block in question, check to see if any of the
440 // loads in this block are invalidated before they are reached.
441 for (BasicBlock::iterator BBI = I->first->begin(); ; ++BBI) {
442 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
443 if (LI->getOperand(0) == LoadPtr && !LI->isVolatile()) {
444 // The load is in the set!
445 RetVals.push_back(BBI);
446 if (--NumLoads == 0) break; // Found last load to check.
447 }
448 } else if (AA.getModRefInfo(BBI, LoadPtr, LoadSize)
449 & AliasAnalysis::Mod) {
450 // If there is a modifying instruction, nothing below it will value
451 // # the same.
452 break;
453 }
454 }
455 } else {
456 // If the block dominates LI, make sure that the loads in the block are
457 // not invalidated before the block ends.
458 BasicBlock::iterator BBI = I->first->end();
459 while (1) {
460 --BBI;
461 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
462 if (LI->getOperand(0) == LoadPtr && !LI->isVolatile()) {
463 // The load is the same as this load!
464 RetVals.push_back(BBI);
465 if (--NumLoads == 0) break; // Found all of the laods.
466 }
467 } else if (AA.getModRefInfo(BBI, LoadPtr, LoadSize)
468 & AliasAnalysis::Mod) {
469 // If there is a modifying instruction, nothing above it will value
470 // # the same.
471 break;
472 }
473 }
474 }
475 }
476 }
477
478 // Handle candidate stores. If the loaded location is clobbered on entrance
479 // to the LoadBB, no store outside of the LoadBB can value number equal, so
480 // quick exit.
481 if (LoadInvalidatedInBBBefore)
482 return;
483
484 // Stores in the load-bb are handled above.
485 CandidateStores.erase(LoadBB);
486
487 for (std::set<BasicBlock*>::iterator I = CandidateStores.begin(),
488 E = CandidateStores.end(); I != E; ++I)
489 if (DT.dominates(*I, LoadBB)) {
490 BasicBlock *StoreBB = *I;
491
492 // Check to see if the path from the store to the load is transparent
493 // w.r.t. the memory location.
494 bool CantEqual = false;
495 std::set<BasicBlock*> Visited;
496 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
497 PI != E; ++PI)
498 if (!isPathTransparentTo(*PI, StoreBB, LoadPtr, LoadSize, AA,
499 Visited, TransparentBlocks)) {
500 // None of these stores can VN the same.
501 CantEqual = true;
502 break;
503 }
504 Visited.clear();
505 if (!CantEqual) {
506 // Okay, the path from the store block to the load block is clear, and
507 // we know that there are no invalidating instructions from the start
508 // of the load block to the load itself. Now we just scan the store
509 // block.
510
511 BasicBlock::iterator BBI = StoreBB->end();
512 while (1) {
513 assert(BBI != StoreBB->begin() &&
514 "There is a store in this block of the pointer, but the store"
515 " doesn't mod the address being stored to?? Must be a bug in"
516 " the alias analysis implementation!");
517 --BBI;
518 if (AA.getModRefInfo(BBI, LoadPtr, LoadSize) & AliasAnalysis::Mod) {
519 // If the invalidating instruction is one of the candidates,
520 // then it provides the value the load loads.
521 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
522 if (SI->getOperand(1) == LoadPtr)
523 RetVals.push_back(SI->getOperand(0));
524 break;
525 }
526 }
527 }
528 }
529}