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