Implement test/Regression/Transforms/GCSE/undefined_load.ll
[oota-llvm.git] / lib / Analysis / LoadValueNumbering.cpp
1 //===- LoadValueNumbering.cpp - Load Value #'ing Implementation -*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
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/Constant.h"
26 #include "llvm/Function.h"
27 #include "llvm/iMemory.h"
28 #include "llvm/iOther.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Type.h"
31 #include "llvm/Analysis/ValueNumbering.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/Dominators.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Target/TargetData.h"
36 #include <set>
37 using namespace llvm;
38
39 namespace {
40   // FIXME: This should not be a FunctionPass.
41   struct LoadVN : public FunctionPass, public ValueNumbering {
42     
43     /// Pass Implementation stuff.  This doesn't do any analysis.
44     ///
45     bool runOnFunction(Function &) { return false; }
46     
47     /// getAnalysisUsage - Does not modify anything.  It uses Value Numbering
48     /// and Alias Analysis.
49     ///
50     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
51     
52     /// getEqualNumberNodes - Return nodes with the same value number as the
53     /// specified Value.  This fills in the argument vector with any equal
54     /// values.
55     ///
56     virtual void getEqualNumberNodes(Value *V1,
57                                      std::vector<Value*> &RetVals) const;
58
59     /// getCallEqualNumberNodes - Given a call instruction, find other calls
60     /// that have the same value number.
61     void getCallEqualNumberNodes(CallInst *CI,
62                                  std::vector<Value*> &RetVals) const;
63   };
64
65   // Register this pass...
66   RegisterOpt<LoadVN> X("load-vn", "Load Value Numbering");
67
68   // Declare that we implement the ValueNumbering interface
69   RegisterAnalysisGroup<ValueNumbering, LoadVN> Y;
70 }
71
72 Pass *llvm::createLoadValueNumberingPass() { return new LoadVN(); }
73
74
75 /// getAnalysisUsage - Does not modify anything.  It uses Value Numbering and
76 /// Alias Analysis.
77 ///
78 void LoadVN::getAnalysisUsage(AnalysisUsage &AU) const {
79   AU.setPreservesAll();
80   AU.addRequired<AliasAnalysis>();
81   AU.addRequired<ValueNumbering>();
82   AU.addRequired<DominatorSet>();
83   AU.addRequired<TargetData>();
84 }
85
86 static bool isPathTransparentTo(BasicBlock *CurBlock, BasicBlock *Dom,
87                                 Value *Ptr, unsigned Size, AliasAnalysis &AA,
88                                 std::set<BasicBlock*> &Visited,
89                                 std::map<BasicBlock*, bool> &TransparentBlocks){
90   // If we have already checked out this path, or if we reached our destination,
91   // stop searching, returning success.
92   if (CurBlock == Dom || !Visited.insert(CurBlock).second)
93     return true;
94   
95   // Check whether this block is known transparent or not.
96   std::map<BasicBlock*, bool>::iterator TBI =
97     TransparentBlocks.lower_bound(CurBlock);
98
99   if (TBI == TransparentBlocks.end() || TBI->first != CurBlock) {
100     // If this basic block can modify the memory location, then the path is not
101     // transparent!
102     if (AA.canBasicBlockModify(*CurBlock, Ptr, Size)) {
103       TransparentBlocks.insert(TBI, std::make_pair(CurBlock, false));
104       return false;
105     }
106       TransparentBlocks.insert(TBI, std::make_pair(CurBlock, true));
107   } else if (!TBI->second)
108     // This block is known non-transparent, so that path can't be either.
109     return false;
110   
111   // The current block is known to be transparent.  The entire path is
112   // transparent if all of the predecessors paths to the parent is also
113   // transparent to the memory location.
114   for (pred_iterator PI = pred_begin(CurBlock), E = pred_end(CurBlock);
115        PI != E; ++PI)
116     if (!isPathTransparentTo(*PI, Dom, Ptr, Size, AA, Visited,
117                              TransparentBlocks))
118       return false;
119   return true;
120 }
121
122 /// getCallEqualNumberNodes - Given a call instruction, find other calls that
123 /// have the same value number.
124 void LoadVN::getCallEqualNumberNodes(CallInst *CI,
125                                      std::vector<Value*> &RetVals) const {
126   Function *CF = CI->getCalledFunction();
127   if (CF == 0) return;  // Indirect call.
128   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
129   if (!AA.onlyReadsMemory(CF)) return;  // Nothing we can do.
130
131   // Scan all of the arguments of the function, looking for one that is not
132   // global.  In particular, we would prefer to have an argument or instruction
133   // operand to chase the def-use chains of.
134   Value *Op = CF;
135   for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
136     if (isa<Argument>(CI->getOperand(i)) ||
137         isa<Instruction>(CI->getOperand(i))) {
138       Op = CI->getOperand(i);
139       break;
140     }
141
142   // Identify all lexically identical calls in this function.
143   std::vector<CallInst*> IdenticalCalls;
144
145   Function *CIFunc = CI->getParent()->getParent();
146   for (Value::use_iterator UI = Op->use_begin(), E = Op->use_end(); UI != E;
147        ++UI)
148     if (CallInst *C = dyn_cast<CallInst>(*UI))
149       if (C->getNumOperands() == CI->getNumOperands() &&
150           C->getOperand(0) == CI->getOperand(0) &&
151           C->getParent()->getParent() == CIFunc && C != CI) {
152         bool AllOperandsEqual = true;
153         for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
154           if (C->getOperand(i) != CI->getOperand(i)) {
155             AllOperandsEqual = false;
156             break;
157           }
158
159         if (AllOperandsEqual)
160           IdenticalCalls.push_back(C);
161       }
162   
163   if (IdenticalCalls.empty()) return;
164
165   // Eliminate duplicates, which could occur if we chose a value that is passed
166   // into a call site multiple times.
167   std::sort(IdenticalCalls.begin(), IdenticalCalls.end());
168   IdenticalCalls.erase(std::unique(IdenticalCalls.begin(),IdenticalCalls.end()),
169                        IdenticalCalls.end());
170
171   // If the call reads memory, we must make sure that there are no stores
172   // between the calls in question.
173   //
174   // FIXME: This should use mod/ref information.  What we really care about it
175   // whether an intervening instruction could modify memory that is read, not
176   // ANY memory.
177   //
178   if (!AA.doesNotAccessMemory(CF)) {
179     DominatorSet &DomSetInfo = getAnalysis<DominatorSet>();
180     BasicBlock *CIBB = CI->getParent();
181     for (unsigned i = 0; i != IdenticalCalls.size(); ++i) {
182       CallInst *C = IdenticalCalls[i];
183       bool CantEqual = false;
184
185       if (DomSetInfo.dominates(CIBB, C->getParent())) {
186         // FIXME: we currently only handle the case where both calls are in the
187         // same basic block.
188         if (CIBB != C->getParent()) {
189           CantEqual = true;
190         } else {
191           Instruction *First = CI, *Second = C;
192           if (!DomSetInfo.dominates(CI, C))
193             std::swap(First, Second);
194           
195           // Scan the instructions between the calls, checking for stores or
196           // calls to dangerous functions.
197           BasicBlock::iterator I = First;
198           for (++First; I != BasicBlock::iterator(Second); ++I) {
199             if (isa<StoreInst>(I)) {
200               // FIXME: We could use mod/ref information to make this much
201               // better!
202               CantEqual = true;
203               break;
204             } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
205               if (CI->getCalledFunction() == 0 ||
206                   !AA.onlyReadsMemory(CI->getCalledFunction())) {
207                 CantEqual = true;
208                 break;
209               }
210             } else if (I->mayWriteToMemory()) {
211               CantEqual = true;
212               break;
213             }
214           }
215         }
216
217       } else if (DomSetInfo.dominates(C->getParent(), CIBB)) {
218         // FIXME: We could implement this, but we don't for now.
219         CantEqual = true;
220       } else {
221         // FIXME: if one doesn't dominate the other, we can't tell yet.
222         CantEqual = true;
223       }
224
225
226       if (CantEqual) {
227         // This call does not produce the same value as the one in the query.
228         std::swap(IdenticalCalls[i--], IdenticalCalls.back());
229         IdenticalCalls.pop_back();
230       }
231     }
232   }
233
234   // Any calls that are identical and not destroyed will produce equal values!
235   for (unsigned i = 0, e = IdenticalCalls.size(); i != e; ++i)
236     RetVals.push_back(IdenticalCalls[i]);
237 }
238
239 // getEqualNumberNodes - Return nodes with the same value number as the
240 // specified Value.  This fills in the argument vector with any equal values.
241 //
242 void LoadVN::getEqualNumberNodes(Value *V,
243                                  std::vector<Value*> &RetVals) const {
244   // If the alias analysis has any must alias information to share with us, we
245   // can definitely use it.
246   if (isa<PointerType>(V->getType()))
247     getAnalysis<AliasAnalysis>().getMustAliases(V, RetVals);
248
249   if (!isa<LoadInst>(V)) {
250     if (CallInst *CI = dyn_cast<CallInst>(V))
251       getCallEqualNumberNodes(CI, RetVals);
252
253     // Not a load instruction?  Just chain to the base value numbering
254     // implementation to satisfy the request...
255     assert(&getAnalysis<ValueNumbering>() != (ValueNumbering*)this &&
256            "getAnalysis() returned this!");
257
258     return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
259   }
260
261   // Volatile loads cannot be replaced with the value of other loads.
262   LoadInst *LI = cast<LoadInst>(V);
263   if (LI->isVolatile())
264     return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
265   
266   // If we have a load instruction, find all of the load and store instructions
267   // that use the same source operand.  We implement this recursively, because
268   // there could be a load of a load of a load that are all identical.  We are
269   // guaranteed that this cannot be an infinite recursion because load
270   // instructions would have to pass through a PHI node in order for there to be
271   // a cycle.  The PHI node would be handled by the else case here, breaking the
272   // infinite recursion.
273   //
274   std::vector<Value*> PointerSources;
275   getEqualNumberNodes(LI->getOperand(0), PointerSources);
276   PointerSources.push_back(LI->getOperand(0));
277   
278   BasicBlock *LoadBB = LI->getParent();
279   Function *F = LoadBB->getParent();
280   
281   // Now that we know the set of equivalent source pointers for the load
282   // instruction, look to see if there are any load or store candidates that are
283   // identical.
284   //
285   std::map<BasicBlock*, std::vector<LoadInst*> >  CandidateLoads;
286   std::map<BasicBlock*, std::vector<StoreInst*> > CandidateStores;
287   std::set<AllocationInst*> Allocations;
288   
289   while (!PointerSources.empty()) {
290     Value *Source = PointerSources.back();
291     PointerSources.pop_back();                // Get a source pointer...
292
293     if (AllocationInst *AI = dyn_cast<AllocationInst>(Source))
294       Allocations.insert(AI);
295     
296     for (Value::use_iterator UI = Source->use_begin(), UE = Source->use_end();
297          UI != UE; ++UI)
298       if (LoadInst *Cand = dyn_cast<LoadInst>(*UI)) {// Is a load of source?
299         if (Cand->getParent()->getParent() == F &&   // In the same function?
300             Cand != LI && !Cand->isVolatile())       // Not LI itself?
301           CandidateLoads[Cand->getParent()].push_back(Cand);     // Got one...
302       } else if (StoreInst *Cand = dyn_cast<StoreInst>(*UI)) {
303         if (Cand->getParent()->getParent() == F && !Cand->isVolatile() &&
304             Cand->getOperand(1) == Source)  // It's a store THROUGH the ptr...
305           CandidateStores[Cand->getParent()].push_back(Cand);
306       }
307   }
308   
309   // Get alias analysis & dominators.
310   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
311   DominatorSet &DomSetInfo = getAnalysis<DominatorSet>();
312   Value *LoadPtr = LI->getOperand(0);
313   // Find out how many bytes of memory are loaded by the load instruction...
314   unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(LI->getType());
315
316   // Find all of the candidate loads and stores that are in the same block as
317   // the defining instruction.
318   std::set<Instruction*> Instrs;
319   Instrs.insert(CandidateLoads[LoadBB].begin(), CandidateLoads[LoadBB].end());
320   CandidateLoads.erase(LoadBB);
321   Instrs.insert(CandidateStores[LoadBB].begin(), CandidateStores[LoadBB].end());
322   CandidateStores.erase(LoadBB);
323
324   // Figure out if the load is invalidated from the entry of the block it is in
325   // until the actual instruction.  This scans the block backwards from LI.  If
326   // we see any candidate load or store instructions, then we know that the
327   // candidates have the same value # as LI.
328   bool LoadInvalidatedInBBBefore = false;
329   for (BasicBlock::iterator I = LI; I != LoadBB->begin(); ) {
330     --I;
331     // If this instruction is a candidate load before LI, we know there are no
332     // invalidating instructions between it and LI, so they have the same value
333     // number.
334     if (isa<LoadInst>(I) && Instrs.count(I)) {
335       RetVals.push_back(I);
336       Instrs.erase(I);
337     } else if (AllocationInst *AI = dyn_cast<AllocationInst>(I)) {
338       // If we run into an allocation of the value being loaded, then the
339       // contenxt are not initialized.  We can return any value, so we will
340       // return a zero.
341       if (Allocations.count(AI)) {
342         LoadInvalidatedInBBBefore = true;
343         RetVals.push_back(Constant::getNullValue(LI->getType()));
344         break;
345       }
346     }
347
348     if (AA.getModRefInfo(I, LoadPtr, LoadSize) & AliasAnalysis::Mod) {
349       // If the invalidating instruction is a store, and its in our candidate
350       // set, then we can do store-load forwarding: the load has the same value
351       // # as the stored value.
352       if (isa<StoreInst>(I) && Instrs.count(I)) {
353         Instrs.erase(I);
354         RetVals.push_back(I->getOperand(0));
355       }
356
357       LoadInvalidatedInBBBefore = true;
358       break;
359     }
360   }
361
362   // Figure out if the load is invalidated between the load and the exit of the
363   // block it is defined in.  While we are scanning the current basic block, if
364   // we see any candidate loads, then we know they have the same value # as LI.
365   //
366   bool LoadInvalidatedInBBAfter = false;
367   for (BasicBlock::iterator I = LI->getNext(); I != LoadBB->end(); ++I) {
368     // If this instruction is a load, then this instruction returns the same
369     // value as LI.
370     if (isa<LoadInst>(I) && Instrs.count(I)) {
371       RetVals.push_back(I);
372       Instrs.erase(I);
373     }
374
375     if (AA.getModRefInfo(I, LoadPtr, LoadSize) & AliasAnalysis::Mod) {
376       LoadInvalidatedInBBAfter = true;
377       break;
378     }
379   }
380
381   // If there is anything left in the Instrs set, it could not possibly equal
382   // LI.
383   Instrs.clear();
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*, std::vector<LoadInst*> >::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 (DomSetInfo.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 (DomSetInfo.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       Instrs.insert(I->second.begin(), I->second.end());
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 (isa<LoadInst>(BBI) && Instrs.count(BBI)) {
443             // The load is in the set!
444             RetVals.push_back(BBI);
445             Instrs.erase(BBI);
446             if (Instrs.empty()) break;
447           } else if (AA.getModRefInfo(BBI, LoadPtr, LoadSize)
448                              & AliasAnalysis::Mod) {
449             // If there is a modifying instruction, nothing below it will value
450             // # the same.
451             break;
452           }
453         }
454       } else {
455         // If the block dominates LI, make sure that the loads in the block are
456         // not invalidated before the block ends.
457         BasicBlock::iterator BBI = I->first->end();
458         while (1) {
459           --BBI;
460           if (isa<LoadInst>(BBI) && Instrs.count(BBI)) {
461             // The load is in the set!
462             RetVals.push_back(BBI);
463             Instrs.erase(BBI);
464             if (Instrs.empty()) break;
465           } else if (AA.getModRefInfo(BBI, LoadPtr, LoadSize)
466                              & AliasAnalysis::Mod) {
467             // If there is a modifying instruction, nothing above it will value
468             // # the same.
469             break;
470           }
471         }
472       }
473
474       Instrs.clear();
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   for (std::map<BasicBlock*, std::vector<StoreInst*> >::iterator
485          I = CandidateStores.begin(), E = CandidateStores.end(); I != E; ++I)
486     if (DomSetInfo.dominates(I->first, LoadBB)) {
487       // Check to see if the path from the store to the load is transparent
488       // w.r.t. the memory location.
489       bool CantEqual = false;
490       std::set<BasicBlock*> Visited;
491       for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
492            PI != E; ++PI)
493         if (!isPathTransparentTo(*PI, I->first, LoadPtr, LoadSize, AA,
494                                  Visited, TransparentBlocks)) {
495           // None of these stores can VN the same.
496           CantEqual = true;
497           break;
498         }
499       Visited.clear();
500       if (!CantEqual) {
501         // Okay, the path from the store block to the load block is clear, and
502         // we know that there are no invalidating instructions from the start
503         // of the load block to the load itself.  Now we just scan the store
504         // block.
505
506         BasicBlock::iterator BBI = I->first->end();
507         while (1) {
508           --BBI;
509           if (AA.getModRefInfo(BBI, LoadPtr, LoadSize)& AliasAnalysis::Mod){
510             // If the invalidating instruction is one of the candidates,
511             // then it provides the value the load loads.
512             if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
513               if (std::find(I->second.begin(), I->second.end(), SI) !=
514                   I->second.end())
515                 RetVals.push_back(SI->getOperand(0));
516             break;
517           }
518         }
519       }
520     }
521 }