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