1 //===- FunctionComparator.h - Function Comparator -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the FunctionComparator and GlobalNumberState classes
11 // which are used by the MergeFunctions pass for comparing functions.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/FunctionComparator.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/Hashing.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/InstrTypes.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/raw_ostream.h"
54 #define DEBUG_TYPE "functioncomparator"
56 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
62 int FunctionComparator::cmpOrderings(AtomicOrdering L, AtomicOrdering R) const {
63 if ((int)L < (int)R) return -1;
64 if ((int)L > (int)R) return 1;
68 int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
69 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
71 if (L.ugt(R)) return 1;
72 if (R.ugt(L)) return -1;
76 int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
77 // Floats are ordered first by semantics (i.e. float, double, half, etc.),
78 // then by value interpreted as a bitstring (aka APInt).
79 const fltSemantics &SL = L.getSemantics(), &SR = R.getSemantics();
80 if (int Res = cmpNumbers(APFloat::semanticsPrecision(SL),
81 APFloat::semanticsPrecision(SR)))
83 if (int Res = cmpNumbers(APFloat::semanticsMaxExponent(SL),
84 APFloat::semanticsMaxExponent(SR)))
86 if (int Res = cmpNumbers(APFloat::semanticsMinExponent(SL),
87 APFloat::semanticsMinExponent(SR)))
89 if (int Res = cmpNumbers(APFloat::semanticsSizeInBits(SL),
90 APFloat::semanticsSizeInBits(SR)))
92 return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
95 int FunctionComparator::cmpMem(StringRef L, StringRef R) const {
96 // Prevent heavy comparison, compare sizes first.
97 if (int Res = cmpNumbers(L.size(), R.size()))
100 // Compare strings lexicographically only when it is necessary: only when
101 // strings are equal in size.
105 int FunctionComparator::cmpAttrs(const AttributeList L,
106 const AttributeList R) const {
107 if (int Res = cmpNumbers(L.getNumAttrSets(), R.getNumAttrSets()))
110 for (unsigned i = L.index_begin(), e = L.index_end(); i != e; ++i) {
111 AttributeSet LAS = L.getAttributes(i);
112 AttributeSet RAS = R.getAttributes(i);
113 AttributeSet::iterator LI = LAS.begin(), LE = LAS.end();
114 AttributeSet::iterator RI = RAS.begin(), RE = RAS.end();
115 for (; LI != LE && RI != RE; ++LI, ++RI) {
131 int FunctionComparator::cmpRangeMetadata(const MDNode *L,
132 const MDNode *R) const {
139 // Range metadata is a sequence of numbers. Make sure they are the same
141 // TODO: Note that as this is metadata, it is possible to drop and/or merge
142 // this data when considering functions to merge. Thus this comparison would
143 // return 0 (i.e. equivalent), but merging would become more complicated
144 // because the ranges would need to be unioned. It is not likely that
145 // functions differ ONLY in this metadata if they are actually the same
146 // function semantically.
147 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
149 for (size_t I = 0; I < L->getNumOperands(); ++I) {
150 ConstantInt *LLow = mdconst::extract<ConstantInt>(L->getOperand(I));
151 ConstantInt *RLow = mdconst::extract<ConstantInt>(R->getOperand(I));
152 if (int Res = cmpAPInts(LLow->getValue(), RLow->getValue()))
158 int FunctionComparator::cmpOperandBundlesSchema(const Instruction *L,
159 const Instruction *R) const {
160 ImmutableCallSite LCS(L);
161 ImmutableCallSite RCS(R);
163 assert(LCS && RCS && "Must be calls or invokes!");
164 assert(LCS.isCall() == RCS.isCall() && "Can't compare otherwise!");
167 cmpNumbers(LCS.getNumOperandBundles(), RCS.getNumOperandBundles()))
170 for (unsigned i = 0, e = LCS.getNumOperandBundles(); i != e; ++i) {
171 auto OBL = LCS.getOperandBundleAt(i);
172 auto OBR = RCS.getOperandBundleAt(i);
174 if (int Res = OBL.getTagName().compare(OBR.getTagName()))
177 if (int Res = cmpNumbers(OBL.Inputs.size(), OBR.Inputs.size()))
184 /// Constants comparison:
185 /// 1. Check whether type of L constant could be losslessly bitcasted to R
187 /// 2. Compare constant contents.
188 /// For more details see declaration comments.
189 int FunctionComparator::cmpConstants(const Constant *L,
190 const Constant *R) const {
191 Type *TyL = L->getType();
192 Type *TyR = R->getType();
194 // Check whether types are bitcastable. This part is just re-factored
195 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
196 // we also pack into result which type is "less" for us.
197 int TypesRes = cmpTypes(TyL, TyR);
199 // Types are different, but check whether we can bitcast them.
200 if (!TyL->isFirstClassType()) {
201 if (TyR->isFirstClassType())
203 // Neither TyL nor TyR are values of first class type. Return the result
204 // of comparing the types
207 if (!TyR->isFirstClassType()) {
208 if (TyL->isFirstClassType())
213 // Vector -> Vector conversions are always lossless if the two vector types
214 // have the same size, otherwise not.
215 unsigned TyLWidth = 0;
216 unsigned TyRWidth = 0;
218 if (auto *VecTyL = dyn_cast<VectorType>(TyL))
219 TyLWidth = VecTyL->getBitWidth();
220 if (auto *VecTyR = dyn_cast<VectorType>(TyR))
221 TyRWidth = VecTyR->getBitWidth();
223 if (TyLWidth != TyRWidth)
224 return cmpNumbers(TyLWidth, TyRWidth);
226 // Zero bit-width means neither TyL nor TyR are vectors.
228 PointerType *PTyL = dyn_cast<PointerType>(TyL);
229 PointerType *PTyR = dyn_cast<PointerType>(TyR);
231 unsigned AddrSpaceL = PTyL->getAddressSpace();
232 unsigned AddrSpaceR = PTyR->getAddressSpace();
233 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
241 // TyL and TyR aren't vectors, nor pointers. We don't know how to
247 // OK, types are bitcastable, now check constant contents.
249 if (L->isNullValue() && R->isNullValue())
251 if (L->isNullValue() && !R->isNullValue())
253 if (!L->isNullValue() && R->isNullValue())
256 auto GlobalValueL = const_cast<GlobalValue *>(dyn_cast<GlobalValue>(L));
257 auto GlobalValueR = const_cast<GlobalValue *>(dyn_cast<GlobalValue>(R));
258 if (GlobalValueL && GlobalValueR) {
259 return cmpGlobalValues(GlobalValueL, GlobalValueR);
262 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
265 if (const auto *SeqL = dyn_cast<ConstantDataSequential>(L)) {
266 const auto *SeqR = cast<ConstantDataSequential>(R);
267 // This handles ConstantDataArray and ConstantDataVector. Note that we
268 // compare the two raw data arrays, which might differ depending on the host
269 // endianness. This isn't a problem though, because the endiness of a module
270 // will affect the order of the constants, but this order is the same
271 // for a given input module and host platform.
272 return cmpMem(SeqL->getRawDataValues(), SeqR->getRawDataValues());
275 switch (L->getValueID()) {
276 case Value::UndefValueVal:
277 case Value::ConstantTokenNoneVal:
279 case Value::ConstantIntVal: {
280 const APInt &LInt = cast<ConstantInt>(L)->getValue();
281 const APInt &RInt = cast<ConstantInt>(R)->getValue();
282 return cmpAPInts(LInt, RInt);
284 case Value::ConstantFPVal: {
285 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
286 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
287 return cmpAPFloats(LAPF, RAPF);
289 case Value::ConstantArrayVal: {
290 const ConstantArray *LA = cast<ConstantArray>(L);
291 const ConstantArray *RA = cast<ConstantArray>(R);
292 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
293 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
294 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
296 for (uint64_t i = 0; i < NumElementsL; ++i) {
297 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
298 cast<Constant>(RA->getOperand(i))))
303 case Value::ConstantStructVal: {
304 const ConstantStruct *LS = cast<ConstantStruct>(L);
305 const ConstantStruct *RS = cast<ConstantStruct>(R);
306 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
307 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
308 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
310 for (unsigned i = 0; i != NumElementsL; ++i) {
311 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
312 cast<Constant>(RS->getOperand(i))))
317 case Value::ConstantVectorVal: {
318 const ConstantVector *LV = cast<ConstantVector>(L);
319 const ConstantVector *RV = cast<ConstantVector>(R);
320 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
321 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
322 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
324 for (uint64_t i = 0; i < NumElementsL; ++i) {
325 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
326 cast<Constant>(RV->getOperand(i))))
331 case Value::ConstantExprVal: {
332 const ConstantExpr *LE = cast<ConstantExpr>(L);
333 const ConstantExpr *RE = cast<ConstantExpr>(R);
334 unsigned NumOperandsL = LE->getNumOperands();
335 unsigned NumOperandsR = RE->getNumOperands();
336 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
338 for (unsigned i = 0; i < NumOperandsL; ++i) {
339 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
340 cast<Constant>(RE->getOperand(i))))
345 case Value::BlockAddressVal: {
346 const BlockAddress *LBA = cast<BlockAddress>(L);
347 const BlockAddress *RBA = cast<BlockAddress>(R);
348 if (int Res = cmpValues(LBA->getFunction(), RBA->getFunction()))
350 if (LBA->getFunction() == RBA->getFunction()) {
351 // They are BBs in the same function. Order by which comes first in the
352 // BB order of the function. This order is deterministic.
353 Function* F = LBA->getFunction();
354 BasicBlock *LBB = LBA->getBasicBlock();
355 BasicBlock *RBB = RBA->getBasicBlock();
358 for(BasicBlock &BB : F->getBasicBlockList()) {
366 llvm_unreachable("Basic Block Address does not point to a basic block in "
370 // cmpValues said the functions are the same. So because they aren't
371 // literally the same pointer, they must respectively be the left and
373 assert(LBA->getFunction() == FnL && RBA->getFunction() == FnR);
374 // cmpValues will tell us if these are equivalent BasicBlocks, in the
375 // context of their respective functions.
376 return cmpValues(LBA->getBasicBlock(), RBA->getBasicBlock());
379 default: // Unknown constant, abort.
380 DEBUG(dbgs() << "Looking at valueID " << L->getValueID() << "\n");
381 llvm_unreachable("Constant ValueID not recognized.");
386 int FunctionComparator::cmpGlobalValues(GlobalValue *L, GlobalValue *R) const {
387 uint64_t LNumber = GlobalNumbers->getNumber(L);
388 uint64_t RNumber = GlobalNumbers->getNumber(R);
389 return cmpNumbers(LNumber, RNumber);
392 /// cmpType - compares two types,
393 /// defines total ordering among the types set.
394 /// See method declaration comments for more details.
395 int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
396 PointerType *PTyL = dyn_cast<PointerType>(TyL);
397 PointerType *PTyR = dyn_cast<PointerType>(TyR);
399 const DataLayout &DL = FnL->getParent()->getDataLayout();
400 if (PTyL && PTyL->getAddressSpace() == 0)
401 TyL = DL.getIntPtrType(TyL);
402 if (PTyR && PTyR->getAddressSpace() == 0)
403 TyR = DL.getIntPtrType(TyR);
408 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
411 switch (TyL->getTypeID()) {
413 llvm_unreachable("Unknown type!");
414 // Fall through in Release mode.
416 case Type::IntegerTyID:
417 return cmpNumbers(cast<IntegerType>(TyL)->getBitWidth(),
418 cast<IntegerType>(TyR)->getBitWidth());
419 // TyL == TyR would have returned true earlier, because types are uniqued.
421 case Type::FloatTyID:
422 case Type::DoubleTyID:
423 case Type::X86_FP80TyID:
424 case Type::FP128TyID:
425 case Type::PPC_FP128TyID:
426 case Type::LabelTyID:
427 case Type::MetadataTyID:
428 case Type::TokenTyID:
431 case Type::PointerTyID:
432 assert(PTyL && PTyR && "Both types must be pointers here.");
433 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
435 case Type::StructTyID: {
436 StructType *STyL = cast<StructType>(TyL);
437 StructType *STyR = cast<StructType>(TyR);
438 if (STyL->getNumElements() != STyR->getNumElements())
439 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
441 if (STyL->isPacked() != STyR->isPacked())
442 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
444 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
445 if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
451 case Type::FunctionTyID: {
452 FunctionType *FTyL = cast<FunctionType>(TyL);
453 FunctionType *FTyR = cast<FunctionType>(TyR);
454 if (FTyL->getNumParams() != FTyR->getNumParams())
455 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
457 if (FTyL->isVarArg() != FTyR->isVarArg())
458 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
460 if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
463 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
464 if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
470 case Type::ArrayTyID:
471 case Type::VectorTyID: {
472 auto *STyL = cast<SequentialType>(TyL);
473 auto *STyR = cast<SequentialType>(TyR);
474 if (STyL->getNumElements() != STyR->getNumElements())
475 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
476 return cmpTypes(STyL->getElementType(), STyR->getElementType());
481 // Determine whether the two operations are the same except that pointer-to-A
482 // and pointer-to-B are equivalent. This should be kept in sync with
483 // Instruction::isSameOperationAs.
484 // Read method declaration comments for more details.
485 int FunctionComparator::cmpOperations(const Instruction *L,
486 const Instruction *R,
487 bool &needToCmpOperands) const {
488 needToCmpOperands = true;
489 if (int Res = cmpValues(L, R))
492 // Differences from Instruction::isSameOperationAs:
493 // * replace type comparison with calls to cmpTypes.
494 // * we test for I->getRawSubclassOptionalData (nuw/nsw/tail) at the top.
495 // * because of the above, we don't test for the tail bit on calls later on.
496 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
499 if (const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(L)) {
500 needToCmpOperands = false;
501 const GetElementPtrInst *GEPR = cast<GetElementPtrInst>(R);
503 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
505 return cmpGEPs(GEPL, GEPR);
508 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
511 if (int Res = cmpTypes(L->getType(), R->getType()))
514 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
515 R->getRawSubclassOptionalData()))
518 // We have two instructions of identical opcode and #operands. Check to see
519 // if all operands are the same type
520 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
522 cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
526 // Check special state that is a part of some instructions.
527 if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
528 if (int Res = cmpTypes(AI->getAllocatedType(),
529 cast<AllocaInst>(R)->getAllocatedType()))
531 return cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment());
533 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
534 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
537 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
540 cmpOrderings(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
542 if (int Res = cmpNumbers(LI->getSyncScopeID(),
543 cast<LoadInst>(R)->getSyncScopeID()))
545 return cmpRangeMetadata(LI->getMetadata(LLVMContext::MD_range),
546 cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
548 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
550 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
553 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
556 cmpOrderings(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
558 return cmpNumbers(SI->getSyncScopeID(),
559 cast<StoreInst>(R)->getSyncScopeID());
561 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
562 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
563 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
564 if (int Res = cmpNumbers(CI->getCallingConv(),
565 cast<CallInst>(R)->getCallingConv()))
568 cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
570 if (int Res = cmpOperandBundlesSchema(CI, R))
572 return cmpRangeMetadata(
573 CI->getMetadata(LLVMContext::MD_range),
574 cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
576 if (const InvokeInst *II = dyn_cast<InvokeInst>(L)) {
577 if (int Res = cmpNumbers(II->getCallingConv(),
578 cast<InvokeInst>(R)->getCallingConv()))
581 cmpAttrs(II->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
583 if (int Res = cmpOperandBundlesSchema(II, R))
585 return cmpRangeMetadata(
586 II->getMetadata(LLVMContext::MD_range),
587 cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
589 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
590 ArrayRef<unsigned> LIndices = IVI->getIndices();
591 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
592 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
594 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
595 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
600 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
601 ArrayRef<unsigned> LIndices = EVI->getIndices();
602 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
603 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
605 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
606 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
610 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
612 cmpOrderings(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
614 return cmpNumbers(FI->getSyncScopeID(),
615 cast<FenceInst>(R)->getSyncScopeID());
617 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
618 if (int Res = cmpNumbers(CXI->isVolatile(),
619 cast<AtomicCmpXchgInst>(R)->isVolatile()))
621 if (int Res = cmpNumbers(CXI->isWeak(),
622 cast<AtomicCmpXchgInst>(R)->isWeak()))
625 cmpOrderings(CXI->getSuccessOrdering(),
626 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
629 cmpOrderings(CXI->getFailureOrdering(),
630 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
632 return cmpNumbers(CXI->getSyncScopeID(),
633 cast<AtomicCmpXchgInst>(R)->getSyncScopeID());
635 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
636 if (int Res = cmpNumbers(RMWI->getOperation(),
637 cast<AtomicRMWInst>(R)->getOperation()))
639 if (int Res = cmpNumbers(RMWI->isVolatile(),
640 cast<AtomicRMWInst>(R)->isVolatile()))
642 if (int Res = cmpOrderings(RMWI->getOrdering(),
643 cast<AtomicRMWInst>(R)->getOrdering()))
645 return cmpNumbers(RMWI->getSyncScopeID(),
646 cast<AtomicRMWInst>(R)->getSyncScopeID());
648 if (const PHINode *PNL = dyn_cast<PHINode>(L)) {
649 const PHINode *PNR = cast<PHINode>(R);
650 // Ensure that in addition to the incoming values being identical
651 // (checked by the caller of this function), the incoming blocks
652 // are also identical.
653 for (unsigned i = 0, e = PNL->getNumIncomingValues(); i != e; ++i) {
655 cmpValues(PNL->getIncomingBlock(i), PNR->getIncomingBlock(i)))
662 // Determine whether two GEP operations perform the same underlying arithmetic.
663 // Read method declaration comments for more details.
664 int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
665 const GEPOperator *GEPR) const {
666 unsigned int ASL = GEPL->getPointerAddressSpace();
667 unsigned int ASR = GEPR->getPointerAddressSpace();
669 if (int Res = cmpNumbers(ASL, ASR))
672 // When we have target data, we can reduce the GEP down to the value in bytes
673 // added to the address.
674 const DataLayout &DL = FnL->getParent()->getDataLayout();
675 unsigned BitWidth = DL.getPointerSizeInBits(ASL);
676 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
677 if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
678 GEPR->accumulateConstantOffset(DL, OffsetR))
679 return cmpAPInts(OffsetL, OffsetR);
680 if (int Res = cmpTypes(GEPL->getSourceElementType(),
681 GEPR->getSourceElementType()))
684 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
687 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
688 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
695 int FunctionComparator::cmpInlineAsm(const InlineAsm *L,
696 const InlineAsm *R) const {
697 // InlineAsm's are uniqued. If they are the same pointer, obviously they are
698 // the same, otherwise compare the fields.
701 if (int Res = cmpTypes(L->getFunctionType(), R->getFunctionType()))
703 if (int Res = cmpMem(L->getAsmString(), R->getAsmString()))
705 if (int Res = cmpMem(L->getConstraintString(), R->getConstraintString()))
707 if (int Res = cmpNumbers(L->hasSideEffects(), R->hasSideEffects()))
709 if (int Res = cmpNumbers(L->isAlignStack(), R->isAlignStack()))
711 if (int Res = cmpNumbers(L->getDialect(), R->getDialect()))
713 assert(L->getFunctionType() != R->getFunctionType());
717 /// Compare two values used by the two functions under pair-wise comparison. If
718 /// this is the first time the values are seen, they're added to the mapping so
719 /// that we will detect mismatches on next use.
720 /// See comments in declaration for more details.
721 int FunctionComparator::cmpValues(const Value *L, const Value *R) const {
722 // Catch self-reference case.
734 const Constant *ConstL = dyn_cast<Constant>(L);
735 const Constant *ConstR = dyn_cast<Constant>(R);
736 if (ConstL && ConstR) {
739 return cmpConstants(ConstL, ConstR);
747 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
748 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
750 if (InlineAsmL && InlineAsmR)
751 return cmpInlineAsm(InlineAsmL, InlineAsmR);
757 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
758 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
760 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
763 // Test whether two basic blocks have equivalent behaviour.
764 int FunctionComparator::cmpBasicBlocks(const BasicBlock *BBL,
765 const BasicBlock *BBR) const {
766 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
767 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
770 bool needToCmpOperands = true;
771 if (int Res = cmpOperations(&*InstL, &*InstR, needToCmpOperands))
773 if (needToCmpOperands) {
774 assert(InstL->getNumOperands() == InstR->getNumOperands());
776 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
777 Value *OpL = InstL->getOperand(i);
778 Value *OpR = InstR->getOperand(i);
779 if (int Res = cmpValues(OpL, OpR))
781 // cmpValues should ensure this is true.
782 assert(cmpTypes(OpL->getType(), OpR->getType()) == 0);
788 } while (InstL != InstLE && InstR != InstRE);
790 if (InstL != InstLE && InstR == InstRE)
792 if (InstL == InstLE && InstR != InstRE)
797 int FunctionComparator::compareSignature() const {
798 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
801 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
805 if (int Res = cmpMem(FnL->getGC(), FnR->getGC()))
809 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
812 if (FnL->hasSection()) {
813 if (int Res = cmpMem(FnL->getSection(), FnR->getSection()))
817 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
820 // TODO: if it's internal and only used in direct calls, we could handle this
822 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
825 if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
828 assert(FnL->arg_size() == FnR->arg_size() &&
829 "Identically typed functions have different numbers of args!");
831 // Visit the arguments so that they get enumerated in the order they're
833 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
834 ArgRI = FnR->arg_begin(),
835 ArgLE = FnL->arg_end();
836 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
837 if (cmpValues(&*ArgLI, &*ArgRI) != 0)
838 llvm_unreachable("Arguments repeat!");
843 // Test whether the two functions have equivalent behaviour.
844 int FunctionComparator::compare() {
847 if (int Res = compareSignature())
850 // We do a CFG-ordered walk since the actual ordering of the blocks in the
851 // linked list is immaterial. Our walk starts at the entry block for both
852 // functions, then takes each block from each terminator in order. As an
853 // artifact, this also means that unreachable blocks are ignored.
854 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
855 SmallPtrSet<const BasicBlock *, 32> VisitedBBs; // in terms of F1.
857 FnLBBs.push_back(&FnL->getEntryBlock());
858 FnRBBs.push_back(&FnR->getEntryBlock());
860 VisitedBBs.insert(FnLBBs[0]);
861 while (!FnLBBs.empty()) {
862 const BasicBlock *BBL = FnLBBs.pop_back_val();
863 const BasicBlock *BBR = FnRBBs.pop_back_val();
865 if (int Res = cmpValues(BBL, BBR))
868 if (int Res = cmpBasicBlocks(BBL, BBR))
871 const TerminatorInst *TermL = BBL->getTerminator();
872 const TerminatorInst *TermR = BBR->getTerminator();
874 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
875 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
876 if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
879 FnLBBs.push_back(TermL->getSuccessor(i));
880 FnRBBs.push_back(TermR->getSuccessor(i));
888 // Accumulate the hash of a sequence of 64-bit integers. This is similar to a
889 // hash of a sequence of 64bit ints, but the entire input does not need to be
890 // available at once. This interface is necessary for functionHash because it
891 // needs to accumulate the hash as the structure of the function is traversed
892 // without saving these values to an intermediate buffer. This form of hashing
893 // is not often needed, as usually the object to hash is just read from a
895 class HashAccumulator64 {
899 // Initialize to random constant, so the state isn't zero.
900 HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
902 void add(uint64_t V) {
903 Hash = hashing::detail::hash_16_bytes(Hash, V);
906 // No finishing is required, because the entire hash value is used.
907 uint64_t getHash() { return Hash; }
910 } // end anonymous namespace
912 // A function hash is calculated by considering only the number of arguments and
913 // whether a function is varargs, the order of basic blocks (given by the
914 // successors of each basic block in depth first order), and the order of
915 // opcodes of each instruction within each of these basic blocks. This mirrors
916 // the strategy compare() uses to compare functions by walking the BBs in depth
917 // first order and comparing each instruction in sequence. Because this hash
918 // does not look at the operands, it is insensitive to things such as the
919 // target of calls and the constants used in the function, which makes it useful
920 // when possibly merging functions which are the same modulo constants and call
922 FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
927 SmallVector<const BasicBlock *, 8> BBs;
928 SmallSet<const BasicBlock *, 16> VisitedBBs;
930 // Walk the blocks in the same order as FunctionComparator::cmpBasicBlocks(),
931 // accumulating the hash of the function "structure." (BB and opcode sequence)
932 BBs.push_back(&F.getEntryBlock());
933 VisitedBBs.insert(BBs[0]);
934 while (!BBs.empty()) {
935 const BasicBlock *BB = BBs.pop_back_val();
936 // This random value acts as a block header, as otherwise the partition of
937 // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
939 for (auto &Inst : *BB) {
940 H.add(Inst.getOpcode());
942 const TerminatorInst *Term = BB->getTerminator();
943 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
944 if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
946 BBs.push_back(Term->getSuccessor(i));