1 //===-- DifferenceEngine.cpp - Structural function/module comparison ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the implementation of the LLVM difference
11 // engine, which structurally compares global values within a module.
13 //===----------------------------------------------------------------------===//
15 #include "DifferenceEngine.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/Support/CallSite.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/type_traits.h"
37 /// A priority queue, implemented as a heap.
38 template <class T, class Sorter, unsigned InlineCapacity>
41 llvm::SmallVector<T, InlineCapacity> Storage;
44 PriorityQueue(const Sorter &Precedes) : Precedes(Precedes) {}
46 /// Checks whether the heap is empty.
47 bool empty() const { return Storage.empty(); }
49 /// Insert a new value on the heap.
50 void insert(const T &V) {
51 unsigned Index = Storage.size();
53 if (Index == 0) return;
55 T *data = Storage.data();
57 unsigned Target = (Index + 1) / 2 - 1;
58 if (!Precedes(data[Index], data[Target])) return;
59 std::swap(data[Index], data[Target]);
60 if (Target == 0) return;
65 /// Remove the minimum value in the heap. Only valid on a non-empty heap.
70 unsigned NewSize = Storage.size() - 1;
72 // Move the slot at the end to the beginning.
73 if (isPodLike<T>::value)
74 Storage[0] = Storage[NewSize];
76 std::swap(Storage[0], Storage[NewSize]);
78 // Bubble the root up as necessary.
81 // With a 1-based index, the children would be Index*2 and Index*2+1.
82 unsigned R = (Index + 1) * 2;
85 // If R is out of bounds, we're done after this in any case.
87 // If L is also out of bounds, we're done immediately.
88 if (L >= NewSize) break;
90 // Otherwise, test whether we should swap L and Index.
91 if (Precedes(Storage[L], Storage[Index]))
92 std::swap(Storage[L], Storage[Index]);
96 // Otherwise, we need to compare with the smaller of L and R.
97 // Prefer R because it's closer to the end of the array.
98 unsigned IndexToTest = (Precedes(Storage[L], Storage[R]) ? L : R);
100 // If Index is >= the min of L and R, then heap ordering is restored.
101 if (!Precedes(Storage[IndexToTest], Storage[Index]))
104 // Otherwise, keep bubbling up.
105 std::swap(Storage[IndexToTest], Storage[Index]);
115 /// A function-scope difference engine.
116 class FunctionDifferenceEngine {
117 DifferenceEngine &Engine;
119 /// The current mapping from old local values to new local values.
120 DenseMap<Value*, Value*> Values;
122 /// The current mapping from old blocks to new blocks.
123 DenseMap<BasicBlock*, BasicBlock*> Blocks;
125 DenseSet<std::pair<Value*, Value*> > TentativeValues;
127 unsigned getUnprocPredCount(BasicBlock *Block) const {
129 for (pred_iterator I = pred_begin(Block), E = pred_end(Block); I != E; ++I)
130 if (!Blocks.count(*I)) Count++;
134 typedef std::pair<BasicBlock*, BasicBlock*> BlockPair;
136 /// A type which sorts a priority queue by the number of unprocessed
137 /// predecessor blocks it has remaining.
139 /// This is actually really expensive to calculate.
141 const FunctionDifferenceEngine &fde;
142 explicit QueueSorter(const FunctionDifferenceEngine &fde) : fde(fde) {}
144 bool operator()(const BlockPair &Old, const BlockPair &New) {
145 return fde.getUnprocPredCount(Old.first)
146 < fde.getUnprocPredCount(New.first);
150 /// A queue of unified blocks to process.
151 PriorityQueue<BlockPair, QueueSorter, 20> Queue;
153 /// Try to unify the given two blocks. Enqueues them for processing
154 /// if they haven't already been processed.
156 /// Returns true if there was a problem unifying them.
157 bool tryUnify(BasicBlock *L, BasicBlock *R) {
158 BasicBlock *&Ref = Blocks[L];
161 if (Ref == R) return false;
163 Engine.logf("successor %l cannot be equivalent to %r; "
164 "it's already equivalent to %r")
170 Queue.insert(BlockPair(L, R));
174 /// Unifies two instructions, given that they're known not to have
175 /// structural differences.
176 void unify(Instruction *L, Instruction *R) {
177 DifferenceEngine::Context C(Engine, L, R);
179 bool Result = diff(L, R, true, true);
180 assert(!Result && "structural differences second time around?");
186 void processQueue() {
187 while (!Queue.empty()) {
188 BlockPair Pair = Queue.remove_min();
189 diff(Pair.first, Pair.second);
193 void diff(BasicBlock *L, BasicBlock *R) {
194 DifferenceEngine::Context C(Engine, L, R);
196 BasicBlock::iterator LI = L->begin(), LE = L->end();
197 BasicBlock::iterator RI = R->begin(), RE = R->end();
199 llvm::SmallVector<std::pair<Instruction*,Instruction*>, 20> TentativePairs;
202 assert(LI != LE && RI != RE);
203 Instruction *LeftI = &*LI, *RightI = &*RI;
205 // If the instructions differ, start the more sophisticated diff
206 // algorithm at the start of the block.
207 if (diff(LeftI, RightI, false, false)) {
208 TentativeValues.clear();
209 return runBlockDiff(L->begin(), R->begin());
212 // Otherwise, tentatively unify them.
213 if (!LeftI->use_empty())
214 TentativeValues.insert(std::make_pair(LeftI, RightI));
217 } while (LI != LE); // This is sufficient: we can't get equality of
218 // terminators if there are residual instructions.
220 // Unify everything in the block, non-tentatively this time.
221 TentativeValues.clear();
222 for (LI = L->begin(), RI = R->begin(); LI != LE; ++LI, ++RI)
226 bool matchForBlockDiff(Instruction *L, Instruction *R);
227 void runBlockDiff(BasicBlock::iterator LI, BasicBlock::iterator RI);
229 bool diffCallSites(CallSite L, CallSite R, bool Complain) {
230 // FIXME: call attributes
231 if (!equivalentAsOperands(L.getCalledValue(), R.getCalledValue())) {
232 if (Complain) Engine.log("called functions differ");
235 if (L.arg_size() != R.arg_size()) {
236 if (Complain) Engine.log("argument counts differ");
239 for (unsigned I = 0, E = L.arg_size(); I != E; ++I)
240 if (!equivalentAsOperands(L.getArgument(I), R.getArgument(I))) {
242 Engine.logf("arguments %l and %r differ")
243 << L.getArgument(I) << R.getArgument(I);
249 bool diff(Instruction *L, Instruction *R, bool Complain, bool TryUnify) {
250 // FIXME: metadata (if Complain is set)
252 // Different opcodes always imply different operations.
253 if (L->getOpcode() != R->getOpcode()) {
254 if (Complain) Engine.log("different instruction types");
258 if (isa<CmpInst>(L)) {
259 if (cast<CmpInst>(L)->getPredicate()
260 != cast<CmpInst>(R)->getPredicate()) {
261 if (Complain) Engine.log("different predicates");
264 } else if (isa<CallInst>(L)) {
265 return diffCallSites(CallSite(L), CallSite(R), Complain);
266 } else if (isa<PHINode>(L)) {
269 // This is really wierd; type uniquing is broken?
270 if (L->getType() != R->getType()) {
271 if (!L->getType()->isPointerTy() || !R->getType()->isPointerTy()) {
272 if (Complain) Engine.log("different phi types");
279 } else if (isa<InvokeInst>(L)) {
280 InvokeInst *LI = cast<InvokeInst>(L);
281 InvokeInst *RI = cast<InvokeInst>(R);
282 if (diffCallSites(CallSite(LI), CallSite(RI), Complain))
286 tryUnify(LI->getNormalDest(), RI->getNormalDest());
287 tryUnify(LI->getUnwindDest(), RI->getUnwindDest());
291 } else if (isa<BranchInst>(L)) {
292 BranchInst *LI = cast<BranchInst>(L);
293 BranchInst *RI = cast<BranchInst>(R);
294 if (LI->isConditional() != RI->isConditional()) {
295 if (Complain) Engine.log("branch conditionality differs");
299 if (LI->isConditional()) {
300 if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
301 if (Complain) Engine.log("branch conditions differ");
304 if (TryUnify) tryUnify(LI->getSuccessor(1), RI->getSuccessor(1));
306 if (TryUnify) tryUnify(LI->getSuccessor(0), RI->getSuccessor(0));
309 } else if (isa<SwitchInst>(L)) {
310 SwitchInst *LI = cast<SwitchInst>(L);
311 SwitchInst *RI = cast<SwitchInst>(R);
312 if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
313 if (Complain) Engine.log("switch conditions differ");
316 if (TryUnify) tryUnify(LI->getDefaultDest(), RI->getDefaultDest());
318 bool Difference = false;
320 DenseMap<ConstantInt*,BasicBlock*> LCases;
321 for (unsigned I = 1, E = LI->getNumCases(); I != E; ++I)
322 LCases[LI->getCaseValue(I)] = LI->getSuccessor(I);
323 for (unsigned I = 1, E = RI->getNumCases(); I != E; ++I) {
324 ConstantInt *CaseValue = RI->getCaseValue(I);
325 BasicBlock *LCase = LCases[CaseValue];
327 if (TryUnify) tryUnify(LCase, RI->getSuccessor(I));
328 LCases.erase(CaseValue);
329 } else if (!Difference) {
331 Engine.logf("right switch has extra case %r") << CaseValue;
336 for (DenseMap<ConstantInt*,BasicBlock*>::iterator
337 I = LCases.begin(), E = LCases.end(); I != E; ++I) {
339 Engine.logf("left switch has extra case %l") << I->first;
343 } else if (isa<UnreachableInst>(L)) {
347 if (L->getNumOperands() != R->getNumOperands()) {
348 if (Complain) Engine.log("instructions have different operand counts");
352 for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
353 Value *LO = L->getOperand(I), *RO = R->getOperand(I);
354 if (!equivalentAsOperands(LO, RO)) {
355 if (Complain) Engine.logf("operands %l and %r differ") << LO << RO;
363 bool equivalentAsOperands(Constant *L, Constant *R) {
364 // Use equality as a preliminary filter.
368 if (L->getValueID() != R->getValueID())
371 // Ask the engine about global values.
372 if (isa<GlobalValue>(L))
373 return Engine.equivalentAsOperands(cast<GlobalValue>(L),
374 cast<GlobalValue>(R));
376 // Compare constant expressions structurally.
377 if (isa<ConstantExpr>(L))
378 return equivalentAsOperands(cast<ConstantExpr>(L),
379 cast<ConstantExpr>(R));
381 // Nulls of the "same type" don't always actually have the same
382 // type; I don't know why. Just white-list them.
383 if (isa<ConstantPointerNull>(L))
386 // Block addresses only match if we've already encountered the
387 // block. FIXME: tentative matches?
388 if (isa<BlockAddress>(L))
389 return Blocks[cast<BlockAddress>(L)->getBasicBlock()]
390 == cast<BlockAddress>(R)->getBasicBlock();
395 bool equivalentAsOperands(ConstantExpr *L, ConstantExpr *R) {
398 if (L->getOpcode() != R->getOpcode())
401 switch (L->getOpcode()) {
402 case Instruction::ICmp:
403 case Instruction::FCmp:
404 if (L->getPredicate() != R->getPredicate())
408 case Instruction::GetElementPtr:
416 if (L->getNumOperands() != R->getNumOperands())
419 for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I)
420 if (!equivalentAsOperands(L->getOperand(I), R->getOperand(I)))
426 bool equivalentAsOperands(Value *L, Value *R) {
427 // Fall out if the values have different kind.
428 // This possibly shouldn't take priority over oracles.
429 if (L->getValueID() != R->getValueID())
432 // Value subtypes: Argument, Constant, Instruction, BasicBlock,
433 // InlineAsm, MDNode, MDString, PseudoSourceValue
435 if (isa<Constant>(L))
436 return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R));
438 if (isa<Instruction>(L))
439 return Values[L] == R || TentativeValues.count(std::make_pair(L, R));
441 if (isa<Argument>(L))
442 return Values[L] == R;
444 if (isa<BasicBlock>(L))
445 return Blocks[cast<BasicBlock>(L)] != R;
447 // Pretend everything else is identical.
451 // Avoid a gcc warning about accessing 'this' in an initializer.
452 FunctionDifferenceEngine *this_() { return this; }
455 FunctionDifferenceEngine(DifferenceEngine &Engine) :
456 Engine(Engine), Queue(QueueSorter(*this_())) {}
458 void diff(Function *L, Function *R) {
459 if (L->arg_size() != R->arg_size())
460 Engine.log("different argument counts");
462 // Map the arguments.
463 for (Function::arg_iterator
464 LI = L->arg_begin(), LE = L->arg_end(),
465 RI = R->arg_begin(), RE = R->arg_end();
466 LI != LE && RI != RE; ++LI, ++RI)
469 tryUnify(&*L->begin(), &*R->begin());
475 DiffEntry() : Cost(0) {}
478 llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange
481 bool FunctionDifferenceEngine::matchForBlockDiff(Instruction *L,
483 return !diff(L, R, false, false);
486 void FunctionDifferenceEngine::runBlockDiff(BasicBlock::iterator LStart,
487 BasicBlock::iterator RStart) {
488 BasicBlock::iterator LE = LStart->getParent()->end();
489 BasicBlock::iterator RE = RStart->getParent()->end();
491 unsigned NL = std::distance(LStart, LE);
493 SmallVector<DiffEntry, 20> Paths1(NL+1);
494 SmallVector<DiffEntry, 20> Paths2(NL+1);
496 DiffEntry *Cur = Paths1.data();
497 DiffEntry *Next = Paths2.data();
499 const unsigned LeftCost = 2;
500 const unsigned RightCost = 2;
501 const unsigned MatchCost = 0;
503 assert(TentativeValues.empty());
505 // Initialize the first column.
506 for (unsigned I = 0; I != NL+1; ++I) {
507 Cur[I].Cost = I * LeftCost;
508 for (unsigned J = 0; J != I; ++J)
509 Cur[I].Path.push_back(DifferenceEngine::DC_left);
512 for (BasicBlock::iterator RI = RStart; RI != RE; ++RI) {
513 // Initialize the first row.
515 Next[0].Cost += RightCost;
516 Next[0].Path.push_back(DifferenceEngine::DC_right);
519 for (BasicBlock::iterator LI = LStart; LI != LE; ++LI, ++Index) {
520 if (matchForBlockDiff(&*LI, &*RI)) {
521 Next[Index] = Cur[Index-1];
522 Next[Index].Cost += MatchCost;
523 Next[Index].Path.push_back(DifferenceEngine::DC_match);
524 TentativeValues.insert(std::make_pair(&*LI, &*RI));
525 } else if (Next[Index-1].Cost <= Cur[Index].Cost) {
526 Next[Index] = Next[Index-1];
527 Next[Index].Cost += LeftCost;
528 Next[Index].Path.push_back(DifferenceEngine::DC_left);
530 Next[Index] = Cur[Index];
531 Next[Index].Cost += RightCost;
532 Next[Index].Path.push_back(DifferenceEngine::DC_right);
536 std::swap(Cur, Next);
539 // We don't need the tentative values anymore; everything from here
540 // on out should be non-tentative.
541 TentativeValues.clear();
543 SmallVectorImpl<char> &Path = Cur[NL].Path;
544 BasicBlock::iterator LI = LStart, RI = RStart;
546 DifferenceEngine::DiffLogBuilder Diff(Engine);
548 // Drop trailing matches.
549 while (Path.back() == DifferenceEngine::DC_match)
552 // Skip leading matches.
553 SmallVectorImpl<char>::iterator
554 PI = Path.begin(), PE = Path.end();
555 while (PI != PE && *PI == DifferenceEngine::DC_match) {
560 for (; PI != PE; ++PI) {
561 switch (static_cast<DifferenceEngine::DiffChange>(*PI)) {
562 case DifferenceEngine::DC_match:
563 assert(LI != LE && RI != RE);
565 Instruction *L = &*LI, *R = &*RI;
572 case DifferenceEngine::DC_left:
578 case DifferenceEngine::DC_right:
586 // Finishing unifying and complaining about the tails of the block,
587 // which should be matches all the way through.
594 // If the terminators have different kinds, but one is an invoke and the
595 // other is an unconditional branch immediately following a call, unify
596 // the results and the destinations.
597 TerminatorInst *LTerm = LStart->getParent()->getTerminator();
598 TerminatorInst *RTerm = RStart->getParent()->getTerminator();
599 if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) {
600 if (cast<BranchInst>(LTerm)->isConditional()) return;
601 BasicBlock::iterator I = LTerm;
602 if (I == LStart->getParent()->begin()) return;
604 if (!isa<CallInst>(*I)) return;
605 CallInst *LCall = cast<CallInst>(&*I);
606 InvokeInst *RInvoke = cast<InvokeInst>(RTerm);
607 if (!equivalentAsOperands(LCall->getCalledValue(), RInvoke->getCalledValue()))
609 if (!LCall->use_empty())
610 Values[LCall] = RInvoke;
611 tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest());
612 } else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) {
613 if (cast<BranchInst>(RTerm)->isConditional()) return;
614 BasicBlock::iterator I = RTerm;
615 if (I == RStart->getParent()->begin()) return;
617 if (!isa<CallInst>(*I)) return;
618 CallInst *RCall = cast<CallInst>(I);
619 InvokeInst *LInvoke = cast<InvokeInst>(LTerm);
620 if (!equivalentAsOperands(LInvoke->getCalledValue(), RCall->getCalledValue()))
622 if (!LInvoke->use_empty())
623 Values[LInvoke] = RCall;
624 tryUnify(LInvoke->getNormalDest(), RTerm->getSuccessor(0));
630 void DifferenceEngine::diff(Function *L, Function *R) {
631 Context C(*this, L, R);
634 // FIXME: attributes and CC
635 // FIXME: parameter attributes
637 // If both are declarations, we're done.
638 if (L->empty() && R->empty())
641 log("left function is declaration, right function is definition");
643 log("right function is declaration, left function is definition");
645 FunctionDifferenceEngine(*this).diff(L, R);
648 void DifferenceEngine::diff(Module *L, Module *R) {
650 SmallVector<std::pair<Function*,Function*>, 20> Queue;
652 for (Module::iterator I = L->begin(), E = L->end(); I != E; ++I) {
654 LNames.insert(LFn->getName());
656 if (Function *RFn = R->getFunction(LFn->getName()))
657 Queue.push_back(std::make_pair(LFn, RFn));
659 logf("function %l exists only in left module") << LFn;
662 for (Module::iterator I = R->begin(), E = R->end(); I != E; ++I) {
664 if (!LNames.count(RFn->getName()))
665 logf("function %r exists only in right module") << RFn;
668 for (SmallVectorImpl<std::pair<Function*,Function*> >::iterator
669 I = Queue.begin(), E = Queue.end(); I != E; ++I)
670 diff(I->first, I->second);
673 bool DifferenceEngine::equivalentAsOperands(GlobalValue *L, GlobalValue *R) {
674 if (globalValueOracle) return (*globalValueOracle)(L, R);
675 return L->getName() == R->getName();