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