1 //===- IRSimilarityIdentifier.cpp - Find similarity in a module -----------===//
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 // \file
10 // Implementation file for the IRSimilarityIdentifier for identifying
11 // similarities in IR including the IRInstructionMapper.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/IRSimilarityIdentifier.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/Operator.h"
19 #include "llvm/IR/User.h"
20 #include "llvm/InitializePasses.h"
21 #include "llvm/Support/SuffixTree.h"
22 
23 using namespace llvm;
24 using namespace IRSimilarity;
25 
26 namespace llvm {
27 cl::opt<bool>
28     DisableBranches("no-ir-sim-branch-matching", cl::init(false),
29                     cl::ReallyHidden,
30                     cl::desc("disable similarity matching, and outlining, "
31                              "across branches for debugging purposes."));
32 
33 cl::opt<bool>
34     DisableIndirectCalls("no-ir-sim-indirect-calls", cl::init(false),
35                          cl::ReallyHidden,
36                          cl::desc("disable outlining indirect calls."));
37 
38 cl::opt<bool>
39     MatchCallsByName("ir-sim-calls-by-name", cl::init(false), cl::ReallyHidden,
40                      cl::desc("only allow matching call instructions if the "
41                               "name and type signature match."));
42 
43 cl::opt<bool>
44     DisableIntrinsics("no-ir-sim-intrinsics", cl::init(false), cl::ReallyHidden,
45                       cl::desc("Don't match or outline intrinsics"));
46 } // namespace llvm
47 
48 IRInstructionData::IRInstructionData(Instruction &I, bool Legality,
49                                      IRInstructionDataList &IDList)
50     : Inst(&I), Legal(Legality), IDL(&IDList) {
51   initializeInstruction();
52 }
53 
54 void IRInstructionData::initializeInstruction() {
55   // We check for whether we have a comparison instruction.  If it is, we
56   // find the "less than" version of the predicate for consistency for
57   // comparison instructions throught the program.
58   if (CmpInst *C = dyn_cast<CmpInst>(Inst)) {
59     CmpInst::Predicate Predicate = predicateForConsistency(C);
60     if (Predicate != C->getPredicate())
61       RevisedPredicate = Predicate;
62   }
63 
64   // Here we collect the operands and their types for determining whether
65   // the structure of the operand use matches between two different candidates.
66   for (Use &OI : Inst->operands()) {
67     if (isa<CmpInst>(Inst) && RevisedPredicate.hasValue()) {
68       // If we have a CmpInst where the predicate is reversed, it means the
69       // operands must be reversed as well.
70       OperVals.insert(OperVals.begin(), OI.get());
71       continue;
72     }
73 
74     OperVals.push_back(OI.get());
75   }
76 
77   // We capture the incoming BasicBlocks as values as well as the incoming
78   // Values in order to check for structural similarity.
79   if (PHINode *PN = dyn_cast<PHINode>(Inst))
80     for (BasicBlock *BB : PN->blocks())
81       OperVals.push_back(BB);
82 }
83 
84 IRInstructionData::IRInstructionData(IRInstructionDataList &IDList)
85     : IDL(&IDList) {}
86 
87 void IRInstructionData::setBranchSuccessors(
88     DenseMap<BasicBlock *, unsigned> &BasicBlockToInteger) {
89   assert(isa<BranchInst>(Inst) && "Instruction must be branch");
90 
91   BranchInst *BI = cast<BranchInst>(Inst);
92   DenseMap<BasicBlock *, unsigned>::iterator BBNumIt;
93 
94   BBNumIt = BasicBlockToInteger.find(BI->getParent());
95   assert(BBNumIt != BasicBlockToInteger.end() &&
96          "Could not find location for BasicBlock!");
97 
98   int CurrentBlockNumber = static_cast<int>(BBNumIt->second);
99 
100   for (BasicBlock *Successor : BI->successors()) {
101     BBNumIt = BasicBlockToInteger.find(Successor);
102     assert(BBNumIt != BasicBlockToInteger.end() &&
103            "Could not find number for BasicBlock!");
104     int OtherBlockNumber = static_cast<int>(BBNumIt->second);
105 
106     int Relative = OtherBlockNumber - CurrentBlockNumber;
107     RelativeBlockLocations.push_back(Relative);
108   }
109 }
110 
111 void IRInstructionData::setCalleeName(bool MatchByName) {
112   CallInst *CI = dyn_cast<CallInst>(Inst);
113   assert(CI && "Instruction must be call");
114 
115   CalleeName = "";
116   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
117     // To hash intrinsics, we use the opcode, and types like the other
118     // instructions, but also, the Intrinsic ID, and the Name of the
119     // intrinsic.
120     Intrinsic::ID IntrinsicID = II->getIntrinsicID();
121     FunctionType *FT = II->getFunctionType();
122     // If there is an overloaded name, we have to use the complex version
123     // of getName to get the entire string.
124     if (Intrinsic::isOverloaded(IntrinsicID))
125       CalleeName =
126           Intrinsic::getName(IntrinsicID, FT->params(), II->getModule(), FT);
127     // If there is not an overloaded name, we only need to use this version.
128     else
129       CalleeName = Intrinsic::getName(IntrinsicID).str();
130 
131     return;
132   }
133 
134   if (!CI->isIndirectCall() && MatchByName)
135     CalleeName = CI->getCalledFunction()->getName().str();
136 }
137 
138 void IRInstructionData::setPHIPredecessors(
139     DenseMap<BasicBlock *, unsigned> &BasicBlockToInteger) {
140   assert(isa<PHINode>(Inst) && "Instruction must be phi node");
141 
142   PHINode *PN = cast<PHINode>(Inst);
143   DenseMap<BasicBlock *, unsigned>::iterator BBNumIt;
144 
145   BBNumIt = BasicBlockToInteger.find(PN->getParent());
146   assert(BBNumIt != BasicBlockToInteger.end() &&
147          "Could not find location for BasicBlock!");
148 
149   int CurrentBlockNumber = static_cast<int>(BBNumIt->second);
150 
151   // Convert the incoming blocks of the PHINode to an integer value, based on
152   // the relative distances between the current block and the incoming block.
153   for (unsigned Idx = 0; Idx < PN->getNumIncomingValues(); Idx++) {
154     BasicBlock *Incoming = PN->getIncomingBlock(Idx);
155     BBNumIt = BasicBlockToInteger.find(Incoming);
156     assert(BBNumIt != BasicBlockToInteger.end() &&
157            "Could not find number for BasicBlock!");
158     int OtherBlockNumber = static_cast<int>(BBNumIt->second);
159 
160     int Relative = OtherBlockNumber - CurrentBlockNumber;
161     RelativeBlockLocations.push_back(Relative);
162     RelativeBlockLocations.push_back(Relative);
163   }
164 }
165 
166 CmpInst::Predicate IRInstructionData::predicateForConsistency(CmpInst *CI) {
167   switch (CI->getPredicate()) {
168   case CmpInst::FCMP_OGT:
169   case CmpInst::FCMP_UGT:
170   case CmpInst::FCMP_OGE:
171   case CmpInst::FCMP_UGE:
172   case CmpInst::ICMP_SGT:
173   case CmpInst::ICMP_UGT:
174   case CmpInst::ICMP_SGE:
175   case CmpInst::ICMP_UGE:
176     return CI->getSwappedPredicate();
177   default:
178     return CI->getPredicate();
179   }
180 }
181 
182 CmpInst::Predicate IRInstructionData::getPredicate() const {
183   assert(isa<CmpInst>(Inst) &&
184          "Can only get a predicate from a compare instruction");
185 
186   if (RevisedPredicate.hasValue())
187     return RevisedPredicate.getValue();
188 
189   return cast<CmpInst>(Inst)->getPredicate();
190 }
191 
192 StringRef IRInstructionData::getCalleeName() const {
193   assert(isa<CallInst>(Inst) &&
194          "Can only get a name from a call instruction");
195 
196   assert(CalleeName.hasValue() && "CalleeName has not been set");
197 
198   return *CalleeName;
199 }
200 
201 bool IRSimilarity::isClose(const IRInstructionData &A,
202                            const IRInstructionData &B) {
203 
204   if (!A.Legal || !B.Legal)
205     return false;
206 
207   // Check if we are performing the same sort of operation on the same types
208   // but not on the same values.
209   if (!A.Inst->isSameOperationAs(B.Inst)) {
210     // If there is a predicate, this means that either there is a swapped
211     // predicate, or that the types are different, we want to make sure that
212     // the predicates are equivalent via swapping.
213     if (isa<CmpInst>(A.Inst) && isa<CmpInst>(B.Inst)) {
214 
215       if (A.getPredicate() != B.getPredicate())
216         return false;
217 
218       // If the predicates are the same via swap, make sure that the types are
219       // still the same.
220       auto ZippedTypes = zip(A.OperVals, B.OperVals);
221 
222       return all_of(
223           ZippedTypes, [](std::tuple<llvm::Value *, llvm::Value *> R) {
224             return std::get<0>(R)->getType() == std::get<1>(R)->getType();
225           });
226     }
227 
228     return false;
229   }
230 
231   // Since any GEP Instruction operands after the first operand cannot be
232   // defined by a register, we must make sure that the operands after the first
233   // are the same in the two instructions
234   if (auto *GEP = dyn_cast<GetElementPtrInst>(A.Inst)) {
235     auto *OtherGEP = cast<GetElementPtrInst>(B.Inst);
236 
237     // If the instructions do not have the same inbounds restrictions, we do
238     // not consider them the same.
239     if (GEP->isInBounds() != OtherGEP->isInBounds())
240       return false;
241 
242     auto ZippedOperands = zip(GEP->indices(), OtherGEP->indices());
243 
244     // We increment here since we do not care about the first instruction,
245     // we only care about the following operands since they must be the
246     // exact same to be considered similar.
247     return all_of(drop_begin(ZippedOperands),
248                   [](std::tuple<llvm::Use &, llvm::Use &> R) {
249                     return std::get<0>(R) == std::get<1>(R);
250                   });
251   }
252 
253   // If the instructions are functions calls, we make sure that the function
254   // name is the same.  We already know that the types are since is
255   // isSameOperationAs is true.
256   if (isa<CallInst>(A.Inst) && isa<CallInst>(B.Inst)) {
257     if (A.getCalleeName().str() != B.getCalleeName().str())
258       return false;
259   }
260 
261   if (isa<BranchInst>(A.Inst) && isa<BranchInst>(B.Inst) &&
262       A.RelativeBlockLocations.size() != B.RelativeBlockLocations.size())
263     return false;
264 
265   return true;
266 }
267 
268 // TODO: This is the same as the MachineOutliner, and should be consolidated
269 // into the same interface.
270 void IRInstructionMapper::convertToUnsignedVec(
271     BasicBlock &BB, std::vector<IRInstructionData *> &InstrList,
272     std::vector<unsigned> &IntegerMapping) {
273   BasicBlock::iterator It = BB.begin();
274 
275   std::vector<unsigned> IntegerMappingForBB;
276   std::vector<IRInstructionData *> InstrListForBB;
277 
278   for (BasicBlock::iterator Et = BB.end(); It != Et; ++It) {
279     switch (InstClassifier.visit(*It)) {
280     case InstrType::Legal:
281       mapToLegalUnsigned(It, IntegerMappingForBB, InstrListForBB);
282       break;
283     case InstrType::Illegal:
284       mapToIllegalUnsigned(It, IntegerMappingForBB, InstrListForBB);
285       break;
286     case InstrType::Invisible:
287       AddedIllegalLastTime = false;
288       break;
289     }
290   }
291 
292   if (AddedIllegalLastTime)
293     mapToIllegalUnsigned(It, IntegerMappingForBB, InstrListForBB, true);
294   for (IRInstructionData *ID : InstrListForBB)
295     this->IDL->push_back(*ID);
296   llvm::append_range(InstrList, InstrListForBB);
297   llvm::append_range(IntegerMapping, IntegerMappingForBB);
298 }
299 
300 // TODO: This is the same as the MachineOutliner, and should be consolidated
301 // into the same interface.
302 unsigned IRInstructionMapper::mapToLegalUnsigned(
303     BasicBlock::iterator &It, std::vector<unsigned> &IntegerMappingForBB,
304     std::vector<IRInstructionData *> &InstrListForBB) {
305   // We added something legal, so we should unset the AddedLegalLastTime
306   // flag.
307   AddedIllegalLastTime = false;
308 
309   // If we have at least two adjacent legal instructions (which may have
310   // invisible instructions in between), remember that.
311   if (CanCombineWithPrevInstr)
312     HaveLegalRange = true;
313   CanCombineWithPrevInstr = true;
314 
315   // Get the integer for this instruction or give it the current
316   // LegalInstrNumber.
317   IRInstructionData *ID = allocateIRInstructionData(*It, true, *IDL);
318   InstrListForBB.push_back(ID);
319 
320   if (isa<BranchInst>(*It))
321     ID->setBranchSuccessors(BasicBlockToInteger);
322 
323   if (isa<CallInst>(*It))
324     ID->setCalleeName(EnableMatchCallsByName);
325 
326   if (isa<PHINode>(*It))
327     ID->setPHIPredecessors(BasicBlockToInteger);
328 
329   // Add to the instruction list
330   bool WasInserted;
331   DenseMap<IRInstructionData *, unsigned, IRInstructionDataTraits>::iterator
332       ResultIt;
333   std::tie(ResultIt, WasInserted) =
334       InstructionIntegerMap.insert(std::make_pair(ID, LegalInstrNumber));
335   unsigned INumber = ResultIt->second;
336 
337   // There was an insertion.
338   if (WasInserted)
339     LegalInstrNumber++;
340 
341   IntegerMappingForBB.push_back(INumber);
342 
343   // Make sure we don't overflow or use any integers reserved by the DenseMap.
344   assert(LegalInstrNumber < IllegalInstrNumber &&
345          "Instruction mapping overflow!");
346 
347   assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
348          "Tried to assign DenseMap tombstone or empty key to instruction.");
349   assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
350          "Tried to assign DenseMap tombstone or empty key to instruction.");
351 
352   return INumber;
353 }
354 
355 IRInstructionData *
356 IRInstructionMapper::allocateIRInstructionData(Instruction &I, bool Legality,
357                                                IRInstructionDataList &IDL) {
358   return new (InstDataAllocator->Allocate()) IRInstructionData(I, Legality, IDL);
359 }
360 
361 IRInstructionData *
362 IRInstructionMapper::allocateIRInstructionData(IRInstructionDataList &IDL) {
363   return new (InstDataAllocator->Allocate()) IRInstructionData(IDL);
364 }
365 
366 IRInstructionDataList *
367 IRInstructionMapper::allocateIRInstructionDataList() {
368   return new (IDLAllocator->Allocate()) IRInstructionDataList();
369 }
370 
371 // TODO: This is the same as the MachineOutliner, and should be consolidated
372 // into the same interface.
373 unsigned IRInstructionMapper::mapToIllegalUnsigned(
374     BasicBlock::iterator &It, std::vector<unsigned> &IntegerMappingForBB,
375     std::vector<IRInstructionData *> &InstrListForBB, bool End) {
376   // Can't combine an illegal instruction. Set the flag.
377   CanCombineWithPrevInstr = false;
378 
379   // Only add one illegal number per range of legal numbers.
380   if (AddedIllegalLastTime)
381     return IllegalInstrNumber;
382 
383   IRInstructionData *ID = nullptr;
384   if (!End)
385     ID = allocateIRInstructionData(*It, false, *IDL);
386   else
387     ID = allocateIRInstructionData(*IDL);
388   InstrListForBB.push_back(ID);
389 
390   // Remember that we added an illegal number last time.
391   AddedIllegalLastTime = true;
392   unsigned INumber = IllegalInstrNumber;
393   IntegerMappingForBB.push_back(IllegalInstrNumber--);
394 
395   assert(LegalInstrNumber < IllegalInstrNumber &&
396          "Instruction mapping overflow!");
397 
398   assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
399          "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
400 
401   assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
402          "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
403 
404   return INumber;
405 }
406 
407 IRSimilarityCandidate::IRSimilarityCandidate(unsigned StartIdx, unsigned Len,
408                                              IRInstructionData *FirstInstIt,
409                                              IRInstructionData *LastInstIt)
410     : StartIdx(StartIdx), Len(Len) {
411 
412   assert(FirstInstIt != nullptr && "Instruction is nullptr!");
413   assert(LastInstIt != nullptr && "Instruction is nullptr!");
414   assert(StartIdx + Len > StartIdx &&
415          "Overflow for IRSimilarityCandidate range?");
416   assert(Len - 1 == static_cast<unsigned>(std::distance(
417                         iterator(FirstInstIt), iterator(LastInstIt))) &&
418          "Length of the first and last IRInstructionData do not match the "
419          "given length");
420 
421   // We iterate over the given instructions, and map each unique value
422   // to a unique number in the IRSimilarityCandidate ValueToNumber and
423   // NumberToValue maps.  A constant get its own value globally, the individual
424   // uses of the constants are not considered to be unique.
425   //
426   // IR:                    Mapping Added:
427   // %add1 = add i32 %a, c1    %add1 -> 3, %a -> 1, c1 -> 2
428   // %add2 = add i32 %a, %1    %add2 -> 4
429   // %add3 = add i32 c2, c1    %add3 -> 6, c2 -> 5
430   //
431   // when replace with global values, starting from 1, would be
432   //
433   // 3 = add i32 1, 2
434   // 4 = add i32 1, 3
435   // 6 = add i32 5, 2
436   unsigned LocalValNumber = 1;
437   IRInstructionDataList::iterator ID = iterator(*FirstInstIt);
438   for (unsigned Loc = StartIdx; Loc < StartIdx + Len; Loc++, ID++) {
439     // Map the operand values to an unsigned integer if it does not already
440     // have an unsigned integer assigned to it.
441     for (Value *Arg : ID->OperVals)
442       if (ValueToNumber.find(Arg) == ValueToNumber.end()) {
443         ValueToNumber.try_emplace(Arg, LocalValNumber);
444         NumberToValue.try_emplace(LocalValNumber, Arg);
445         LocalValNumber++;
446       }
447 
448     // Mapping the instructions to an unsigned integer if it is not already
449     // exist in the mapping.
450     if (ValueToNumber.find(ID->Inst) == ValueToNumber.end()) {
451       ValueToNumber.try_emplace(ID->Inst, LocalValNumber);
452       NumberToValue.try_emplace(LocalValNumber, ID->Inst);
453       LocalValNumber++;
454     }
455   }
456 
457   // Setting the first and last instruction data pointers for the candidate.  If
458   // we got through the entire for loop without hitting an assert, we know
459   // that both of these instructions are not nullptrs.
460   FirstInst = FirstInstIt;
461   LastInst = LastInstIt;
462 }
463 
464 bool IRSimilarityCandidate::isSimilar(const IRSimilarityCandidate &A,
465                                       const IRSimilarityCandidate &B) {
466   if (A.getLength() != B.getLength())
467     return false;
468 
469   auto InstrDataForBoth =
470       zip(make_range(A.begin(), A.end()), make_range(B.begin(), B.end()));
471 
472   return all_of(InstrDataForBoth,
473                 [](std::tuple<IRInstructionData &, IRInstructionData &> R) {
474                   IRInstructionData &A = std::get<0>(R);
475                   IRInstructionData &B = std::get<1>(R);
476                   if (!A.Legal || !B.Legal)
477                     return false;
478                   return isClose(A, B);
479                 });
480 }
481 
482 /// Determine if one or more of the assigned global value numbers for the
483 /// operands in \p TargetValueNumbers is in the current mapping set for operand
484 /// numbers in \p SourceOperands.  The set of possible corresponding global
485 /// value numbers are replaced with the most recent version of compatible
486 /// values.
487 ///
488 /// \param [in] SourceValueToNumberMapping - The mapping of a Value to global
489 /// value number for the source IRInstructionCandidate.
490 /// \param [in, out] CurrentSrcTgtNumberMapping - The current mapping of source
491 /// IRSimilarityCandidate global value numbers to a set of possible numbers in
492 /// the target.
493 /// \param [in] SourceOperands - The operands in the original
494 /// IRSimilarityCandidate in the current instruction.
495 /// \param [in] TargetValueNumbers - The global value numbers of the operands in
496 /// the corresponding Instruction in the other IRSimilarityCandidate.
497 /// \returns true if there exists a possible mapping between the source
498 /// Instruction operands and the target Instruction operands, and false if not.
499 static bool checkNumberingAndReplaceCommutative(
500   const DenseMap<Value *, unsigned> &SourceValueToNumberMapping,
501   DenseMap<unsigned, DenseSet<unsigned>> &CurrentSrcTgtNumberMapping,
502   ArrayRef<Value *> &SourceOperands,
503   DenseSet<unsigned> &TargetValueNumbers){
504 
505   DenseMap<unsigned, DenseSet<unsigned>>::iterator ValueMappingIt;
506 
507   unsigned ArgVal;
508   bool WasInserted;
509 
510   // Iterate over the operands in the source IRSimilarityCandidate to determine
511   // whether there exists an operand in the other IRSimilarityCandidate that
512   // creates a valid mapping of Value to Value between the
513   // IRSimilarityCaniddates.
514   for (Value *V : SourceOperands) {
515     ArgVal = SourceValueToNumberMapping.find(V)->second;
516 
517     std::tie(ValueMappingIt, WasInserted) = CurrentSrcTgtNumberMapping.insert(
518         std::make_pair(ArgVal, TargetValueNumbers));
519 
520     // Instead of finding a current mapping, we inserted a set.  This means a
521     // mapping did not exist for the source Instruction operand, it has no
522     // current constraints we need to check.
523     if (WasInserted)
524       continue;
525 
526     // If a mapping already exists for the source operand to the values in the
527     // other IRSimilarityCandidate we need to iterate over the items in other
528     // IRSimilarityCandidate's Instruction to determine whether there is a valid
529     // mapping of Value to Value.
530     DenseSet<unsigned> NewSet;
531     for (unsigned &Curr : ValueMappingIt->second)
532       // If we can find the value in the mapping, we add it to the new set.
533       if (TargetValueNumbers.contains(Curr))
534         NewSet.insert(Curr);
535 
536     // If we could not find a Value, return 0.
537     if (NewSet.empty())
538       return false;
539 
540     // Otherwise replace the old mapping with the newly constructed one.
541     if (NewSet.size() != ValueMappingIt->second.size())
542       ValueMappingIt->second.swap(NewSet);
543 
544     // We have reached no conclusions about the mapping, and cannot remove
545     // any items from the other operands, so we move to check the next operand.
546     if (ValueMappingIt->second.size() != 1)
547       continue;
548 
549 
550     unsigned ValToRemove = *ValueMappingIt->second.begin();
551     // When there is only one item left in the mapping for and operand, remove
552     // the value from the other operands.  If it results in there being no
553     // mapping, return false, it means the mapping is wrong
554     for (Value *InnerV : SourceOperands) {
555       if (V == InnerV)
556         continue;
557 
558       unsigned InnerVal = SourceValueToNumberMapping.find(InnerV)->second;
559       ValueMappingIt = CurrentSrcTgtNumberMapping.find(InnerVal);
560       if (ValueMappingIt == CurrentSrcTgtNumberMapping.end())
561         continue;
562 
563       ValueMappingIt->second.erase(ValToRemove);
564       if (ValueMappingIt->second.empty())
565         return false;
566     }
567   }
568 
569   return true;
570 }
571 
572 /// Determine if operand number \p TargetArgVal is in the current mapping set
573 /// for operand number \p SourceArgVal.
574 ///
575 /// \param [in, out] CurrentSrcTgtNumberMapping current mapping of global
576 /// value numbers from source IRSimilarityCandidate to target
577 /// IRSimilarityCandidate.
578 /// \param [in] SourceArgVal The global value number for an operand in the
579 /// in the original candidate.
580 /// \param [in] TargetArgVal The global value number for the corresponding
581 /// operand in the other candidate.
582 /// \returns True if there exists a mapping and false if not.
583 bool checkNumberingAndReplace(
584     DenseMap<unsigned, DenseSet<unsigned>> &CurrentSrcTgtNumberMapping,
585     unsigned SourceArgVal, unsigned TargetArgVal) {
586   // We are given two unsigned integers representing the global values of
587   // the operands in different IRSimilarityCandidates and a current mapping
588   // between the two.
589   //
590   // Source Operand GVN: 1
591   // Target Operand GVN: 2
592   // CurrentMapping: {1: {1, 2}}
593   //
594   // Since we have mapping, and the target operand is contained in the set, we
595   // update it to:
596   // CurrentMapping: {1: {2}}
597   // and can return true. But, if the mapping was
598   // CurrentMapping: {1: {3}}
599   // we would return false.
600 
601   bool WasInserted;
602   DenseMap<unsigned, DenseSet<unsigned>>::iterator Val;
603 
604   std::tie(Val, WasInserted) = CurrentSrcTgtNumberMapping.insert(
605       std::make_pair(SourceArgVal, DenseSet<unsigned>({TargetArgVal})));
606 
607   // If we created a new mapping, then we are done.
608   if (WasInserted)
609     return true;
610 
611   // If there is more than one option in the mapping set, and the target value
612   // is included in the mapping set replace that set with one that only includes
613   // the target value, as it is the only valid mapping via the non commutative
614   // instruction.
615 
616   DenseSet<unsigned> &TargetSet = Val->second;
617   if (TargetSet.size() > 1 && TargetSet.contains(TargetArgVal)) {
618     TargetSet.clear();
619     TargetSet.insert(TargetArgVal);
620     return true;
621   }
622 
623   // Return true if we can find the value in the set.
624   return TargetSet.contains(TargetArgVal);
625 }
626 
627 bool IRSimilarityCandidate::compareNonCommutativeOperandMapping(
628     OperandMapping A, OperandMapping B) {
629   // Iterators to keep track of where we are in the operands for each
630   // Instruction.
631   ArrayRef<Value *>::iterator VItA = A.OperVals.begin();
632   ArrayRef<Value *>::iterator VItB = B.OperVals.begin();
633   unsigned OperandLength = A.OperVals.size();
634 
635   // For each operand, get the value numbering and ensure it is consistent.
636   for (unsigned Idx = 0; Idx < OperandLength; Idx++, VItA++, VItB++) {
637     unsigned OperValA = A.IRSC.ValueToNumber.find(*VItA)->second;
638     unsigned OperValB = B.IRSC.ValueToNumber.find(*VItB)->second;
639 
640     // Attempt to add a set with only the target value.  If there is no mapping
641     // we can create it here.
642     //
643     // For an instruction like a subtraction:
644     // IRSimilarityCandidateA:  IRSimilarityCandidateB:
645     // %resultA = sub %a, %b    %resultB = sub %d, %e
646     //
647     // We map %a -> %d and %b -> %e.
648     //
649     // And check to see whether their mapping is consistent in
650     // checkNumberingAndReplace.
651 
652     if (!checkNumberingAndReplace(A.ValueNumberMapping, OperValA, OperValB))
653       return false;
654 
655     if (!checkNumberingAndReplace(B.ValueNumberMapping, OperValB, OperValA))
656       return false;
657   }
658   return true;
659 }
660 
661 bool IRSimilarityCandidate::compareCommutativeOperandMapping(
662     OperandMapping A, OperandMapping B) {
663   DenseSet<unsigned> ValueNumbersA;
664   DenseSet<unsigned> ValueNumbersB;
665 
666   ArrayRef<Value *>::iterator VItA = A.OperVals.begin();
667   ArrayRef<Value *>::iterator VItB = B.OperVals.begin();
668   unsigned OperandLength = A.OperVals.size();
669 
670   // Find the value number sets for the operands.
671   for (unsigned Idx = 0; Idx < OperandLength;
672        Idx++, VItA++, VItB++) {
673     ValueNumbersA.insert(A.IRSC.ValueToNumber.find(*VItA)->second);
674     ValueNumbersB.insert(B.IRSC.ValueToNumber.find(*VItB)->second);
675   }
676 
677   // Iterate over the operands in the first IRSimilarityCandidate and make sure
678   // there exists a possible mapping with the operands in the second
679   // IRSimilarityCandidate.
680   if (!checkNumberingAndReplaceCommutative(A.IRSC.ValueToNumber,
681                                            A.ValueNumberMapping, A.OperVals,
682                                            ValueNumbersB))
683     return false;
684 
685   // Iterate over the operands in the second IRSimilarityCandidate and make sure
686   // there exists a possible mapping with the operands in the first
687   // IRSimilarityCandidate.
688   if (!checkNumberingAndReplaceCommutative(B.IRSC.ValueToNumber,
689                                            B.ValueNumberMapping, B.OperVals,
690                                            ValueNumbersA))
691     return false;
692 
693   return true;
694 }
695 
696 bool IRSimilarityCandidate::checkRelativeLocations(RelativeLocMapping A,
697                                                    RelativeLocMapping B) {
698   // Get the basic blocks the label refers to.
699   BasicBlock *ABB = static_cast<BasicBlock *>(A.OperVal);
700   BasicBlock *BBB = static_cast<BasicBlock *>(B.OperVal);
701 
702   // Get the basic blocks contained in each region.
703   DenseSet<BasicBlock *> BasicBlockA;
704   DenseSet<BasicBlock *> BasicBlockB;
705   A.IRSC.getBasicBlocks(BasicBlockA);
706   B.IRSC.getBasicBlocks(BasicBlockB);
707 
708   // Determine if the block is contained in the region.
709   bool AContained = BasicBlockA.contains(ABB);
710   bool BContained = BasicBlockB.contains(BBB);
711 
712   // Both blocks need to be contained in the region, or both need to be outside
713   // the reigon.
714   if (AContained != BContained)
715     return false;
716 
717   // If both are contained, then we need to make sure that the relative
718   // distance to the target blocks are the same.
719   if (AContained)
720     return A.RelativeLocation == B.RelativeLocation;
721   return true;
722 }
723 
724 bool IRSimilarityCandidate::compareStructure(const IRSimilarityCandidate &A,
725                                              const IRSimilarityCandidate &B) {
726   DenseMap<unsigned, DenseSet<unsigned>> MappingA;
727   DenseMap<unsigned, DenseSet<unsigned>> MappingB;
728   return IRSimilarityCandidate::compareStructure(A, B, MappingA, MappingB);
729 }
730 
731 typedef detail::zippy<detail::zip_shortest, SmallVector<int, 4> &,
732                       SmallVector<int, 4> &, ArrayRef<Value *> &,
733                       ArrayRef<Value *> &>
734     ZippedRelativeLocationsT;
735 
736 bool IRSimilarityCandidate::compareStructure(
737     const IRSimilarityCandidate &A, const IRSimilarityCandidate &B,
738     DenseMap<unsigned, DenseSet<unsigned>> &ValueNumberMappingA,
739     DenseMap<unsigned, DenseSet<unsigned>> &ValueNumberMappingB) {
740   if (A.getLength() != B.getLength())
741     return false;
742 
743   if (A.ValueToNumber.size() != B.ValueToNumber.size())
744     return false;
745 
746   iterator ItA = A.begin();
747   iterator ItB = B.begin();
748 
749   // These ValueNumber Mapping sets create a create a mapping between the values
750   // in one candidate to values in the other candidate.  If we create a set with
751   // one element, and that same element maps to the original element in the
752   // candidate we have a good mapping.
753   DenseMap<unsigned, DenseSet<unsigned>>::iterator ValueMappingIt;
754 
755 
756   // Iterate over the instructions contained in each candidate
757   unsigned SectionLength = A.getStartIdx() + A.getLength();
758   for (unsigned Loc = A.getStartIdx(); Loc < SectionLength;
759        ItA++, ItB++, Loc++) {
760     // Make sure the instructions are similar to one another.
761     if (!isClose(*ItA, *ItB))
762       return false;
763 
764     Instruction *IA = ItA->Inst;
765     Instruction *IB = ItB->Inst;
766 
767     if (!ItA->Legal || !ItB->Legal)
768       return false;
769 
770     // Get the operand sets for the instructions.
771     ArrayRef<Value *> OperValsA = ItA->OperVals;
772     ArrayRef<Value *> OperValsB = ItB->OperVals;
773 
774     unsigned InstValA = A.ValueToNumber.find(IA)->second;
775     unsigned InstValB = B.ValueToNumber.find(IB)->second;
776 
777     bool WasInserted;
778     // Ensure that the mappings for the instructions exists.
779     std::tie(ValueMappingIt, WasInserted) = ValueNumberMappingA.insert(
780         std::make_pair(InstValA, DenseSet<unsigned>({InstValB})));
781     if (!WasInserted && !ValueMappingIt->second.contains(InstValB))
782       return false;
783 
784     std::tie(ValueMappingIt, WasInserted) = ValueNumberMappingB.insert(
785         std::make_pair(InstValB, DenseSet<unsigned>({InstValA})));
786     if (!WasInserted && !ValueMappingIt->second.contains(InstValA))
787       return false;
788 
789     // We have different paths for commutative instructions and non-commutative
790     // instructions since commutative instructions could allow multiple mappings
791     // to certain values.
792     if (IA->isCommutative() && !isa<FPMathOperator>(IA) &&
793         !isa<IntrinsicInst>(IA)) {
794       if (!compareCommutativeOperandMapping(
795               {A, OperValsA, ValueNumberMappingA},
796               {B, OperValsB, ValueNumberMappingB}))
797         return false;
798       continue;
799     }
800 
801     // Handle the non-commutative cases.
802     if (!compareNonCommutativeOperandMapping(
803             {A, OperValsA, ValueNumberMappingA},
804             {B, OperValsB, ValueNumberMappingB}))
805       return false;
806 
807     // Here we check that between two corresponding instructions,
808     // when referring to a basic block in the same region, the
809     // relative locations are the same. And, that the instructions refer to
810     // basic blocks outside the region in the same corresponding locations.
811 
812     // We are able to make the assumption about blocks outside of the region
813     // since the target block labels are considered values and will follow the
814     // same number matching that we defined for the other instructions in the
815     // region.  So, at this point, in each location we target a specific block
816     // outside the region, we are targeting a corresponding block in each
817     // analagous location in the region we are comparing to.
818     if (!(isa<BranchInst>(IA) && isa<BranchInst>(IB)) &&
819         !(isa<PHINode>(IA) && isa<PHINode>(IB)))
820       continue;
821 
822     SmallVector<int, 4> &RelBlockLocsA = ItA->RelativeBlockLocations;
823     SmallVector<int, 4> &RelBlockLocsB = ItB->RelativeBlockLocations;
824     if (RelBlockLocsA.size() != RelBlockLocsB.size() &&
825         OperValsA.size() != OperValsB.size())
826       return false;
827 
828     ZippedRelativeLocationsT ZippedRelativeLocations =
829         zip(RelBlockLocsA, RelBlockLocsB, OperValsA, OperValsB);
830     if (any_of(ZippedRelativeLocations,
831                [&A, &B](std::tuple<int, int, Value *, Value *> R) {
832                  return !checkRelativeLocations(
833                      {A, std::get<0>(R), std::get<2>(R)},
834                      {B, std::get<1>(R), std::get<3>(R)});
835                }))
836       return false;
837   }
838   return true;
839 }
840 
841 bool IRSimilarityCandidate::overlap(const IRSimilarityCandidate &A,
842                                     const IRSimilarityCandidate &B) {
843   auto DoesOverlap = [](const IRSimilarityCandidate &X,
844                         const IRSimilarityCandidate &Y) {
845     // Check:
846     // XXXXXX        X starts before Y ends
847     //      YYYYYYY  Y starts after X starts
848     return X.StartIdx <= Y.getEndIdx() && Y.StartIdx >= X.StartIdx;
849   };
850 
851   return DoesOverlap(A, B) || DoesOverlap(B, A);
852 }
853 
854 void IRSimilarityIdentifier::populateMapper(
855     Module &M, std::vector<IRInstructionData *> &InstrList,
856     std::vector<unsigned> &IntegerMapping) {
857 
858   std::vector<IRInstructionData *> InstrListForModule;
859   std::vector<unsigned> IntegerMappingForModule;
860   // Iterate over the functions in the module to map each Instruction in each
861   // BasicBlock to an unsigned integer.
862   Mapper.initializeForBBs(M);
863 
864   for (Function &F : M) {
865 
866     if (F.empty())
867       continue;
868 
869     for (BasicBlock &BB : F) {
870 
871       // BB has potential to have similarity since it has a size greater than 2
872       // and can therefore match other regions greater than 2. Map it to a list
873       // of unsigned integers.
874       Mapper.convertToUnsignedVec(BB, InstrListForModule,
875                                   IntegerMappingForModule);
876     }
877 
878     BasicBlock::iterator It = F.begin()->end();
879     Mapper.mapToIllegalUnsigned(It, IntegerMappingForModule, InstrListForModule,
880                                 true);
881     if (InstrListForModule.size() > 0)
882       Mapper.IDL->push_back(*InstrListForModule.back());
883   }
884 
885   // Insert the InstrListForModule at the end of the overall InstrList so that
886   // we can have a long InstrList for the entire set of Modules being analyzed.
887   llvm::append_range(InstrList, InstrListForModule);
888   // Do the same as above, but for IntegerMapping.
889   llvm::append_range(IntegerMapping, IntegerMappingForModule);
890 }
891 
892 void IRSimilarityIdentifier::populateMapper(
893     ArrayRef<std::unique_ptr<Module>> &Modules,
894     std::vector<IRInstructionData *> &InstrList,
895     std::vector<unsigned> &IntegerMapping) {
896 
897   // Iterate over, and map the instructions in each module.
898   for (const std::unique_ptr<Module> &M : Modules)
899     populateMapper(*M, InstrList, IntegerMapping);
900 }
901 
902 /// From a repeated subsequence, find all the different instances of the
903 /// subsequence from the \p InstrList, and create an IRSimilarityCandidate from
904 /// the IRInstructionData in subsequence.
905 ///
906 /// \param [in] Mapper - The instruction mapper for basic correctness checks.
907 /// \param [in] InstrList - The vector that holds the instruction data.
908 /// \param [in] IntegerMapping - The vector that holds the mapped integers.
909 /// \param [out] CandsForRepSubstring - The vector to store the generated
910 /// IRSimilarityCandidates.
911 static void createCandidatesFromSuffixTree(
912     const IRInstructionMapper& Mapper, std::vector<IRInstructionData *> &InstrList,
913     std::vector<unsigned> &IntegerMapping, SuffixTree::RepeatedSubstring &RS,
914     std::vector<IRSimilarityCandidate> &CandsForRepSubstring) {
915 
916   unsigned StringLen = RS.Length;
917   if (StringLen < 2)
918     return;
919 
920   // Create an IRSimilarityCandidate for instance of this subsequence \p RS.
921   for (const unsigned &StartIdx : RS.StartIndices) {
922     unsigned EndIdx = StartIdx + StringLen - 1;
923 
924     // Check that this subsequence does not contain an illegal instruction.
925     bool ContainsIllegal = false;
926     for (unsigned CurrIdx = StartIdx; CurrIdx <= EndIdx; CurrIdx++) {
927       unsigned Key = IntegerMapping[CurrIdx];
928       if (Key > Mapper.IllegalInstrNumber) {
929         ContainsIllegal = true;
930         break;
931       }
932     }
933 
934     // If we have an illegal instruction, we should not create an
935     // IRSimilarityCandidate for this region.
936     if (ContainsIllegal)
937       continue;
938 
939     // We are getting iterators to the instructions in this region of code
940     // by advancing the start and end indices from the start of the
941     // InstrList.
942     std::vector<IRInstructionData *>::iterator StartIt = InstrList.begin();
943     std::advance(StartIt, StartIdx);
944     std::vector<IRInstructionData *>::iterator EndIt = InstrList.begin();
945     std::advance(EndIt, EndIdx);
946 
947     CandsForRepSubstring.emplace_back(StartIdx, StringLen, *StartIt, *EndIt);
948   }
949 }
950 
951 void IRSimilarityCandidate::createCanonicalRelationFrom(
952     IRSimilarityCandidate &SourceCand,
953     DenseMap<unsigned, DenseSet<unsigned>> &ToSourceMapping,
954     DenseMap<unsigned, DenseSet<unsigned>> &FromSourceMapping) {
955   assert(SourceCand.CanonNumToNumber.size() != 0 &&
956          "Base canonical relationship is empty!");
957   assert(SourceCand.NumberToCanonNum.size() != 0 &&
958          "Base canonical relationship is empty!");
959 
960   assert(CanonNumToNumber.size() == 0 && "Canonical Relationship is non-empty");
961   assert(NumberToCanonNum.size() == 0 && "Canonical Relationship is non-empty");
962 
963   DenseSet<unsigned> UsedGVNs;
964   // Iterate over the mappings provided from this candidate to SourceCand.  We
965   // are then able to map the GVN in this candidate to the same canonical number
966   // given to the corresponding GVN in SourceCand.
967   for (std::pair<unsigned, DenseSet<unsigned>> &GVNMapping : ToSourceMapping) {
968     unsigned SourceGVN = GVNMapping.first;
969 
970     assert(GVNMapping.second.size() != 0 && "Possible GVNs is 0!");
971 
972     unsigned ResultGVN;
973     // We need special handling if we have more than one potential value.  This
974     // means that there are at least two GVNs that could correspond to this GVN.
975     // This could lead to potential swapping later on, so we make a decision
976     // here to ensure a one-to-one mapping.
977     if (GVNMapping.second.size() > 1) {
978       bool Found = false;
979       for (unsigned Val : GVNMapping.second) {
980         // We make sure the target value number hasn't already been reserved.
981         if (UsedGVNs.contains(Val))
982           continue;
983 
984         // We make sure that the opposite mapping is still consistent.
985         DenseMap<unsigned, DenseSet<unsigned>>::iterator It =
986             FromSourceMapping.find(Val);
987 
988         if (!It->second.contains(SourceGVN))
989           continue;
990 
991         // We pick the first item that satisfies these conditions.
992         Found = true;
993         ResultGVN = Val;
994         break;
995       }
996 
997       assert(Found && "Could not find matching value for source GVN");
998       (void)Found;
999 
1000     } else
1001       ResultGVN = *GVNMapping.second.begin();
1002 
1003     // Whatever GVN is found, we mark it as used.
1004     UsedGVNs.insert(ResultGVN);
1005 
1006     unsigned CanonNum = *SourceCand.getCanonicalNum(ResultGVN);
1007     CanonNumToNumber.insert(std::make_pair(CanonNum, SourceGVN));
1008     NumberToCanonNum.insert(std::make_pair(SourceGVN, CanonNum));
1009   }
1010 }
1011 
1012 void IRSimilarityCandidate::createCanonicalMappingFor(
1013     IRSimilarityCandidate &CurrCand) {
1014   assert(CurrCand.CanonNumToNumber.size() == 0 &&
1015          "Canonical Relationship is non-empty");
1016   assert(CurrCand.NumberToCanonNum.size() == 0 &&
1017          "Canonical Relationship is non-empty");
1018 
1019   unsigned CanonNum = 0;
1020   // Iterate over the value numbers found, the order does not matter in this
1021   // case.
1022   for (std::pair<unsigned, Value *> &NumToVal : CurrCand.NumberToValue) {
1023     CurrCand.NumberToCanonNum.insert(std::make_pair(NumToVal.first, CanonNum));
1024     CurrCand.CanonNumToNumber.insert(std::make_pair(CanonNum, NumToVal.first));
1025     CanonNum++;
1026   }
1027 }
1028 
1029 /// From the list of IRSimilarityCandidates, perform a comparison between each
1030 /// IRSimilarityCandidate to determine if there are overlapping
1031 /// IRInstructionData, or if they do not have the same structure.
1032 ///
1033 /// \param [in] CandsForRepSubstring - The vector containing the
1034 /// IRSimilarityCandidates.
1035 /// \param [out] StructuralGroups - the mapping of unsigned integers to vector
1036 /// of IRSimilarityCandidates where each of the IRSimilarityCandidates in the
1037 /// vector are structurally similar to one another.
1038 static void findCandidateStructures(
1039     std::vector<IRSimilarityCandidate> &CandsForRepSubstring,
1040     DenseMap<unsigned, SimilarityGroup> &StructuralGroups) {
1041   std::vector<IRSimilarityCandidate>::iterator CandIt, CandEndIt, InnerCandIt,
1042       InnerCandEndIt;
1043 
1044   // IRSimilarityCandidates each have a structure for operand use.  It is
1045   // possible that two instances of the same subsequences have different
1046   // structure. Each type of structure found is assigned a number.  This
1047   // DenseMap maps an IRSimilarityCandidate to which type of similarity
1048   // discovered it fits within.
1049   DenseMap<IRSimilarityCandidate *, unsigned> CandToGroup;
1050 
1051   // Find the compatibility from each candidate to the others to determine
1052   // which candidates overlap and which have the same structure by mapping
1053   // each structure to a different group.
1054   bool SameStructure;
1055   bool Inserted;
1056   unsigned CurrentGroupNum = 0;
1057   unsigned OuterGroupNum;
1058   DenseMap<IRSimilarityCandidate *, unsigned>::iterator CandToGroupIt;
1059   DenseMap<IRSimilarityCandidate *, unsigned>::iterator CandToGroupItInner;
1060   DenseMap<unsigned, SimilarityGroup>::iterator CurrentGroupPair;
1061 
1062   // Iterate over the candidates to determine its structural and overlapping
1063   // compatibility with other instructions
1064   DenseMap<unsigned, DenseSet<unsigned>> ValueNumberMappingA;
1065   DenseMap<unsigned, DenseSet<unsigned>> ValueNumberMappingB;
1066   for (CandIt = CandsForRepSubstring.begin(),
1067       CandEndIt = CandsForRepSubstring.end();
1068        CandIt != CandEndIt; CandIt++) {
1069 
1070     // Determine if it has an assigned structural group already.
1071     CandToGroupIt = CandToGroup.find(&*CandIt);
1072     if (CandToGroupIt == CandToGroup.end()) {
1073       // If not, we assign it one, and add it to our mapping.
1074       std::tie(CandToGroupIt, Inserted) =
1075           CandToGroup.insert(std::make_pair(&*CandIt, CurrentGroupNum++));
1076     }
1077 
1078     // Get the structural group number from the iterator.
1079     OuterGroupNum = CandToGroupIt->second;
1080 
1081     // Check if we already have a list of IRSimilarityCandidates for the current
1082     // structural group.  Create one if one does not exist.
1083     CurrentGroupPair = StructuralGroups.find(OuterGroupNum);
1084     if (CurrentGroupPair == StructuralGroups.end()) {
1085       IRSimilarityCandidate::createCanonicalMappingFor(*CandIt);
1086       std::tie(CurrentGroupPair, Inserted) = StructuralGroups.insert(
1087           std::make_pair(OuterGroupNum, SimilarityGroup({*CandIt})));
1088     }
1089 
1090     // Iterate over the IRSimilarityCandidates following the current
1091     // IRSimilarityCandidate in the list to determine whether the two
1092     // IRSimilarityCandidates are compatible.  This is so we do not repeat pairs
1093     // of IRSimilarityCandidates.
1094     for (InnerCandIt = std::next(CandIt),
1095         InnerCandEndIt = CandsForRepSubstring.end();
1096          InnerCandIt != InnerCandEndIt; InnerCandIt++) {
1097 
1098       // We check if the inner item has a group already, if it does, we skip it.
1099       CandToGroupItInner = CandToGroup.find(&*InnerCandIt);
1100       if (CandToGroupItInner != CandToGroup.end())
1101         continue;
1102 
1103       // Otherwise we determine if they have the same structure and add it to
1104       // vector if they match.
1105       ValueNumberMappingA.clear();
1106       ValueNumberMappingB.clear();
1107       SameStructure = IRSimilarityCandidate::compareStructure(
1108           *CandIt, *InnerCandIt, ValueNumberMappingA, ValueNumberMappingB);
1109       if (!SameStructure)
1110         continue;
1111 
1112       InnerCandIt->createCanonicalRelationFrom(*CandIt, ValueNumberMappingA,
1113                                                ValueNumberMappingB);
1114       CandToGroup.insert(std::make_pair(&*InnerCandIt, OuterGroupNum));
1115       CurrentGroupPair->second.push_back(*InnerCandIt);
1116     }
1117   }
1118 }
1119 
1120 void IRSimilarityIdentifier::findCandidates(
1121     std::vector<IRInstructionData *> &InstrList,
1122     std::vector<unsigned> &IntegerMapping) {
1123   SuffixTree ST(IntegerMapping);
1124 
1125   std::vector<IRSimilarityCandidate> CandsForRepSubstring;
1126   std::vector<SimilarityGroup> NewCandidateGroups;
1127 
1128   DenseMap<unsigned, SimilarityGroup> StructuralGroups;
1129 
1130   // Iterate over the subsequences found by the Suffix Tree to create
1131   // IRSimilarityCandidates for each repeated subsequence and determine which
1132   // instances are structurally similar to one another.
1133   for (SuffixTree::RepeatedSubstring &RS : ST) {
1134     createCandidatesFromSuffixTree(Mapper, InstrList, IntegerMapping, RS,
1135                                    CandsForRepSubstring);
1136 
1137     if (CandsForRepSubstring.size() < 2)
1138       continue;
1139 
1140     findCandidateStructures(CandsForRepSubstring, StructuralGroups);
1141     for (std::pair<unsigned, SimilarityGroup> &Group : StructuralGroups)
1142       // We only add the group if it contains more than one
1143       // IRSimilarityCandidate.  If there is only one, that means there is no
1144       // other repeated subsequence with the same structure.
1145       if (Group.second.size() > 1)
1146         SimilarityCandidates->push_back(Group.second);
1147 
1148     CandsForRepSubstring.clear();
1149     StructuralGroups.clear();
1150     NewCandidateGroups.clear();
1151   }
1152 }
1153 
1154 SimilarityGroupList &IRSimilarityIdentifier::findSimilarity(
1155     ArrayRef<std::unique_ptr<Module>> Modules) {
1156   resetSimilarityCandidates();
1157 
1158   std::vector<IRInstructionData *> InstrList;
1159   std::vector<unsigned> IntegerMapping;
1160   Mapper.InstClassifier.EnableBranches = this->EnableBranches;
1161   Mapper.InstClassifier.EnableIndirectCalls = EnableIndirectCalls;
1162   Mapper.EnableMatchCallsByName = EnableMatchingCallsByName;
1163   Mapper.InstClassifier.EnableIntrinsics = EnableIntrinsics;
1164   Mapper.InstClassifier.EnableMustTailCalls = EnableMustTailCalls;
1165 
1166   populateMapper(Modules, InstrList, IntegerMapping);
1167   findCandidates(InstrList, IntegerMapping);
1168 
1169   return SimilarityCandidates.getValue();
1170 }
1171 
1172 SimilarityGroupList &IRSimilarityIdentifier::findSimilarity(Module &M) {
1173   resetSimilarityCandidates();
1174   Mapper.InstClassifier.EnableBranches = this->EnableBranches;
1175   Mapper.InstClassifier.EnableIndirectCalls = EnableIndirectCalls;
1176   Mapper.EnableMatchCallsByName = EnableMatchingCallsByName;
1177   Mapper.InstClassifier.EnableIntrinsics = EnableIntrinsics;
1178   Mapper.InstClassifier.EnableMustTailCalls = EnableMustTailCalls;
1179 
1180   std::vector<IRInstructionData *> InstrList;
1181   std::vector<unsigned> IntegerMapping;
1182 
1183   populateMapper(M, InstrList, IntegerMapping);
1184   findCandidates(InstrList, IntegerMapping);
1185 
1186   return SimilarityCandidates.getValue();
1187 }
1188 
1189 INITIALIZE_PASS(IRSimilarityIdentifierWrapperPass, "ir-similarity-identifier",
1190                 "ir-similarity-identifier", false, true)
1191 
1192 IRSimilarityIdentifierWrapperPass::IRSimilarityIdentifierWrapperPass()
1193     : ModulePass(ID) {
1194   initializeIRSimilarityIdentifierWrapperPassPass(
1195       *PassRegistry::getPassRegistry());
1196 }
1197 
1198 bool IRSimilarityIdentifierWrapperPass::doInitialization(Module &M) {
1199   IRSI.reset(new IRSimilarityIdentifier(!DisableBranches, !DisableIndirectCalls,
1200                                         MatchCallsByName, !DisableIntrinsics,
1201                                         false));
1202   return false;
1203 }
1204 
1205 bool IRSimilarityIdentifierWrapperPass::doFinalization(Module &M) {
1206   IRSI.reset();
1207   return false;
1208 }
1209 
1210 bool IRSimilarityIdentifierWrapperPass::runOnModule(Module &M) {
1211   IRSI->findSimilarity(M);
1212   return false;
1213 }
1214 
1215 AnalysisKey IRSimilarityAnalysis::Key;
1216 IRSimilarityIdentifier IRSimilarityAnalysis::run(Module &M,
1217                                                  ModuleAnalysisManager &) {
1218   auto IRSI = IRSimilarityIdentifier(!DisableBranches, !DisableIndirectCalls,
1219                                      MatchCallsByName, !DisableIntrinsics,
1220                                      false);
1221   IRSI.findSimilarity(M);
1222   return IRSI;
1223 }
1224 
1225 PreservedAnalyses
1226 IRSimilarityAnalysisPrinterPass::run(Module &M, ModuleAnalysisManager &AM) {
1227   IRSimilarityIdentifier &IRSI = AM.getResult<IRSimilarityAnalysis>(M);
1228   Optional<SimilarityGroupList> &SimilarityCandidatesOpt = IRSI.getSimilarity();
1229 
1230   for (std::vector<IRSimilarityCandidate> &CandVec : *SimilarityCandidatesOpt) {
1231     OS << CandVec.size() << " candidates of length "
1232        << CandVec.begin()->getLength() << ".  Found in: \n";
1233     for (IRSimilarityCandidate &Cand : CandVec) {
1234       OS << "  Function: " << Cand.front()->Inst->getFunction()->getName().str()
1235          << ", Basic Block: ";
1236       if (Cand.front()->Inst->getParent()->getName().str() == "")
1237         OS << "(unnamed)";
1238       else
1239         OS << Cand.front()->Inst->getParent()->getName().str();
1240       OS << "\n    Start Instruction: ";
1241       Cand.frontInstruction()->print(OS);
1242       OS << "\n      End Instruction: ";
1243       Cand.backInstruction()->print(OS);
1244       OS << "\n";
1245     }
1246   }
1247 
1248   return PreservedAnalyses::all();
1249 }
1250 
1251 char IRSimilarityIdentifierWrapperPass::ID = 0;
1252