+/// Given the index of a tied register operand, find the operand it is tied to.
+/// Defs are tied to uses and vice versa. Returns the index of the tied operand
+/// which must exist.
+unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
+ // It doesn't usually happen, but an instruction can have multiple pairs of
+ // tied operands.
+ SmallVector<unsigned, 4> Uses, Defs;
+ unsigned PairNo = ~0u;
+ for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
+ const MachineOperand &MO = getOperand(i);
+ if (!MO.isReg() || !MO.isTied())
+ continue;
+ if (MO.isUse()) {
+ if (i == OpIdx)
+ PairNo = Uses.size();
+ Uses.push_back(i);
+ } else {
+ if (i == OpIdx)
+ PairNo = Defs.size();
+ Defs.push_back(i);
+ }
+ }
+ // For each tied use there must be a tied def and vice versa.
+ assert(Uses.size() == Defs.size() && "Tied uses and defs don't match");
+ assert(PairNo < Uses.size() && "OpIdx must be a tied register operand");
+
+ // Find the matching operand.
+ return (getOperand(OpIdx).isDef() ? Uses : Defs)[PairNo];
+}
+