xref: /freebsd-src/contrib/llvm-project/llvm/tools/llvm-diff/lib/DifferenceEngine.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1349cc55cSDimitry Andric //===-- DifferenceEngine.cpp - Structural function/module comparison ------===//
2349cc55cSDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6349cc55cSDimitry Andric //
7349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
8349cc55cSDimitry Andric //
9349cc55cSDimitry Andric // This header defines the implementation of the LLVM difference
10349cc55cSDimitry Andric // engine, which structurally compares global values within a module.
11349cc55cSDimitry Andric //
12349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
13349cc55cSDimitry Andric 
14349cc55cSDimitry Andric #include "DifferenceEngine.h"
15349cc55cSDimitry Andric #include "llvm/ADT/DenseMap.h"
16349cc55cSDimitry Andric #include "llvm/ADT/DenseSet.h"
17349cc55cSDimitry Andric #include "llvm/ADT/SmallString.h"
18349cc55cSDimitry Andric #include "llvm/ADT/SmallVector.h"
19349cc55cSDimitry Andric #include "llvm/ADT/StringSet.h"
20bdd1243dSDimitry Andric #include "llvm/IR/BasicBlock.h"
21349cc55cSDimitry Andric #include "llvm/IR/CFG.h"
22349cc55cSDimitry Andric #include "llvm/IR/Constants.h"
23349cc55cSDimitry Andric #include "llvm/IR/Function.h"
24349cc55cSDimitry Andric #include "llvm/IR/Instructions.h"
25349cc55cSDimitry Andric #include "llvm/IR/Module.h"
26349cc55cSDimitry Andric #include "llvm/Support/ErrorHandling.h"
27349cc55cSDimitry Andric #include "llvm/Support/raw_ostream.h"
28349cc55cSDimitry Andric #include "llvm/Support/type_traits.h"
29349cc55cSDimitry Andric #include <utility>
30349cc55cSDimitry Andric 
31349cc55cSDimitry Andric using namespace llvm;
32349cc55cSDimitry Andric 
33349cc55cSDimitry Andric namespace {
34349cc55cSDimitry Andric 
35349cc55cSDimitry Andric /// A priority queue, implemented as a heap.
36349cc55cSDimitry Andric template <class T, class Sorter, unsigned InlineCapacity>
37349cc55cSDimitry Andric class PriorityQueue {
38349cc55cSDimitry Andric   Sorter Precedes;
39349cc55cSDimitry Andric   llvm::SmallVector<T, InlineCapacity> Storage;
40349cc55cSDimitry Andric 
41349cc55cSDimitry Andric public:
42349cc55cSDimitry Andric   PriorityQueue(const Sorter &Precedes) : Precedes(Precedes) {}
43349cc55cSDimitry Andric 
44349cc55cSDimitry Andric   /// Checks whether the heap is empty.
45349cc55cSDimitry Andric   bool empty() const { return Storage.empty(); }
46349cc55cSDimitry Andric 
47349cc55cSDimitry Andric   /// Insert a new value on the heap.
48349cc55cSDimitry Andric   void insert(const T &V) {
49349cc55cSDimitry Andric     unsigned Index = Storage.size();
50349cc55cSDimitry Andric     Storage.push_back(V);
51349cc55cSDimitry Andric     if (Index == 0) return;
52349cc55cSDimitry Andric 
53349cc55cSDimitry Andric     T *data = Storage.data();
54349cc55cSDimitry Andric     while (true) {
55349cc55cSDimitry Andric       unsigned Target = (Index + 1) / 2 - 1;
56349cc55cSDimitry Andric       if (!Precedes(data[Index], data[Target])) return;
57349cc55cSDimitry Andric       std::swap(data[Index], data[Target]);
58349cc55cSDimitry Andric       if (Target == 0) return;
59349cc55cSDimitry Andric       Index = Target;
60349cc55cSDimitry Andric     }
61349cc55cSDimitry Andric   }
62349cc55cSDimitry Andric 
63349cc55cSDimitry Andric   /// Remove the minimum value in the heap.  Only valid on a non-empty heap.
64349cc55cSDimitry Andric   T remove_min() {
65349cc55cSDimitry Andric     assert(!empty());
66349cc55cSDimitry Andric     T tmp = Storage[0];
67349cc55cSDimitry Andric 
68349cc55cSDimitry Andric     unsigned NewSize = Storage.size() - 1;
69349cc55cSDimitry Andric     if (NewSize) {
70349cc55cSDimitry Andric       // Move the slot at the end to the beginning.
71349cc55cSDimitry Andric       if (std::is_trivially_copyable<T>::value)
72349cc55cSDimitry Andric         Storage[0] = Storage[NewSize];
73349cc55cSDimitry Andric       else
74349cc55cSDimitry Andric         std::swap(Storage[0], Storage[NewSize]);
75349cc55cSDimitry Andric 
76349cc55cSDimitry Andric       // Bubble the root up as necessary.
77349cc55cSDimitry Andric       unsigned Index = 0;
78349cc55cSDimitry Andric       while (true) {
79349cc55cSDimitry Andric         // With a 1-based index, the children would be Index*2 and Index*2+1.
80349cc55cSDimitry Andric         unsigned R = (Index + 1) * 2;
81349cc55cSDimitry Andric         unsigned L = R - 1;
82349cc55cSDimitry Andric 
83349cc55cSDimitry Andric         // If R is out of bounds, we're done after this in any case.
84349cc55cSDimitry Andric         if (R >= NewSize) {
85349cc55cSDimitry Andric           // If L is also out of bounds, we're done immediately.
86349cc55cSDimitry Andric           if (L >= NewSize) break;
87349cc55cSDimitry Andric 
88349cc55cSDimitry Andric           // Otherwise, test whether we should swap L and Index.
89349cc55cSDimitry Andric           if (Precedes(Storage[L], Storage[Index]))
90349cc55cSDimitry Andric             std::swap(Storage[L], Storage[Index]);
91349cc55cSDimitry Andric           break;
92349cc55cSDimitry Andric         }
93349cc55cSDimitry Andric 
94349cc55cSDimitry Andric         // Otherwise, we need to compare with the smaller of L and R.
95349cc55cSDimitry Andric         // Prefer R because it's closer to the end of the array.
96349cc55cSDimitry Andric         unsigned IndexToTest = (Precedes(Storage[L], Storage[R]) ? L : R);
97349cc55cSDimitry Andric 
98349cc55cSDimitry Andric         // If Index is >= the min of L and R, then heap ordering is restored.
99349cc55cSDimitry Andric         if (!Precedes(Storage[IndexToTest], Storage[Index]))
100349cc55cSDimitry Andric           break;
101349cc55cSDimitry Andric 
102349cc55cSDimitry Andric         // Otherwise, keep bubbling up.
103349cc55cSDimitry Andric         std::swap(Storage[IndexToTest], Storage[Index]);
104349cc55cSDimitry Andric         Index = IndexToTest;
105349cc55cSDimitry Andric       }
106349cc55cSDimitry Andric     }
107349cc55cSDimitry Andric     Storage.pop_back();
108349cc55cSDimitry Andric 
109349cc55cSDimitry Andric     return tmp;
110349cc55cSDimitry Andric   }
111349cc55cSDimitry Andric };
112349cc55cSDimitry Andric 
113349cc55cSDimitry Andric /// A function-scope difference engine.
114349cc55cSDimitry Andric class FunctionDifferenceEngine {
115349cc55cSDimitry Andric   DifferenceEngine &Engine;
116349cc55cSDimitry Andric 
117349cc55cSDimitry Andric   // Some initializers may reference the variable we're currently checking. This
118349cc55cSDimitry Andric   // can cause an infinite loop. The Saved[LR]HS ivars can be checked to prevent
119349cc55cSDimitry Andric   // recursing.
120349cc55cSDimitry Andric   const Value *SavedLHS;
121349cc55cSDimitry Andric   const Value *SavedRHS;
122349cc55cSDimitry Andric 
123bdd1243dSDimitry Andric   // The current mapping from old local values to new local values.
124349cc55cSDimitry Andric   DenseMap<const Value *, const Value *> Values;
125349cc55cSDimitry Andric 
126bdd1243dSDimitry Andric   // The current mapping from old blocks to new blocks.
127349cc55cSDimitry Andric   DenseMap<const BasicBlock *, const BasicBlock *> Blocks;
128349cc55cSDimitry Andric 
129bdd1243dSDimitry Andric   // The tentative mapping from old local values while comparing a pair of
130bdd1243dSDimitry Andric   // basic blocks. Once the pair has been processed, the tentative mapping is
131bdd1243dSDimitry Andric   // committed to the Values map.
132349cc55cSDimitry Andric   DenseSet<std::pair<const Value *, const Value *>> TentativeValues;
133349cc55cSDimitry Andric 
134bdd1243dSDimitry Andric   // Equivalence Assumptions
135bdd1243dSDimitry Andric   //
136bdd1243dSDimitry Andric   // For basic blocks in loops, some values in phi nodes may depend on
137bdd1243dSDimitry Andric   // values from not yet processed basic blocks in the loop. When encountering
138bdd1243dSDimitry Andric   // such values, we optimistically asssume their equivalence and store this
139bdd1243dSDimitry Andric   // assumption in a BlockDiffCandidate for the pair of compared BBs.
140bdd1243dSDimitry Andric   //
141bdd1243dSDimitry Andric   // Once we have diffed all BBs, for every BlockDiffCandidate, we check all
142bdd1243dSDimitry Andric   // stored assumptions using the Values map that stores proven equivalences
143bdd1243dSDimitry Andric   // between the old and new values, and report a diff if an assumption cannot
144bdd1243dSDimitry Andric   // be proven to be true.
145bdd1243dSDimitry Andric   //
146bdd1243dSDimitry Andric   // Note that after having made an assumption, all further determined
147bdd1243dSDimitry Andric   // equivalences implicitly depend on that assumption. These will not be
148bdd1243dSDimitry Andric   // reverted or reported if the assumption proves to be false, because these
149bdd1243dSDimitry Andric   // are considered indirect diffs caused by earlier direct diffs.
150bdd1243dSDimitry Andric   //
151bdd1243dSDimitry Andric   // We aim to avoid false negatives in llvm-diff, that is, ensure that
152bdd1243dSDimitry Andric   // whenever no diff is reported, the functions are indeed equal. If
153bdd1243dSDimitry Andric   // assumptions were made, this is not entirely clear, because in principle we
154bdd1243dSDimitry Andric   // could end up with a circular proof where the proof of equivalence of two
155bdd1243dSDimitry Andric   // nodes is depending on the assumption of their equivalence.
156bdd1243dSDimitry Andric   //
157bdd1243dSDimitry Andric   // To see that assumptions do not add false negatives, note that if we do not
158bdd1243dSDimitry Andric   // report a diff, this means that there is an equivalence mapping between old
159bdd1243dSDimitry Andric   // and new values that is consistent with all assumptions made. The circular
160bdd1243dSDimitry Andric   // dependency that exists on an IR value level does not exist at run time,
161bdd1243dSDimitry Andric   // because the values selected by the phi nodes must always already have been
162bdd1243dSDimitry Andric   // computed. Hence, we can prove equivalence of the old and new functions by
163bdd1243dSDimitry Andric   // considering step-wise parallel execution, and incrementally proving
164bdd1243dSDimitry Andric   // equivalence of every new computed value. Another way to think about it is
165bdd1243dSDimitry Andric   // to imagine cloning the loop BBs for every iteration, turning the loops
166bdd1243dSDimitry Andric   // into (possibly infinite) DAGs, and proving equivalence by induction on the
167bdd1243dSDimitry Andric   // iteration, using the computed value mapping.
168bdd1243dSDimitry Andric 
169bdd1243dSDimitry Andric   // The class BlockDiffCandidate stores pairs which either have already been
170bdd1243dSDimitry Andric   // proven to differ, or pairs whose equivalence depends on assumptions to be
171bdd1243dSDimitry Andric   // verified later.
172bdd1243dSDimitry Andric   struct BlockDiffCandidate {
173bdd1243dSDimitry Andric     const BasicBlock *LBB;
174bdd1243dSDimitry Andric     const BasicBlock *RBB;
175bdd1243dSDimitry Andric     // Maps old values to assumed-to-be-equivalent new values
176bdd1243dSDimitry Andric     SmallDenseMap<const Value *, const Value *> EquivalenceAssumptions;
177bdd1243dSDimitry Andric     // If set, we already know the blocks differ.
178bdd1243dSDimitry Andric     bool KnownToDiffer;
179bdd1243dSDimitry Andric   };
180bdd1243dSDimitry Andric 
181bdd1243dSDimitry Andric   // List of block diff candidates in the order found by processing.
182bdd1243dSDimitry Andric   // We generate reports in this order.
183bdd1243dSDimitry Andric   // For every LBB, there may only be one corresponding RBB.
184bdd1243dSDimitry Andric   SmallVector<BlockDiffCandidate> BlockDiffCandidates;
185bdd1243dSDimitry Andric   // Maps LBB to the index of its BlockDiffCandidate, if existing.
186bdd1243dSDimitry Andric   DenseMap<const BasicBlock *, uint64_t> BlockDiffCandidateIndices;
187bdd1243dSDimitry Andric 
188bdd1243dSDimitry Andric   // Note: Every LBB must always be queried together with the same RBB.
189bdd1243dSDimitry Andric   // The returned reference is not permanently valid and should not be stored.
190bdd1243dSDimitry Andric   BlockDiffCandidate &getOrCreateBlockDiffCandidate(const BasicBlock *LBB,
191bdd1243dSDimitry Andric                                                     const BasicBlock *RBB) {
192bdd1243dSDimitry Andric     auto It = BlockDiffCandidateIndices.find(LBB);
193bdd1243dSDimitry Andric     // Check if LBB already has a diff candidate
194bdd1243dSDimitry Andric     if (It == BlockDiffCandidateIndices.end()) {
195bdd1243dSDimitry Andric       // Add new one
196bdd1243dSDimitry Andric       BlockDiffCandidateIndices[LBB] = BlockDiffCandidates.size();
197bdd1243dSDimitry Andric       BlockDiffCandidates.push_back(
198bdd1243dSDimitry Andric           {LBB, RBB, SmallDenseMap<const Value *, const Value *>(), false});
199bdd1243dSDimitry Andric       return BlockDiffCandidates.back();
200bdd1243dSDimitry Andric     }
201bdd1243dSDimitry Andric     // Use existing one
202bdd1243dSDimitry Andric     BlockDiffCandidate &Result = BlockDiffCandidates[It->second];
203bdd1243dSDimitry Andric     assert(Result.RBB == RBB && "Inconsistent basic block pairing!");
204bdd1243dSDimitry Andric     return Result;
205bdd1243dSDimitry Andric   }
206bdd1243dSDimitry Andric 
207bdd1243dSDimitry Andric   // Optionally passed to equivalence checker functions, so these can add
208bdd1243dSDimitry Andric   // assumptions in BlockDiffCandidates. Its presence controls whether
209bdd1243dSDimitry Andric   // assumptions are generated.
210bdd1243dSDimitry Andric   struct AssumptionContext {
211bdd1243dSDimitry Andric     // The two basic blocks that need the two compared values to be equivalent.
212bdd1243dSDimitry Andric     const BasicBlock *LBB;
213bdd1243dSDimitry Andric     const BasicBlock *RBB;
214bdd1243dSDimitry Andric   };
215bdd1243dSDimitry Andric 
216349cc55cSDimitry Andric   unsigned getUnprocPredCount(const BasicBlock *Block) const {
217*7a6dacacSDimitry Andric     return llvm::count_if(predecessors(Block), [&](const BasicBlock *Pred) {
218*7a6dacacSDimitry Andric       return !Blocks.contains(Pred);
219*7a6dacacSDimitry Andric     });
220349cc55cSDimitry Andric   }
221349cc55cSDimitry Andric 
222349cc55cSDimitry Andric   typedef std::pair<const BasicBlock *, const BasicBlock *> BlockPair;
223349cc55cSDimitry Andric 
224349cc55cSDimitry Andric   /// A type which sorts a priority queue by the number of unprocessed
225349cc55cSDimitry Andric   /// predecessor blocks it has remaining.
226349cc55cSDimitry Andric   ///
227349cc55cSDimitry Andric   /// This is actually really expensive to calculate.
228349cc55cSDimitry Andric   struct QueueSorter {
229349cc55cSDimitry Andric     const FunctionDifferenceEngine &fde;
230349cc55cSDimitry Andric     explicit QueueSorter(const FunctionDifferenceEngine &fde) : fde(fde) {}
231349cc55cSDimitry Andric 
232349cc55cSDimitry Andric     bool operator()(BlockPair &Old, BlockPair &New) {
233349cc55cSDimitry Andric       return fde.getUnprocPredCount(Old.first)
234349cc55cSDimitry Andric            < fde.getUnprocPredCount(New.first);
235349cc55cSDimitry Andric     }
236349cc55cSDimitry Andric   };
237349cc55cSDimitry Andric 
238349cc55cSDimitry Andric   /// A queue of unified blocks to process.
239349cc55cSDimitry Andric   PriorityQueue<BlockPair, QueueSorter, 20> Queue;
240349cc55cSDimitry Andric 
241349cc55cSDimitry Andric   /// Try to unify the given two blocks.  Enqueues them for processing
242349cc55cSDimitry Andric   /// if they haven't already been processed.
243349cc55cSDimitry Andric   ///
244349cc55cSDimitry Andric   /// Returns true if there was a problem unifying them.
245349cc55cSDimitry Andric   bool tryUnify(const BasicBlock *L, const BasicBlock *R) {
246349cc55cSDimitry Andric     const BasicBlock *&Ref = Blocks[L];
247349cc55cSDimitry Andric 
248349cc55cSDimitry Andric     if (Ref) {
249349cc55cSDimitry Andric       if (Ref == R) return false;
250349cc55cSDimitry Andric 
251349cc55cSDimitry Andric       Engine.logf("successor %l cannot be equivalent to %r; "
252349cc55cSDimitry Andric                   "it's already equivalent to %r")
253349cc55cSDimitry Andric         << L << R << Ref;
254349cc55cSDimitry Andric       return true;
255349cc55cSDimitry Andric     }
256349cc55cSDimitry Andric 
257349cc55cSDimitry Andric     Ref = R;
258349cc55cSDimitry Andric     Queue.insert(BlockPair(L, R));
259349cc55cSDimitry Andric     return false;
260349cc55cSDimitry Andric   }
261349cc55cSDimitry Andric 
262349cc55cSDimitry Andric   /// Unifies two instructions, given that they're known not to have
263349cc55cSDimitry Andric   /// structural differences.
264349cc55cSDimitry Andric   void unify(const Instruction *L, const Instruction *R) {
265349cc55cSDimitry Andric     DifferenceEngine::Context C(Engine, L, R);
266349cc55cSDimitry Andric 
267bdd1243dSDimitry Andric     bool Result = diff(L, R, true, true, true);
268349cc55cSDimitry Andric     assert(!Result && "structural differences second time around?");
269349cc55cSDimitry Andric     (void) Result;
270349cc55cSDimitry Andric     if (!L->use_empty())
271349cc55cSDimitry Andric       Values[L] = R;
272349cc55cSDimitry Andric   }
273349cc55cSDimitry Andric 
274349cc55cSDimitry Andric   void processQueue() {
275349cc55cSDimitry Andric     while (!Queue.empty()) {
276349cc55cSDimitry Andric       BlockPair Pair = Queue.remove_min();
277349cc55cSDimitry Andric       diff(Pair.first, Pair.second);
278349cc55cSDimitry Andric     }
279349cc55cSDimitry Andric   }
280349cc55cSDimitry Andric 
281bdd1243dSDimitry Andric   void checkAndReportDiffCandidates() {
282bdd1243dSDimitry Andric     for (BlockDiffCandidate &BDC : BlockDiffCandidates) {
283bdd1243dSDimitry Andric 
284bdd1243dSDimitry Andric       // Check assumptions
285bdd1243dSDimitry Andric       for (const auto &[L, R] : BDC.EquivalenceAssumptions) {
286bdd1243dSDimitry Andric         auto It = Values.find(L);
287bdd1243dSDimitry Andric         if (It == Values.end() || It->second != R) {
288bdd1243dSDimitry Andric           BDC.KnownToDiffer = true;
289bdd1243dSDimitry Andric           break;
290bdd1243dSDimitry Andric         }
291bdd1243dSDimitry Andric       }
292bdd1243dSDimitry Andric 
293bdd1243dSDimitry Andric       // Run block diff if the BBs differ
294bdd1243dSDimitry Andric       if (BDC.KnownToDiffer) {
295bdd1243dSDimitry Andric         DifferenceEngine::Context C(Engine, BDC.LBB, BDC.RBB);
296bdd1243dSDimitry Andric         runBlockDiff(BDC.LBB->begin(), BDC.RBB->begin());
297bdd1243dSDimitry Andric       }
298bdd1243dSDimitry Andric     }
299bdd1243dSDimitry Andric   }
300bdd1243dSDimitry Andric 
301349cc55cSDimitry Andric   void diff(const BasicBlock *L, const BasicBlock *R) {
302349cc55cSDimitry Andric     DifferenceEngine::Context C(Engine, L, R);
303349cc55cSDimitry Andric 
304349cc55cSDimitry Andric     BasicBlock::const_iterator LI = L->begin(), LE = L->end();
305349cc55cSDimitry Andric     BasicBlock::const_iterator RI = R->begin();
306349cc55cSDimitry Andric 
307349cc55cSDimitry Andric     do {
308349cc55cSDimitry Andric       assert(LI != LE && RI != R->end());
309349cc55cSDimitry Andric       const Instruction *LeftI = &*LI, *RightI = &*RI;
310349cc55cSDimitry Andric 
311349cc55cSDimitry Andric       // If the instructions differ, start the more sophisticated diff
312349cc55cSDimitry Andric       // algorithm at the start of the block.
313bdd1243dSDimitry Andric       if (diff(LeftI, RightI, false, false, true)) {
314349cc55cSDimitry Andric         TentativeValues.clear();
315bdd1243dSDimitry Andric         // Register (L, R) as diffing pair. Note that we could directly emit a
316bdd1243dSDimitry Andric         // block diff here, but this way we ensure all diffs are emitted in one
317bdd1243dSDimitry Andric         // consistent order, independent of whether the diffs were detected
318bdd1243dSDimitry Andric         // immediately or via invalid assumptions.
319bdd1243dSDimitry Andric         getOrCreateBlockDiffCandidate(L, R).KnownToDiffer = true;
320bdd1243dSDimitry Andric         return;
321349cc55cSDimitry Andric       }
322349cc55cSDimitry Andric 
323349cc55cSDimitry Andric       // Otherwise, tentatively unify them.
324349cc55cSDimitry Andric       if (!LeftI->use_empty())
325349cc55cSDimitry Andric         TentativeValues.insert(std::make_pair(LeftI, RightI));
326349cc55cSDimitry Andric 
327349cc55cSDimitry Andric       ++LI;
328349cc55cSDimitry Andric       ++RI;
329349cc55cSDimitry Andric     } while (LI != LE); // This is sufficient: we can't get equality of
330349cc55cSDimitry Andric                         // terminators if there are residual instructions.
331349cc55cSDimitry Andric 
332349cc55cSDimitry Andric     // Unify everything in the block, non-tentatively this time.
333349cc55cSDimitry Andric     TentativeValues.clear();
334349cc55cSDimitry Andric     for (LI = L->begin(), RI = R->begin(); LI != LE; ++LI, ++RI)
335349cc55cSDimitry Andric       unify(&*LI, &*RI);
336349cc55cSDimitry Andric   }
337349cc55cSDimitry Andric 
338349cc55cSDimitry Andric   bool matchForBlockDiff(const Instruction *L, const Instruction *R);
339349cc55cSDimitry Andric   void runBlockDiff(BasicBlock::const_iterator LI,
340349cc55cSDimitry Andric                     BasicBlock::const_iterator RI);
341349cc55cSDimitry Andric 
342349cc55cSDimitry Andric   bool diffCallSites(const CallBase &L, const CallBase &R, bool Complain) {
343349cc55cSDimitry Andric     // FIXME: call attributes
344bdd1243dSDimitry Andric     AssumptionContext AC = {L.getParent(), R.getParent()};
345bdd1243dSDimitry Andric     if (!equivalentAsOperands(L.getCalledOperand(), R.getCalledOperand(),
346bdd1243dSDimitry Andric                               &AC)) {
347349cc55cSDimitry Andric       if (Complain) Engine.log("called functions differ");
348349cc55cSDimitry Andric       return true;
349349cc55cSDimitry Andric     }
350349cc55cSDimitry Andric     if (L.arg_size() != R.arg_size()) {
351349cc55cSDimitry Andric       if (Complain) Engine.log("argument counts differ");
352349cc55cSDimitry Andric       return true;
353349cc55cSDimitry Andric     }
354349cc55cSDimitry Andric     for (unsigned I = 0, E = L.arg_size(); I != E; ++I)
355bdd1243dSDimitry Andric       if (!equivalentAsOperands(L.getArgOperand(I), R.getArgOperand(I), &AC)) {
356349cc55cSDimitry Andric         if (Complain)
357349cc55cSDimitry Andric           Engine.logf("arguments %l and %r differ")
358349cc55cSDimitry Andric               << L.getArgOperand(I) << R.getArgOperand(I);
359349cc55cSDimitry Andric         return true;
360349cc55cSDimitry Andric       }
361349cc55cSDimitry Andric     return false;
362349cc55cSDimitry Andric   }
363349cc55cSDimitry Andric 
364bdd1243dSDimitry Andric   // If AllowAssumptions is enabled, whenever we encounter a pair of values
365bdd1243dSDimitry Andric   // that we cannot prove to be equivalent, we assume equivalence and store that
366bdd1243dSDimitry Andric   // assumption to be checked later in BlockDiffCandidates.
367349cc55cSDimitry Andric   bool diff(const Instruction *L, const Instruction *R, bool Complain,
368bdd1243dSDimitry Andric             bool TryUnify, bool AllowAssumptions) {
369349cc55cSDimitry Andric     // FIXME: metadata (if Complain is set)
370bdd1243dSDimitry Andric     AssumptionContext ACValue = {L->getParent(), R->getParent()};
371bdd1243dSDimitry Andric     // nullptr AssumptionContext disables assumption generation.
372bdd1243dSDimitry Andric     const AssumptionContext *AC = AllowAssumptions ? &ACValue : nullptr;
373349cc55cSDimitry Andric 
374349cc55cSDimitry Andric     // Different opcodes always imply different operations.
375349cc55cSDimitry Andric     if (L->getOpcode() != R->getOpcode()) {
376349cc55cSDimitry Andric       if (Complain) Engine.log("different instruction types");
377349cc55cSDimitry Andric       return true;
378349cc55cSDimitry Andric     }
379349cc55cSDimitry Andric 
380349cc55cSDimitry Andric     if (isa<CmpInst>(L)) {
381349cc55cSDimitry Andric       if (cast<CmpInst>(L)->getPredicate()
382349cc55cSDimitry Andric             != cast<CmpInst>(R)->getPredicate()) {
383349cc55cSDimitry Andric         if (Complain) Engine.log("different predicates");
384349cc55cSDimitry Andric         return true;
385349cc55cSDimitry Andric       }
386349cc55cSDimitry Andric     } else if (isa<CallInst>(L)) {
387349cc55cSDimitry Andric       return diffCallSites(cast<CallInst>(*L), cast<CallInst>(*R), Complain);
388349cc55cSDimitry Andric     } else if (isa<PHINode>(L)) {
3894824e7fdSDimitry Andric       const PHINode &LI = cast<PHINode>(*L);
3904824e7fdSDimitry Andric       const PHINode &RI = cast<PHINode>(*R);
391349cc55cSDimitry Andric 
392349cc55cSDimitry Andric       // This is really weird;  type uniquing is broken?
3934824e7fdSDimitry Andric       if (LI.getType() != RI.getType()) {
3944824e7fdSDimitry Andric         if (!LI.getType()->isPointerTy() || !RI.getType()->isPointerTy()) {
395349cc55cSDimitry Andric           if (Complain) Engine.log("different phi types");
396349cc55cSDimitry Andric           return true;
397349cc55cSDimitry Andric         }
398349cc55cSDimitry Andric       }
3994824e7fdSDimitry Andric 
4004824e7fdSDimitry Andric       if (LI.getNumIncomingValues() != RI.getNumIncomingValues()) {
4014824e7fdSDimitry Andric         if (Complain)
4024824e7fdSDimitry Andric           Engine.log("PHI node # of incoming values differ");
4034824e7fdSDimitry Andric         return true;
4044824e7fdSDimitry Andric       }
4054824e7fdSDimitry Andric 
4064824e7fdSDimitry Andric       for (unsigned I = 0; I < LI.getNumIncomingValues(); ++I) {
4074824e7fdSDimitry Andric         if (TryUnify)
4084824e7fdSDimitry Andric           tryUnify(LI.getIncomingBlock(I), RI.getIncomingBlock(I));
4094824e7fdSDimitry Andric 
4104824e7fdSDimitry Andric         if (!equivalentAsOperands(LI.getIncomingValue(I),
411bdd1243dSDimitry Andric                                   RI.getIncomingValue(I), AC)) {
4124824e7fdSDimitry Andric           if (Complain)
4134824e7fdSDimitry Andric             Engine.log("PHI node incoming values differ");
4144824e7fdSDimitry Andric           return true;
4154824e7fdSDimitry Andric         }
4164824e7fdSDimitry Andric       }
4174824e7fdSDimitry Andric 
418349cc55cSDimitry Andric       return false;
419349cc55cSDimitry Andric 
420349cc55cSDimitry Andric     // Terminators.
421349cc55cSDimitry Andric     } else if (isa<InvokeInst>(L)) {
422349cc55cSDimitry Andric       const InvokeInst &LI = cast<InvokeInst>(*L);
423349cc55cSDimitry Andric       const InvokeInst &RI = cast<InvokeInst>(*R);
424349cc55cSDimitry Andric       if (diffCallSites(LI, RI, Complain))
425349cc55cSDimitry Andric         return true;
426349cc55cSDimitry Andric 
427349cc55cSDimitry Andric       if (TryUnify) {
428349cc55cSDimitry Andric         tryUnify(LI.getNormalDest(), RI.getNormalDest());
429349cc55cSDimitry Andric         tryUnify(LI.getUnwindDest(), RI.getUnwindDest());
430349cc55cSDimitry Andric       }
431349cc55cSDimitry Andric       return false;
432349cc55cSDimitry Andric 
433349cc55cSDimitry Andric     } else if (isa<CallBrInst>(L)) {
434349cc55cSDimitry Andric       const CallBrInst &LI = cast<CallBrInst>(*L);
435349cc55cSDimitry Andric       const CallBrInst &RI = cast<CallBrInst>(*R);
436349cc55cSDimitry Andric       if (LI.getNumIndirectDests() != RI.getNumIndirectDests()) {
437349cc55cSDimitry Andric         if (Complain)
438349cc55cSDimitry Andric           Engine.log("callbr # of indirect destinations differ");
439349cc55cSDimitry Andric         return true;
440349cc55cSDimitry Andric       }
441349cc55cSDimitry Andric 
442349cc55cSDimitry Andric       // Perform the "try unify" step so that we can equate the indirect
443349cc55cSDimitry Andric       // destinations before checking the call site.
444349cc55cSDimitry Andric       for (unsigned I = 0; I < LI.getNumIndirectDests(); I++)
445349cc55cSDimitry Andric         tryUnify(LI.getIndirectDest(I), RI.getIndirectDest(I));
446349cc55cSDimitry Andric 
447349cc55cSDimitry Andric       if (diffCallSites(LI, RI, Complain))
448349cc55cSDimitry Andric         return true;
449349cc55cSDimitry Andric 
450349cc55cSDimitry Andric       if (TryUnify)
451349cc55cSDimitry Andric         tryUnify(LI.getDefaultDest(), RI.getDefaultDest());
452349cc55cSDimitry Andric       return false;
453349cc55cSDimitry Andric 
454349cc55cSDimitry Andric     } else if (isa<BranchInst>(L)) {
455349cc55cSDimitry Andric       const BranchInst *LI = cast<BranchInst>(L);
456349cc55cSDimitry Andric       const BranchInst *RI = cast<BranchInst>(R);
457349cc55cSDimitry Andric       if (LI->isConditional() != RI->isConditional()) {
458349cc55cSDimitry Andric         if (Complain) Engine.log("branch conditionality differs");
459349cc55cSDimitry Andric         return true;
460349cc55cSDimitry Andric       }
461349cc55cSDimitry Andric 
462349cc55cSDimitry Andric       if (LI->isConditional()) {
463bdd1243dSDimitry Andric         if (!equivalentAsOperands(LI->getCondition(), RI->getCondition(), AC)) {
464349cc55cSDimitry Andric           if (Complain) Engine.log("branch conditions differ");
465349cc55cSDimitry Andric           return true;
466349cc55cSDimitry Andric         }
467349cc55cSDimitry Andric         if (TryUnify) tryUnify(LI->getSuccessor(1), RI->getSuccessor(1));
468349cc55cSDimitry Andric       }
469349cc55cSDimitry Andric       if (TryUnify) tryUnify(LI->getSuccessor(0), RI->getSuccessor(0));
470349cc55cSDimitry Andric       return false;
471349cc55cSDimitry Andric 
472349cc55cSDimitry Andric     } else if (isa<IndirectBrInst>(L)) {
473349cc55cSDimitry Andric       const IndirectBrInst *LI = cast<IndirectBrInst>(L);
474349cc55cSDimitry Andric       const IndirectBrInst *RI = cast<IndirectBrInst>(R);
475349cc55cSDimitry Andric       if (LI->getNumDestinations() != RI->getNumDestinations()) {
476349cc55cSDimitry Andric         if (Complain) Engine.log("indirectbr # of destinations differ");
477349cc55cSDimitry Andric         return true;
478349cc55cSDimitry Andric       }
479349cc55cSDimitry Andric 
480bdd1243dSDimitry Andric       if (!equivalentAsOperands(LI->getAddress(), RI->getAddress(), AC)) {
481349cc55cSDimitry Andric         if (Complain) Engine.log("indirectbr addresses differ");
482349cc55cSDimitry Andric         return true;
483349cc55cSDimitry Andric       }
484349cc55cSDimitry Andric 
485349cc55cSDimitry Andric       if (TryUnify) {
486349cc55cSDimitry Andric         for (unsigned i = 0; i < LI->getNumDestinations(); i++) {
487349cc55cSDimitry Andric           tryUnify(LI->getDestination(i), RI->getDestination(i));
488349cc55cSDimitry Andric         }
489349cc55cSDimitry Andric       }
490349cc55cSDimitry Andric       return false;
491349cc55cSDimitry Andric 
492349cc55cSDimitry Andric     } else if (isa<SwitchInst>(L)) {
493349cc55cSDimitry Andric       const SwitchInst *LI = cast<SwitchInst>(L);
494349cc55cSDimitry Andric       const SwitchInst *RI = cast<SwitchInst>(R);
495bdd1243dSDimitry Andric       if (!equivalentAsOperands(LI->getCondition(), RI->getCondition(), AC)) {
496349cc55cSDimitry Andric         if (Complain) Engine.log("switch conditions differ");
497349cc55cSDimitry Andric         return true;
498349cc55cSDimitry Andric       }
499349cc55cSDimitry Andric       if (TryUnify) tryUnify(LI->getDefaultDest(), RI->getDefaultDest());
500349cc55cSDimitry Andric 
501349cc55cSDimitry Andric       bool Difference = false;
502349cc55cSDimitry Andric 
503349cc55cSDimitry Andric       DenseMap<const ConstantInt *, const BasicBlock *> LCases;
504349cc55cSDimitry Andric       for (auto Case : LI->cases())
505349cc55cSDimitry Andric         LCases[Case.getCaseValue()] = Case.getCaseSuccessor();
506349cc55cSDimitry Andric 
507349cc55cSDimitry Andric       for (auto Case : RI->cases()) {
508349cc55cSDimitry Andric         const ConstantInt *CaseValue = Case.getCaseValue();
509349cc55cSDimitry Andric         const BasicBlock *LCase = LCases[CaseValue];
510349cc55cSDimitry Andric         if (LCase) {
511349cc55cSDimitry Andric           if (TryUnify)
512349cc55cSDimitry Andric             tryUnify(LCase, Case.getCaseSuccessor());
513349cc55cSDimitry Andric           LCases.erase(CaseValue);
514349cc55cSDimitry Andric         } else if (Complain || !Difference) {
515349cc55cSDimitry Andric           if (Complain)
516349cc55cSDimitry Andric             Engine.logf("right switch has extra case %r") << CaseValue;
517349cc55cSDimitry Andric           Difference = true;
518349cc55cSDimitry Andric         }
519349cc55cSDimitry Andric       }
520349cc55cSDimitry Andric       if (!Difference)
521349cc55cSDimitry Andric         for (DenseMap<const ConstantInt *, const BasicBlock *>::iterator
522349cc55cSDimitry Andric                  I = LCases.begin(),
523349cc55cSDimitry Andric                  E = LCases.end();
524349cc55cSDimitry Andric              I != E; ++I) {
525349cc55cSDimitry Andric           if (Complain)
526349cc55cSDimitry Andric             Engine.logf("left switch has extra case %l") << I->first;
527349cc55cSDimitry Andric           Difference = true;
528349cc55cSDimitry Andric         }
529349cc55cSDimitry Andric       return Difference;
530349cc55cSDimitry Andric     } else if (isa<UnreachableInst>(L)) {
531349cc55cSDimitry Andric       return false;
532349cc55cSDimitry Andric     }
533349cc55cSDimitry Andric 
534349cc55cSDimitry Andric     if (L->getNumOperands() != R->getNumOperands()) {
535349cc55cSDimitry Andric       if (Complain) Engine.log("instructions have different operand counts");
536349cc55cSDimitry Andric       return true;
537349cc55cSDimitry Andric     }
538349cc55cSDimitry Andric 
539349cc55cSDimitry Andric     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
540349cc55cSDimitry Andric       Value *LO = L->getOperand(I), *RO = R->getOperand(I);
541bdd1243dSDimitry Andric       if (!equivalentAsOperands(LO, RO, AC)) {
542349cc55cSDimitry Andric         if (Complain) Engine.logf("operands %l and %r differ") << LO << RO;
543349cc55cSDimitry Andric         return true;
544349cc55cSDimitry Andric       }
545349cc55cSDimitry Andric     }
546349cc55cSDimitry Andric 
547349cc55cSDimitry Andric     return false;
548349cc55cSDimitry Andric   }
549349cc55cSDimitry Andric 
550349cc55cSDimitry Andric public:
551bdd1243dSDimitry Andric   bool equivalentAsOperands(const Constant *L, const Constant *R,
552bdd1243dSDimitry Andric                             const AssumptionContext *AC) {
553349cc55cSDimitry Andric     // Use equality as a preliminary filter.
554349cc55cSDimitry Andric     if (L == R)
555349cc55cSDimitry Andric       return true;
556349cc55cSDimitry Andric 
557349cc55cSDimitry Andric     if (L->getValueID() != R->getValueID())
558349cc55cSDimitry Andric       return false;
559349cc55cSDimitry Andric 
560349cc55cSDimitry Andric     // Ask the engine about global values.
561349cc55cSDimitry Andric     if (isa<GlobalValue>(L))
562349cc55cSDimitry Andric       return Engine.equivalentAsOperands(cast<GlobalValue>(L),
563349cc55cSDimitry Andric                                          cast<GlobalValue>(R));
564349cc55cSDimitry Andric 
565349cc55cSDimitry Andric     // Compare constant expressions structurally.
566349cc55cSDimitry Andric     if (isa<ConstantExpr>(L))
567bdd1243dSDimitry Andric       return equivalentAsOperands(cast<ConstantExpr>(L), cast<ConstantExpr>(R),
568bdd1243dSDimitry Andric                                   AC);
569349cc55cSDimitry Andric 
570349cc55cSDimitry Andric     // Constants of the "same type" don't always actually have the same
571349cc55cSDimitry Andric     // type; I don't know why.  Just white-list them.
572349cc55cSDimitry Andric     if (isa<ConstantPointerNull>(L) || isa<UndefValue>(L) || isa<ConstantAggregateZero>(L))
573349cc55cSDimitry Andric       return true;
574349cc55cSDimitry Andric 
575349cc55cSDimitry Andric     // Block addresses only match if we've already encountered the
576349cc55cSDimitry Andric     // block.  FIXME: tentative matches?
577349cc55cSDimitry Andric     if (isa<BlockAddress>(L))
578349cc55cSDimitry Andric       return Blocks[cast<BlockAddress>(L)->getBasicBlock()]
579349cc55cSDimitry Andric                  == cast<BlockAddress>(R)->getBasicBlock();
580349cc55cSDimitry Andric 
581349cc55cSDimitry Andric     // If L and R are ConstantVectors, compare each element
582349cc55cSDimitry Andric     if (isa<ConstantVector>(L)) {
583349cc55cSDimitry Andric       const ConstantVector *CVL = cast<ConstantVector>(L);
584349cc55cSDimitry Andric       const ConstantVector *CVR = cast<ConstantVector>(R);
585349cc55cSDimitry Andric       if (CVL->getType()->getNumElements() != CVR->getType()->getNumElements())
586349cc55cSDimitry Andric         return false;
587349cc55cSDimitry Andric       for (unsigned i = 0; i < CVL->getType()->getNumElements(); i++) {
588bdd1243dSDimitry Andric         if (!equivalentAsOperands(CVL->getOperand(i), CVR->getOperand(i), AC))
589349cc55cSDimitry Andric           return false;
590349cc55cSDimitry Andric       }
591349cc55cSDimitry Andric       return true;
592349cc55cSDimitry Andric     }
593349cc55cSDimitry Andric 
594349cc55cSDimitry Andric     // If L and R are ConstantArrays, compare the element count and types.
595349cc55cSDimitry Andric     if (isa<ConstantArray>(L)) {
596349cc55cSDimitry Andric       const ConstantArray *CAL = cast<ConstantArray>(L);
597349cc55cSDimitry Andric       const ConstantArray *CAR = cast<ConstantArray>(R);
598349cc55cSDimitry Andric       // Sometimes a type may be equivalent, but not uniquified---e.g. it may
599349cc55cSDimitry Andric       // contain a GEP instruction. Do a deeper comparison of the types.
600349cc55cSDimitry Andric       if (CAL->getType()->getNumElements() != CAR->getType()->getNumElements())
601349cc55cSDimitry Andric         return false;
602349cc55cSDimitry Andric 
603349cc55cSDimitry Andric       for (unsigned I = 0; I < CAL->getType()->getNumElements(); ++I) {
604349cc55cSDimitry Andric         if (!equivalentAsOperands(CAL->getAggregateElement(I),
605bdd1243dSDimitry Andric                                   CAR->getAggregateElement(I), AC))
606349cc55cSDimitry Andric           return false;
607349cc55cSDimitry Andric       }
608349cc55cSDimitry Andric 
609349cc55cSDimitry Andric       return true;
610349cc55cSDimitry Andric     }
611349cc55cSDimitry Andric 
612349cc55cSDimitry Andric     // If L and R are ConstantStructs, compare each field and type.
613349cc55cSDimitry Andric     if (isa<ConstantStruct>(L)) {
614349cc55cSDimitry Andric       const ConstantStruct *CSL = cast<ConstantStruct>(L);
615349cc55cSDimitry Andric       const ConstantStruct *CSR = cast<ConstantStruct>(R);
616349cc55cSDimitry Andric 
617349cc55cSDimitry Andric       const StructType *LTy = cast<StructType>(CSL->getType());
618349cc55cSDimitry Andric       const StructType *RTy = cast<StructType>(CSR->getType());
619349cc55cSDimitry Andric 
620349cc55cSDimitry Andric       // The StructTypes should have the same attributes. Don't use
621349cc55cSDimitry Andric       // isLayoutIdentical(), because that just checks the element pointers,
622349cc55cSDimitry Andric       // which may not work here.
623349cc55cSDimitry Andric       if (LTy->getNumElements() != RTy->getNumElements() ||
624349cc55cSDimitry Andric           LTy->isPacked() != RTy->isPacked())
625349cc55cSDimitry Andric         return false;
626349cc55cSDimitry Andric 
627349cc55cSDimitry Andric       for (unsigned I = 0; I < LTy->getNumElements(); I++) {
628349cc55cSDimitry Andric         const Value *LAgg = CSL->getAggregateElement(I);
629349cc55cSDimitry Andric         const Value *RAgg = CSR->getAggregateElement(I);
630349cc55cSDimitry Andric 
631349cc55cSDimitry Andric         if (LAgg == SavedLHS || RAgg == SavedRHS) {
632349cc55cSDimitry Andric           if (LAgg != SavedLHS || RAgg != SavedRHS)
633349cc55cSDimitry Andric             // If the left and right operands aren't both re-analyzing the
634349cc55cSDimitry Andric             // variable, then the initialiers don't match, so report "false".
635349cc55cSDimitry Andric             // Otherwise, we skip these operands..
636349cc55cSDimitry Andric             return false;
637349cc55cSDimitry Andric 
638349cc55cSDimitry Andric           continue;
639349cc55cSDimitry Andric         }
640349cc55cSDimitry Andric 
641bdd1243dSDimitry Andric         if (!equivalentAsOperands(LAgg, RAgg, AC)) {
642349cc55cSDimitry Andric           return false;
643349cc55cSDimitry Andric         }
644349cc55cSDimitry Andric       }
645349cc55cSDimitry Andric 
646349cc55cSDimitry Andric       return true;
647349cc55cSDimitry Andric     }
648349cc55cSDimitry Andric 
649349cc55cSDimitry Andric     return false;
650349cc55cSDimitry Andric   }
651349cc55cSDimitry Andric 
652bdd1243dSDimitry Andric   bool equivalentAsOperands(const ConstantExpr *L, const ConstantExpr *R,
653bdd1243dSDimitry Andric                             const AssumptionContext *AC) {
654349cc55cSDimitry Andric     if (L == R)
655349cc55cSDimitry Andric       return true;
656349cc55cSDimitry Andric 
657349cc55cSDimitry Andric     if (L->getOpcode() != R->getOpcode())
658349cc55cSDimitry Andric       return false;
659349cc55cSDimitry Andric 
660349cc55cSDimitry Andric     switch (L->getOpcode()) {
661349cc55cSDimitry Andric     case Instruction::GetElementPtr:
662349cc55cSDimitry Andric       // FIXME: inbounds?
663349cc55cSDimitry Andric       break;
664349cc55cSDimitry Andric 
665349cc55cSDimitry Andric     default:
666349cc55cSDimitry Andric       break;
667349cc55cSDimitry Andric     }
668349cc55cSDimitry Andric 
669349cc55cSDimitry Andric     if (L->getNumOperands() != R->getNumOperands())
670349cc55cSDimitry Andric       return false;
671349cc55cSDimitry Andric 
672349cc55cSDimitry Andric     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
673349cc55cSDimitry Andric       const auto *LOp = L->getOperand(I);
674349cc55cSDimitry Andric       const auto *ROp = R->getOperand(I);
675349cc55cSDimitry Andric 
676349cc55cSDimitry Andric       if (LOp == SavedLHS || ROp == SavedRHS) {
677349cc55cSDimitry Andric         if (LOp != SavedLHS || ROp != SavedRHS)
678349cc55cSDimitry Andric           // If the left and right operands aren't both re-analyzing the
679349cc55cSDimitry Andric           // variable, then the initialiers don't match, so report "false".
680349cc55cSDimitry Andric           // Otherwise, we skip these operands..
681349cc55cSDimitry Andric           return false;
682349cc55cSDimitry Andric 
683349cc55cSDimitry Andric         continue;
684349cc55cSDimitry Andric       }
685349cc55cSDimitry Andric 
686bdd1243dSDimitry Andric       if (!equivalentAsOperands(LOp, ROp, AC))
687349cc55cSDimitry Andric         return false;
688349cc55cSDimitry Andric     }
689349cc55cSDimitry Andric 
690349cc55cSDimitry Andric     return true;
691349cc55cSDimitry Andric   }
692349cc55cSDimitry Andric 
693bdd1243dSDimitry Andric   // There are cases where we cannot determine whether two values are
694bdd1243dSDimitry Andric   // equivalent, because it depends on not yet processed basic blocks -- see the
695bdd1243dSDimitry Andric   // documentation on assumptions.
696bdd1243dSDimitry Andric   //
697bdd1243dSDimitry Andric   // AC is the context in which we are currently performing a diff.
698bdd1243dSDimitry Andric   // When we encounter a pair of values for which we can neither prove
699bdd1243dSDimitry Andric   // equivalence nor the opposite, we do the following:
700bdd1243dSDimitry Andric   //  * If AC is nullptr, we treat the pair as non-equivalent.
701bdd1243dSDimitry Andric   //  * If AC is set, we add an assumption for the basic blocks given by AC,
702bdd1243dSDimitry Andric   //    and treat the pair as equivalent. The assumption is checked later.
703bdd1243dSDimitry Andric   bool equivalentAsOperands(const Value *L, const Value *R,
704bdd1243dSDimitry Andric                             const AssumptionContext *AC) {
705349cc55cSDimitry Andric     // Fall out if the values have different kind.
706349cc55cSDimitry Andric     // This possibly shouldn't take priority over oracles.
707349cc55cSDimitry Andric     if (L->getValueID() != R->getValueID())
708349cc55cSDimitry Andric       return false;
709349cc55cSDimitry Andric 
710349cc55cSDimitry Andric     // Value subtypes:  Argument, Constant, Instruction, BasicBlock,
711349cc55cSDimitry Andric     //                  InlineAsm, MDNode, MDString, PseudoSourceValue
712349cc55cSDimitry Andric 
713349cc55cSDimitry Andric     if (isa<Constant>(L))
714bdd1243dSDimitry Andric       return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R), AC);
715349cc55cSDimitry Andric 
716bdd1243dSDimitry Andric     if (isa<Instruction>(L)) {
717bdd1243dSDimitry Andric       auto It = Values.find(L);
718bdd1243dSDimitry Andric       if (It != Values.end())
719bdd1243dSDimitry Andric         return It->second == R;
720bdd1243dSDimitry Andric 
721bdd1243dSDimitry Andric       if (TentativeValues.count(std::make_pair(L, R)))
722bdd1243dSDimitry Andric         return true;
723bdd1243dSDimitry Andric 
724bdd1243dSDimitry Andric       // L and R might be equivalent, this could depend on not yet processed
725bdd1243dSDimitry Andric       // basic blocks, so we cannot decide here.
726bdd1243dSDimitry Andric       if (AC) {
727bdd1243dSDimitry Andric         // Add an assumption, unless there is a conflict with an existing one
728bdd1243dSDimitry Andric         BlockDiffCandidate &BDC =
729bdd1243dSDimitry Andric             getOrCreateBlockDiffCandidate(AC->LBB, AC->RBB);
730bdd1243dSDimitry Andric         auto InsertionResult = BDC.EquivalenceAssumptions.insert({L, R});
731bdd1243dSDimitry Andric         if (!InsertionResult.second && InsertionResult.first->second != R) {
732bdd1243dSDimitry Andric           // We already have a conflicting equivalence assumption for L, so at
733bdd1243dSDimitry Andric           // least one must be wrong, and we know that there is a diff.
734bdd1243dSDimitry Andric           BDC.KnownToDiffer = true;
735bdd1243dSDimitry Andric           BDC.EquivalenceAssumptions.clear();
736bdd1243dSDimitry Andric           return false;
737bdd1243dSDimitry Andric         }
738bdd1243dSDimitry Andric         // Optimistically assume equivalence, and check later once all BBs
739bdd1243dSDimitry Andric         // have been processed.
740bdd1243dSDimitry Andric         return true;
741bdd1243dSDimitry Andric       }
742bdd1243dSDimitry Andric 
743bdd1243dSDimitry Andric       // Assumptions disabled, so pessimistically assume non-equivalence.
744bdd1243dSDimitry Andric       return false;
745bdd1243dSDimitry Andric     }
746349cc55cSDimitry Andric 
747349cc55cSDimitry Andric     if (isa<Argument>(L))
748349cc55cSDimitry Andric       return Values[L] == R;
749349cc55cSDimitry Andric 
750349cc55cSDimitry Andric     if (isa<BasicBlock>(L))
751349cc55cSDimitry Andric       return Blocks[cast<BasicBlock>(L)] != R;
752349cc55cSDimitry Andric 
753349cc55cSDimitry Andric     // Pretend everything else is identical.
754349cc55cSDimitry Andric     return true;
755349cc55cSDimitry Andric   }
756349cc55cSDimitry Andric 
757349cc55cSDimitry Andric   // Avoid a gcc warning about accessing 'this' in an initializer.
758349cc55cSDimitry Andric   FunctionDifferenceEngine *this_() { return this; }
759349cc55cSDimitry Andric 
760349cc55cSDimitry Andric public:
761349cc55cSDimitry Andric   FunctionDifferenceEngine(DifferenceEngine &Engine,
762349cc55cSDimitry Andric                            const Value *SavedLHS = nullptr,
763349cc55cSDimitry Andric                            const Value *SavedRHS = nullptr)
764349cc55cSDimitry Andric       : Engine(Engine), SavedLHS(SavedLHS), SavedRHS(SavedRHS),
765349cc55cSDimitry Andric         Queue(QueueSorter(*this_())) {}
766349cc55cSDimitry Andric 
767349cc55cSDimitry Andric   void diff(const Function *L, const Function *R) {
768bdd1243dSDimitry Andric     assert(Values.empty() && "Multiple diffs per engine are not supported!");
769bdd1243dSDimitry Andric 
770349cc55cSDimitry Andric     if (L->arg_size() != R->arg_size())
771349cc55cSDimitry Andric       Engine.log("different argument counts");
772349cc55cSDimitry Andric 
773349cc55cSDimitry Andric     // Map the arguments.
774349cc55cSDimitry Andric     for (Function::const_arg_iterator LI = L->arg_begin(), LE = L->arg_end(),
775349cc55cSDimitry Andric                                       RI = R->arg_begin(), RE = R->arg_end();
776349cc55cSDimitry Andric          LI != LE && RI != RE; ++LI, ++RI)
777349cc55cSDimitry Andric       Values[&*LI] = &*RI;
778349cc55cSDimitry Andric 
779349cc55cSDimitry Andric     tryUnify(&*L->begin(), &*R->begin());
780349cc55cSDimitry Andric     processQueue();
781bdd1243dSDimitry Andric     checkAndReportDiffCandidates();
782349cc55cSDimitry Andric   }
783349cc55cSDimitry Andric };
784349cc55cSDimitry Andric 
785349cc55cSDimitry Andric struct DiffEntry {
7865f757f3fSDimitry Andric   DiffEntry() = default;
787349cc55cSDimitry Andric 
7885f757f3fSDimitry Andric   unsigned Cost = 0;
789349cc55cSDimitry Andric   llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange
790349cc55cSDimitry Andric };
791349cc55cSDimitry Andric 
792349cc55cSDimitry Andric bool FunctionDifferenceEngine::matchForBlockDiff(const Instruction *L,
793349cc55cSDimitry Andric                                                  const Instruction *R) {
794bdd1243dSDimitry Andric   return !diff(L, R, false, false, false);
795349cc55cSDimitry Andric }
796349cc55cSDimitry Andric 
797349cc55cSDimitry Andric void FunctionDifferenceEngine::runBlockDiff(BasicBlock::const_iterator LStart,
798349cc55cSDimitry Andric                                             BasicBlock::const_iterator RStart) {
799349cc55cSDimitry Andric   BasicBlock::const_iterator LE = LStart->getParent()->end();
800349cc55cSDimitry Andric   BasicBlock::const_iterator RE = RStart->getParent()->end();
801349cc55cSDimitry Andric 
802349cc55cSDimitry Andric   unsigned NL = std::distance(LStart, LE);
803349cc55cSDimitry Andric 
804349cc55cSDimitry Andric   SmallVector<DiffEntry, 20> Paths1(NL+1);
805349cc55cSDimitry Andric   SmallVector<DiffEntry, 20> Paths2(NL+1);
806349cc55cSDimitry Andric 
807349cc55cSDimitry Andric   DiffEntry *Cur = Paths1.data();
808349cc55cSDimitry Andric   DiffEntry *Next = Paths2.data();
809349cc55cSDimitry Andric 
810349cc55cSDimitry Andric   const unsigned LeftCost = 2;
811349cc55cSDimitry Andric   const unsigned RightCost = 2;
812349cc55cSDimitry Andric   const unsigned MatchCost = 0;
813349cc55cSDimitry Andric 
814349cc55cSDimitry Andric   assert(TentativeValues.empty());
815349cc55cSDimitry Andric 
816349cc55cSDimitry Andric   // Initialize the first column.
817349cc55cSDimitry Andric   for (unsigned I = 0; I != NL+1; ++I) {
818349cc55cSDimitry Andric     Cur[I].Cost = I * LeftCost;
819349cc55cSDimitry Andric     for (unsigned J = 0; J != I; ++J)
820349cc55cSDimitry Andric       Cur[I].Path.push_back(DC_left);
821349cc55cSDimitry Andric   }
822349cc55cSDimitry Andric 
823349cc55cSDimitry Andric   for (BasicBlock::const_iterator RI = RStart; RI != RE; ++RI) {
824349cc55cSDimitry Andric     // Initialize the first row.
825349cc55cSDimitry Andric     Next[0] = Cur[0];
826349cc55cSDimitry Andric     Next[0].Cost += RightCost;
827349cc55cSDimitry Andric     Next[0].Path.push_back(DC_right);
828349cc55cSDimitry Andric 
829349cc55cSDimitry Andric     unsigned Index = 1;
830349cc55cSDimitry Andric     for (BasicBlock::const_iterator LI = LStart; LI != LE; ++LI, ++Index) {
831349cc55cSDimitry Andric       if (matchForBlockDiff(&*LI, &*RI)) {
832349cc55cSDimitry Andric         Next[Index] = Cur[Index-1];
833349cc55cSDimitry Andric         Next[Index].Cost += MatchCost;
834349cc55cSDimitry Andric         Next[Index].Path.push_back(DC_match);
835349cc55cSDimitry Andric         TentativeValues.insert(std::make_pair(&*LI, &*RI));
836349cc55cSDimitry Andric       } else if (Next[Index-1].Cost <= Cur[Index].Cost) {
837349cc55cSDimitry Andric         Next[Index] = Next[Index-1];
838349cc55cSDimitry Andric         Next[Index].Cost += LeftCost;
839349cc55cSDimitry Andric         Next[Index].Path.push_back(DC_left);
840349cc55cSDimitry Andric       } else {
841349cc55cSDimitry Andric         Next[Index] = Cur[Index];
842349cc55cSDimitry Andric         Next[Index].Cost += RightCost;
843349cc55cSDimitry Andric         Next[Index].Path.push_back(DC_right);
844349cc55cSDimitry Andric       }
845349cc55cSDimitry Andric     }
846349cc55cSDimitry Andric 
847349cc55cSDimitry Andric     std::swap(Cur, Next);
848349cc55cSDimitry Andric   }
849349cc55cSDimitry Andric 
850349cc55cSDimitry Andric   // We don't need the tentative values anymore; everything from here
851349cc55cSDimitry Andric   // on out should be non-tentative.
852349cc55cSDimitry Andric   TentativeValues.clear();
853349cc55cSDimitry Andric 
854349cc55cSDimitry Andric   SmallVectorImpl<char> &Path = Cur[NL].Path;
855349cc55cSDimitry Andric   BasicBlock::const_iterator LI = LStart, RI = RStart;
856349cc55cSDimitry Andric 
857349cc55cSDimitry Andric   DiffLogBuilder Diff(Engine.getConsumer());
858349cc55cSDimitry Andric 
859349cc55cSDimitry Andric   // Drop trailing matches.
860349cc55cSDimitry Andric   while (Path.size() && Path.back() == DC_match)
861349cc55cSDimitry Andric     Path.pop_back();
862349cc55cSDimitry Andric 
863349cc55cSDimitry Andric   // Skip leading matches.
864349cc55cSDimitry Andric   SmallVectorImpl<char>::iterator
865349cc55cSDimitry Andric     PI = Path.begin(), PE = Path.end();
866349cc55cSDimitry Andric   while (PI != PE && *PI == DC_match) {
867349cc55cSDimitry Andric     unify(&*LI, &*RI);
868349cc55cSDimitry Andric     ++PI;
869349cc55cSDimitry Andric     ++LI;
870349cc55cSDimitry Andric     ++RI;
871349cc55cSDimitry Andric   }
872349cc55cSDimitry Andric 
873349cc55cSDimitry Andric   for (; PI != PE; ++PI) {
874349cc55cSDimitry Andric     switch (static_cast<DiffChange>(*PI)) {
875349cc55cSDimitry Andric     case DC_match:
876349cc55cSDimitry Andric       assert(LI != LE && RI != RE);
877349cc55cSDimitry Andric       {
878349cc55cSDimitry Andric         const Instruction *L = &*LI, *R = &*RI;
879349cc55cSDimitry Andric         unify(L, R);
880349cc55cSDimitry Andric         Diff.addMatch(L, R);
881349cc55cSDimitry Andric       }
882349cc55cSDimitry Andric       ++LI; ++RI;
883349cc55cSDimitry Andric       break;
884349cc55cSDimitry Andric 
885349cc55cSDimitry Andric     case DC_left:
886349cc55cSDimitry Andric       assert(LI != LE);
887349cc55cSDimitry Andric       Diff.addLeft(&*LI);
888349cc55cSDimitry Andric       ++LI;
889349cc55cSDimitry Andric       break;
890349cc55cSDimitry Andric 
891349cc55cSDimitry Andric     case DC_right:
892349cc55cSDimitry Andric       assert(RI != RE);
893349cc55cSDimitry Andric       Diff.addRight(&*RI);
894349cc55cSDimitry Andric       ++RI;
895349cc55cSDimitry Andric       break;
896349cc55cSDimitry Andric     }
897349cc55cSDimitry Andric   }
898349cc55cSDimitry Andric 
899349cc55cSDimitry Andric   // Finishing unifying and complaining about the tails of the block,
900349cc55cSDimitry Andric   // which should be matches all the way through.
901349cc55cSDimitry Andric   while (LI != LE) {
902349cc55cSDimitry Andric     assert(RI != RE);
903349cc55cSDimitry Andric     unify(&*LI, &*RI);
904349cc55cSDimitry Andric     ++LI;
905349cc55cSDimitry Andric     ++RI;
906349cc55cSDimitry Andric   }
907349cc55cSDimitry Andric 
908349cc55cSDimitry Andric   // If the terminators have different kinds, but one is an invoke and the
909349cc55cSDimitry Andric   // other is an unconditional branch immediately following a call, unify
910349cc55cSDimitry Andric   // the results and the destinations.
911349cc55cSDimitry Andric   const Instruction *LTerm = LStart->getParent()->getTerminator();
912349cc55cSDimitry Andric   const Instruction *RTerm = RStart->getParent()->getTerminator();
913349cc55cSDimitry Andric   if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) {
914349cc55cSDimitry Andric     if (cast<BranchInst>(LTerm)->isConditional()) return;
915349cc55cSDimitry Andric     BasicBlock::const_iterator I = LTerm->getIterator();
916349cc55cSDimitry Andric     if (I == LStart->getParent()->begin()) return;
917349cc55cSDimitry Andric     --I;
918349cc55cSDimitry Andric     if (!isa<CallInst>(*I)) return;
919349cc55cSDimitry Andric     const CallInst *LCall = cast<CallInst>(&*I);
920349cc55cSDimitry Andric     const InvokeInst *RInvoke = cast<InvokeInst>(RTerm);
921349cc55cSDimitry Andric     if (!equivalentAsOperands(LCall->getCalledOperand(),
922bdd1243dSDimitry Andric                               RInvoke->getCalledOperand(), nullptr))
923349cc55cSDimitry Andric       return;
924349cc55cSDimitry Andric     if (!LCall->use_empty())
925349cc55cSDimitry Andric       Values[LCall] = RInvoke;
926349cc55cSDimitry Andric     tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest());
927349cc55cSDimitry Andric   } else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) {
928349cc55cSDimitry Andric     if (cast<BranchInst>(RTerm)->isConditional()) return;
929349cc55cSDimitry Andric     BasicBlock::const_iterator I = RTerm->getIterator();
930349cc55cSDimitry Andric     if (I == RStart->getParent()->begin()) return;
931349cc55cSDimitry Andric     --I;
932349cc55cSDimitry Andric     if (!isa<CallInst>(*I)) return;
933349cc55cSDimitry Andric     const CallInst *RCall = cast<CallInst>(I);
934349cc55cSDimitry Andric     const InvokeInst *LInvoke = cast<InvokeInst>(LTerm);
935349cc55cSDimitry Andric     if (!equivalentAsOperands(LInvoke->getCalledOperand(),
936bdd1243dSDimitry Andric                               RCall->getCalledOperand(), nullptr))
937349cc55cSDimitry Andric       return;
938349cc55cSDimitry Andric     if (!LInvoke->use_empty())
939349cc55cSDimitry Andric       Values[LInvoke] = RCall;
940349cc55cSDimitry Andric     tryUnify(LInvoke->getNormalDest(), RTerm->getSuccessor(0));
941349cc55cSDimitry Andric   }
942349cc55cSDimitry Andric }
943349cc55cSDimitry Andric }
944349cc55cSDimitry Andric 
945349cc55cSDimitry Andric void DifferenceEngine::Oracle::anchor() { }
946349cc55cSDimitry Andric 
947349cc55cSDimitry Andric void DifferenceEngine::diff(const Function *L, const Function *R) {
948349cc55cSDimitry Andric   Context C(*this, L, R);
949349cc55cSDimitry Andric 
950349cc55cSDimitry Andric   // FIXME: types
951349cc55cSDimitry Andric   // FIXME: attributes and CC
952349cc55cSDimitry Andric   // FIXME: parameter attributes
953349cc55cSDimitry Andric 
954349cc55cSDimitry Andric   // If both are declarations, we're done.
955349cc55cSDimitry Andric   if (L->empty() && R->empty())
956349cc55cSDimitry Andric     return;
957349cc55cSDimitry Andric   else if (L->empty())
958349cc55cSDimitry Andric     log("left function is declaration, right function is definition");
959349cc55cSDimitry Andric   else if (R->empty())
960349cc55cSDimitry Andric     log("right function is declaration, left function is definition");
961349cc55cSDimitry Andric   else
962349cc55cSDimitry Andric     FunctionDifferenceEngine(*this).diff(L, R);
963349cc55cSDimitry Andric }
964349cc55cSDimitry Andric 
965349cc55cSDimitry Andric void DifferenceEngine::diff(const Module *L, const Module *R) {
966349cc55cSDimitry Andric   StringSet<> LNames;
967349cc55cSDimitry Andric   SmallVector<std::pair<const Function *, const Function *>, 20> Queue;
968349cc55cSDimitry Andric 
969349cc55cSDimitry Andric   unsigned LeftAnonCount = 0;
970349cc55cSDimitry Andric   unsigned RightAnonCount = 0;
971349cc55cSDimitry Andric 
972349cc55cSDimitry Andric   for (Module::const_iterator I = L->begin(), E = L->end(); I != E; ++I) {
973349cc55cSDimitry Andric     const Function *LFn = &*I;
974349cc55cSDimitry Andric     StringRef Name = LFn->getName();
975349cc55cSDimitry Andric     if (Name.empty()) {
976349cc55cSDimitry Andric       ++LeftAnonCount;
977349cc55cSDimitry Andric       continue;
978349cc55cSDimitry Andric     }
979349cc55cSDimitry Andric 
980349cc55cSDimitry Andric     LNames.insert(Name);
981349cc55cSDimitry Andric 
982349cc55cSDimitry Andric     if (Function *RFn = R->getFunction(LFn->getName()))
983349cc55cSDimitry Andric       Queue.push_back(std::make_pair(LFn, RFn));
984349cc55cSDimitry Andric     else
985349cc55cSDimitry Andric       logf("function %l exists only in left module") << LFn;
986349cc55cSDimitry Andric   }
987349cc55cSDimitry Andric 
988349cc55cSDimitry Andric   for (Module::const_iterator I = R->begin(), E = R->end(); I != E; ++I) {
989349cc55cSDimitry Andric     const Function *RFn = &*I;
990349cc55cSDimitry Andric     StringRef Name = RFn->getName();
991349cc55cSDimitry Andric     if (Name.empty()) {
992349cc55cSDimitry Andric       ++RightAnonCount;
993349cc55cSDimitry Andric       continue;
994349cc55cSDimitry Andric     }
995349cc55cSDimitry Andric 
996349cc55cSDimitry Andric     if (!LNames.count(Name))
997349cc55cSDimitry Andric       logf("function %r exists only in right module") << RFn;
998349cc55cSDimitry Andric   }
999349cc55cSDimitry Andric 
1000349cc55cSDimitry Andric   if (LeftAnonCount != 0 || RightAnonCount != 0) {
1001349cc55cSDimitry Andric     SmallString<32> Tmp;
1002349cc55cSDimitry Andric     logf(("not comparing " + Twine(LeftAnonCount) +
1003349cc55cSDimitry Andric           " anonymous functions in the left module and " +
1004349cc55cSDimitry Andric           Twine(RightAnonCount) + " in the right module")
1005349cc55cSDimitry Andric              .toStringRef(Tmp));
1006349cc55cSDimitry Andric   }
1007349cc55cSDimitry Andric 
1008349cc55cSDimitry Andric   for (SmallVectorImpl<std::pair<const Function *, const Function *>>::iterator
1009349cc55cSDimitry Andric            I = Queue.begin(),
1010349cc55cSDimitry Andric            E = Queue.end();
1011349cc55cSDimitry Andric        I != E; ++I)
1012349cc55cSDimitry Andric     diff(I->first, I->second);
1013349cc55cSDimitry Andric }
1014349cc55cSDimitry Andric 
1015349cc55cSDimitry Andric bool DifferenceEngine::equivalentAsOperands(const GlobalValue *L,
1016349cc55cSDimitry Andric                                             const GlobalValue *R) {
1017349cc55cSDimitry Andric   if (globalValueOracle) return (*globalValueOracle)(L, R);
1018349cc55cSDimitry Andric 
1019349cc55cSDimitry Andric   if (isa<GlobalVariable>(L) && isa<GlobalVariable>(R)) {
1020349cc55cSDimitry Andric     const GlobalVariable *GVL = cast<GlobalVariable>(L);
1021349cc55cSDimitry Andric     const GlobalVariable *GVR = cast<GlobalVariable>(R);
1022349cc55cSDimitry Andric     if (GVL->hasLocalLinkage() && GVL->hasUniqueInitializer() &&
1023349cc55cSDimitry Andric         GVR->hasLocalLinkage() && GVR->hasUniqueInitializer())
1024349cc55cSDimitry Andric       return FunctionDifferenceEngine(*this, GVL, GVR)
1025bdd1243dSDimitry Andric           .equivalentAsOperands(GVL->getInitializer(), GVR->getInitializer(),
1026bdd1243dSDimitry Andric                                 nullptr);
1027349cc55cSDimitry Andric   }
1028349cc55cSDimitry Andric 
1029349cc55cSDimitry Andric   return L->getName() == R->getName();
1030349cc55cSDimitry Andric }
1031