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 interface to the LLVM difference engine,
11 // which structurally compares functions within a module.
13 //===----------------------------------------------------------------------===//
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>
23 #include <llvm/Module.h>
24 #include <llvm/Function.h>
25 #include <llvm/Instructions.h>
26 #include <llvm/Support/CFG.h>
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>
33 #include "DifferenceEngine.h"
39 /// A priority queue, implemented as a heap.
40 template <class T, class Sorter, unsigned InlineCapacity>
43 llvm::SmallVector<T, InlineCapacity> Storage;
46 PriorityQueue(const Sorter &Precedes) : Precedes(Precedes) {}
48 /// Checks whether the heap is empty.
49 bool empty() const { return Storage.empty(); }
51 /// Insert a new value on the heap.
52 void insert(const T &V) {
53 unsigned Index = Storage.size();
55 if (Index == 0) return;
57 T *data = Storage.data();
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;
67 /// Remove the minimum value in the heap. Only valid on a non-empty heap.
72 unsigned NewSize = Storage.size() - 1;
74 // Move the slot at the end to the beginning.
75 if (isPodLike<T>::value)
76 Storage[0] = Storage[NewSize];
78 std::swap(Storage[0], Storage[NewSize]);
80 // Bubble the root up as necessary.
83 // With a 1-based index, the children would be Index*2 and Index*2+1.
84 unsigned R = (Index + 1) * 2;
87 // If R is out of bounds, we're done after this in any case.
89 // If L is also out of bounds, we're done immediately.
90 if (L >= NewSize) break;
92 // Otherwise, test whether we should swap L and Index.
93 if (Precedes(Storage[L], Storage[Index]))
94 std::swap(Storage[L], Storage[Index]);
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);
102 // If Index is >= the min of L and R, then heap ordering is restored.
103 if (!Precedes(Storage[IndexToTest], Storage[Index]))
106 // Otherwise, keep bubbling up.
107 std::swap(Storage[IndexToTest], Storage[Index]);
117 /// A function-scope difference engine.
118 class FunctionDifferenceEngine {
119 DifferenceEngine &Engine;
121 /// The current mapping from old local values to new local values.
122 DenseMap<Value*, Value*> Values;
124 /// The current mapping from old blocks to new blocks.
125 DenseMap<BasicBlock*, BasicBlock*> Blocks;
127 DenseSet<std::pair<Value*, Value*> > TentativeValues;
129 unsigned getUnprocPredCount(BasicBlock *Block) const {
131 for (pred_iterator I = pred_begin(Block), E = pred_end(Block); I != E; ++I)
132 if (!Blocks.count(*I)) Count++;
136 typedef std::pair<BasicBlock*, BasicBlock*> BlockPair;
138 /// A type which sorts a priority queue by the number of unprocessed
139 /// predecessor blocks it has remaining.
141 /// This is actually really expensive to calculate.
143 const FunctionDifferenceEngine &fde;
144 explicit QueueSorter(const FunctionDifferenceEngine &fde) : fde(fde) {}
146 bool operator()(const BlockPair &Old, const BlockPair &New) {
147 return fde.getUnprocPredCount(Old.first)
148 < fde.getUnprocPredCount(New.first);
152 /// A queue of unified blocks to process.
153 PriorityQueue<BlockPair, QueueSorter, 20> Queue;
155 /// Try to unify the given two blocks. Enqueues them for processing
156 /// if they haven't already been processed.
158 /// Returns true if there was a problem unifying them.
159 bool tryUnify(BasicBlock *L, BasicBlock *R) {
160 BasicBlock *&Ref = Blocks[L];
163 if (Ref == R) return false;
165 Engine.logf("successor %l cannot be equivalent to %r; "
166 "it's already equivalent to %r")
172 Queue.insert(BlockPair(L, R));
176 void processQueue() {
177 while (!Queue.empty()) {
178 BlockPair Pair = Queue.remove_min();
179 diff(Pair.first, Pair.second);
183 void diff(BasicBlock *L, BasicBlock *R) {
184 DifferenceEngine::Context C(Engine, L, R);
186 BasicBlock::iterator LI = L->begin(), LE = L->end();
187 BasicBlock::iterator RI = R->begin(), RE = R->end();
189 llvm::SmallVector<std::pair<Instruction*,Instruction*>, 20> TentativePairs;
192 assert(LI != LE && RI != RE);
193 Instruction *LeftI = &*LI, *RightI = &*RI;
195 // If the instructions differ, start the more sophisticated diff
196 // algorithm at the start of the block.
197 if (diff(LeftI, RightI, false, false)) {
198 TentativeValues.clear();
199 return runBlockDiff(L->begin(), R->begin());
202 // Otherwise, tentatively unify them.
203 if (!LeftI->use_empty())
204 TentativeValues.insert(std::make_pair(LeftI, RightI));
207 } while (LI != LE); // This is sufficient: we can't get equality of
208 // terminators if there are residual instructions.
210 TentativeValues.clear();
212 // Do another pass over the block, this time in complaints mode.
213 LI = L->begin(); RI = R->begin();
215 assert(LI != LE && RI != RE);
216 bool Result = diff(&*LI, &*RI, true, true);
217 assert(!Result && "structural differences second time around?");
220 // Make the mapping non-tentative this time.
221 if (!LI->use_empty())
228 bool matchForBlockDiff(Instruction *L, Instruction *R);
229 void runBlockDiff(BasicBlock::iterator LI, BasicBlock::iterator RI);
231 bool diffCallSites(CallSite L, CallSite R, bool Complain) {
232 // FIXME: call attributes
233 if (!equivalentAsOperands(L.getCalledValue(), R.getCalledValue())) {
234 if (Complain) Engine.log("called functions differ");
237 if (L.arg_size() != R.arg_size()) {
238 if (Complain) Engine.log("argument counts differ");
241 for (unsigned I = 0, E = L.arg_size(); I != E; ++I)
242 if (!equivalentAsOperands(L.getArgument(I), R.getArgument(I))) {
244 Engine.logf("arguments %l and %r differ")
245 << L.getArgument(I) << R.getArgument(I);
251 bool diff(Instruction *L, Instruction *R, bool Complain, bool TryUnify) {
252 // FIXME: metadata (if Complain is set)
254 // Different opcodes always imply different operations.
255 if (L->getOpcode() != R->getOpcode()) {
256 if (Complain) Engine.log("different instruction types");
260 if (isa<CmpInst>(L)) {
261 if (cast<CmpInst>(L)->getPredicate()
262 != cast<CmpInst>(R)->getPredicate()) {
263 if (Complain) Engine.log("different predicates");
266 } else if (isa<CallInst>(L)) {
267 return diffCallSites(CallSite(L), CallSite(R), Complain);
268 } else if (isa<PHINode>(L)) {
271 // This is really wierd; type uniquing is broken?
272 if (L->getType() != R->getType()) {
273 if (!L->getType()->isPointerTy() || !R->getType()->isPointerTy()) {
274 if (Complain) Engine.log("different phi types");
281 } else if (isa<InvokeInst>(L)) {
282 InvokeInst *LI = cast<InvokeInst>(L);
283 InvokeInst *RI = cast<InvokeInst>(R);
284 if (diffCallSites(CallSite(LI), CallSite(RI), Complain))
288 tryUnify(LI->getNormalDest(), RI->getNormalDest());
289 tryUnify(LI->getUnwindDest(), RI->getUnwindDest());
293 } else if (isa<BranchInst>(L)) {
294 BranchInst *LI = cast<BranchInst>(L);
295 BranchInst *RI = cast<BranchInst>(R);
296 if (LI->isConditional() != RI->isConditional()) {
297 if (Complain) Engine.log("branch conditionality differs");
301 if (LI->isConditional()) {
302 if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
303 if (Complain) Engine.log("branch conditions differ");
306 if (TryUnify) tryUnify(LI->getSuccessor(1), RI->getSuccessor(1));
308 if (TryUnify) tryUnify(LI->getSuccessor(0), RI->getSuccessor(0));
311 } else if (isa<SwitchInst>(L)) {
312 SwitchInst *LI = cast<SwitchInst>(L);
313 SwitchInst *RI = cast<SwitchInst>(R);
314 if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
315 if (Complain) Engine.log("switch conditions differ");
318 if (TryUnify) tryUnify(LI->getDefaultDest(), RI->getDefaultDest());
320 bool Difference = false;
322 DenseMap<ConstantInt*,BasicBlock*> LCases;
323 for (unsigned I = 1, E = LI->getNumCases(); I != E; ++I)
324 LCases[LI->getCaseValue(I)] = LI->getSuccessor(I);
325 for (unsigned I = 1, E = RI->getNumCases(); I != E; ++I) {
326 ConstantInt *CaseValue = RI->getCaseValue(I);
327 BasicBlock *LCase = LCases[CaseValue];
329 if (TryUnify) tryUnify(LCase, RI->getSuccessor(I));
330 LCases.erase(CaseValue);
331 } else if (!Difference) {
333 Engine.logf("right switch has extra case %r") << CaseValue;
338 for (DenseMap<ConstantInt*,BasicBlock*>::iterator
339 I = LCases.begin(), E = LCases.end(); I != E; ++I) {
341 Engine.logf("left switch has extra case %l") << I->first;
345 } else if (isa<UnreachableInst>(L)) {
349 if (L->getNumOperands() != R->getNumOperands()) {
350 if (Complain) Engine.log("instructions have different operand counts");
354 for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
355 Value *LO = L->getOperand(I), *RO = R->getOperand(I);
356 if (!equivalentAsOperands(LO, RO)) {
357 if (Complain) Engine.logf("operands %l and %r differ") << LO << RO;
365 bool equivalentAsOperands(Constant *L, Constant *R) {
366 // Use equality as a preliminary filter.
370 if (L->getValueID() != R->getValueID())
373 // Ask the engine about global values.
374 if (isa<GlobalValue>(L))
375 return Engine.equivalentAsOperands(cast<GlobalValue>(L),
376 cast<GlobalValue>(R));
378 // Compare constant expressions structurally.
379 if (isa<ConstantExpr>(L))
380 return equivalentAsOperands(cast<ConstantExpr>(L),
381 cast<ConstantExpr>(R));
383 // Nulls of the "same type" don't always actually have the same
384 // type; I don't know why. Just white-list them.
385 if (isa<ConstantPointerNull>(L))
388 // Block addresses only match if we've already encountered the
389 // block. FIXME: tentative matches?
390 if (isa<BlockAddress>(L))
391 return Blocks[cast<BlockAddress>(L)->getBasicBlock()]
392 == cast<BlockAddress>(R)->getBasicBlock();
397 bool equivalentAsOperands(ConstantExpr *L, ConstantExpr *R) {
400 if (L->getOpcode() != R->getOpcode())
403 switch (L->getOpcode()) {
404 case Instruction::ICmp:
405 case Instruction::FCmp:
406 if (L->getPredicate() != R->getPredicate())
410 case Instruction::GetElementPtr:
418 if (L->getNumOperands() != R->getNumOperands())
421 for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I)
422 if (!equivalentAsOperands(L->getOperand(I), R->getOperand(I)))
428 bool equivalentAsOperands(Value *L, Value *R) {
429 // Fall out if the values have different kind.
430 // This possibly shouldn't take priority over oracles.
431 if (L->getValueID() != R->getValueID())
434 // Value subtypes: Argument, Constant, Instruction, BasicBlock,
435 // InlineAsm, MDNode, MDString, PseudoSourceValue
437 if (isa<Constant>(L))
438 return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R));
440 if (isa<Instruction>(L))
441 return Values[L] == R || TentativeValues.count(std::make_pair(L, R));
443 if (isa<Argument>(L))
444 return Values[L] == R;
446 if (isa<BasicBlock>(L))
447 return Blocks[cast<BasicBlock>(L)] != R;
449 // Pretend everything else is identical.
453 // Avoid a gcc warning about accessing 'this' in an initializer.
454 FunctionDifferenceEngine *this_() { return this; }
457 FunctionDifferenceEngine(DifferenceEngine &Engine) :
458 Engine(Engine), Queue(QueueSorter(*this_())) {}
460 void diff(Function *L, Function *R) {
461 if (L->arg_size() != R->arg_size())
462 Engine.log("different argument counts");
464 // Map the arguments.
465 for (Function::arg_iterator
466 LI = L->arg_begin(), LE = L->arg_end(),
467 RI = R->arg_begin(), RE = R->arg_end();
468 LI != LE && RI != RE; ++LI, ++RI)
471 tryUnify(&*L->begin(), &*R->begin());
477 DiffEntry() : Cost(0) {}
480 llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange
483 bool FunctionDifferenceEngine::matchForBlockDiff(Instruction *L,
485 return !diff(L, R, false, false);
488 void FunctionDifferenceEngine::runBlockDiff(BasicBlock::iterator LStart,
489 BasicBlock::iterator RStart) {
490 BasicBlock::iterator LE = LStart->getParent()->end();
491 BasicBlock::iterator RE = RStart->getParent()->end();
493 unsigned NL = std::distance(LStart, LE);
495 SmallVector<DiffEntry, 20> Paths1(NL+1);
496 SmallVector<DiffEntry, 20> Paths2(NL+1);
498 DiffEntry *Cur = Paths1.data();
499 DiffEntry *Next = Paths2.data();
501 const unsigned LeftCost = 2;
502 const unsigned RightCost = 2;
503 const unsigned MatchCost = 0;
505 assert(TentativeValues.empty());
507 // Initialize the first column.
508 for (unsigned I = 0; I != NL+1; ++I) {
509 Cur[I].Cost = I * LeftCost;
510 for (unsigned J = 0; J != I; ++J)
511 Cur[I].Path.push_back(DifferenceEngine::DC_left);
514 for (BasicBlock::iterator RI = RStart; RI != RE; ++RI) {
515 // Initialize the first row.
517 Next[0].Cost += RightCost;
518 Next[0].Path.push_back(DifferenceEngine::DC_right);
521 for (BasicBlock::iterator LI = LStart; LI != LE; ++LI, ++Index) {
522 if (matchForBlockDiff(&*LI, &*RI)) {
523 Next[Index] = Cur[Index-1];
524 Next[Index].Cost += MatchCost;
525 Next[Index].Path.push_back(DifferenceEngine::DC_match);
526 TentativeValues.insert(std::make_pair(&*LI, &*RI));
527 } else if (Next[Index-1].Cost <= Cur[Index].Cost) {
528 Next[Index] = Next[Index-1];
529 Next[Index].Cost += LeftCost;
530 Next[Index].Path.push_back(DifferenceEngine::DC_left);
532 Next[Index] = Cur[Index];
533 Next[Index].Cost += RightCost;
534 Next[Index].Path.push_back(DifferenceEngine::DC_right);
538 std::swap(Cur, Next);
541 SmallVectorImpl<char> &Path = Cur[NL].Path;
542 BasicBlock::iterator LI = LStart, RI = RStart;
544 DifferenceEngine::DiffLogBuilder Diff(Engine);
546 // Drop trailing matches.
547 while (Path.back() == DifferenceEngine::DC_match)
550 // Skip leading matches.
551 SmallVectorImpl<char>::iterator
552 PI = Path.begin(), PE = Path.end();
553 while (PI != PE && *PI == DifferenceEngine::DC_match)
556 for (; PI != PE; ++PI) {
557 switch (static_cast<DifferenceEngine::DiffChange>(*PI)) {
558 case DifferenceEngine::DC_match:
559 assert(LI != LE && RI != RE);
561 Instruction *L = &*LI, *R = &*RI;
562 DifferenceEngine::Context C(Engine, L, R);
563 diff(L, R, true, true); // complain and unify successors
564 Values[L] = R; // make non-tentative
570 case DifferenceEngine::DC_left:
576 case DifferenceEngine::DC_right:
584 TentativeValues.clear();
589 void DifferenceEngine::diff(Function *L, Function *R) {
590 Context C(*this, L, R);
593 // FIXME: attributes and CC
594 // FIXME: parameter attributes
596 // If both are declarations, we're done.
597 if (L->empty() && R->empty())
600 log("left function is declaration, right function is definition");
602 log("right function is declaration, left function is definition");
604 FunctionDifferenceEngine(*this).diff(L, R);
607 void DifferenceEngine::diff(Module *L, Module *R) {
609 SmallVector<std::pair<Function*,Function*>, 20> Queue;
611 for (Module::iterator I = L->begin(), E = L->end(); I != E; ++I) {
613 LNames.insert(LFn->getName());
615 if (Function *RFn = R->getFunction(LFn->getName()))
616 Queue.push_back(std::make_pair(LFn, RFn));
618 logf("function %l exists only in left module") << LFn;
621 for (Module::iterator I = R->begin(), E = R->end(); I != E; ++I) {
623 if (!LNames.count(RFn->getName()))
624 logf("function %r exists only in right module") << RFn;
627 for (SmallVectorImpl<std::pair<Function*,Function*> >::iterator
628 I = Queue.begin(), E = Queue.end(); I != E; ++I)
629 diff(I->first, I->second);
632 bool DifferenceEngine::equivalentAsOperands(GlobalValue *L, GlobalValue *R) {
633 if (globalValueOracle) return (*globalValueOracle)(L, R);
634 return L->getName() == R->getName();