When unifying instructions during a block diff, actually complain about
[oota-llvm.git] / tools / llvm-diff / DifferenceEngine.cpp
1 //===-- DifferenceEngine.cpp - Structural function/module comparison ------===//
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 //
10 // This header defines the interface to the LLVM difference engine,
11 // which structurally compares functions within a module.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include <utility>
16
17 #include <llvm/ADT/DenseMap.h>
18 #include <llvm/ADT/DenseSet.h>
19 #include <llvm/ADT/SmallVector.h>
20 #include <llvm/ADT/StringRef.h>
21 #include <llvm/ADT/StringSet.h>
22
23 #include <llvm/Module.h>
24 #include <llvm/Function.h>
25 #include <llvm/Instructions.h>
26 #include <llvm/Support/CFG.h>
27
28 #include <llvm/Support/raw_ostream.h>
29 #include <llvm/Support/type_traits.h>
30 #include <llvm/Support/ErrorHandling.h>
31 #include <llvm/Support/CallSite.h>
32
33 #include "DifferenceEngine.h"
34
35 using namespace llvm;
36
37 namespace {
38
39 /// A priority queue, implemented as a heap.
40 template <class T, class Sorter, unsigned InlineCapacity>
41 class PriorityQueue {
42   Sorter Precedes;
43   llvm::SmallVector<T, InlineCapacity> Storage;
44
45 public:
46   PriorityQueue(const Sorter &Precedes) : Precedes(Precedes) {}
47
48   /// Checks whether the heap is empty.
49   bool empty() const { return Storage.empty(); }
50
51   /// Insert a new value on the heap.
52   void insert(const T &V) {
53     unsigned Index = Storage.size();
54     Storage.push_back(V);
55     if (Index == 0) return;
56
57     T *data = Storage.data();
58     while (true) {
59       unsigned Target = (Index + 1) / 2 - 1;
60       if (!Precedes(data[Index], data[Target])) return;
61       std::swap(data[Index], data[Target]);
62       if (Target == 0) return;
63       Index = Target;
64     }
65   }
66
67   /// Remove the minimum value in the heap.  Only valid on a non-empty heap.
68   T remove_min() {
69     assert(!empty());
70     T tmp = Storage[0];
71     
72     unsigned NewSize = Storage.size() - 1;
73     if (NewSize) {
74       // Move the slot at the end to the beginning.
75       if (isPodLike<T>::value)
76         Storage[0] = Storage[NewSize];
77       else
78         std::swap(Storage[0], Storage[NewSize]);
79
80       // Bubble the root up as necessary.
81       unsigned Index = 0;
82       while (true) {
83         // With a 1-based index, the children would be Index*2 and Index*2+1.
84         unsigned R = (Index + 1) * 2;
85         unsigned L = R - 1;
86
87         // If R is out of bounds, we're done after this in any case.
88         if (R >= NewSize) {
89           // If L is also out of bounds, we're done immediately.
90           if (L >= NewSize) break;
91
92           // Otherwise, test whether we should swap L and Index.
93           if (Precedes(Storage[L], Storage[Index]))
94             std::swap(Storage[L], Storage[Index]);
95           break;
96         }
97
98         // Otherwise, we need to compare with the smaller of L and R.
99         // Prefer R because it's closer to the end of the array.
100         unsigned IndexToTest = (Precedes(Storage[L], Storage[R]) ? L : R);
101
102         // If Index is >= the min of L and R, then heap ordering is restored.
103         if (!Precedes(Storage[IndexToTest], Storage[Index]))
104           break;
105
106         // Otherwise, keep bubbling up.
107         std::swap(Storage[IndexToTest], Storage[Index]);
108         Index = IndexToTest;
109       }
110     }
111     Storage.pop_back();
112
113     return tmp;
114   }
115 };
116
117 /// A function-scope difference engine.
118 class FunctionDifferenceEngine {
119   DifferenceEngine &Engine;
120
121   /// The current mapping from old local values to new local values.
122   DenseMap<Value*, Value*> Values;
123
124   /// The current mapping from old blocks to new blocks.
125   DenseMap<BasicBlock*, BasicBlock*> Blocks;
126
127   DenseSet<std::pair<Value*, Value*> > TentativeValues;
128
129   unsigned getUnprocPredCount(BasicBlock *Block) const {
130     unsigned Count = 0;
131     for (pred_iterator I = pred_begin(Block), E = pred_end(Block); I != E; ++I)
132       if (!Blocks.count(*I)) Count++;
133     return Count;
134   }
135
136   typedef std::pair<BasicBlock*, BasicBlock*> BlockPair;
137
138   /// A type which sorts a priority queue by the number of unprocessed
139   /// predecessor blocks it has remaining.
140   ///
141   /// This is actually really expensive to calculate.
142   struct QueueSorter {
143     const FunctionDifferenceEngine &fde;
144     explicit QueueSorter(const FunctionDifferenceEngine &fde) : fde(fde) {}
145
146     bool operator()(const BlockPair &Old, const BlockPair &New) {
147       return fde.getUnprocPredCount(Old.first)
148            < fde.getUnprocPredCount(New.first);
149     }
150   };
151
152   /// A queue of unified blocks to process.
153   PriorityQueue<BlockPair, QueueSorter, 20> Queue;
154
155   /// Try to unify the given two blocks.  Enqueues them for processing
156   /// if they haven't already been processed.
157   ///
158   /// Returns true if there was a problem unifying them.
159   bool tryUnify(BasicBlock *L, BasicBlock *R) {
160     BasicBlock *&Ref = Blocks[L];
161
162     if (Ref) {
163       if (Ref == R) return false;
164
165       Engine.logf("successor %l cannot be equivalent to %r; "
166                   "it's already equivalent to %r")
167         << L << R << Ref;
168       return true;
169     }
170
171     Ref = R;
172     Queue.insert(BlockPair(L, R));
173     return false;
174   }
175
176   void processQueue() {
177     while (!Queue.empty()) {
178       BlockPair Pair = Queue.remove_min();
179       diff(Pair.first, Pair.second);
180     }
181   }
182
183   void diff(BasicBlock *L, BasicBlock *R) {
184     DifferenceEngine::Context C(Engine, L, R);
185
186     BasicBlock::iterator LI = L->begin(), LE = L->end();
187     BasicBlock::iterator RI = R->begin(), RE = R->end();
188
189     llvm::SmallVector<std::pair<Instruction*,Instruction*>, 20> TentativePairs;
190
191     do {
192       assert(LI != LE && RI != RE);
193       Instruction *LeftI = &*LI, *RightI = &*RI;
194
195       // If the instructions differ, start the more sophisticated diff
196       // algorithm at the start of the block.
197       if (diff(LeftI, RightI, false, true)) {
198         TentativeValues.clear();
199         return runBlockDiff(L->begin(), R->begin());
200       }
201
202       // Otherwise, tentatively unify them.
203       if (!LeftI->use_empty())
204         TentativeValues.insert(std::make_pair(LeftI, RightI));
205
206       ++LI, ++RI;
207     } while (LI != LE); // This is sufficient: we can't get equality of
208                         // terminators if there are residual instructions.
209
210     // Make all the tentative pairs solid.
211     for (llvm::DenseSet<std::pair<Value*,Value*> >::iterator
212            I = TentativeValues.begin(), E = TentativeValues.end(); I != E; ++I)
213       Values[I->first] = I->second;
214     TentativeValues.clear();
215   }
216
217   bool matchForBlockDiff(Instruction *L, Instruction *R);
218   void runBlockDiff(BasicBlock::iterator LI, BasicBlock::iterator RI);
219
220   bool diffCallSites(CallSite L, CallSite R, bool Complain) {
221     // FIXME: call attributes
222     if (!equivalentAsOperands(L.getCalledValue(), R.getCalledValue())) {
223       if (Complain) Engine.log("called functions differ");
224       return true;
225     }
226     if (L.arg_size() != R.arg_size()) {
227       if (Complain) Engine.log("argument counts differ");
228       return true;
229     }
230     for (unsigned I = 0, E = L.arg_size(); I != E; ++I)
231       if (!equivalentAsOperands(L.getArgument(I), R.getArgument(I))) {
232         if (Complain)
233           Engine.logf("arguments %l and %r differ")
234             << L.getArgument(I) << R.getArgument(I);
235         return true;
236       }
237     return false;
238   }
239
240   bool diff(Instruction *L, Instruction *R, bool Complain, bool TryUnify) {
241     // FIXME: metadata (if Complain is set)
242
243     // Different opcodes always imply different operations.
244     if (L->getOpcode() != R->getOpcode()) {
245       if (Complain) Engine.log("different instruction types");
246       return true;
247     }
248
249     if (isa<CmpInst>(L)) {
250       if (cast<CmpInst>(L)->getPredicate()
251             != cast<CmpInst>(R)->getPredicate()) {
252         if (Complain) Engine.log("different predicates");
253         return true;
254       }
255     } else if (isa<CallInst>(L)) {
256       return diffCallSites(CallSite(L), CallSite(R), Complain);
257     } else if (isa<PHINode>(L)) {
258       // FIXME: implement.
259
260       // This is really wierd;  type uniquing is broken?
261       if (L->getType() != R->getType()) {
262         if (!L->getType()->isPointerTy() || !R->getType()->isPointerTy()) {
263           if (Complain) Engine.log("different phi types");
264           return true;
265         }
266       }
267       return false;
268
269     // Terminators.
270     } else if (isa<InvokeInst>(L)) {
271       InvokeInst *LI = cast<InvokeInst>(L);
272       InvokeInst *RI = cast<InvokeInst>(R);
273       if (diffCallSites(CallSite(LI), CallSite(RI), Complain))
274         return true;
275
276       if (TryUnify) {
277         tryUnify(LI->getNormalDest(), RI->getNormalDest());
278         tryUnify(LI->getUnwindDest(), RI->getUnwindDest());
279       }
280       return false;
281
282     } else if (isa<BranchInst>(L)) {
283       BranchInst *LI = cast<BranchInst>(L);
284       BranchInst *RI = cast<BranchInst>(R);
285       if (LI->isConditional() != RI->isConditional()) {
286         if (Complain) Engine.log("branch conditionality differs");
287         return true;
288       }
289
290       if (LI->isConditional()) {
291         if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
292           if (Complain) Engine.log("branch conditions differ");
293           return true;
294         }
295         if (TryUnify) tryUnify(LI->getSuccessor(1), RI->getSuccessor(1));
296       }
297       if (TryUnify) tryUnify(LI->getSuccessor(0), RI->getSuccessor(0));
298       return false;
299
300     } else if (isa<SwitchInst>(L)) {
301       SwitchInst *LI = cast<SwitchInst>(L);
302       SwitchInst *RI = cast<SwitchInst>(R);
303       if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
304         if (Complain) Engine.log("switch conditions differ");
305         return true;
306       }
307       if (TryUnify) tryUnify(LI->getDefaultDest(), RI->getDefaultDest());
308
309       bool Difference = false;
310
311       DenseMap<ConstantInt*,BasicBlock*> LCases;
312       for (unsigned I = 1, E = LI->getNumCases(); I != E; ++I)
313         LCases[LI->getCaseValue(I)] = LI->getSuccessor(I);
314       for (unsigned I = 1, E = RI->getNumCases(); I != E; ++I) {
315         ConstantInt *CaseValue = RI->getCaseValue(I);
316         BasicBlock *LCase = LCases[CaseValue];
317         if (LCase) {
318           if (TryUnify) tryUnify(LCase, RI->getSuccessor(I));
319           LCases.erase(CaseValue);
320         } else if (!Difference) {
321           if (Complain)
322             Engine.logf("right switch has extra case %r") << CaseValue;
323           Difference = true;
324         }
325       }
326       if (!Difference)
327         for (DenseMap<ConstantInt*,BasicBlock*>::iterator
328                I = LCases.begin(), E = LCases.end(); I != E; ++I) {
329           if (Complain)
330             Engine.logf("left switch has extra case %l") << I->first;
331           Difference = true;
332         }
333       return Difference;
334     } else if (isa<UnreachableInst>(L)) {
335       return false;
336     }
337
338     if (L->getNumOperands() != R->getNumOperands()) {
339       if (Complain) Engine.log("instructions have different operand counts");
340       return true;
341     }
342
343     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
344       Value *LO = L->getOperand(I), *RO = R->getOperand(I);
345       if (!equivalentAsOperands(LO, RO)) {
346         if (Complain) Engine.logf("operands %l and %r differ") << LO << RO;
347         return true;
348       }
349     }
350
351     return false;
352   }
353
354   bool equivalentAsOperands(Constant *L, Constant *R) {
355     // Use equality as a preliminary filter.
356     if (L == R)
357       return true;
358
359     if (L->getValueID() != R->getValueID())
360       return false;
361     
362     // Ask the engine about global values.
363     if (isa<GlobalValue>(L))
364       return Engine.equivalentAsOperands(cast<GlobalValue>(L),
365                                          cast<GlobalValue>(R));
366
367     // Compare constant expressions structurally.
368     if (isa<ConstantExpr>(L))
369       return equivalentAsOperands(cast<ConstantExpr>(L),
370                                   cast<ConstantExpr>(R));
371
372     // Nulls of the "same type" don't always actually have the same
373     // type; I don't know why.  Just white-list them.
374     if (isa<ConstantPointerNull>(L))
375       return true;
376
377     // Block addresses only match if we've already encountered the
378     // block.  FIXME: tentative matches?
379     if (isa<BlockAddress>(L))
380       return Blocks[cast<BlockAddress>(L)->getBasicBlock()]
381                  == cast<BlockAddress>(R)->getBasicBlock();
382
383     return false;
384   }
385
386   bool equivalentAsOperands(ConstantExpr *L, ConstantExpr *R) {
387     if (L == R)
388       return true;
389     if (L->getOpcode() != R->getOpcode())
390       return false;
391
392     switch (L->getOpcode()) {
393     case Instruction::ICmp:
394     case Instruction::FCmp:
395       if (L->getPredicate() != R->getPredicate())
396         return false;
397       break;
398
399     case Instruction::GetElementPtr:
400       // FIXME: inbounds?
401       break;
402
403     default:
404       break;
405     }
406
407     if (L->getNumOperands() != R->getNumOperands())
408       return false;
409
410     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I)
411       if (!equivalentAsOperands(L->getOperand(I), R->getOperand(I)))
412         return false;
413
414     return true;
415   }
416
417   bool equivalentAsOperands(Value *L, Value *R) {
418     // Fall out if the values have different kind.
419     // This possibly shouldn't take priority over oracles.
420     if (L->getValueID() != R->getValueID())
421       return false;
422
423     // Value subtypes:  Argument, Constant, Instruction, BasicBlock,
424     //                  InlineAsm, MDNode, MDString, PseudoSourceValue
425
426     if (isa<Constant>(L))
427       return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R));
428
429     if (isa<Instruction>(L))
430       return Values[L] == R || TentativeValues.count(std::make_pair(L, R));
431
432     if (isa<Argument>(L))
433       return Values[L] == R;
434
435     if (isa<BasicBlock>(L))
436       return Blocks[cast<BasicBlock>(L)] != R;
437
438     // Pretend everything else is identical.
439     return true;
440   }
441
442   // Avoid a gcc warning about accessing 'this' in an initializer.
443   FunctionDifferenceEngine *this_() { return this; }
444
445 public:
446   FunctionDifferenceEngine(DifferenceEngine &Engine) :
447     Engine(Engine), Queue(QueueSorter(*this_())) {}
448
449   void diff(Function *L, Function *R) {
450     if (L->arg_size() != R->arg_size())
451       Engine.log("different argument counts");
452
453     // Map the arguments.
454     for (Function::arg_iterator
455            LI = L->arg_begin(), LE = L->arg_end(),
456            RI = R->arg_begin(), RE = R->arg_end();
457          LI != LE && RI != RE; ++LI, ++RI)
458       Values[&*LI] = &*RI;
459
460     tryUnify(&*L->begin(), &*R->begin());
461     processQueue();
462   }
463 };
464
465 struct DiffEntry {
466   DiffEntry() : Cost(0) {}
467
468   unsigned Cost;
469   llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange
470 };
471
472 bool FunctionDifferenceEngine::matchForBlockDiff(Instruction *L,
473                                                  Instruction *R) {
474   return !diff(L, R, false, false);
475 }
476
477 void FunctionDifferenceEngine::runBlockDiff(BasicBlock::iterator LStart,
478                                             BasicBlock::iterator RStart) {
479   BasicBlock::iterator LE = LStart->getParent()->end();
480   BasicBlock::iterator RE = RStart->getParent()->end();
481
482   unsigned NL = std::distance(LStart, LE);
483
484   SmallVector<DiffEntry, 20> Paths1(NL+1);
485   SmallVector<DiffEntry, 20> Paths2(NL+1);
486
487   DiffEntry *Cur = Paths1.data();
488   DiffEntry *Next = Paths2.data();
489
490   const unsigned LeftCost = 2;
491   const unsigned RightCost = 2;
492   const unsigned MatchCost = 0;
493
494   assert(TentativeValues.empty());
495
496   // Initialize the first column.
497   for (unsigned I = 0; I != NL+1; ++I) {
498     Cur[I].Cost = I * LeftCost;
499     for (unsigned J = 0; J != I; ++J)
500       Cur[I].Path.push_back(DifferenceEngine::DC_left);
501   }
502
503   for (BasicBlock::iterator RI = RStart; RI != RE; ++RI) {
504     // Initialize the first row.
505     Next[0] = Cur[0];
506     Next[0].Cost += RightCost;
507     Next[0].Path.push_back(DifferenceEngine::DC_right);
508
509     unsigned Index = 1;
510     for (BasicBlock::iterator LI = LStart; LI != LE; ++LI, ++Index) {
511       if (matchForBlockDiff(&*LI, &*RI)) {
512         Next[Index] = Cur[Index-1];
513         Next[Index].Cost += MatchCost;
514         Next[Index].Path.push_back(DifferenceEngine::DC_match);
515         TentativeValues.insert(std::make_pair(&*LI, &*RI));
516       } else if (Next[Index-1].Cost <= Cur[Index].Cost) {
517         Next[Index] = Next[Index-1];
518         Next[Index].Cost += LeftCost;
519         Next[Index].Path.push_back(DifferenceEngine::DC_left);
520       } else {
521         Next[Index] = Cur[Index];
522         Next[Index].Cost += RightCost;
523         Next[Index].Path.push_back(DifferenceEngine::DC_right);
524       }
525     }
526
527     std::swap(Cur, Next);
528   }
529
530   SmallVectorImpl<char> &Path = Cur[NL].Path;
531   BasicBlock::iterator LI = LStart, RI = RStart;
532
533   DifferenceEngine::DiffLogBuilder Diff(Engine);
534
535   // Drop trailing matches.
536   while (Path.back() == DifferenceEngine::DC_match)
537     Path.pop_back();
538
539   // Skip leading matches.
540   SmallVectorImpl<char>::iterator
541     PI = Path.begin(), PE = Path.end();
542   while (PI != PE && *PI == DifferenceEngine::DC_match)
543     ++PI, ++LI, ++RI;
544
545   for (; PI != PE; ++PI) {
546     switch (static_cast<DifferenceEngine::DiffChange>(*PI)) {
547     case DifferenceEngine::DC_match:
548       assert(LI != LE && RI != RE);
549       {
550         Instruction *L = &*LI, *R = &*RI;
551         DifferenceEngine::Context C(Engine, L, R);
552         diff(L, R, true, true); // complain and unify successors
553         Values[L] = R; // make non-tentative
554         Diff.addMatch(L, R);
555       }
556       ++LI; ++RI;
557       break;
558
559     case DifferenceEngine::DC_left:
560       assert(LI != LE);
561       Diff.addLeft(&*LI);
562       ++LI;
563       break;
564
565     case DifferenceEngine::DC_right:
566       assert(RI != RE);
567       Diff.addRight(&*RI);
568       ++RI;
569       break;
570     }
571   }
572
573   TentativeValues.clear();
574 }
575
576 }
577
578 void DifferenceEngine::diff(Function *L, Function *R) {
579   Context C(*this, L, R);
580
581   // FIXME: types
582   // FIXME: attributes and CC
583   // FIXME: parameter attributes
584   
585   // If both are declarations, we're done.
586   if (L->empty() && R->empty())
587     return;
588   else if (L->empty())
589     log("left function is declaration, right function is definition");
590   else if (R->empty())
591     log("right function is declaration, left function is definition");
592   else
593     FunctionDifferenceEngine(*this).diff(L, R);
594 }
595
596 void DifferenceEngine::diff(Module *L, Module *R) {
597   StringSet<> LNames;
598   SmallVector<std::pair<Function*,Function*>, 20> Queue;
599
600   for (Module::iterator I = L->begin(), E = L->end(); I != E; ++I) {
601     Function *LFn = &*I;
602     LNames.insert(LFn->getName());
603
604     if (Function *RFn = R->getFunction(LFn->getName()))
605       Queue.push_back(std::make_pair(LFn, RFn));
606     else
607       logf("function %l exists only in left module") << LFn;
608   }
609
610   for (Module::iterator I = R->begin(), E = R->end(); I != E; ++I) {
611     Function *RFn = &*I;
612     if (!LNames.count(RFn->getName()))
613       logf("function %r exists only in right module") << RFn;
614   }
615
616   for (SmallVectorImpl<std::pair<Function*,Function*> >::iterator
617          I = Queue.begin(), E = Queue.end(); I != E; ++I)
618     diff(I->first, I->second);
619 }
620
621 bool DifferenceEngine::equivalentAsOperands(GlobalValue *L, GlobalValue *R) {
622   if (globalValueOracle) return (*globalValueOracle)(L, R);
623   return L->getName() == R->getName();
624 }