xref: /llvm-project/llvm/lib/Transforms/Utils/FunctionComparator.cpp (revision f7fe7ea24d368f45deee1aed5e4c582ac69edd0b)
1 //===- FunctionComparator.h - Function Comparator -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the FunctionComparator and GlobalNumberState classes
10 // which are used by the MergeFunctions pass for comparing functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/FunctionComparator.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/IR/Attributes.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalValue.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/InstrTypes.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include <cassert>
45 #include <cstddef>
46 #include <cstdint>
47 #include <utility>
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "functioncomparator"
52 
53 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
54   if (L < R)
55     return -1;
56   if (L > R)
57     return 1;
58   return 0;
59 }
60 
61 int FunctionComparator::cmpOrderings(AtomicOrdering L, AtomicOrdering R) const {
62   if ((int)L < (int)R)
63     return -1;
64   if ((int)L > (int)R)
65     return 1;
66   return 0;
67 }
68 
69 int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
70   if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
71     return Res;
72   if (L.ugt(R))
73     return 1;
74   if (R.ugt(L))
75     return -1;
76   return 0;
77 }
78 
79 int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
80   // Floats are ordered first by semantics (i.e. float, double, half, etc.),
81   // then by value interpreted as a bitstring (aka APInt).
82   const fltSemantics &SL = L.getSemantics(), &SR = R.getSemantics();
83   if (int Res = cmpNumbers(APFloat::semanticsPrecision(SL),
84                            APFloat::semanticsPrecision(SR)))
85     return Res;
86   if (int Res = cmpNumbers(APFloat::semanticsMaxExponent(SL),
87                            APFloat::semanticsMaxExponent(SR)))
88     return Res;
89   if (int Res = cmpNumbers(APFloat::semanticsMinExponent(SL),
90                            APFloat::semanticsMinExponent(SR)))
91     return Res;
92   if (int Res = cmpNumbers(APFloat::semanticsSizeInBits(SL),
93                            APFloat::semanticsSizeInBits(SR)))
94     return Res;
95   return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
96 }
97 
98 int FunctionComparator::cmpMem(StringRef L, StringRef R) const {
99   // Prevent heavy comparison, compare sizes first.
100   if (int Res = cmpNumbers(L.size(), R.size()))
101     return Res;
102 
103   // Compare strings lexicographically only when it is necessary: only when
104   // strings are equal in size.
105   return L.compare(R);
106 }
107 
108 int FunctionComparator::cmpAttrs(const AttributeList L,
109                                  const AttributeList R) const {
110   if (int Res = cmpNumbers(L.getNumAttrSets(), R.getNumAttrSets()))
111     return Res;
112 
113   for (unsigned i = L.index_begin(), e = L.index_end(); i != e; ++i) {
114     AttributeSet LAS = L.getAttributes(i);
115     AttributeSet RAS = R.getAttributes(i);
116     AttributeSet::iterator LI = LAS.begin(), LE = LAS.end();
117     AttributeSet::iterator RI = RAS.begin(), RE = RAS.end();
118     for (; LI != LE && RI != RE; ++LI, ++RI) {
119       Attribute LA = *LI;
120       Attribute RA = *RI;
121       if (LA.isTypeAttribute() && RA.isTypeAttribute()) {
122         if (LA.getKindAsEnum() != RA.getKindAsEnum())
123           return cmpNumbers(LA.getKindAsEnum(), RA.getKindAsEnum());
124 
125         Type *TyL = LA.getValueAsType();
126         Type *TyR = RA.getValueAsType();
127         if (TyL && TyR) {
128           if (int Res = cmpTypes(TyL, TyR))
129             return Res;
130           continue;
131         }
132 
133         // Two pointers, at least one null, so the comparison result is
134         // independent of the value of a real pointer.
135         if (int Res = cmpNumbers((uint64_t)TyL, (uint64_t)TyR))
136           return Res;
137         continue;
138       }
139       if (LA < RA)
140         return -1;
141       if (RA < LA)
142         return 1;
143     }
144     if (LI != LE)
145       return 1;
146     if (RI != RE)
147       return -1;
148   }
149   return 0;
150 }
151 
152 int FunctionComparator::cmpRangeMetadata(const MDNode *L,
153                                          const MDNode *R) const {
154   if (L == R)
155     return 0;
156   if (!L)
157     return -1;
158   if (!R)
159     return 1;
160   // Range metadata is a sequence of numbers. Make sure they are the same
161   // sequence.
162   // TODO: Note that as this is metadata, it is possible to drop and/or merge
163   // this data when considering functions to merge. Thus this comparison would
164   // return 0 (i.e. equivalent), but merging would become more complicated
165   // because the ranges would need to be unioned. It is not likely that
166   // functions differ ONLY in this metadata if they are actually the same
167   // function semantically.
168   if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
169     return Res;
170   for (size_t I = 0; I < L->getNumOperands(); ++I) {
171     ConstantInt *LLow = mdconst::extract<ConstantInt>(L->getOperand(I));
172     ConstantInt *RLow = mdconst::extract<ConstantInt>(R->getOperand(I));
173     if (int Res = cmpAPInts(LLow->getValue(), RLow->getValue()))
174       return Res;
175   }
176   return 0;
177 }
178 
179 int FunctionComparator::cmpOperandBundlesSchema(const CallBase &LCS,
180                                                 const CallBase &RCS) const {
181   assert(LCS.getOpcode() == RCS.getOpcode() && "Can't compare otherwise!");
182 
183   if (int Res =
184           cmpNumbers(LCS.getNumOperandBundles(), RCS.getNumOperandBundles()))
185     return Res;
186 
187   for (unsigned I = 0, E = LCS.getNumOperandBundles(); I != E; ++I) {
188     auto OBL = LCS.getOperandBundleAt(I);
189     auto OBR = RCS.getOperandBundleAt(I);
190 
191     if (int Res = OBL.getTagName().compare(OBR.getTagName()))
192       return Res;
193 
194     if (int Res = cmpNumbers(OBL.Inputs.size(), OBR.Inputs.size()))
195       return Res;
196   }
197 
198   return 0;
199 }
200 
201 /// Constants comparison:
202 /// 1. Check whether type of L constant could be losslessly bitcasted to R
203 /// type.
204 /// 2. Compare constant contents.
205 /// For more details see declaration comments.
206 int FunctionComparator::cmpConstants(const Constant *L,
207                                      const Constant *R) const {
208   Type *TyL = L->getType();
209   Type *TyR = R->getType();
210 
211   // Check whether types are bitcastable. This part is just re-factored
212   // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
213   // we also pack into result which type is "less" for us.
214   int TypesRes = cmpTypes(TyL, TyR);
215   if (TypesRes != 0) {
216     // Types are different, but check whether we can bitcast them.
217     if (!TyL->isFirstClassType()) {
218       if (TyR->isFirstClassType())
219         return -1;
220       // Neither TyL nor TyR are values of first class type. Return the result
221       // of comparing the types
222       return TypesRes;
223     }
224     if (!TyR->isFirstClassType()) {
225       if (TyL->isFirstClassType())
226         return 1;
227       return TypesRes;
228     }
229 
230     // Vector -> Vector conversions are always lossless if the two vector types
231     // have the same size, otherwise not.
232     unsigned TyLWidth = 0;
233     unsigned TyRWidth = 0;
234 
235     if (auto *VecTyL = dyn_cast<VectorType>(TyL))
236       TyLWidth = VecTyL->getPrimitiveSizeInBits().getFixedSize();
237     if (auto *VecTyR = dyn_cast<VectorType>(TyR))
238       TyRWidth = VecTyR->getPrimitiveSizeInBits().getFixedSize();
239 
240     if (TyLWidth != TyRWidth)
241       return cmpNumbers(TyLWidth, TyRWidth);
242 
243     // Zero bit-width means neither TyL nor TyR are vectors.
244     if (!TyLWidth) {
245       PointerType *PTyL = dyn_cast<PointerType>(TyL);
246       PointerType *PTyR = dyn_cast<PointerType>(TyR);
247       if (PTyL && PTyR) {
248         unsigned AddrSpaceL = PTyL->getAddressSpace();
249         unsigned AddrSpaceR = PTyR->getAddressSpace();
250         if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
251           return Res;
252       }
253       if (PTyL)
254         return 1;
255       if (PTyR)
256         return -1;
257 
258       // TyL and TyR aren't vectors, nor pointers. We don't know how to
259       // bitcast them.
260       return TypesRes;
261     }
262   }
263 
264   // OK, types are bitcastable, now check constant contents.
265 
266   if (L->isNullValue() && R->isNullValue())
267     return TypesRes;
268   if (L->isNullValue() && !R->isNullValue())
269     return 1;
270   if (!L->isNullValue() && R->isNullValue())
271     return -1;
272 
273   auto GlobalValueL = const_cast<GlobalValue *>(dyn_cast<GlobalValue>(L));
274   auto GlobalValueR = const_cast<GlobalValue *>(dyn_cast<GlobalValue>(R));
275   if (GlobalValueL && GlobalValueR) {
276     return cmpGlobalValues(GlobalValueL, GlobalValueR);
277   }
278 
279   if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
280     return Res;
281 
282   if (const auto *SeqL = dyn_cast<ConstantDataSequential>(L)) {
283     const auto *SeqR = cast<ConstantDataSequential>(R);
284     // This handles ConstantDataArray and ConstantDataVector. Note that we
285     // compare the two raw data arrays, which might differ depending on the host
286     // endianness. This isn't a problem though, because the endiness of a module
287     // will affect the order of the constants, but this order is the same
288     // for a given input module and host platform.
289     return cmpMem(SeqL->getRawDataValues(), SeqR->getRawDataValues());
290   }
291 
292   switch (L->getValueID()) {
293   case Value::UndefValueVal:
294   case Value::ConstantTokenNoneVal:
295     return TypesRes;
296   case Value::ConstantIntVal: {
297     const APInt &LInt = cast<ConstantInt>(L)->getValue();
298     const APInt &RInt = cast<ConstantInt>(R)->getValue();
299     return cmpAPInts(LInt, RInt);
300   }
301   case Value::ConstantFPVal: {
302     const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
303     const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
304     return cmpAPFloats(LAPF, RAPF);
305   }
306   case Value::ConstantArrayVal: {
307     const ConstantArray *LA = cast<ConstantArray>(L);
308     const ConstantArray *RA = cast<ConstantArray>(R);
309     uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
310     uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
311     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
312       return Res;
313     for (uint64_t i = 0; i < NumElementsL; ++i) {
314       if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
315                                  cast<Constant>(RA->getOperand(i))))
316         return Res;
317     }
318     return 0;
319   }
320   case Value::ConstantStructVal: {
321     const ConstantStruct *LS = cast<ConstantStruct>(L);
322     const ConstantStruct *RS = cast<ConstantStruct>(R);
323     unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
324     unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
325     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
326       return Res;
327     for (unsigned i = 0; i != NumElementsL; ++i) {
328       if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
329                                  cast<Constant>(RS->getOperand(i))))
330         return Res;
331     }
332     return 0;
333   }
334   case Value::ConstantVectorVal: {
335     const ConstantVector *LV = cast<ConstantVector>(L);
336     const ConstantVector *RV = cast<ConstantVector>(R);
337     unsigned NumElementsL = cast<FixedVectorType>(TyL)->getNumElements();
338     unsigned NumElementsR = cast<FixedVectorType>(TyR)->getNumElements();
339     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
340       return Res;
341     for (uint64_t i = 0; i < NumElementsL; ++i) {
342       if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
343                                  cast<Constant>(RV->getOperand(i))))
344         return Res;
345     }
346     return 0;
347   }
348   case Value::ConstantExprVal: {
349     const ConstantExpr *LE = cast<ConstantExpr>(L);
350     const ConstantExpr *RE = cast<ConstantExpr>(R);
351     unsigned NumOperandsL = LE->getNumOperands();
352     unsigned NumOperandsR = RE->getNumOperands();
353     if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
354       return Res;
355     for (unsigned i = 0; i < NumOperandsL; ++i) {
356       if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
357                                  cast<Constant>(RE->getOperand(i))))
358         return Res;
359     }
360     return 0;
361   }
362   case Value::BlockAddressVal: {
363     const BlockAddress *LBA = cast<BlockAddress>(L);
364     const BlockAddress *RBA = cast<BlockAddress>(R);
365     if (int Res = cmpValues(LBA->getFunction(), RBA->getFunction()))
366       return Res;
367     if (LBA->getFunction() == RBA->getFunction()) {
368       // They are BBs in the same function. Order by which comes first in the
369       // BB order of the function. This order is deterministic.
370       Function *F = LBA->getFunction();
371       BasicBlock *LBB = LBA->getBasicBlock();
372       BasicBlock *RBB = RBA->getBasicBlock();
373       if (LBB == RBB)
374         return 0;
375       for (BasicBlock &BB : F->getBasicBlockList()) {
376         if (&BB == LBB) {
377           assert(&BB != RBB);
378           return -1;
379         }
380         if (&BB == RBB)
381           return 1;
382       }
383       llvm_unreachable("Basic Block Address does not point to a basic block in "
384                        "its function.");
385       return -1;
386     } else {
387       // cmpValues said the functions are the same. So because they aren't
388       // literally the same pointer, they must respectively be the left and
389       // right functions.
390       assert(LBA->getFunction() == FnL && RBA->getFunction() == FnR);
391       // cmpValues will tell us if these are equivalent BasicBlocks, in the
392       // context of their respective functions.
393       return cmpValues(LBA->getBasicBlock(), RBA->getBasicBlock());
394     }
395   }
396   default: // Unknown constant, abort.
397     LLVM_DEBUG(dbgs() << "Looking at valueID " << L->getValueID() << "\n");
398     llvm_unreachable("Constant ValueID not recognized.");
399     return -1;
400   }
401 }
402 
403 int FunctionComparator::cmpGlobalValues(GlobalValue *L, GlobalValue *R) const {
404   uint64_t LNumber = GlobalNumbers->getNumber(L);
405   uint64_t RNumber = GlobalNumbers->getNumber(R);
406   return cmpNumbers(LNumber, RNumber);
407 }
408 
409 /// cmpType - compares two types,
410 /// defines total ordering among the types set.
411 /// See method declaration comments for more details.
412 int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
413   PointerType *PTyL = dyn_cast<PointerType>(TyL);
414   PointerType *PTyR = dyn_cast<PointerType>(TyR);
415 
416   const DataLayout &DL = FnL->getParent()->getDataLayout();
417   if (PTyL && PTyL->getAddressSpace() == 0)
418     TyL = DL.getIntPtrType(TyL);
419   if (PTyR && PTyR->getAddressSpace() == 0)
420     TyR = DL.getIntPtrType(TyR);
421 
422   if (TyL == TyR)
423     return 0;
424 
425   if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
426     return Res;
427 
428   switch (TyL->getTypeID()) {
429   default:
430     llvm_unreachable("Unknown type!");
431   case Type::IntegerTyID:
432     return cmpNumbers(cast<IntegerType>(TyL)->getBitWidth(),
433                       cast<IntegerType>(TyR)->getBitWidth());
434   // TyL == TyR would have returned true earlier, because types are uniqued.
435   case Type::VoidTyID:
436   case Type::FloatTyID:
437   case Type::DoubleTyID:
438   case Type::X86_FP80TyID:
439   case Type::FP128TyID:
440   case Type::PPC_FP128TyID:
441   case Type::LabelTyID:
442   case Type::MetadataTyID:
443   case Type::TokenTyID:
444     return 0;
445 
446   case Type::PointerTyID:
447     assert(PTyL && PTyR && "Both types must be pointers here.");
448     return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
449 
450   case Type::StructTyID: {
451     StructType *STyL = cast<StructType>(TyL);
452     StructType *STyR = cast<StructType>(TyR);
453     if (STyL->getNumElements() != STyR->getNumElements())
454       return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
455 
456     if (STyL->isPacked() != STyR->isPacked())
457       return cmpNumbers(STyL->isPacked(), STyR->isPacked());
458 
459     for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
460       if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
461         return Res;
462     }
463     return 0;
464   }
465 
466   case Type::FunctionTyID: {
467     FunctionType *FTyL = cast<FunctionType>(TyL);
468     FunctionType *FTyR = cast<FunctionType>(TyR);
469     if (FTyL->getNumParams() != FTyR->getNumParams())
470       return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
471 
472     if (FTyL->isVarArg() != FTyR->isVarArg())
473       return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
474 
475     if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
476       return Res;
477 
478     for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
479       if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
480         return Res;
481     }
482     return 0;
483   }
484 
485   case Type::ArrayTyID: {
486     auto *STyL = cast<ArrayType>(TyL);
487     auto *STyR = cast<ArrayType>(TyR);
488     if (STyL->getNumElements() != STyR->getNumElements())
489       return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
490     return cmpTypes(STyL->getElementType(), STyR->getElementType());
491   }
492   case Type::FixedVectorTyID:
493   case Type::ScalableVectorTyID: {
494     auto *STyL = cast<VectorType>(TyL);
495     auto *STyR = cast<VectorType>(TyR);
496     if (STyL->getElementCount().isScalable() !=
497         STyR->getElementCount().isScalable())
498       return cmpNumbers(STyL->getElementCount().isScalable(),
499                         STyR->getElementCount().isScalable());
500     if (STyL->getElementCount() != STyR->getElementCount())
501       return cmpNumbers(STyL->getElementCount().getKnownMinValue(),
502                         STyR->getElementCount().getKnownMinValue());
503     return cmpTypes(STyL->getElementType(), STyR->getElementType());
504   }
505   }
506 }
507 
508 // Determine whether the two operations are the same except that pointer-to-A
509 // and pointer-to-B are equivalent. This should be kept in sync with
510 // Instruction::isSameOperationAs.
511 // Read method declaration comments for more details.
512 int FunctionComparator::cmpOperations(const Instruction *L,
513                                       const Instruction *R,
514                                       bool &needToCmpOperands) const {
515   needToCmpOperands = true;
516   if (int Res = cmpValues(L, R))
517     return Res;
518 
519   // Differences from Instruction::isSameOperationAs:
520   //  * replace type comparison with calls to cmpTypes.
521   //  * we test for I->getRawSubclassOptionalData (nuw/nsw/tail) at the top.
522   //  * because of the above, we don't test for the tail bit on calls later on.
523   if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
524     return Res;
525 
526   if (const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(L)) {
527     needToCmpOperands = false;
528     const GetElementPtrInst *GEPR = cast<GetElementPtrInst>(R);
529     if (int Res =
530             cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
531       return Res;
532     return cmpGEPs(GEPL, GEPR);
533   }
534 
535   if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
536     return Res;
537 
538   if (int Res = cmpTypes(L->getType(), R->getType()))
539     return Res;
540 
541   if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
542                            R->getRawSubclassOptionalData()))
543     return Res;
544 
545   // We have two instructions of identical opcode and #operands.  Check to see
546   // if all operands are the same type
547   for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
548     if (int Res =
549             cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
550       return Res;
551   }
552 
553   // Check special state that is a part of some instructions.
554   if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
555     if (int Res = cmpTypes(AI->getAllocatedType(),
556                            cast<AllocaInst>(R)->getAllocatedType()))
557       return Res;
558     return cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment());
559   }
560   if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
561     if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
562       return Res;
563     if (int Res =
564             cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
565       return Res;
566     if (int Res =
567             cmpOrderings(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
568       return Res;
569     if (int Res = cmpNumbers(LI->getSyncScopeID(),
570                              cast<LoadInst>(R)->getSyncScopeID()))
571       return Res;
572     return cmpRangeMetadata(
573         LI->getMetadata(LLVMContext::MD_range),
574         cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
575   }
576   if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
577     if (int Res =
578             cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
579       return Res;
580     if (int Res =
581             cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
582       return Res;
583     if (int Res =
584             cmpOrderings(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
585       return Res;
586     return cmpNumbers(SI->getSyncScopeID(),
587                       cast<StoreInst>(R)->getSyncScopeID());
588   }
589   if (const CmpInst *CI = dyn_cast<CmpInst>(L))
590     return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
591   if (auto *CBL = dyn_cast<CallBase>(L)) {
592     auto *CBR = cast<CallBase>(R);
593     if (int Res = cmpNumbers(CBL->getCallingConv(), CBR->getCallingConv()))
594       return Res;
595     if (int Res = cmpAttrs(CBL->getAttributes(), CBR->getAttributes()))
596       return Res;
597     if (int Res = cmpOperandBundlesSchema(*CBL, *CBR))
598       return Res;
599     if (const CallInst *CI = dyn_cast<CallInst>(L))
600       if (int Res = cmpNumbers(CI->getTailCallKind(),
601                                cast<CallInst>(R)->getTailCallKind()))
602         return Res;
603     return cmpRangeMetadata(L->getMetadata(LLVMContext::MD_range),
604                             R->getMetadata(LLVMContext::MD_range));
605   }
606   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
607     ArrayRef<unsigned> LIndices = IVI->getIndices();
608     ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
609     if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
610       return Res;
611     for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
612       if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
613         return Res;
614     }
615     return 0;
616   }
617   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
618     ArrayRef<unsigned> LIndices = EVI->getIndices();
619     ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
620     if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
621       return Res;
622     for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
623       if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
624         return Res;
625     }
626   }
627   if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
628     if (int Res =
629             cmpOrderings(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
630       return Res;
631     return cmpNumbers(FI->getSyncScopeID(),
632                       cast<FenceInst>(R)->getSyncScopeID());
633   }
634   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
635     if (int Res = cmpNumbers(CXI->isVolatile(),
636                              cast<AtomicCmpXchgInst>(R)->isVolatile()))
637       return Res;
638     if (int Res =
639             cmpNumbers(CXI->isWeak(), cast<AtomicCmpXchgInst>(R)->isWeak()))
640       return Res;
641     if (int Res =
642             cmpOrderings(CXI->getSuccessOrdering(),
643                          cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
644       return Res;
645     if (int Res =
646             cmpOrderings(CXI->getFailureOrdering(),
647                          cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
648       return Res;
649     return cmpNumbers(CXI->getSyncScopeID(),
650                       cast<AtomicCmpXchgInst>(R)->getSyncScopeID());
651   }
652   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
653     if (int Res = cmpNumbers(RMWI->getOperation(),
654                              cast<AtomicRMWInst>(R)->getOperation()))
655       return Res;
656     if (int Res = cmpNumbers(RMWI->isVolatile(),
657                              cast<AtomicRMWInst>(R)->isVolatile()))
658       return Res;
659     if (int Res = cmpOrderings(RMWI->getOrdering(),
660                                cast<AtomicRMWInst>(R)->getOrdering()))
661       return Res;
662     return cmpNumbers(RMWI->getSyncScopeID(),
663                       cast<AtomicRMWInst>(R)->getSyncScopeID());
664   }
665   if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(L)) {
666     ArrayRef<int> LMask = SVI->getShuffleMask();
667     ArrayRef<int> RMask = cast<ShuffleVectorInst>(R)->getShuffleMask();
668     if (int Res = cmpNumbers(LMask.size(), RMask.size()))
669       return Res;
670     for (size_t i = 0, e = LMask.size(); i != e; ++i) {
671       if (int Res = cmpNumbers(LMask[i], RMask[i]))
672         return Res;
673     }
674   }
675   if (const PHINode *PNL = dyn_cast<PHINode>(L)) {
676     const PHINode *PNR = cast<PHINode>(R);
677     // Ensure that in addition to the incoming values being identical
678     // (checked by the caller of this function), the incoming blocks
679     // are also identical.
680     for (unsigned i = 0, e = PNL->getNumIncomingValues(); i != e; ++i) {
681       if (int Res =
682               cmpValues(PNL->getIncomingBlock(i), PNR->getIncomingBlock(i)))
683         return Res;
684     }
685   }
686   return 0;
687 }
688 
689 // Determine whether two GEP operations perform the same underlying arithmetic.
690 // Read method declaration comments for more details.
691 int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
692                                 const GEPOperator *GEPR) const {
693   unsigned int ASL = GEPL->getPointerAddressSpace();
694   unsigned int ASR = GEPR->getPointerAddressSpace();
695 
696   if (int Res = cmpNumbers(ASL, ASR))
697     return Res;
698 
699   // When we have target data, we can reduce the GEP down to the value in bytes
700   // added to the address.
701   const DataLayout &DL = FnL->getParent()->getDataLayout();
702   unsigned BitWidth = DL.getPointerSizeInBits(ASL);
703   APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
704   if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
705       GEPR->accumulateConstantOffset(DL, OffsetR))
706     return cmpAPInts(OffsetL, OffsetR);
707   if (int Res =
708           cmpTypes(GEPL->getSourceElementType(), GEPR->getSourceElementType()))
709     return Res;
710 
711   if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
712     return Res;
713 
714   for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
715     if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
716       return Res;
717   }
718 
719   return 0;
720 }
721 
722 int FunctionComparator::cmpInlineAsm(const InlineAsm *L,
723                                      const InlineAsm *R) const {
724   // InlineAsm's are uniqued. If they are the same pointer, obviously they are
725   // the same, otherwise compare the fields.
726   if (L == R)
727     return 0;
728   if (int Res = cmpTypes(L->getFunctionType(), R->getFunctionType()))
729     return Res;
730   if (int Res = cmpMem(L->getAsmString(), R->getAsmString()))
731     return Res;
732   if (int Res = cmpMem(L->getConstraintString(), R->getConstraintString()))
733     return Res;
734   if (int Res = cmpNumbers(L->hasSideEffects(), R->hasSideEffects()))
735     return Res;
736   if (int Res = cmpNumbers(L->isAlignStack(), R->isAlignStack()))
737     return Res;
738   if (int Res = cmpNumbers(L->getDialect(), R->getDialect()))
739     return Res;
740   assert(L->getFunctionType() != R->getFunctionType());
741   return 0;
742 }
743 
744 /// Compare two values used by the two functions under pair-wise comparison. If
745 /// this is the first time the values are seen, they're added to the mapping so
746 /// that we will detect mismatches on next use.
747 /// See comments in declaration for more details.
748 int FunctionComparator::cmpValues(const Value *L, const Value *R) const {
749   // Catch self-reference case.
750   if (L == FnL) {
751     if (R == FnR)
752       return 0;
753     return -1;
754   }
755   if (R == FnR) {
756     if (L == FnL)
757       return 0;
758     return 1;
759   }
760 
761   const Constant *ConstL = dyn_cast<Constant>(L);
762   const Constant *ConstR = dyn_cast<Constant>(R);
763   if (ConstL && ConstR) {
764     if (L == R)
765       return 0;
766     return cmpConstants(ConstL, ConstR);
767   }
768 
769   if (ConstL)
770     return 1;
771   if (ConstR)
772     return -1;
773 
774   const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
775   const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
776 
777   if (InlineAsmL && InlineAsmR)
778     return cmpInlineAsm(InlineAsmL, InlineAsmR);
779   if (InlineAsmL)
780     return 1;
781   if (InlineAsmR)
782     return -1;
783 
784   auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
785        RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
786 
787   return cmpNumbers(LeftSN.first->second, RightSN.first->second);
788 }
789 
790 // Test whether two basic blocks have equivalent behaviour.
791 int FunctionComparator::cmpBasicBlocks(const BasicBlock *BBL,
792                                        const BasicBlock *BBR) const {
793   BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
794   BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
795 
796   do {
797     bool needToCmpOperands = true;
798     if (int Res = cmpOperations(&*InstL, &*InstR, needToCmpOperands))
799       return Res;
800     if (needToCmpOperands) {
801       assert(InstL->getNumOperands() == InstR->getNumOperands());
802 
803       for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
804         Value *OpL = InstL->getOperand(i);
805         Value *OpR = InstR->getOperand(i);
806         if (int Res = cmpValues(OpL, OpR))
807           return Res;
808         // cmpValues should ensure this is true.
809         assert(cmpTypes(OpL->getType(), OpR->getType()) == 0);
810       }
811     }
812 
813     ++InstL;
814     ++InstR;
815   } while (InstL != InstLE && InstR != InstRE);
816 
817   if (InstL != InstLE && InstR == InstRE)
818     return 1;
819   if (InstL == InstLE && InstR != InstRE)
820     return -1;
821   return 0;
822 }
823 
824 int FunctionComparator::compareSignature() const {
825   if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
826     return Res;
827 
828   if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
829     return Res;
830 
831   if (FnL->hasGC()) {
832     if (int Res = cmpMem(FnL->getGC(), FnR->getGC()))
833       return Res;
834   }
835 
836   if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
837     return Res;
838 
839   if (FnL->hasSection()) {
840     if (int Res = cmpMem(FnL->getSection(), FnR->getSection()))
841       return Res;
842   }
843 
844   if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
845     return Res;
846 
847   // TODO: if it's internal and only used in direct calls, we could handle this
848   // case too.
849   if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
850     return Res;
851 
852   if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
853     return Res;
854 
855   assert(FnL->arg_size() == FnR->arg_size() &&
856          "Identically typed functions have different numbers of args!");
857 
858   // Visit the arguments so that they get enumerated in the order they're
859   // passed in.
860   for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
861                                     ArgRI = FnR->arg_begin(),
862                                     ArgLE = FnL->arg_end();
863        ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
864     if (cmpValues(&*ArgLI, &*ArgRI) != 0)
865       llvm_unreachable("Arguments repeat!");
866   }
867   return 0;
868 }
869 
870 // Test whether the two functions have equivalent behaviour.
871 int FunctionComparator::compare() {
872   beginCompare();
873 
874   if (int Res = compareSignature())
875     return Res;
876 
877   // We do a CFG-ordered walk since the actual ordering of the blocks in the
878   // linked list is immaterial. Our walk starts at the entry block for both
879   // functions, then takes each block from each terminator in order. As an
880   // artifact, this also means that unreachable blocks are ignored.
881   SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
882   SmallPtrSet<const BasicBlock *, 32> VisitedBBs; // in terms of F1.
883 
884   FnLBBs.push_back(&FnL->getEntryBlock());
885   FnRBBs.push_back(&FnR->getEntryBlock());
886 
887   VisitedBBs.insert(FnLBBs[0]);
888   while (!FnLBBs.empty()) {
889     const BasicBlock *BBL = FnLBBs.pop_back_val();
890     const BasicBlock *BBR = FnRBBs.pop_back_val();
891 
892     if (int Res = cmpValues(BBL, BBR))
893       return Res;
894 
895     if (int Res = cmpBasicBlocks(BBL, BBR))
896       return Res;
897 
898     const Instruction *TermL = BBL->getTerminator();
899     const Instruction *TermR = BBR->getTerminator();
900 
901     assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
902     for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
903       if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
904         continue;
905 
906       FnLBBs.push_back(TermL->getSuccessor(i));
907       FnRBBs.push_back(TermR->getSuccessor(i));
908     }
909   }
910   return 0;
911 }
912 
913 namespace {
914 
915 // Accumulate the hash of a sequence of 64-bit integers. This is similar to a
916 // hash of a sequence of 64bit ints, but the entire input does not need to be
917 // available at once. This interface is necessary for functionHash because it
918 // needs to accumulate the hash as the structure of the function is traversed
919 // without saving these values to an intermediate buffer. This form of hashing
920 // is not often needed, as usually the object to hash is just read from a
921 // buffer.
922 class HashAccumulator64 {
923   uint64_t Hash;
924 
925 public:
926   // Initialize to random constant, so the state isn't zero.
927   HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
928 
929   void add(uint64_t V) { Hash = hashing::detail::hash_16_bytes(Hash, V); }
930 
931   // No finishing is required, because the entire hash value is used.
932   uint64_t getHash() { return Hash; }
933 };
934 
935 } // end anonymous namespace
936 
937 // A function hash is calculated by considering only the number of arguments and
938 // whether a function is varargs, the order of basic blocks (given by the
939 // successors of each basic block in depth first order), and the order of
940 // opcodes of each instruction within each of these basic blocks. This mirrors
941 // the strategy compare() uses to compare functions by walking the BBs in depth
942 // first order and comparing each instruction in sequence. Because this hash
943 // does not look at the operands, it is insensitive to things such as the
944 // target of calls and the constants used in the function, which makes it useful
945 // when possibly merging functions which are the same modulo constants and call
946 // targets.
947 FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
948   HashAccumulator64 H;
949   H.add(F.isVarArg());
950   H.add(F.arg_size());
951 
952   SmallVector<const BasicBlock *, 8> BBs;
953   SmallPtrSet<const BasicBlock *, 16> VisitedBBs;
954 
955   // Walk the blocks in the same order as FunctionComparator::cmpBasicBlocks(),
956   // accumulating the hash of the function "structure." (BB and opcode sequence)
957   BBs.push_back(&F.getEntryBlock());
958   VisitedBBs.insert(BBs[0]);
959   while (!BBs.empty()) {
960     const BasicBlock *BB = BBs.pop_back_val();
961     // This random value acts as a block header, as otherwise the partition of
962     // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
963     H.add(45798);
964     for (auto &Inst : *BB) {
965       H.add(Inst.getOpcode());
966     }
967     const Instruction *Term = BB->getTerminator();
968     for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
969       if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
970         continue;
971       BBs.push_back(Term->getSuccessor(i));
972     }
973   }
974   return H.getHash();
975 }
976