1 //===- HexagonInstrInfo.cpp - Hexagon Instruction Information -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the Hexagon implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "HexagonInstrInfo.h"
14 #include "Hexagon.h"
15 #include "HexagonFrameLowering.h"
16 #include "HexagonHazardRecognizer.h"
17 #include "HexagonRegisterInfo.h"
18 #include "HexagonSubtarget.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/CodeGen/DFAPacketizer.h"
24 #include "llvm/CodeGen/LivePhysRegs.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineInstrBundle.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/ScheduleDAG.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetOpcodes.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCInstrDesc.h"
44 #include "llvm/MC/MCInstrItineraries.h"
45 #include "llvm/MC/MCRegisterInfo.h"
46 #include "llvm/Support/BranchProbability.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MachineValueType.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include <cassert>
55 #include <cctype>
56 #include <cstdint>
57 #include <cstring>
58 #include <iterator>
59 #include <string>
60 #include <utility>
61 
62 using namespace llvm;
63 
64 #define DEBUG_TYPE "hexagon-instrinfo"
65 
66 #define GET_INSTRINFO_CTOR_DTOR
67 #define GET_INSTRMAP_INFO
68 #include "HexagonDepTimingClasses.h"
69 #include "HexagonGenDFAPacketizer.inc"
70 #include "HexagonGenInstrInfo.inc"
71 
72 cl::opt<bool> ScheduleInlineAsm("hexagon-sched-inline-asm", cl::Hidden,
73   cl::init(false), cl::desc("Do not consider inline-asm a scheduling/"
74                             "packetization boundary."));
75 
76 static cl::opt<bool> EnableBranchPrediction("hexagon-enable-branch-prediction",
77   cl::Hidden, cl::init(true), cl::desc("Enable branch prediction"));
78 
79 static cl::opt<bool> DisableNVSchedule("disable-hexagon-nv-schedule",
80   cl::Hidden, cl::ZeroOrMore, cl::init(false),
81   cl::desc("Disable schedule adjustment for new value stores."));
82 
83 static cl::opt<bool> EnableTimingClassLatency(
84   "enable-timing-class-latency", cl::Hidden, cl::init(false),
85   cl::desc("Enable timing class latency"));
86 
87 static cl::opt<bool> EnableALUForwarding(
88   "enable-alu-forwarding", cl::Hidden, cl::init(true),
89   cl::desc("Enable vec alu forwarding"));
90 
91 static cl::opt<bool> EnableACCForwarding(
92   "enable-acc-forwarding", cl::Hidden, cl::init(true),
93   cl::desc("Enable vec acc forwarding"));
94 
95 static cl::opt<bool> BranchRelaxAsmLarge("branch-relax-asm-large",
96   cl::init(true), cl::Hidden, cl::ZeroOrMore, cl::desc("branch relax asm"));
97 
98 static cl::opt<bool> UseDFAHazardRec("dfa-hazard-rec",
99   cl::init(true), cl::Hidden, cl::ZeroOrMore,
100   cl::desc("Use the DFA based hazard recognizer."));
101 
102 /// Constants for Hexagon instructions.
103 const int Hexagon_MEMW_OFFSET_MAX = 4095;
104 const int Hexagon_MEMW_OFFSET_MIN = -4096;
105 const int Hexagon_MEMD_OFFSET_MAX = 8191;
106 const int Hexagon_MEMD_OFFSET_MIN = -8192;
107 const int Hexagon_MEMH_OFFSET_MAX = 2047;
108 const int Hexagon_MEMH_OFFSET_MIN = -2048;
109 const int Hexagon_MEMB_OFFSET_MAX = 1023;
110 const int Hexagon_MEMB_OFFSET_MIN = -1024;
111 const int Hexagon_ADDI_OFFSET_MAX = 32767;
112 const int Hexagon_ADDI_OFFSET_MIN = -32768;
113 
114 // Pin the vtable to this file.
115 void HexagonInstrInfo::anchor() {}
116 
117 HexagonInstrInfo::HexagonInstrInfo(HexagonSubtarget &ST)
118   : HexagonGenInstrInfo(Hexagon::ADJCALLSTACKDOWN, Hexagon::ADJCALLSTACKUP),
119     Subtarget(ST) {}
120 
121 namespace llvm {
122 namespace HexagonFUnits {
123   bool isSlot0Only(unsigned units);
124 }
125 }
126 
127 static bool isIntRegForSubInst(unsigned Reg) {
128   return (Reg >= Hexagon::R0 && Reg <= Hexagon::R7) ||
129          (Reg >= Hexagon::R16 && Reg <= Hexagon::R23);
130 }
131 
132 static bool isDblRegForSubInst(unsigned Reg, const HexagonRegisterInfo &HRI) {
133   return isIntRegForSubInst(HRI.getSubReg(Reg, Hexagon::isub_lo)) &&
134          isIntRegForSubInst(HRI.getSubReg(Reg, Hexagon::isub_hi));
135 }
136 
137 /// Calculate number of instructions excluding the debug instructions.
138 static unsigned nonDbgMICount(MachineBasicBlock::const_instr_iterator MIB,
139                               MachineBasicBlock::const_instr_iterator MIE) {
140   unsigned Count = 0;
141   for (; MIB != MIE; ++MIB) {
142     if (!MIB->isDebugInstr())
143       ++Count;
144   }
145   return Count;
146 }
147 
148 /// Find the hardware loop instruction used to set-up the specified loop.
149 /// On Hexagon, we have two instructions used to set-up the hardware loop
150 /// (LOOP0, LOOP1) with corresponding endloop (ENDLOOP0, ENDLOOP1) instructions
151 /// to indicate the end of a loop.
152 MachineInstr *HexagonInstrInfo::findLoopInstr(MachineBasicBlock *BB,
153       unsigned EndLoopOp, MachineBasicBlock *TargetBB,
154       SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
155   unsigned LOOPi;
156   unsigned LOOPr;
157   if (EndLoopOp == Hexagon::ENDLOOP0) {
158     LOOPi = Hexagon::J2_loop0i;
159     LOOPr = Hexagon::J2_loop0r;
160   } else { // EndLoopOp == Hexagon::EndLOOP1
161     LOOPi = Hexagon::J2_loop1i;
162     LOOPr = Hexagon::J2_loop1r;
163   }
164 
165   // The loop set-up instruction will be in a predecessor block
166   for (MachineBasicBlock *PB : BB->predecessors()) {
167     // If this has been visited, already skip it.
168     if (!Visited.insert(PB).second)
169       continue;
170     if (PB == BB)
171       continue;
172     for (auto I = PB->instr_rbegin(), E = PB->instr_rend(); I != E; ++I) {
173       unsigned Opc = I->getOpcode();
174       if (Opc == LOOPi || Opc == LOOPr)
175         return &*I;
176       // We've reached a different loop, which means the loop01 has been
177       // removed.
178       if (Opc == EndLoopOp && I->getOperand(0).getMBB() != TargetBB)
179         return nullptr;
180     }
181     // Check the predecessors for the LOOP instruction.
182     if (MachineInstr *Loop = findLoopInstr(PB, EndLoopOp, TargetBB, Visited))
183       return Loop;
184   }
185   return nullptr;
186 }
187 
188 /// Gather register def/uses from MI.
189 /// This treats possible (predicated) defs as actually happening ones
190 /// (conservatively).
191 static inline void parseOperands(const MachineInstr &MI,
192       SmallVector<unsigned, 4> &Defs, SmallVector<unsigned, 8> &Uses) {
193   Defs.clear();
194   Uses.clear();
195 
196   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
197     const MachineOperand &MO = MI.getOperand(i);
198 
199     if (!MO.isReg())
200       continue;
201 
202     Register Reg = MO.getReg();
203     if (!Reg)
204       continue;
205 
206     if (MO.isUse())
207       Uses.push_back(MO.getReg());
208 
209     if (MO.isDef())
210       Defs.push_back(MO.getReg());
211   }
212 }
213 
214 // Position dependent, so check twice for swap.
215 static bool isDuplexPairMatch(unsigned Ga, unsigned Gb) {
216   switch (Ga) {
217   case HexagonII::HSIG_None:
218   default:
219     return false;
220   case HexagonII::HSIG_L1:
221     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_A);
222   case HexagonII::HSIG_L2:
223     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_L2 ||
224             Gb == HexagonII::HSIG_A);
225   case HexagonII::HSIG_S1:
226     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_L2 ||
227             Gb == HexagonII::HSIG_S1 || Gb == HexagonII::HSIG_A);
228   case HexagonII::HSIG_S2:
229     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_L2 ||
230             Gb == HexagonII::HSIG_S1 || Gb == HexagonII::HSIG_S2 ||
231             Gb == HexagonII::HSIG_A);
232   case HexagonII::HSIG_A:
233     return (Gb == HexagonII::HSIG_A);
234   case HexagonII::HSIG_Compound:
235     return (Gb == HexagonII::HSIG_Compound);
236   }
237   return false;
238 }
239 
240 /// isLoadFromStackSlot - If the specified machine instruction is a direct
241 /// load from a stack slot, return the virtual or physical register number of
242 /// the destination along with the FrameIndex of the loaded stack slot.  If
243 /// not, return 0.  This predicate must return 0 if the instruction has
244 /// any side effects other than loading from the stack slot.
245 unsigned HexagonInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
246                                                int &FrameIndex) const {
247   switch (MI.getOpcode()) {
248     default:
249       break;
250     case Hexagon::L2_loadri_io:
251     case Hexagon::L2_loadrd_io:
252     case Hexagon::V6_vL32b_ai:
253     case Hexagon::V6_vL32b_nt_ai:
254     case Hexagon::V6_vL32Ub_ai:
255     case Hexagon::LDriw_pred:
256     case Hexagon::LDriw_ctr:
257     case Hexagon::PS_vloadrq_ai:
258     case Hexagon::PS_vloadrw_ai:
259     case Hexagon::PS_vloadrw_nt_ai: {
260       const MachineOperand OpFI = MI.getOperand(1);
261       if (!OpFI.isFI())
262         return 0;
263       const MachineOperand OpOff = MI.getOperand(2);
264       if (!OpOff.isImm() || OpOff.getImm() != 0)
265         return 0;
266       FrameIndex = OpFI.getIndex();
267       return MI.getOperand(0).getReg();
268     }
269 
270     case Hexagon::L2_ploadrit_io:
271     case Hexagon::L2_ploadrif_io:
272     case Hexagon::L2_ploadrdt_io:
273     case Hexagon::L2_ploadrdf_io: {
274       const MachineOperand OpFI = MI.getOperand(2);
275       if (!OpFI.isFI())
276         return 0;
277       const MachineOperand OpOff = MI.getOperand(3);
278       if (!OpOff.isImm() || OpOff.getImm() != 0)
279         return 0;
280       FrameIndex = OpFI.getIndex();
281       return MI.getOperand(0).getReg();
282     }
283   }
284 
285   return 0;
286 }
287 
288 /// isStoreToStackSlot - If the specified machine instruction is a direct
289 /// store to a stack slot, return the virtual or physical register number of
290 /// the source reg along with the FrameIndex of the loaded stack slot.  If
291 /// not, return 0.  This predicate must return 0 if the instruction has
292 /// any side effects other than storing to the stack slot.
293 unsigned HexagonInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
294                                               int &FrameIndex) const {
295   switch (MI.getOpcode()) {
296     default:
297       break;
298     case Hexagon::S2_storerb_io:
299     case Hexagon::S2_storerh_io:
300     case Hexagon::S2_storeri_io:
301     case Hexagon::S2_storerd_io:
302     case Hexagon::V6_vS32b_ai:
303     case Hexagon::V6_vS32Ub_ai:
304     case Hexagon::STriw_pred:
305     case Hexagon::STriw_ctr:
306     case Hexagon::PS_vstorerq_ai:
307     case Hexagon::PS_vstorerw_ai: {
308       const MachineOperand &OpFI = MI.getOperand(0);
309       if (!OpFI.isFI())
310         return 0;
311       const MachineOperand &OpOff = MI.getOperand(1);
312       if (!OpOff.isImm() || OpOff.getImm() != 0)
313         return 0;
314       FrameIndex = OpFI.getIndex();
315       return MI.getOperand(2).getReg();
316     }
317 
318     case Hexagon::S2_pstorerbt_io:
319     case Hexagon::S2_pstorerbf_io:
320     case Hexagon::S2_pstorerht_io:
321     case Hexagon::S2_pstorerhf_io:
322     case Hexagon::S2_pstorerit_io:
323     case Hexagon::S2_pstorerif_io:
324     case Hexagon::S2_pstorerdt_io:
325     case Hexagon::S2_pstorerdf_io: {
326       const MachineOperand &OpFI = MI.getOperand(1);
327       if (!OpFI.isFI())
328         return 0;
329       const MachineOperand &OpOff = MI.getOperand(2);
330       if (!OpOff.isImm() || OpOff.getImm() != 0)
331         return 0;
332       FrameIndex = OpFI.getIndex();
333       return MI.getOperand(3).getReg();
334     }
335   }
336 
337   return 0;
338 }
339 
340 /// This function checks if the instruction or bundle of instructions
341 /// has load from stack slot and returns frameindex and machine memory
342 /// operand of that instruction if true.
343 bool HexagonInstrInfo::hasLoadFromStackSlot(
344     const MachineInstr &MI,
345     SmallVectorImpl<const MachineMemOperand *> &Accesses) const {
346   if (MI.isBundle()) {
347     const MachineBasicBlock *MBB = MI.getParent();
348     MachineBasicBlock::const_instr_iterator MII = MI.getIterator();
349     for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII)
350       if (TargetInstrInfo::hasLoadFromStackSlot(*MII, Accesses))
351         return true;
352     return false;
353   }
354 
355   return TargetInstrInfo::hasLoadFromStackSlot(MI, Accesses);
356 }
357 
358 /// This function checks if the instruction or bundle of instructions
359 /// has store to stack slot and returns frameindex and machine memory
360 /// operand of that instruction if true.
361 bool HexagonInstrInfo::hasStoreToStackSlot(
362     const MachineInstr &MI,
363     SmallVectorImpl<const MachineMemOperand *> &Accesses) const {
364   if (MI.isBundle()) {
365     const MachineBasicBlock *MBB = MI.getParent();
366     MachineBasicBlock::const_instr_iterator MII = MI.getIterator();
367     for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII)
368       if (TargetInstrInfo::hasStoreToStackSlot(*MII, Accesses))
369         return true;
370     return false;
371   }
372 
373   return TargetInstrInfo::hasStoreToStackSlot(MI, Accesses);
374 }
375 
376 /// This function can analyze one/two way branching only and should (mostly) be
377 /// called by target independent side.
378 /// First entry is always the opcode of the branching instruction, except when
379 /// the Cond vector is supposed to be empty, e.g., when analyzeBranch fails, a
380 /// BB with only unconditional jump. Subsequent entries depend upon the opcode,
381 /// e.g. Jump_c p will have
382 /// Cond[0] = Jump_c
383 /// Cond[1] = p
384 /// HW-loop ENDLOOP:
385 /// Cond[0] = ENDLOOP
386 /// Cond[1] = MBB
387 /// New value jump:
388 /// Cond[0] = Hexagon::CMPEQri_f_Jumpnv_t_V4 -- specific opcode
389 /// Cond[1] = R
390 /// Cond[2] = Imm
391 bool HexagonInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
392                                      MachineBasicBlock *&TBB,
393                                      MachineBasicBlock *&FBB,
394                                      SmallVectorImpl<MachineOperand> &Cond,
395                                      bool AllowModify) const {
396   TBB = nullptr;
397   FBB = nullptr;
398   Cond.clear();
399 
400   // If the block has no terminators, it just falls into the block after it.
401   MachineBasicBlock::instr_iterator I = MBB.instr_end();
402   if (I == MBB.instr_begin())
403     return false;
404 
405   // A basic block may looks like this:
406   //
407   //  [   insn
408   //     EH_LABEL
409   //      insn
410   //      insn
411   //      insn
412   //     EH_LABEL
413   //      insn     ]
414   //
415   // It has two succs but does not have a terminator
416   // Don't know how to handle it.
417   do {
418     --I;
419     if (I->isEHLabel())
420       // Don't analyze EH branches.
421       return true;
422   } while (I != MBB.instr_begin());
423 
424   I = MBB.instr_end();
425   --I;
426 
427   while (I->isDebugInstr()) {
428     if (I == MBB.instr_begin())
429       return false;
430     --I;
431   }
432 
433   bool JumpToBlock = I->getOpcode() == Hexagon::J2_jump &&
434                      I->getOperand(0).isMBB();
435   // Delete the J2_jump if it's equivalent to a fall-through.
436   if (AllowModify && JumpToBlock &&
437       MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
438     LLVM_DEBUG(dbgs() << "\nErasing the jump to successor block\n";);
439     I->eraseFromParent();
440     I = MBB.instr_end();
441     if (I == MBB.instr_begin())
442       return false;
443     --I;
444   }
445   if (!isUnpredicatedTerminator(*I))
446     return false;
447 
448   // Get the last instruction in the block.
449   MachineInstr *LastInst = &*I;
450   MachineInstr *SecondLastInst = nullptr;
451   // Find one more terminator if present.
452   while (true) {
453     if (&*I != LastInst && !I->isBundle() && isUnpredicatedTerminator(*I)) {
454       if (!SecondLastInst)
455         SecondLastInst = &*I;
456       else
457         // This is a third branch.
458         return true;
459     }
460     if (I == MBB.instr_begin())
461       break;
462     --I;
463   }
464 
465   int LastOpcode = LastInst->getOpcode();
466   int SecLastOpcode = SecondLastInst ? SecondLastInst->getOpcode() : 0;
467   // If the branch target is not a basic block, it could be a tail call.
468   // (It is, if the target is a function.)
469   if (LastOpcode == Hexagon::J2_jump && !LastInst->getOperand(0).isMBB())
470     return true;
471   if (SecLastOpcode == Hexagon::J2_jump &&
472       !SecondLastInst->getOperand(0).isMBB())
473     return true;
474 
475   bool LastOpcodeHasJMP_c = PredOpcodeHasJMP_c(LastOpcode);
476   bool LastOpcodeHasNVJump = isNewValueJump(*LastInst);
477 
478   if (LastOpcodeHasJMP_c && !LastInst->getOperand(1).isMBB())
479     return true;
480 
481   // If there is only one terminator instruction, process it.
482   if (LastInst && !SecondLastInst) {
483     if (LastOpcode == Hexagon::J2_jump) {
484       TBB = LastInst->getOperand(0).getMBB();
485       return false;
486     }
487     if (isEndLoopN(LastOpcode)) {
488       TBB = LastInst->getOperand(0).getMBB();
489       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
490       Cond.push_back(LastInst->getOperand(0));
491       return false;
492     }
493     if (LastOpcodeHasJMP_c) {
494       TBB = LastInst->getOperand(1).getMBB();
495       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
496       Cond.push_back(LastInst->getOperand(0));
497       return false;
498     }
499     // Only supporting rr/ri versions of new-value jumps.
500     if (LastOpcodeHasNVJump && (LastInst->getNumExplicitOperands() == 3)) {
501       TBB = LastInst->getOperand(2).getMBB();
502       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
503       Cond.push_back(LastInst->getOperand(0));
504       Cond.push_back(LastInst->getOperand(1));
505       return false;
506     }
507     LLVM_DEBUG(dbgs() << "\nCant analyze " << printMBBReference(MBB)
508                       << " with one jump\n";);
509     // Otherwise, don't know what this is.
510     return true;
511   }
512 
513   bool SecLastOpcodeHasJMP_c = PredOpcodeHasJMP_c(SecLastOpcode);
514   bool SecLastOpcodeHasNVJump = isNewValueJump(*SecondLastInst);
515   if (SecLastOpcodeHasJMP_c && (LastOpcode == Hexagon::J2_jump)) {
516     if (!SecondLastInst->getOperand(1).isMBB())
517       return true;
518     TBB =  SecondLastInst->getOperand(1).getMBB();
519     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
520     Cond.push_back(SecondLastInst->getOperand(0));
521     FBB = LastInst->getOperand(0).getMBB();
522     return false;
523   }
524 
525   // Only supporting rr/ri versions of new-value jumps.
526   if (SecLastOpcodeHasNVJump &&
527       (SecondLastInst->getNumExplicitOperands() == 3) &&
528       (LastOpcode == Hexagon::J2_jump)) {
529     TBB = SecondLastInst->getOperand(2).getMBB();
530     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
531     Cond.push_back(SecondLastInst->getOperand(0));
532     Cond.push_back(SecondLastInst->getOperand(1));
533     FBB = LastInst->getOperand(0).getMBB();
534     return false;
535   }
536 
537   // If the block ends with two Hexagon:JMPs, handle it.  The second one is not
538   // executed, so remove it.
539   if (SecLastOpcode == Hexagon::J2_jump && LastOpcode == Hexagon::J2_jump) {
540     TBB = SecondLastInst->getOperand(0).getMBB();
541     I = LastInst->getIterator();
542     if (AllowModify)
543       I->eraseFromParent();
544     return false;
545   }
546 
547   // If the block ends with an ENDLOOP, and J2_jump, handle it.
548   if (isEndLoopN(SecLastOpcode) && LastOpcode == Hexagon::J2_jump) {
549     TBB = SecondLastInst->getOperand(0).getMBB();
550     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
551     Cond.push_back(SecondLastInst->getOperand(0));
552     FBB = LastInst->getOperand(0).getMBB();
553     return false;
554   }
555   LLVM_DEBUG(dbgs() << "\nCant analyze " << printMBBReference(MBB)
556                     << " with two jumps";);
557   // Otherwise, can't handle this.
558   return true;
559 }
560 
561 unsigned HexagonInstrInfo::removeBranch(MachineBasicBlock &MBB,
562                                         int *BytesRemoved) const {
563   assert(!BytesRemoved && "code size not handled");
564 
565   LLVM_DEBUG(dbgs() << "\nRemoving branches out of " << printMBBReference(MBB));
566   MachineBasicBlock::iterator I = MBB.end();
567   unsigned Count = 0;
568   while (I != MBB.begin()) {
569     --I;
570     if (I->isDebugInstr())
571       continue;
572     // Only removing branches from end of MBB.
573     if (!I->isBranch())
574       return Count;
575     if (Count && (I->getOpcode() == Hexagon::J2_jump))
576       llvm_unreachable("Malformed basic block: unconditional branch not last");
577     MBB.erase(&MBB.back());
578     I = MBB.end();
579     ++Count;
580   }
581   return Count;
582 }
583 
584 unsigned HexagonInstrInfo::insertBranch(MachineBasicBlock &MBB,
585                                         MachineBasicBlock *TBB,
586                                         MachineBasicBlock *FBB,
587                                         ArrayRef<MachineOperand> Cond,
588                                         const DebugLoc &DL,
589                                         int *BytesAdded) const {
590   unsigned BOpc   = Hexagon::J2_jump;
591   unsigned BccOpc = Hexagon::J2_jumpt;
592   assert(validateBranchCond(Cond) && "Invalid branching condition");
593   assert(TBB && "insertBranch must not be told to insert a fallthrough");
594   assert(!BytesAdded && "code size not handled");
595 
596   // Check if reverseBranchCondition has asked to reverse this branch
597   // If we want to reverse the branch an odd number of times, we want
598   // J2_jumpf.
599   if (!Cond.empty() && Cond[0].isImm())
600     BccOpc = Cond[0].getImm();
601 
602   if (!FBB) {
603     if (Cond.empty()) {
604       // Due to a bug in TailMerging/CFG Optimization, we need to add a
605       // special case handling of a predicated jump followed by an
606       // unconditional jump. If not, Tail Merging and CFG Optimization go
607       // into an infinite loop.
608       MachineBasicBlock *NewTBB, *NewFBB;
609       SmallVector<MachineOperand, 4> Cond;
610       auto Term = MBB.getFirstTerminator();
611       if (Term != MBB.end() && isPredicated(*Term) &&
612           !analyzeBranch(MBB, NewTBB, NewFBB, Cond, false) &&
613           MachineFunction::iterator(NewTBB) == ++MBB.getIterator()) {
614         reverseBranchCondition(Cond);
615         removeBranch(MBB);
616         return insertBranch(MBB, TBB, nullptr, Cond, DL);
617       }
618       BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
619     } else if (isEndLoopN(Cond[0].getImm())) {
620       int EndLoopOp = Cond[0].getImm();
621       assert(Cond[1].isMBB());
622       // Since we're adding an ENDLOOP, there better be a LOOP instruction.
623       // Check for it, and change the BB target if needed.
624       SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
625       MachineInstr *Loop = findLoopInstr(TBB, EndLoopOp, Cond[1].getMBB(),
626                                          VisitedBBs);
627       assert(Loop != nullptr && "Inserting an ENDLOOP without a LOOP");
628       Loop->getOperand(0).setMBB(TBB);
629       // Add the ENDLOOP after the finding the LOOP0.
630       BuildMI(&MBB, DL, get(EndLoopOp)).addMBB(TBB);
631     } else if (isNewValueJump(Cond[0].getImm())) {
632       assert((Cond.size() == 3) && "Only supporting rr/ri version of nvjump");
633       // New value jump
634       // (ins IntRegs:$src1, IntRegs:$src2, brtarget:$offset)
635       // (ins IntRegs:$src1, u5Imm:$src2, brtarget:$offset)
636       unsigned Flags1 = getUndefRegState(Cond[1].isUndef());
637       LLVM_DEBUG(dbgs() << "\nInserting NVJump for "
638                         << printMBBReference(MBB););
639       if (Cond[2].isReg()) {
640         unsigned Flags2 = getUndefRegState(Cond[2].isUndef());
641         BuildMI(&MBB, DL, get(BccOpc)).addReg(Cond[1].getReg(), Flags1).
642           addReg(Cond[2].getReg(), Flags2).addMBB(TBB);
643       } else if(Cond[2].isImm()) {
644         BuildMI(&MBB, DL, get(BccOpc)).addReg(Cond[1].getReg(), Flags1).
645           addImm(Cond[2].getImm()).addMBB(TBB);
646       } else
647         llvm_unreachable("Invalid condition for branching");
648     } else {
649       assert((Cond.size() == 2) && "Malformed cond vector");
650       const MachineOperand &RO = Cond[1];
651       unsigned Flags = getUndefRegState(RO.isUndef());
652       BuildMI(&MBB, DL, get(BccOpc)).addReg(RO.getReg(), Flags).addMBB(TBB);
653     }
654     return 1;
655   }
656   assert((!Cond.empty()) &&
657          "Cond. cannot be empty when multiple branchings are required");
658   assert((!isNewValueJump(Cond[0].getImm())) &&
659          "NV-jump cannot be inserted with another branch");
660   // Special case for hardware loops.  The condition is a basic block.
661   if (isEndLoopN(Cond[0].getImm())) {
662     int EndLoopOp = Cond[0].getImm();
663     assert(Cond[1].isMBB());
664     // Since we're adding an ENDLOOP, there better be a LOOP instruction.
665     // Check for it, and change the BB target if needed.
666     SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
667     MachineInstr *Loop = findLoopInstr(TBB, EndLoopOp, Cond[1].getMBB(),
668                                        VisitedBBs);
669     assert(Loop != nullptr && "Inserting an ENDLOOP without a LOOP");
670     Loop->getOperand(0).setMBB(TBB);
671     // Add the ENDLOOP after the finding the LOOP0.
672     BuildMI(&MBB, DL, get(EndLoopOp)).addMBB(TBB);
673   } else {
674     const MachineOperand &RO = Cond[1];
675     unsigned Flags = getUndefRegState(RO.isUndef());
676     BuildMI(&MBB, DL, get(BccOpc)).addReg(RO.getReg(), Flags).addMBB(TBB);
677   }
678   BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
679 
680   return 2;
681 }
682 
683 namespace {
684 class HexagonPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
685   MachineInstr *Loop, *EndLoop;
686   MachineFunction *MF;
687   const HexagonInstrInfo *TII;
688   int64_t TripCount;
689   Register LoopCount;
690   DebugLoc DL;
691 
692 public:
693   HexagonPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop)
694       : Loop(Loop), EndLoop(EndLoop), MF(Loop->getParent()->getParent()),
695         TII(MF->getSubtarget<HexagonSubtarget>().getInstrInfo()),
696         DL(Loop->getDebugLoc()) {
697     // Inspect the Loop instruction up-front, as it may be deleted when we call
698     // createTripCountGreaterCondition.
699     TripCount = Loop->getOpcode() == Hexagon::J2_loop0r
700                     ? -1
701                     : Loop->getOperand(1).getImm();
702     if (TripCount == -1)
703       LoopCount = Loop->getOperand(1).getReg();
704   }
705 
706   bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
707     // Only ignore the terminator.
708     return MI == EndLoop;
709   }
710 
711   Optional<bool>
712   createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
713                                   SmallVectorImpl<MachineOperand> &Cond) override {
714     if (TripCount == -1) {
715       // Check if we're done with the loop.
716       unsigned Done = TII->createVR(MF, MVT::i1);
717       MachineInstr *NewCmp = BuildMI(&MBB, DL,
718                                      TII->get(Hexagon::C2_cmpgtui), Done)
719                                  .addReg(LoopCount)
720                                  .addImm(TC);
721       Cond.push_back(MachineOperand::CreateImm(Hexagon::J2_jumpf));
722       Cond.push_back(NewCmp->getOperand(0));
723       return {};
724     }
725 
726     return TripCount > TC;
727   }
728 
729   void setPreheader(MachineBasicBlock *NewPreheader) override {
730     NewPreheader->splice(NewPreheader->getFirstTerminator(), Loop->getParent(),
731                          Loop);
732   }
733 
734   void adjustTripCount(int TripCountAdjust) override {
735     // If the loop trip count is a compile-time value, then just change the
736     // value.
737     if (Loop->getOpcode() == Hexagon::J2_loop0i ||
738         Loop->getOpcode() == Hexagon::J2_loop1i) {
739       int64_t TripCount = Loop->getOperand(1).getImm() + TripCountAdjust;
740       assert(TripCount > 0 && "Can't create an empty or negative loop!");
741       Loop->getOperand(1).setImm(TripCount);
742       return;
743     }
744 
745     // The loop trip count is a run-time value. We generate code to subtract
746     // one from the trip count, and update the loop instruction.
747     Register LoopCount = Loop->getOperand(1).getReg();
748     Register NewLoopCount = TII->createVR(MF, MVT::i32);
749     BuildMI(*Loop->getParent(), Loop, Loop->getDebugLoc(),
750             TII->get(Hexagon::A2_addi), NewLoopCount)
751         .addReg(LoopCount)
752         .addImm(TripCountAdjust);
753     Loop->getOperand(1).setReg(NewLoopCount);
754   }
755 
756   void disposed() override { Loop->eraseFromParent(); }
757 };
758 } // namespace
759 
760 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
761 HexagonInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
762   // We really "analyze" only hardware loops right now.
763   MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
764 
765   if (I != LoopBB->end() && isEndLoopN(I->getOpcode())) {
766     SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
767     MachineInstr *LoopInst = findLoopInstr(
768         LoopBB, I->getOpcode(), I->getOperand(0).getMBB(), VisitedBBs);
769     if (LoopInst)
770       return std::make_unique<HexagonPipelinerLoopInfo>(LoopInst, &*I);
771   }
772   return nullptr;
773 }
774 
775 bool HexagonInstrInfo::isProfitableToIfCvt(MachineBasicBlock &MBB,
776       unsigned NumCycles, unsigned ExtraPredCycles,
777       BranchProbability Probability) const {
778   return nonDbgBBSize(&MBB) <= 3;
779 }
780 
781 bool HexagonInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
782       unsigned NumTCycles, unsigned ExtraTCycles, MachineBasicBlock &FMBB,
783       unsigned NumFCycles, unsigned ExtraFCycles, BranchProbability Probability)
784       const {
785   return nonDbgBBSize(&TMBB) <= 3 && nonDbgBBSize(&FMBB) <= 3;
786 }
787 
788 bool HexagonInstrInfo::isProfitableToDupForIfCvt(MachineBasicBlock &MBB,
789       unsigned NumInstrs, BranchProbability Probability) const {
790   return NumInstrs <= 4;
791 }
792 
793 static void getLiveInRegsAt(LivePhysRegs &Regs, const MachineInstr &MI) {
794   SmallVector<std::pair<MCPhysReg, const MachineOperand*>,2> Clobbers;
795   const MachineBasicBlock &B = *MI.getParent();
796   Regs.addLiveIns(B);
797   auto E = MachineBasicBlock::const_iterator(MI.getIterator());
798   for (auto I = B.begin(); I != E; ++I) {
799     Clobbers.clear();
800     Regs.stepForward(*I, Clobbers);
801   }
802 }
803 
804 static void getLiveOutRegsAt(LivePhysRegs &Regs, const MachineInstr &MI) {
805   const MachineBasicBlock &B = *MI.getParent();
806   Regs.addLiveOuts(B);
807   auto E = ++MachineBasicBlock::const_iterator(MI.getIterator()).getReverse();
808   for (auto I = B.rbegin(); I != E; ++I)
809     Regs.stepBackward(*I);
810 }
811 
812 void HexagonInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
813                                    MachineBasicBlock::iterator I,
814                                    const DebugLoc &DL, MCRegister DestReg,
815                                    MCRegister SrcReg, bool KillSrc) const {
816   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
817   unsigned KillFlag = getKillRegState(KillSrc);
818 
819   if (Hexagon::IntRegsRegClass.contains(SrcReg, DestReg)) {
820     BuildMI(MBB, I, DL, get(Hexagon::A2_tfr), DestReg)
821       .addReg(SrcReg, KillFlag);
822     return;
823   }
824   if (Hexagon::DoubleRegsRegClass.contains(SrcReg, DestReg)) {
825     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrp), DestReg)
826       .addReg(SrcReg, KillFlag);
827     return;
828   }
829   if (Hexagon::PredRegsRegClass.contains(SrcReg, DestReg)) {
830     // Map Pd = Ps to Pd = or(Ps, Ps).
831     BuildMI(MBB, I, DL, get(Hexagon::C2_or), DestReg)
832       .addReg(SrcReg).addReg(SrcReg, KillFlag);
833     return;
834   }
835   if (Hexagon::CtrRegsRegClass.contains(DestReg) &&
836       Hexagon::IntRegsRegClass.contains(SrcReg)) {
837     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrrcr), DestReg)
838       .addReg(SrcReg, KillFlag);
839     return;
840   }
841   if (Hexagon::IntRegsRegClass.contains(DestReg) &&
842       Hexagon::CtrRegsRegClass.contains(SrcReg)) {
843     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrcrr), DestReg)
844       .addReg(SrcReg, KillFlag);
845     return;
846   }
847   if (Hexagon::ModRegsRegClass.contains(DestReg) &&
848       Hexagon::IntRegsRegClass.contains(SrcReg)) {
849     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrrcr), DestReg)
850       .addReg(SrcReg, KillFlag);
851     return;
852   }
853   if (Hexagon::PredRegsRegClass.contains(SrcReg) &&
854       Hexagon::IntRegsRegClass.contains(DestReg)) {
855     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrpr), DestReg)
856       .addReg(SrcReg, KillFlag);
857     return;
858   }
859   if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
860       Hexagon::PredRegsRegClass.contains(DestReg)) {
861     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrrp), DestReg)
862       .addReg(SrcReg, KillFlag);
863     return;
864   }
865   if (Hexagon::PredRegsRegClass.contains(SrcReg) &&
866       Hexagon::IntRegsRegClass.contains(DestReg)) {
867     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrpr), DestReg)
868       .addReg(SrcReg, KillFlag);
869     return;
870   }
871   if (Hexagon::HvxVRRegClass.contains(SrcReg, DestReg)) {
872     BuildMI(MBB, I, DL, get(Hexagon::V6_vassign), DestReg).
873       addReg(SrcReg, KillFlag);
874     return;
875   }
876   if (Hexagon::HvxWRRegClass.contains(SrcReg, DestReg)) {
877     LivePhysRegs LiveAtMI(HRI);
878     getLiveInRegsAt(LiveAtMI, *I);
879     Register SrcLo = HRI.getSubReg(SrcReg, Hexagon::vsub_lo);
880     Register SrcHi = HRI.getSubReg(SrcReg, Hexagon::vsub_hi);
881     unsigned UndefLo = getUndefRegState(!LiveAtMI.contains(SrcLo));
882     unsigned UndefHi = getUndefRegState(!LiveAtMI.contains(SrcHi));
883     BuildMI(MBB, I, DL, get(Hexagon::V6_vcombine), DestReg)
884       .addReg(SrcHi, KillFlag | UndefHi)
885       .addReg(SrcLo, KillFlag | UndefLo);
886     return;
887   }
888   if (Hexagon::HvxQRRegClass.contains(SrcReg, DestReg)) {
889     BuildMI(MBB, I, DL, get(Hexagon::V6_pred_and), DestReg)
890       .addReg(SrcReg)
891       .addReg(SrcReg, KillFlag);
892     return;
893   }
894   if (Hexagon::HvxQRRegClass.contains(SrcReg) &&
895       Hexagon::HvxVRRegClass.contains(DestReg)) {
896     llvm_unreachable("Unimplemented pred to vec");
897     return;
898   }
899   if (Hexagon::HvxQRRegClass.contains(DestReg) &&
900       Hexagon::HvxVRRegClass.contains(SrcReg)) {
901     llvm_unreachable("Unimplemented vec to pred");
902     return;
903   }
904 
905 #ifndef NDEBUG
906   // Show the invalid registers to ease debugging.
907   dbgs() << "Invalid registers for copy in " << printMBBReference(MBB) << ": "
908          << printReg(DestReg, &HRI) << " = " << printReg(SrcReg, &HRI) << '\n';
909 #endif
910   llvm_unreachable("Unimplemented");
911 }
912 
913 void HexagonInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
914       MachineBasicBlock::iterator I, Register SrcReg, bool isKill, int FI,
915       const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const {
916   DebugLoc DL = MBB.findDebugLoc(I);
917   MachineFunction &MF = *MBB.getParent();
918   MachineFrameInfo &MFI = MF.getFrameInfo();
919   unsigned KillFlag = getKillRegState(isKill);
920 
921   MachineMemOperand *MMO = MF.getMachineMemOperand(
922       MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
923       MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
924 
925   if (Hexagon::IntRegsRegClass.hasSubClassEq(RC)) {
926     BuildMI(MBB, I, DL, get(Hexagon::S2_storeri_io))
927       .addFrameIndex(FI).addImm(0)
928       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
929   } else if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC)) {
930     BuildMI(MBB, I, DL, get(Hexagon::S2_storerd_io))
931       .addFrameIndex(FI).addImm(0)
932       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
933   } else if (Hexagon::PredRegsRegClass.hasSubClassEq(RC)) {
934     BuildMI(MBB, I, DL, get(Hexagon::STriw_pred))
935       .addFrameIndex(FI).addImm(0)
936       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
937   } else if (Hexagon::ModRegsRegClass.hasSubClassEq(RC)) {
938     BuildMI(MBB, I, DL, get(Hexagon::STriw_ctr))
939       .addFrameIndex(FI).addImm(0)
940       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
941   } else if (Hexagon::HvxQRRegClass.hasSubClassEq(RC)) {
942     BuildMI(MBB, I, DL, get(Hexagon::PS_vstorerq_ai))
943       .addFrameIndex(FI).addImm(0)
944       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
945   } else if (Hexagon::HvxVRRegClass.hasSubClassEq(RC)) {
946     BuildMI(MBB, I, DL, get(Hexagon::PS_vstorerv_ai))
947       .addFrameIndex(FI).addImm(0)
948       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
949   } else if (Hexagon::HvxWRRegClass.hasSubClassEq(RC)) {
950     BuildMI(MBB, I, DL, get(Hexagon::PS_vstorerw_ai))
951       .addFrameIndex(FI).addImm(0)
952       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
953   } else {
954     llvm_unreachable("Unimplemented");
955   }
956 }
957 
958 void HexagonInstrInfo::loadRegFromStackSlot(
959     MachineBasicBlock &MBB, MachineBasicBlock::iterator I, Register DestReg,
960     int FI, const TargetRegisterClass *RC,
961     const TargetRegisterInfo *TRI) const {
962   DebugLoc DL = MBB.findDebugLoc(I);
963   MachineFunction &MF = *MBB.getParent();
964   MachineFrameInfo &MFI = MF.getFrameInfo();
965 
966   MachineMemOperand *MMO = MF.getMachineMemOperand(
967       MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
968       MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
969 
970   if (Hexagon::IntRegsRegClass.hasSubClassEq(RC)) {
971     BuildMI(MBB, I, DL, get(Hexagon::L2_loadri_io), DestReg)
972       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
973   } else if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC)) {
974     BuildMI(MBB, I, DL, get(Hexagon::L2_loadrd_io), DestReg)
975       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
976   } else if (Hexagon::PredRegsRegClass.hasSubClassEq(RC)) {
977     BuildMI(MBB, I, DL, get(Hexagon::LDriw_pred), DestReg)
978       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
979   } else if (Hexagon::ModRegsRegClass.hasSubClassEq(RC)) {
980     BuildMI(MBB, I, DL, get(Hexagon::LDriw_ctr), DestReg)
981       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
982   } else if (Hexagon::HvxQRRegClass.hasSubClassEq(RC)) {
983     BuildMI(MBB, I, DL, get(Hexagon::PS_vloadrq_ai), DestReg)
984       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
985   } else if (Hexagon::HvxVRRegClass.hasSubClassEq(RC)) {
986     BuildMI(MBB, I, DL, get(Hexagon::PS_vloadrv_ai), DestReg)
987       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
988   } else if (Hexagon::HvxWRRegClass.hasSubClassEq(RC)) {
989     BuildMI(MBB, I, DL, get(Hexagon::PS_vloadrw_ai), DestReg)
990       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
991   } else {
992     llvm_unreachable("Can't store this register to stack slot");
993   }
994 }
995 
996 /// expandPostRAPseudo - This function is called for all pseudo instructions
997 /// that remain after register allocation. Many pseudo instructions are
998 /// created to help register allocation. This is the place to convert them
999 /// into real instructions. The target can edit MI in place, or it can insert
1000 /// new instructions and erase MI. The function should return true if
1001 /// anything was changed.
1002 bool HexagonInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1003   MachineBasicBlock &MBB = *MI.getParent();
1004   MachineFunction &MF = *MBB.getParent();
1005   MachineRegisterInfo &MRI = MF.getRegInfo();
1006   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
1007   LivePhysRegs LiveIn(HRI), LiveOut(HRI);
1008   DebugLoc DL = MI.getDebugLoc();
1009   unsigned Opc = MI.getOpcode();
1010 
1011   auto RealCirc = [&](unsigned Opc, bool HasImm, unsigned MxOp) {
1012     Register Mx = MI.getOperand(MxOp).getReg();
1013     unsigned CSx = (Mx == Hexagon::M0 ? Hexagon::CS0 : Hexagon::CS1);
1014     BuildMI(MBB, MI, DL, get(Hexagon::A2_tfrrcr), CSx)
1015         .add(MI.getOperand((HasImm ? 5 : 4)));
1016     auto MIB = BuildMI(MBB, MI, DL, get(Opc)).add(MI.getOperand(0))
1017         .add(MI.getOperand(1)).add(MI.getOperand(2)).add(MI.getOperand(3));
1018     if (HasImm)
1019       MIB.add(MI.getOperand(4));
1020     MIB.addReg(CSx, RegState::Implicit);
1021     MBB.erase(MI);
1022     return true;
1023   };
1024 
1025   auto UseAligned = [&] (const MachineInstr &MI, unsigned NeedAlign) {
1026     if (MI.memoperands().empty())
1027       return false;
1028     return all_of(MI.memoperands(), [NeedAlign](const MachineMemOperand *MMO) {
1029       return MMO->getAlign() >= NeedAlign;
1030     });
1031   };
1032 
1033   switch (Opc) {
1034     case TargetOpcode::COPY: {
1035       MachineOperand &MD = MI.getOperand(0);
1036       MachineOperand &MS = MI.getOperand(1);
1037       MachineBasicBlock::iterator MBBI = MI.getIterator();
1038       if (MD.getReg() != MS.getReg() && !MS.isUndef()) {
1039         copyPhysReg(MBB, MI, DL, MD.getReg(), MS.getReg(), MS.isKill());
1040         std::prev(MBBI)->copyImplicitOps(*MBB.getParent(), MI);
1041       }
1042       MBB.erase(MBBI);
1043       return true;
1044     }
1045     case Hexagon::PS_aligna:
1046       BuildMI(MBB, MI, DL, get(Hexagon::A2_andir), MI.getOperand(0).getReg())
1047           .addReg(HRI.getFrameRegister())
1048           .addImm(-MI.getOperand(1).getImm());
1049       MBB.erase(MI);
1050       return true;
1051     case Hexagon::V6_vassignp: {
1052       Register SrcReg = MI.getOperand(1).getReg();
1053       Register DstReg = MI.getOperand(0).getReg();
1054       Register SrcLo = HRI.getSubReg(SrcReg, Hexagon::vsub_lo);
1055       Register SrcHi = HRI.getSubReg(SrcReg, Hexagon::vsub_hi);
1056       getLiveInRegsAt(LiveIn, MI);
1057       unsigned UndefLo = getUndefRegState(!LiveIn.contains(SrcLo));
1058       unsigned UndefHi = getUndefRegState(!LiveIn.contains(SrcHi));
1059       unsigned Kill = getKillRegState(MI.getOperand(1).isKill());
1060       BuildMI(MBB, MI, DL, get(Hexagon::V6_vcombine), DstReg)
1061           .addReg(SrcHi, UndefHi)
1062           .addReg(SrcLo, Kill | UndefLo);
1063       MBB.erase(MI);
1064       return true;
1065     }
1066     case Hexagon::V6_lo: {
1067       Register SrcReg = MI.getOperand(1).getReg();
1068       Register DstReg = MI.getOperand(0).getReg();
1069       Register SrcSubLo = HRI.getSubReg(SrcReg, Hexagon::vsub_lo);
1070       copyPhysReg(MBB, MI, DL, DstReg, SrcSubLo, MI.getOperand(1).isKill());
1071       MBB.erase(MI);
1072       MRI.clearKillFlags(SrcSubLo);
1073       return true;
1074     }
1075     case Hexagon::V6_hi: {
1076       Register SrcReg = MI.getOperand(1).getReg();
1077       Register DstReg = MI.getOperand(0).getReg();
1078       Register SrcSubHi = HRI.getSubReg(SrcReg, Hexagon::vsub_hi);
1079       copyPhysReg(MBB, MI, DL, DstReg, SrcSubHi, MI.getOperand(1).isKill());
1080       MBB.erase(MI);
1081       MRI.clearKillFlags(SrcSubHi);
1082       return true;
1083     }
1084     case Hexagon::PS_vloadrv_ai: {
1085       Register DstReg = MI.getOperand(0).getReg();
1086       const MachineOperand &BaseOp = MI.getOperand(1);
1087       assert(BaseOp.getSubReg() == 0);
1088       int Offset = MI.getOperand(2).getImm();
1089       unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
1090       unsigned NewOpc = UseAligned(MI, NeedAlign) ? Hexagon::V6_vL32b_ai
1091                                                   : Hexagon::V6_vL32Ub_ai;
1092       BuildMI(MBB, MI, DL, get(NewOpc), DstReg)
1093           .addReg(BaseOp.getReg(), getRegState(BaseOp))
1094           .addImm(Offset)
1095           .cloneMemRefs(MI);
1096       MBB.erase(MI);
1097       return true;
1098     }
1099     case Hexagon::PS_vloadrw_ai: {
1100       Register DstReg = MI.getOperand(0).getReg();
1101       const MachineOperand &BaseOp = MI.getOperand(1);
1102       assert(BaseOp.getSubReg() == 0);
1103       int Offset = MI.getOperand(2).getImm();
1104       unsigned VecOffset = HRI.getSpillSize(Hexagon::HvxVRRegClass);
1105       unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
1106       unsigned NewOpc = UseAligned(MI, NeedAlign) ? Hexagon::V6_vL32b_ai
1107                                                   : Hexagon::V6_vL32Ub_ai;
1108       BuildMI(MBB, MI, DL, get(NewOpc),
1109               HRI.getSubReg(DstReg, Hexagon::vsub_lo))
1110           .addReg(BaseOp.getReg(), getRegState(BaseOp) & ~RegState::Kill)
1111           .addImm(Offset)
1112           .cloneMemRefs(MI);
1113       BuildMI(MBB, MI, DL, get(NewOpc),
1114               HRI.getSubReg(DstReg, Hexagon::vsub_hi))
1115           .addReg(BaseOp.getReg(), getRegState(BaseOp))
1116           .addImm(Offset + VecOffset)
1117           .cloneMemRefs(MI);
1118       MBB.erase(MI);
1119       return true;
1120     }
1121     case Hexagon::PS_vstorerv_ai: {
1122       const MachineOperand &SrcOp = MI.getOperand(2);
1123       assert(SrcOp.getSubReg() == 0);
1124       const MachineOperand &BaseOp = MI.getOperand(0);
1125       assert(BaseOp.getSubReg() == 0);
1126       int Offset = MI.getOperand(1).getImm();
1127       unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
1128       unsigned NewOpc = UseAligned(MI, NeedAlign) ? Hexagon::V6_vS32b_ai
1129                                                   : Hexagon::V6_vS32Ub_ai;
1130       BuildMI(MBB, MI, DL, get(NewOpc))
1131           .addReg(BaseOp.getReg(), getRegState(BaseOp))
1132           .addImm(Offset)
1133           .addReg(SrcOp.getReg(), getRegState(SrcOp))
1134           .cloneMemRefs(MI);
1135       MBB.erase(MI);
1136       return true;
1137     }
1138     case Hexagon::PS_vstorerw_ai: {
1139       Register SrcReg = MI.getOperand(2).getReg();
1140       const MachineOperand &BaseOp = MI.getOperand(0);
1141       assert(BaseOp.getSubReg() == 0);
1142       int Offset = MI.getOperand(1).getImm();
1143       unsigned VecOffset = HRI.getSpillSize(Hexagon::HvxVRRegClass);
1144       unsigned NeedAlign = HRI.getSpillAlignment(Hexagon::HvxVRRegClass);
1145       unsigned NewOpc = UseAligned(MI, NeedAlign) ? Hexagon::V6_vS32b_ai
1146                                                   : Hexagon::V6_vS32Ub_ai;
1147       BuildMI(MBB, MI, DL, get(NewOpc))
1148           .addReg(BaseOp.getReg(), getRegState(BaseOp) & ~RegState::Kill)
1149           .addImm(Offset)
1150           .addReg(HRI.getSubReg(SrcReg, Hexagon::vsub_lo))
1151           .cloneMemRefs(MI);
1152       BuildMI(MBB, MI, DL, get(NewOpc))
1153           .addReg(BaseOp.getReg(), getRegState(BaseOp))
1154           .addImm(Offset + VecOffset)
1155           .addReg(HRI.getSubReg(SrcReg, Hexagon::vsub_hi))
1156           .cloneMemRefs(MI);
1157       MBB.erase(MI);
1158       return true;
1159     }
1160     case Hexagon::PS_true: {
1161       Register Reg = MI.getOperand(0).getReg();
1162       BuildMI(MBB, MI, DL, get(Hexagon::C2_orn), Reg)
1163         .addReg(Reg, RegState::Undef)
1164         .addReg(Reg, RegState::Undef);
1165       MBB.erase(MI);
1166       return true;
1167     }
1168     case Hexagon::PS_false: {
1169       Register Reg = MI.getOperand(0).getReg();
1170       BuildMI(MBB, MI, DL, get(Hexagon::C2_andn), Reg)
1171         .addReg(Reg, RegState::Undef)
1172         .addReg(Reg, RegState::Undef);
1173       MBB.erase(MI);
1174       return true;
1175     }
1176     case Hexagon::PS_qtrue: {
1177       BuildMI(MBB, MI, DL, get(Hexagon::V6_veqw), MI.getOperand(0).getReg())
1178         .addReg(Hexagon::V0, RegState::Undef)
1179         .addReg(Hexagon::V0, RegState::Undef);
1180       MBB.erase(MI);
1181       return true;
1182     }
1183     case Hexagon::PS_qfalse: {
1184       BuildMI(MBB, MI, DL, get(Hexagon::V6_vgtw), MI.getOperand(0).getReg())
1185         .addReg(Hexagon::V0, RegState::Undef)
1186         .addReg(Hexagon::V0, RegState::Undef);
1187       MBB.erase(MI);
1188       return true;
1189     }
1190     case Hexagon::PS_vdd0: {
1191       Register Vd = MI.getOperand(0).getReg();
1192       BuildMI(MBB, MI, DL, get(Hexagon::V6_vsubw_dv), Vd)
1193         .addReg(Vd, RegState::Undef)
1194         .addReg(Vd, RegState::Undef);
1195       MBB.erase(MI);
1196       return true;
1197     }
1198     case Hexagon::PS_vmulw: {
1199       // Expand a 64-bit vector multiply into 2 32-bit scalar multiplies.
1200       Register DstReg = MI.getOperand(0).getReg();
1201       Register Src1Reg = MI.getOperand(1).getReg();
1202       Register Src2Reg = MI.getOperand(2).getReg();
1203       Register Src1SubHi = HRI.getSubReg(Src1Reg, Hexagon::isub_hi);
1204       Register Src1SubLo = HRI.getSubReg(Src1Reg, Hexagon::isub_lo);
1205       Register Src2SubHi = HRI.getSubReg(Src2Reg, Hexagon::isub_hi);
1206       Register Src2SubLo = HRI.getSubReg(Src2Reg, Hexagon::isub_lo);
1207       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_mpyi),
1208               HRI.getSubReg(DstReg, Hexagon::isub_hi))
1209           .addReg(Src1SubHi)
1210           .addReg(Src2SubHi);
1211       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_mpyi),
1212               HRI.getSubReg(DstReg, Hexagon::isub_lo))
1213           .addReg(Src1SubLo)
1214           .addReg(Src2SubLo);
1215       MBB.erase(MI);
1216       MRI.clearKillFlags(Src1SubHi);
1217       MRI.clearKillFlags(Src1SubLo);
1218       MRI.clearKillFlags(Src2SubHi);
1219       MRI.clearKillFlags(Src2SubLo);
1220       return true;
1221     }
1222     case Hexagon::PS_vmulw_acc: {
1223       // Expand 64-bit vector multiply with addition into 2 scalar multiplies.
1224       Register DstReg = MI.getOperand(0).getReg();
1225       Register Src1Reg = MI.getOperand(1).getReg();
1226       Register Src2Reg = MI.getOperand(2).getReg();
1227       Register Src3Reg = MI.getOperand(3).getReg();
1228       Register Src1SubHi = HRI.getSubReg(Src1Reg, Hexagon::isub_hi);
1229       Register Src1SubLo = HRI.getSubReg(Src1Reg, Hexagon::isub_lo);
1230       Register Src2SubHi = HRI.getSubReg(Src2Reg, Hexagon::isub_hi);
1231       Register Src2SubLo = HRI.getSubReg(Src2Reg, Hexagon::isub_lo);
1232       Register Src3SubHi = HRI.getSubReg(Src3Reg, Hexagon::isub_hi);
1233       Register Src3SubLo = HRI.getSubReg(Src3Reg, Hexagon::isub_lo);
1234       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_maci),
1235               HRI.getSubReg(DstReg, Hexagon::isub_hi))
1236           .addReg(Src1SubHi)
1237           .addReg(Src2SubHi)
1238           .addReg(Src3SubHi);
1239       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_maci),
1240               HRI.getSubReg(DstReg, Hexagon::isub_lo))
1241           .addReg(Src1SubLo)
1242           .addReg(Src2SubLo)
1243           .addReg(Src3SubLo);
1244       MBB.erase(MI);
1245       MRI.clearKillFlags(Src1SubHi);
1246       MRI.clearKillFlags(Src1SubLo);
1247       MRI.clearKillFlags(Src2SubHi);
1248       MRI.clearKillFlags(Src2SubLo);
1249       MRI.clearKillFlags(Src3SubHi);
1250       MRI.clearKillFlags(Src3SubLo);
1251       return true;
1252     }
1253     case Hexagon::PS_pselect: {
1254       const MachineOperand &Op0 = MI.getOperand(0);
1255       const MachineOperand &Op1 = MI.getOperand(1);
1256       const MachineOperand &Op2 = MI.getOperand(2);
1257       const MachineOperand &Op3 = MI.getOperand(3);
1258       Register Rd = Op0.getReg();
1259       Register Pu = Op1.getReg();
1260       Register Rs = Op2.getReg();
1261       Register Rt = Op3.getReg();
1262       DebugLoc DL = MI.getDebugLoc();
1263       unsigned K1 = getKillRegState(Op1.isKill());
1264       unsigned K2 = getKillRegState(Op2.isKill());
1265       unsigned K3 = getKillRegState(Op3.isKill());
1266       if (Rd != Rs)
1267         BuildMI(MBB, MI, DL, get(Hexagon::A2_tfrpt), Rd)
1268           .addReg(Pu, (Rd == Rt) ? K1 : 0)
1269           .addReg(Rs, K2);
1270       if (Rd != Rt)
1271         BuildMI(MBB, MI, DL, get(Hexagon::A2_tfrpf), Rd)
1272           .addReg(Pu, K1)
1273           .addReg(Rt, K3);
1274       MBB.erase(MI);
1275       return true;
1276     }
1277     case Hexagon::PS_vselect: {
1278       const MachineOperand &Op0 = MI.getOperand(0);
1279       const MachineOperand &Op1 = MI.getOperand(1);
1280       const MachineOperand &Op2 = MI.getOperand(2);
1281       const MachineOperand &Op3 = MI.getOperand(3);
1282       getLiveOutRegsAt(LiveOut, MI);
1283       bool IsDestLive = !LiveOut.available(MRI, Op0.getReg());
1284       Register PReg = Op1.getReg();
1285       assert(Op1.getSubReg() == 0);
1286       unsigned PState = getRegState(Op1);
1287 
1288       if (Op0.getReg() != Op2.getReg()) {
1289         unsigned S = Op0.getReg() != Op3.getReg() ? PState & ~RegState::Kill
1290                                                   : PState;
1291         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vcmov))
1292                      .add(Op0)
1293                      .addReg(PReg, S)
1294                      .add(Op2);
1295         if (IsDestLive)
1296           T.addReg(Op0.getReg(), RegState::Implicit);
1297         IsDestLive = true;
1298       }
1299       if (Op0.getReg() != Op3.getReg()) {
1300         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vncmov))
1301                      .add(Op0)
1302                      .addReg(PReg, PState)
1303                      .add(Op3);
1304         if (IsDestLive)
1305           T.addReg(Op0.getReg(), RegState::Implicit);
1306       }
1307       MBB.erase(MI);
1308       return true;
1309     }
1310     case Hexagon::PS_wselect: {
1311       MachineOperand &Op0 = MI.getOperand(0);
1312       MachineOperand &Op1 = MI.getOperand(1);
1313       MachineOperand &Op2 = MI.getOperand(2);
1314       MachineOperand &Op3 = MI.getOperand(3);
1315       getLiveOutRegsAt(LiveOut, MI);
1316       bool IsDestLive = !LiveOut.available(MRI, Op0.getReg());
1317       Register PReg = Op1.getReg();
1318       assert(Op1.getSubReg() == 0);
1319       unsigned PState = getRegState(Op1);
1320 
1321       if (Op0.getReg() != Op2.getReg()) {
1322         unsigned S = Op0.getReg() != Op3.getReg() ? PState & ~RegState::Kill
1323                                                   : PState;
1324         Register SrcLo = HRI.getSubReg(Op2.getReg(), Hexagon::vsub_lo);
1325         Register SrcHi = HRI.getSubReg(Op2.getReg(), Hexagon::vsub_hi);
1326         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vccombine))
1327                      .add(Op0)
1328                      .addReg(PReg, S)
1329                      .addReg(SrcHi)
1330                      .addReg(SrcLo);
1331         if (IsDestLive)
1332           T.addReg(Op0.getReg(), RegState::Implicit);
1333         IsDestLive = true;
1334       }
1335       if (Op0.getReg() != Op3.getReg()) {
1336         Register SrcLo = HRI.getSubReg(Op3.getReg(), Hexagon::vsub_lo);
1337         Register SrcHi = HRI.getSubReg(Op3.getReg(), Hexagon::vsub_hi);
1338         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vnccombine))
1339                      .add(Op0)
1340                      .addReg(PReg, PState)
1341                      .addReg(SrcHi)
1342                      .addReg(SrcLo);
1343         if (IsDestLive)
1344           T.addReg(Op0.getReg(), RegState::Implicit);
1345       }
1346       MBB.erase(MI);
1347       return true;
1348     }
1349 
1350     case Hexagon::PS_crash: {
1351       // Generate a misaligned load that is guaranteed to cause a crash.
1352       class CrashPseudoSourceValue : public PseudoSourceValue {
1353       public:
1354         CrashPseudoSourceValue(const TargetInstrInfo &TII)
1355           : PseudoSourceValue(TargetCustom, TII) {}
1356 
1357         bool isConstant(const MachineFrameInfo *) const override {
1358           return false;
1359         }
1360         bool isAliased(const MachineFrameInfo *) const override {
1361           return false;
1362         }
1363         bool mayAlias(const MachineFrameInfo *) const override {
1364           return false;
1365         }
1366         void printCustom(raw_ostream &OS) const override {
1367           OS << "MisalignedCrash";
1368         }
1369       };
1370 
1371       static const CrashPseudoSourceValue CrashPSV(*this);
1372       MachineMemOperand *MMO = MF.getMachineMemOperand(
1373           MachinePointerInfo(&CrashPSV),
1374           MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 8,
1375           Align(1));
1376       BuildMI(MBB, MI, DL, get(Hexagon::PS_loadrdabs), Hexagon::D13)
1377         .addImm(0xBADC0FEE)  // Misaligned load.
1378         .addMemOperand(MMO);
1379       MBB.erase(MI);
1380       return true;
1381     }
1382 
1383     case Hexagon::PS_tailcall_i:
1384       MI.setDesc(get(Hexagon::J2_jump));
1385       return true;
1386     case Hexagon::PS_tailcall_r:
1387     case Hexagon::PS_jmpret:
1388       MI.setDesc(get(Hexagon::J2_jumpr));
1389       return true;
1390     case Hexagon::PS_jmprett:
1391       MI.setDesc(get(Hexagon::J2_jumprt));
1392       return true;
1393     case Hexagon::PS_jmpretf:
1394       MI.setDesc(get(Hexagon::J2_jumprf));
1395       return true;
1396     case Hexagon::PS_jmprettnewpt:
1397       MI.setDesc(get(Hexagon::J2_jumprtnewpt));
1398       return true;
1399     case Hexagon::PS_jmpretfnewpt:
1400       MI.setDesc(get(Hexagon::J2_jumprfnewpt));
1401       return true;
1402     case Hexagon::PS_jmprettnew:
1403       MI.setDesc(get(Hexagon::J2_jumprtnew));
1404       return true;
1405     case Hexagon::PS_jmpretfnew:
1406       MI.setDesc(get(Hexagon::J2_jumprfnew));
1407       return true;
1408 
1409     case Hexagon::PS_loadrub_pci:
1410       return RealCirc(Hexagon::L2_loadrub_pci, /*HasImm*/true,  /*MxOp*/4);
1411     case Hexagon::PS_loadrb_pci:
1412       return RealCirc(Hexagon::L2_loadrb_pci,  /*HasImm*/true,  /*MxOp*/4);
1413     case Hexagon::PS_loadruh_pci:
1414       return RealCirc(Hexagon::L2_loadruh_pci, /*HasImm*/true,  /*MxOp*/4);
1415     case Hexagon::PS_loadrh_pci:
1416       return RealCirc(Hexagon::L2_loadrh_pci,  /*HasImm*/true,  /*MxOp*/4);
1417     case Hexagon::PS_loadri_pci:
1418       return RealCirc(Hexagon::L2_loadri_pci,  /*HasImm*/true,  /*MxOp*/4);
1419     case Hexagon::PS_loadrd_pci:
1420       return RealCirc(Hexagon::L2_loadrd_pci,  /*HasImm*/true,  /*MxOp*/4);
1421     case Hexagon::PS_loadrub_pcr:
1422       return RealCirc(Hexagon::L2_loadrub_pcr, /*HasImm*/false, /*MxOp*/3);
1423     case Hexagon::PS_loadrb_pcr:
1424       return RealCirc(Hexagon::L2_loadrb_pcr,  /*HasImm*/false, /*MxOp*/3);
1425     case Hexagon::PS_loadruh_pcr:
1426       return RealCirc(Hexagon::L2_loadruh_pcr, /*HasImm*/false, /*MxOp*/3);
1427     case Hexagon::PS_loadrh_pcr:
1428       return RealCirc(Hexagon::L2_loadrh_pcr,  /*HasImm*/false, /*MxOp*/3);
1429     case Hexagon::PS_loadri_pcr:
1430       return RealCirc(Hexagon::L2_loadri_pcr,  /*HasImm*/false, /*MxOp*/3);
1431     case Hexagon::PS_loadrd_pcr:
1432       return RealCirc(Hexagon::L2_loadrd_pcr,  /*HasImm*/false, /*MxOp*/3);
1433     case Hexagon::PS_storerb_pci:
1434       return RealCirc(Hexagon::S2_storerb_pci, /*HasImm*/true,  /*MxOp*/3);
1435     case Hexagon::PS_storerh_pci:
1436       return RealCirc(Hexagon::S2_storerh_pci, /*HasImm*/true,  /*MxOp*/3);
1437     case Hexagon::PS_storerf_pci:
1438       return RealCirc(Hexagon::S2_storerf_pci, /*HasImm*/true,  /*MxOp*/3);
1439     case Hexagon::PS_storeri_pci:
1440       return RealCirc(Hexagon::S2_storeri_pci, /*HasImm*/true,  /*MxOp*/3);
1441     case Hexagon::PS_storerd_pci:
1442       return RealCirc(Hexagon::S2_storerd_pci, /*HasImm*/true,  /*MxOp*/3);
1443     case Hexagon::PS_storerb_pcr:
1444       return RealCirc(Hexagon::S2_storerb_pcr, /*HasImm*/false, /*MxOp*/2);
1445     case Hexagon::PS_storerh_pcr:
1446       return RealCirc(Hexagon::S2_storerh_pcr, /*HasImm*/false, /*MxOp*/2);
1447     case Hexagon::PS_storerf_pcr:
1448       return RealCirc(Hexagon::S2_storerf_pcr, /*HasImm*/false, /*MxOp*/2);
1449     case Hexagon::PS_storeri_pcr:
1450       return RealCirc(Hexagon::S2_storeri_pcr, /*HasImm*/false, /*MxOp*/2);
1451     case Hexagon::PS_storerd_pcr:
1452       return RealCirc(Hexagon::S2_storerd_pcr, /*HasImm*/false, /*MxOp*/2);
1453   }
1454 
1455   return false;
1456 }
1457 
1458 MachineBasicBlock::instr_iterator
1459 HexagonInstrInfo::expandVGatherPseudo(MachineInstr &MI) const {
1460   MachineBasicBlock &MBB = *MI.getParent();
1461   const DebugLoc &DL = MI.getDebugLoc();
1462   unsigned Opc = MI.getOpcode();
1463   MachineBasicBlock::iterator First;
1464 
1465   switch (Opc) {
1466     case Hexagon::V6_vgathermh_pseudo:
1467       First = BuildMI(MBB, MI, DL, get(Hexagon::V6_vgathermh))
1468                   .add(MI.getOperand(1))
1469                   .add(MI.getOperand(2))
1470                   .add(MI.getOperand(3));
1471       BuildMI(MBB, MI, DL, get(Hexagon::V6_vS32b_new_ai))
1472           .add(MI.getOperand(0))
1473           .addImm(0)
1474           .addReg(Hexagon::VTMP);
1475       MBB.erase(MI);
1476       return First.getInstrIterator();
1477 
1478     case Hexagon::V6_vgathermw_pseudo:
1479       First = BuildMI(MBB, MI, DL, get(Hexagon::V6_vgathermw))
1480                   .add(MI.getOperand(1))
1481                   .add(MI.getOperand(2))
1482                   .add(MI.getOperand(3));
1483       BuildMI(MBB, MI, DL, get(Hexagon::V6_vS32b_new_ai))
1484           .add(MI.getOperand(0))
1485           .addImm(0)
1486           .addReg(Hexagon::VTMP);
1487       MBB.erase(MI);
1488       return First.getInstrIterator();
1489 
1490     case Hexagon::V6_vgathermhw_pseudo:
1491       First = BuildMI(MBB, MI, DL, get(Hexagon::V6_vgathermhw))
1492                   .add(MI.getOperand(1))
1493                   .add(MI.getOperand(2))
1494                   .add(MI.getOperand(3));
1495       BuildMI(MBB, MI, DL, get(Hexagon::V6_vS32b_new_ai))
1496           .add(MI.getOperand(0))
1497           .addImm(0)
1498           .addReg(Hexagon::VTMP);
1499       MBB.erase(MI);
1500       return First.getInstrIterator();
1501 
1502     case Hexagon::V6_vgathermhq_pseudo:
1503       First = BuildMI(MBB, MI, DL, get(Hexagon::V6_vgathermhq))
1504                   .add(MI.getOperand(1))
1505                   .add(MI.getOperand(2))
1506                   .add(MI.getOperand(3))
1507                   .add(MI.getOperand(4));
1508       BuildMI(MBB, MI, DL, get(Hexagon::V6_vS32b_new_ai))
1509           .add(MI.getOperand(0))
1510           .addImm(0)
1511           .addReg(Hexagon::VTMP);
1512       MBB.erase(MI);
1513       return First.getInstrIterator();
1514 
1515     case Hexagon::V6_vgathermwq_pseudo:
1516       First = BuildMI(MBB, MI, DL, get(Hexagon::V6_vgathermwq))
1517                   .add(MI.getOperand(1))
1518                   .add(MI.getOperand(2))
1519                   .add(MI.getOperand(3))
1520                   .add(MI.getOperand(4));
1521       BuildMI(MBB, MI, DL, get(Hexagon::V6_vS32b_new_ai))
1522           .add(MI.getOperand(0))
1523           .addImm(0)
1524           .addReg(Hexagon::VTMP);
1525       MBB.erase(MI);
1526       return First.getInstrIterator();
1527 
1528     case Hexagon::V6_vgathermhwq_pseudo:
1529       First = BuildMI(MBB, MI, DL, get(Hexagon::V6_vgathermhwq))
1530                   .add(MI.getOperand(1))
1531                   .add(MI.getOperand(2))
1532                   .add(MI.getOperand(3))
1533                   .add(MI.getOperand(4));
1534       BuildMI(MBB, MI, DL, get(Hexagon::V6_vS32b_new_ai))
1535           .add(MI.getOperand(0))
1536           .addImm(0)
1537           .addReg(Hexagon::VTMP);
1538       MBB.erase(MI);
1539       return First.getInstrIterator();
1540   }
1541 
1542   return MI.getIterator();
1543 }
1544 
1545 // We indicate that we want to reverse the branch by
1546 // inserting the reversed branching opcode.
1547 bool HexagonInstrInfo::reverseBranchCondition(
1548       SmallVectorImpl<MachineOperand> &Cond) const {
1549   if (Cond.empty())
1550     return true;
1551   assert(Cond[0].isImm() && "First entry in the cond vector not imm-val");
1552   unsigned opcode = Cond[0].getImm();
1553   //unsigned temp;
1554   assert(get(opcode).isBranch() && "Should be a branching condition.");
1555   if (isEndLoopN(opcode))
1556     return true;
1557   unsigned NewOpcode = getInvertedPredicatedOpcode(opcode);
1558   Cond[0].setImm(NewOpcode);
1559   return false;
1560 }
1561 
1562 void HexagonInstrInfo::insertNoop(MachineBasicBlock &MBB,
1563       MachineBasicBlock::iterator MI) const {
1564   DebugLoc DL;
1565   BuildMI(MBB, MI, DL, get(Hexagon::A2_nop));
1566 }
1567 
1568 bool HexagonInstrInfo::isPostIncrement(const MachineInstr &MI) const {
1569   return getAddrMode(MI) == HexagonII::PostInc;
1570 }
1571 
1572 // Returns true if an instruction is predicated irrespective of the predicate
1573 // sense. For example, all of the following will return true.
1574 // if (p0) R1 = add(R2, R3)
1575 // if (!p0) R1 = add(R2, R3)
1576 // if (p0.new) R1 = add(R2, R3)
1577 // if (!p0.new) R1 = add(R2, R3)
1578 // Note: New-value stores are not included here as in the current
1579 // implementation, we don't need to check their predicate sense.
1580 bool HexagonInstrInfo::isPredicated(const MachineInstr &MI) const {
1581   const uint64_t F = MI.getDesc().TSFlags;
1582   return (F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask;
1583 }
1584 
1585 bool HexagonInstrInfo::PredicateInstruction(
1586     MachineInstr &MI, ArrayRef<MachineOperand> Cond) const {
1587   if (Cond.empty() || isNewValueJump(Cond[0].getImm()) ||
1588       isEndLoopN(Cond[0].getImm())) {
1589     LLVM_DEBUG(dbgs() << "\nCannot predicate:"; MI.dump(););
1590     return false;
1591   }
1592   int Opc = MI.getOpcode();
1593   assert (isPredicable(MI) && "Expected predicable instruction");
1594   bool invertJump = predOpcodeHasNot(Cond);
1595 
1596   // We have to predicate MI "in place", i.e. after this function returns,
1597   // MI will need to be transformed into a predicated form. To avoid com-
1598   // plicated manipulations with the operands (handling tied operands,
1599   // etc.), build a new temporary instruction, then overwrite MI with it.
1600 
1601   MachineBasicBlock &B = *MI.getParent();
1602   DebugLoc DL = MI.getDebugLoc();
1603   unsigned PredOpc = getCondOpcode(Opc, invertJump);
1604   MachineInstrBuilder T = BuildMI(B, MI, DL, get(PredOpc));
1605   unsigned NOp = 0, NumOps = MI.getNumOperands();
1606   while (NOp < NumOps) {
1607     MachineOperand &Op = MI.getOperand(NOp);
1608     if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
1609       break;
1610     T.add(Op);
1611     NOp++;
1612   }
1613 
1614   unsigned PredReg, PredRegPos, PredRegFlags;
1615   bool GotPredReg = getPredReg(Cond, PredReg, PredRegPos, PredRegFlags);
1616   (void)GotPredReg;
1617   assert(GotPredReg);
1618   T.addReg(PredReg, PredRegFlags);
1619   while (NOp < NumOps)
1620     T.add(MI.getOperand(NOp++));
1621 
1622   MI.setDesc(get(PredOpc));
1623   while (unsigned n = MI.getNumOperands())
1624     MI.RemoveOperand(n-1);
1625   for (unsigned i = 0, n = T->getNumOperands(); i < n; ++i)
1626     MI.addOperand(T->getOperand(i));
1627 
1628   MachineBasicBlock::instr_iterator TI = T->getIterator();
1629   B.erase(TI);
1630 
1631   MachineRegisterInfo &MRI = B.getParent()->getRegInfo();
1632   MRI.clearKillFlags(PredReg);
1633   return true;
1634 }
1635 
1636 bool HexagonInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1637       ArrayRef<MachineOperand> Pred2) const {
1638   // TODO: Fix this
1639   return false;
1640 }
1641 
1642 bool HexagonInstrInfo::DefinesPredicate(MachineInstr &MI,
1643       std::vector<MachineOperand> &Pred) const {
1644   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
1645 
1646   for (unsigned oper = 0; oper < MI.getNumOperands(); ++oper) {
1647     MachineOperand MO = MI.getOperand(oper);
1648     if (MO.isReg()) {
1649       if (!MO.isDef())
1650         continue;
1651       const TargetRegisterClass* RC = HRI.getMinimalPhysRegClass(MO.getReg());
1652       if (RC == &Hexagon::PredRegsRegClass) {
1653         Pred.push_back(MO);
1654         return true;
1655       }
1656       continue;
1657     } else if (MO.isRegMask()) {
1658       for (unsigned PR : Hexagon::PredRegsRegClass) {
1659         if (!MI.modifiesRegister(PR, &HRI))
1660           continue;
1661         Pred.push_back(MO);
1662         return true;
1663       }
1664     }
1665   }
1666   return false;
1667 }
1668 
1669 bool HexagonInstrInfo::isPredicable(const MachineInstr &MI) const {
1670   if (!MI.getDesc().isPredicable())
1671     return false;
1672 
1673   if (MI.isCall() || isTailCall(MI)) {
1674     if (!Subtarget.usePredicatedCalls())
1675       return false;
1676   }
1677 
1678   // HVX loads are not predicable on v60, but are on v62.
1679   if (!Subtarget.hasV62Ops()) {
1680     switch (MI.getOpcode()) {
1681       case Hexagon::V6_vL32b_ai:
1682       case Hexagon::V6_vL32b_pi:
1683       case Hexagon::V6_vL32b_ppu:
1684       case Hexagon::V6_vL32b_cur_ai:
1685       case Hexagon::V6_vL32b_cur_pi:
1686       case Hexagon::V6_vL32b_cur_ppu:
1687       case Hexagon::V6_vL32b_nt_ai:
1688       case Hexagon::V6_vL32b_nt_pi:
1689       case Hexagon::V6_vL32b_nt_ppu:
1690       case Hexagon::V6_vL32b_tmp_ai:
1691       case Hexagon::V6_vL32b_tmp_pi:
1692       case Hexagon::V6_vL32b_tmp_ppu:
1693       case Hexagon::V6_vL32b_nt_cur_ai:
1694       case Hexagon::V6_vL32b_nt_cur_pi:
1695       case Hexagon::V6_vL32b_nt_cur_ppu:
1696       case Hexagon::V6_vL32b_nt_tmp_ai:
1697       case Hexagon::V6_vL32b_nt_tmp_pi:
1698       case Hexagon::V6_vL32b_nt_tmp_ppu:
1699         return false;
1700     }
1701   }
1702   return true;
1703 }
1704 
1705 bool HexagonInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1706                                             const MachineBasicBlock *MBB,
1707                                             const MachineFunction &MF) const {
1708   // Debug info is never a scheduling boundary. It's necessary to be explicit
1709   // due to the special treatment of IT instructions below, otherwise a
1710   // dbg_value followed by an IT will result in the IT instruction being
1711   // considered a scheduling hazard, which is wrong. It should be the actual
1712   // instruction preceding the dbg_value instruction(s), just like it is
1713   // when debug info is not present.
1714   if (MI.isDebugInstr())
1715     return false;
1716 
1717   // Throwing call is a boundary.
1718   if (MI.isCall()) {
1719     // Don't mess around with no return calls.
1720     if (doesNotReturn(MI))
1721       return true;
1722     // If any of the block's successors is a landing pad, this could be a
1723     // throwing call.
1724     for (auto I : MBB->successors())
1725       if (I->isEHPad())
1726         return true;
1727   }
1728 
1729   // Terminators and labels can't be scheduled around.
1730   if (MI.getDesc().isTerminator() || MI.isPosition())
1731     return true;
1732 
1733   if (MI.isInlineAsm() && !ScheduleInlineAsm)
1734     return true;
1735 
1736   return false;
1737 }
1738 
1739 /// Measure the specified inline asm to determine an approximation of its
1740 /// length.
1741 /// Comments (which run till the next SeparatorString or newline) do not
1742 /// count as an instruction.
1743 /// Any other non-whitespace text is considered an instruction, with
1744 /// multiple instructions separated by SeparatorString or newlines.
1745 /// Variable-length instructions are not handled here; this function
1746 /// may be overloaded in the target code to do that.
1747 /// Hexagon counts the number of ##'s and adjust for that many
1748 /// constant exenders.
1749 unsigned HexagonInstrInfo::getInlineAsmLength(const char *Str,
1750                                               const MCAsmInfo &MAI,
1751                                               const TargetSubtargetInfo *STI) const {
1752   StringRef AStr(Str);
1753   // Count the number of instructions in the asm.
1754   bool atInsnStart = true;
1755   unsigned Length = 0;
1756   const unsigned MaxInstLength = MAI.getMaxInstLength(STI);
1757   for (; *Str; ++Str) {
1758     if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
1759                                 strlen(MAI.getSeparatorString())) == 0)
1760       atInsnStart = true;
1761     if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) {
1762       Length += MaxInstLength;
1763       atInsnStart = false;
1764     }
1765     if (atInsnStart && strncmp(Str, MAI.getCommentString().data(),
1766                                MAI.getCommentString().size()) == 0)
1767       atInsnStart = false;
1768   }
1769 
1770   // Add to size number of constant extenders seen * 4.
1771   StringRef Occ("##");
1772   Length += AStr.count(Occ)*4;
1773   return Length;
1774 }
1775 
1776 ScheduleHazardRecognizer*
1777 HexagonInstrInfo::CreateTargetPostRAHazardRecognizer(
1778       const InstrItineraryData *II, const ScheduleDAG *DAG) const {
1779   if (UseDFAHazardRec)
1780     return new HexagonHazardRecognizer(II, this, Subtarget);
1781   return TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
1782 }
1783 
1784 /// For a comparison instruction, return the source registers in
1785 /// \p SrcReg and \p SrcReg2 if having two register operands, and the value it
1786 /// compares against in CmpValue. Return true if the comparison instruction
1787 /// can be analyzed.
1788 bool HexagonInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
1789                                       Register &SrcReg2, int &Mask,
1790                                       int &Value) const {
1791   unsigned Opc = MI.getOpcode();
1792 
1793   // Set mask and the first source register.
1794   switch (Opc) {
1795     case Hexagon::C2_cmpeq:
1796     case Hexagon::C2_cmpeqp:
1797     case Hexagon::C2_cmpgt:
1798     case Hexagon::C2_cmpgtp:
1799     case Hexagon::C2_cmpgtu:
1800     case Hexagon::C2_cmpgtup:
1801     case Hexagon::C4_cmpneq:
1802     case Hexagon::C4_cmplte:
1803     case Hexagon::C4_cmplteu:
1804     case Hexagon::C2_cmpeqi:
1805     case Hexagon::C2_cmpgti:
1806     case Hexagon::C2_cmpgtui:
1807     case Hexagon::C4_cmpneqi:
1808     case Hexagon::C4_cmplteui:
1809     case Hexagon::C4_cmpltei:
1810       SrcReg = MI.getOperand(1).getReg();
1811       Mask = ~0;
1812       break;
1813     case Hexagon::A4_cmpbeq:
1814     case Hexagon::A4_cmpbgt:
1815     case Hexagon::A4_cmpbgtu:
1816     case Hexagon::A4_cmpbeqi:
1817     case Hexagon::A4_cmpbgti:
1818     case Hexagon::A4_cmpbgtui:
1819       SrcReg = MI.getOperand(1).getReg();
1820       Mask = 0xFF;
1821       break;
1822     case Hexagon::A4_cmpheq:
1823     case Hexagon::A4_cmphgt:
1824     case Hexagon::A4_cmphgtu:
1825     case Hexagon::A4_cmpheqi:
1826     case Hexagon::A4_cmphgti:
1827     case Hexagon::A4_cmphgtui:
1828       SrcReg = MI.getOperand(1).getReg();
1829       Mask = 0xFFFF;
1830       break;
1831   }
1832 
1833   // Set the value/second source register.
1834   switch (Opc) {
1835     case Hexagon::C2_cmpeq:
1836     case Hexagon::C2_cmpeqp:
1837     case Hexagon::C2_cmpgt:
1838     case Hexagon::C2_cmpgtp:
1839     case Hexagon::C2_cmpgtu:
1840     case Hexagon::C2_cmpgtup:
1841     case Hexagon::A4_cmpbeq:
1842     case Hexagon::A4_cmpbgt:
1843     case Hexagon::A4_cmpbgtu:
1844     case Hexagon::A4_cmpheq:
1845     case Hexagon::A4_cmphgt:
1846     case Hexagon::A4_cmphgtu:
1847     case Hexagon::C4_cmpneq:
1848     case Hexagon::C4_cmplte:
1849     case Hexagon::C4_cmplteu:
1850       SrcReg2 = MI.getOperand(2).getReg();
1851       return true;
1852 
1853     case Hexagon::C2_cmpeqi:
1854     case Hexagon::C2_cmpgtui:
1855     case Hexagon::C2_cmpgti:
1856     case Hexagon::C4_cmpneqi:
1857     case Hexagon::C4_cmplteui:
1858     case Hexagon::C4_cmpltei:
1859     case Hexagon::A4_cmpbeqi:
1860     case Hexagon::A4_cmpbgti:
1861     case Hexagon::A4_cmpbgtui:
1862     case Hexagon::A4_cmpheqi:
1863     case Hexagon::A4_cmphgti:
1864     case Hexagon::A4_cmphgtui: {
1865       SrcReg2 = 0;
1866       const MachineOperand &Op2 = MI.getOperand(2);
1867       if (!Op2.isImm())
1868         return false;
1869       Value = MI.getOperand(2).getImm();
1870       return true;
1871     }
1872   }
1873 
1874   return false;
1875 }
1876 
1877 unsigned HexagonInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1878                                            const MachineInstr &MI,
1879                                            unsigned *PredCost) const {
1880   return getInstrTimingClassLatency(ItinData, MI);
1881 }
1882 
1883 DFAPacketizer *HexagonInstrInfo::CreateTargetScheduleState(
1884     const TargetSubtargetInfo &STI) const {
1885   const InstrItineraryData *II = STI.getInstrItineraryData();
1886   return static_cast<const HexagonSubtarget&>(STI).createDFAPacketizer(II);
1887 }
1888 
1889 // Inspired by this pair:
1890 //  %r13 = L2_loadri_io %r29, 136; mem:LD4[FixedStack0]
1891 //  S2_storeri_io %r29, 132, killed %r1; flags:  mem:ST4[FixedStack1]
1892 // Currently AA considers the addresses in these instructions to be aliasing.
1893 bool HexagonInstrInfo::areMemAccessesTriviallyDisjoint(
1894     const MachineInstr &MIa, const MachineInstr &MIb) const {
1895   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
1896       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
1897     return false;
1898 
1899   // Instructions that are pure loads, not loads and stores like memops are not
1900   // dependent.
1901   if (MIa.mayLoad() && !isMemOp(MIa) && MIb.mayLoad() && !isMemOp(MIb))
1902     return true;
1903 
1904   // Get the base register in MIa.
1905   unsigned BasePosA, OffsetPosA;
1906   if (!getBaseAndOffsetPosition(MIa, BasePosA, OffsetPosA))
1907     return false;
1908   const MachineOperand &BaseA = MIa.getOperand(BasePosA);
1909   Register BaseRegA = BaseA.getReg();
1910   unsigned BaseSubA = BaseA.getSubReg();
1911 
1912   // Get the base register in MIb.
1913   unsigned BasePosB, OffsetPosB;
1914   if (!getBaseAndOffsetPosition(MIb, BasePosB, OffsetPosB))
1915     return false;
1916   const MachineOperand &BaseB = MIb.getOperand(BasePosB);
1917   Register BaseRegB = BaseB.getReg();
1918   unsigned BaseSubB = BaseB.getSubReg();
1919 
1920   if (BaseRegA != BaseRegB || BaseSubA != BaseSubB)
1921     return false;
1922 
1923   // Get the access sizes.
1924   unsigned SizeA = getMemAccessSize(MIa);
1925   unsigned SizeB = getMemAccessSize(MIb);
1926 
1927   // Get the offsets. Handle immediates only for now.
1928   const MachineOperand &OffA = MIa.getOperand(OffsetPosA);
1929   const MachineOperand &OffB = MIb.getOperand(OffsetPosB);
1930   if (!MIa.getOperand(OffsetPosA).isImm() ||
1931       !MIb.getOperand(OffsetPosB).isImm())
1932     return false;
1933   int OffsetA = isPostIncrement(MIa) ? 0 : OffA.getImm();
1934   int OffsetB = isPostIncrement(MIb) ? 0 : OffB.getImm();
1935 
1936   // This is a mem access with the same base register and known offsets from it.
1937   // Reason about it.
1938   if (OffsetA > OffsetB) {
1939     uint64_t OffDiff = (uint64_t)((int64_t)OffsetA - (int64_t)OffsetB);
1940     return SizeB <= OffDiff;
1941   }
1942   if (OffsetA < OffsetB) {
1943     uint64_t OffDiff = (uint64_t)((int64_t)OffsetB - (int64_t)OffsetA);
1944     return SizeA <= OffDiff;
1945   }
1946 
1947   return false;
1948 }
1949 
1950 /// If the instruction is an increment of a constant value, return the amount.
1951 bool HexagonInstrInfo::getIncrementValue(const MachineInstr &MI,
1952       int &Value) const {
1953   if (isPostIncrement(MI)) {
1954     unsigned BasePos = 0, OffsetPos = 0;
1955     if (!getBaseAndOffsetPosition(MI, BasePos, OffsetPos))
1956       return false;
1957     const MachineOperand &OffsetOp = MI.getOperand(OffsetPos);
1958     if (OffsetOp.isImm()) {
1959       Value = OffsetOp.getImm();
1960       return true;
1961     }
1962   } else if (MI.getOpcode() == Hexagon::A2_addi) {
1963     const MachineOperand &AddOp = MI.getOperand(2);
1964     if (AddOp.isImm()) {
1965       Value = AddOp.getImm();
1966       return true;
1967     }
1968   }
1969 
1970   return false;
1971 }
1972 
1973 std::pair<unsigned, unsigned>
1974 HexagonInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
1975   return std::make_pair(TF & ~HexagonII::MO_Bitmasks,
1976                         TF & HexagonII::MO_Bitmasks);
1977 }
1978 
1979 ArrayRef<std::pair<unsigned, const char*>>
1980 HexagonInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
1981   using namespace HexagonII;
1982 
1983   static const std::pair<unsigned, const char*> Flags[] = {
1984     {MO_PCREL,  "hexagon-pcrel"},
1985     {MO_GOT,    "hexagon-got"},
1986     {MO_LO16,   "hexagon-lo16"},
1987     {MO_HI16,   "hexagon-hi16"},
1988     {MO_GPREL,  "hexagon-gprel"},
1989     {MO_GDGOT,  "hexagon-gdgot"},
1990     {MO_GDPLT,  "hexagon-gdplt"},
1991     {MO_IE,     "hexagon-ie"},
1992     {MO_IEGOT,  "hexagon-iegot"},
1993     {MO_TPREL,  "hexagon-tprel"}
1994   };
1995   return makeArrayRef(Flags);
1996 }
1997 
1998 ArrayRef<std::pair<unsigned, const char*>>
1999 HexagonInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
2000   using namespace HexagonII;
2001 
2002   static const std::pair<unsigned, const char*> Flags[] = {
2003     {HMOTF_ConstExtended, "hexagon-ext"}
2004   };
2005   return makeArrayRef(Flags);
2006 }
2007 
2008 unsigned HexagonInstrInfo::createVR(MachineFunction *MF, MVT VT) const {
2009   MachineRegisterInfo &MRI = MF->getRegInfo();
2010   const TargetRegisterClass *TRC;
2011   if (VT == MVT::i1) {
2012     TRC = &Hexagon::PredRegsRegClass;
2013   } else if (VT == MVT::i32 || VT == MVT::f32) {
2014     TRC = &Hexagon::IntRegsRegClass;
2015   } else if (VT == MVT::i64 || VT == MVT::f64) {
2016     TRC = &Hexagon::DoubleRegsRegClass;
2017   } else {
2018     llvm_unreachable("Cannot handle this register class");
2019   }
2020 
2021   Register NewReg = MRI.createVirtualRegister(TRC);
2022   return NewReg;
2023 }
2024 
2025 bool HexagonInstrInfo::isAbsoluteSet(const MachineInstr &MI) const {
2026   return (getAddrMode(MI) == HexagonII::AbsoluteSet);
2027 }
2028 
2029 bool HexagonInstrInfo::isAccumulator(const MachineInstr &MI) const {
2030   const uint64_t F = MI.getDesc().TSFlags;
2031   return((F >> HexagonII::AccumulatorPos) & HexagonII::AccumulatorMask);
2032 }
2033 
2034 bool HexagonInstrInfo::isBaseImmOffset(const MachineInstr &MI) const {
2035   return getAddrMode(MI) == HexagonII::BaseImmOffset;
2036 }
2037 
2038 bool HexagonInstrInfo::isComplex(const MachineInstr &MI) const {
2039   return !isTC1(MI) && !isTC2Early(MI) && !MI.getDesc().mayLoad() &&
2040          !MI.getDesc().mayStore() &&
2041          MI.getDesc().getOpcode() != Hexagon::S2_allocframe &&
2042          MI.getDesc().getOpcode() != Hexagon::L2_deallocframe &&
2043          !isMemOp(MI) && !MI.isBranch() && !MI.isReturn() && !MI.isCall();
2044 }
2045 
2046 // Return true if the instruction is a compund branch instruction.
2047 bool HexagonInstrInfo::isCompoundBranchInstr(const MachineInstr &MI) const {
2048   return getType(MI) == HexagonII::TypeCJ && MI.isBranch();
2049 }
2050 
2051 // TODO: In order to have isExtendable for fpimm/f32Ext, we need to handle
2052 // isFPImm and later getFPImm as well.
2053 bool HexagonInstrInfo::isConstExtended(const MachineInstr &MI) const {
2054   const uint64_t F = MI.getDesc().TSFlags;
2055   unsigned isExtended = (F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask;
2056   if (isExtended) // Instruction must be extended.
2057     return true;
2058 
2059   unsigned isExtendable =
2060     (F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask;
2061   if (!isExtendable)
2062     return false;
2063 
2064   if (MI.isCall())
2065     return false;
2066 
2067   short ExtOpNum = getCExtOpNum(MI);
2068   const MachineOperand &MO = MI.getOperand(ExtOpNum);
2069   // Use MO operand flags to determine if MO
2070   // has the HMOTF_ConstExtended flag set.
2071   if (MO.getTargetFlags() & HexagonII::HMOTF_ConstExtended)
2072     return true;
2073   // If this is a Machine BB address we are talking about, and it is
2074   // not marked as extended, say so.
2075   if (MO.isMBB())
2076     return false;
2077 
2078   // We could be using an instruction with an extendable immediate and shoehorn
2079   // a global address into it. If it is a global address it will be constant
2080   // extended. We do this for COMBINE.
2081   if (MO.isGlobal() || MO.isSymbol() || MO.isBlockAddress() ||
2082       MO.isJTI() || MO.isCPI() || MO.isFPImm())
2083     return true;
2084 
2085   // If the extendable operand is not 'Immediate' type, the instruction should
2086   // have 'isExtended' flag set.
2087   assert(MO.isImm() && "Extendable operand must be Immediate type");
2088 
2089   int MinValue = getMinValue(MI);
2090   int MaxValue = getMaxValue(MI);
2091   int ImmValue = MO.getImm();
2092 
2093   return (ImmValue < MinValue || ImmValue > MaxValue);
2094 }
2095 
2096 bool HexagonInstrInfo::isDeallocRet(const MachineInstr &MI) const {
2097   switch (MI.getOpcode()) {
2098   case Hexagon::L4_return:
2099   case Hexagon::L4_return_t:
2100   case Hexagon::L4_return_f:
2101   case Hexagon::L4_return_tnew_pnt:
2102   case Hexagon::L4_return_fnew_pnt:
2103   case Hexagon::L4_return_tnew_pt:
2104   case Hexagon::L4_return_fnew_pt:
2105     return true;
2106   }
2107   return false;
2108 }
2109 
2110 // Return true when ConsMI uses a register defined by ProdMI.
2111 bool HexagonInstrInfo::isDependent(const MachineInstr &ProdMI,
2112       const MachineInstr &ConsMI) const {
2113   if (!ProdMI.getDesc().getNumDefs())
2114     return false;
2115   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
2116 
2117   SmallVector<unsigned, 4> DefsA;
2118   SmallVector<unsigned, 4> DefsB;
2119   SmallVector<unsigned, 8> UsesA;
2120   SmallVector<unsigned, 8> UsesB;
2121 
2122   parseOperands(ProdMI, DefsA, UsesA);
2123   parseOperands(ConsMI, DefsB, UsesB);
2124 
2125   for (auto &RegA : DefsA)
2126     for (auto &RegB : UsesB) {
2127       // True data dependency.
2128       if (RegA == RegB)
2129         return true;
2130 
2131       if (Register::isPhysicalRegister(RegA))
2132         for (MCSubRegIterator SubRegs(RegA, &HRI); SubRegs.isValid(); ++SubRegs)
2133           if (RegB == *SubRegs)
2134             return true;
2135 
2136       if (Register::isPhysicalRegister(RegB))
2137         for (MCSubRegIterator SubRegs(RegB, &HRI); SubRegs.isValid(); ++SubRegs)
2138           if (RegA == *SubRegs)
2139             return true;
2140     }
2141 
2142   return false;
2143 }
2144 
2145 // Returns true if the instruction is alread a .cur.
2146 bool HexagonInstrInfo::isDotCurInst(const MachineInstr &MI) const {
2147   switch (MI.getOpcode()) {
2148   case Hexagon::V6_vL32b_cur_pi:
2149   case Hexagon::V6_vL32b_cur_ai:
2150     return true;
2151   }
2152   return false;
2153 }
2154 
2155 // Returns true, if any one of the operands is a dot new
2156 // insn, whether it is predicated dot new or register dot new.
2157 bool HexagonInstrInfo::isDotNewInst(const MachineInstr &MI) const {
2158   if (isNewValueInst(MI) || (isPredicated(MI) && isPredicatedNew(MI)))
2159     return true;
2160 
2161   return false;
2162 }
2163 
2164 /// Symmetrical. See if these two instructions are fit for duplex pair.
2165 bool HexagonInstrInfo::isDuplexPair(const MachineInstr &MIa,
2166       const MachineInstr &MIb) const {
2167   HexagonII::SubInstructionGroup MIaG = getDuplexCandidateGroup(MIa);
2168   HexagonII::SubInstructionGroup MIbG = getDuplexCandidateGroup(MIb);
2169   return (isDuplexPairMatch(MIaG, MIbG) || isDuplexPairMatch(MIbG, MIaG));
2170 }
2171 
2172 bool HexagonInstrInfo::isEarlySourceInstr(const MachineInstr &MI) const {
2173   if (MI.mayLoadOrStore() || MI.isCompare())
2174     return true;
2175 
2176   // Multiply
2177   unsigned SchedClass = MI.getDesc().getSchedClass();
2178   return is_TC4x(SchedClass) || is_TC3x(SchedClass);
2179 }
2180 
2181 bool HexagonInstrInfo::isEndLoopN(unsigned Opcode) const {
2182   return (Opcode == Hexagon::ENDLOOP0 ||
2183           Opcode == Hexagon::ENDLOOP1);
2184 }
2185 
2186 bool HexagonInstrInfo::isExpr(unsigned OpType) const {
2187   switch(OpType) {
2188   case MachineOperand::MO_MachineBasicBlock:
2189   case MachineOperand::MO_GlobalAddress:
2190   case MachineOperand::MO_ExternalSymbol:
2191   case MachineOperand::MO_JumpTableIndex:
2192   case MachineOperand::MO_ConstantPoolIndex:
2193   case MachineOperand::MO_BlockAddress:
2194     return true;
2195   default:
2196     return false;
2197   }
2198 }
2199 
2200 bool HexagonInstrInfo::isExtendable(const MachineInstr &MI) const {
2201   const MCInstrDesc &MID = MI.getDesc();
2202   const uint64_t F = MID.TSFlags;
2203   if ((F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask)
2204     return true;
2205 
2206   // TODO: This is largely obsolete now. Will need to be removed
2207   // in consecutive patches.
2208   switch (MI.getOpcode()) {
2209     // PS_fi and PS_fia remain special cases.
2210     case Hexagon::PS_fi:
2211     case Hexagon::PS_fia:
2212       return true;
2213     default:
2214       return false;
2215   }
2216   return  false;
2217 }
2218 
2219 // This returns true in two cases:
2220 // - The OP code itself indicates that this is an extended instruction.
2221 // - One of MOs has been marked with HMOTF_ConstExtended flag.
2222 bool HexagonInstrInfo::isExtended(const MachineInstr &MI) const {
2223   // First check if this is permanently extended op code.
2224   const uint64_t F = MI.getDesc().TSFlags;
2225   if ((F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask)
2226     return true;
2227   // Use MO operand flags to determine if one of MI's operands
2228   // has HMOTF_ConstExtended flag set.
2229   for (const MachineOperand &MO : MI.operands())
2230     if (MO.getTargetFlags() & HexagonII::HMOTF_ConstExtended)
2231       return true;
2232   return  false;
2233 }
2234 
2235 bool HexagonInstrInfo::isFloat(const MachineInstr &MI) const {
2236   unsigned Opcode = MI.getOpcode();
2237   const uint64_t F = get(Opcode).TSFlags;
2238   return (F >> HexagonII::FPPos) & HexagonII::FPMask;
2239 }
2240 
2241 // No V60 HVX VMEM with A_INDIRECT.
2242 bool HexagonInstrInfo::isHVXMemWithAIndirect(const MachineInstr &I,
2243       const MachineInstr &J) const {
2244   if (!isHVXVec(I))
2245     return false;
2246   if (!I.mayLoad() && !I.mayStore())
2247     return false;
2248   return J.isIndirectBranch() || isIndirectCall(J) || isIndirectL4Return(J);
2249 }
2250 
2251 bool HexagonInstrInfo::isIndirectCall(const MachineInstr &MI) const {
2252   switch (MI.getOpcode()) {
2253   case Hexagon::J2_callr:
2254   case Hexagon::J2_callrf:
2255   case Hexagon::J2_callrt:
2256   case Hexagon::PS_call_nr:
2257     return true;
2258   }
2259   return false;
2260 }
2261 
2262 bool HexagonInstrInfo::isIndirectL4Return(const MachineInstr &MI) const {
2263   switch (MI.getOpcode()) {
2264   case Hexagon::L4_return:
2265   case Hexagon::L4_return_t:
2266   case Hexagon::L4_return_f:
2267   case Hexagon::L4_return_fnew_pnt:
2268   case Hexagon::L4_return_fnew_pt:
2269   case Hexagon::L4_return_tnew_pnt:
2270   case Hexagon::L4_return_tnew_pt:
2271     return true;
2272   }
2273   return false;
2274 }
2275 
2276 bool HexagonInstrInfo::isJumpR(const MachineInstr &MI) const {
2277   switch (MI.getOpcode()) {
2278   case Hexagon::J2_jumpr:
2279   case Hexagon::J2_jumprt:
2280   case Hexagon::J2_jumprf:
2281   case Hexagon::J2_jumprtnewpt:
2282   case Hexagon::J2_jumprfnewpt:
2283   case Hexagon::J2_jumprtnew:
2284   case Hexagon::J2_jumprfnew:
2285     return true;
2286   }
2287   return false;
2288 }
2289 
2290 // Return true if a given MI can accommodate given offset.
2291 // Use abs estimate as oppose to the exact number.
2292 // TODO: This will need to be changed to use MC level
2293 // definition of instruction extendable field size.
2294 bool HexagonInstrInfo::isJumpWithinBranchRange(const MachineInstr &MI,
2295       unsigned offset) const {
2296   // This selection of jump instructions matches to that what
2297   // analyzeBranch can parse, plus NVJ.
2298   if (isNewValueJump(MI)) // r9:2
2299     return isInt<11>(offset);
2300 
2301   switch (MI.getOpcode()) {
2302   // Still missing Jump to address condition on register value.
2303   default:
2304     return false;
2305   case Hexagon::J2_jump: // bits<24> dst; // r22:2
2306   case Hexagon::J2_call:
2307   case Hexagon::PS_call_nr:
2308     return isInt<24>(offset);
2309   case Hexagon::J2_jumpt: //bits<17> dst; // r15:2
2310   case Hexagon::J2_jumpf:
2311   case Hexagon::J2_jumptnew:
2312   case Hexagon::J2_jumptnewpt:
2313   case Hexagon::J2_jumpfnew:
2314   case Hexagon::J2_jumpfnewpt:
2315   case Hexagon::J2_callt:
2316   case Hexagon::J2_callf:
2317     return isInt<17>(offset);
2318   case Hexagon::J2_loop0i:
2319   case Hexagon::J2_loop0iext:
2320   case Hexagon::J2_loop0r:
2321   case Hexagon::J2_loop0rext:
2322   case Hexagon::J2_loop1i:
2323   case Hexagon::J2_loop1iext:
2324   case Hexagon::J2_loop1r:
2325   case Hexagon::J2_loop1rext:
2326     return isInt<9>(offset);
2327   // TODO: Add all the compound branches here. Can we do this in Relation model?
2328   case Hexagon::J4_cmpeqi_tp0_jump_nt:
2329   case Hexagon::J4_cmpeqi_tp1_jump_nt:
2330   case Hexagon::J4_cmpeqn1_tp0_jump_nt:
2331   case Hexagon::J4_cmpeqn1_tp1_jump_nt:
2332     return isInt<11>(offset);
2333   }
2334 }
2335 
2336 bool HexagonInstrInfo::isLateInstrFeedsEarlyInstr(const MachineInstr &LRMI,
2337       const MachineInstr &ESMI) const {
2338   bool isLate = isLateResultInstr(LRMI);
2339   bool isEarly = isEarlySourceInstr(ESMI);
2340 
2341   LLVM_DEBUG(dbgs() << "V60" << (isLate ? "-LR  " : " --  "));
2342   LLVM_DEBUG(LRMI.dump());
2343   LLVM_DEBUG(dbgs() << "V60" << (isEarly ? "-ES  " : " --  "));
2344   LLVM_DEBUG(ESMI.dump());
2345 
2346   if (isLate && isEarly) {
2347     LLVM_DEBUG(dbgs() << "++Is Late Result feeding Early Source\n");
2348     return true;
2349   }
2350 
2351   return false;
2352 }
2353 
2354 bool HexagonInstrInfo::isLateResultInstr(const MachineInstr &MI) const {
2355   switch (MI.getOpcode()) {
2356   case TargetOpcode::EXTRACT_SUBREG:
2357   case TargetOpcode::INSERT_SUBREG:
2358   case TargetOpcode::SUBREG_TO_REG:
2359   case TargetOpcode::REG_SEQUENCE:
2360   case TargetOpcode::IMPLICIT_DEF:
2361   case TargetOpcode::COPY:
2362   case TargetOpcode::INLINEASM:
2363   case TargetOpcode::PHI:
2364     return false;
2365   default:
2366     break;
2367   }
2368 
2369   unsigned SchedClass = MI.getDesc().getSchedClass();
2370   return !is_TC1(SchedClass);
2371 }
2372 
2373 bool HexagonInstrInfo::isLateSourceInstr(const MachineInstr &MI) const {
2374   // Instructions with iclass A_CVI_VX and attribute A_CVI_LATE uses a multiply
2375   // resource, but all operands can be received late like an ALU instruction.
2376   return getType(MI) == HexagonII::TypeCVI_VX_LATE;
2377 }
2378 
2379 bool HexagonInstrInfo::isLoopN(const MachineInstr &MI) const {
2380   unsigned Opcode = MI.getOpcode();
2381   return Opcode == Hexagon::J2_loop0i    ||
2382          Opcode == Hexagon::J2_loop0r    ||
2383          Opcode == Hexagon::J2_loop0iext ||
2384          Opcode == Hexagon::J2_loop0rext ||
2385          Opcode == Hexagon::J2_loop1i    ||
2386          Opcode == Hexagon::J2_loop1r    ||
2387          Opcode == Hexagon::J2_loop1iext ||
2388          Opcode == Hexagon::J2_loop1rext;
2389 }
2390 
2391 bool HexagonInstrInfo::isMemOp(const MachineInstr &MI) const {
2392   switch (MI.getOpcode()) {
2393     default: return false;
2394     case Hexagon::L4_iadd_memopw_io:
2395     case Hexagon::L4_isub_memopw_io:
2396     case Hexagon::L4_add_memopw_io:
2397     case Hexagon::L4_sub_memopw_io:
2398     case Hexagon::L4_and_memopw_io:
2399     case Hexagon::L4_or_memopw_io:
2400     case Hexagon::L4_iadd_memoph_io:
2401     case Hexagon::L4_isub_memoph_io:
2402     case Hexagon::L4_add_memoph_io:
2403     case Hexagon::L4_sub_memoph_io:
2404     case Hexagon::L4_and_memoph_io:
2405     case Hexagon::L4_or_memoph_io:
2406     case Hexagon::L4_iadd_memopb_io:
2407     case Hexagon::L4_isub_memopb_io:
2408     case Hexagon::L4_add_memopb_io:
2409     case Hexagon::L4_sub_memopb_io:
2410     case Hexagon::L4_and_memopb_io:
2411     case Hexagon::L4_or_memopb_io:
2412     case Hexagon::L4_ior_memopb_io:
2413     case Hexagon::L4_ior_memoph_io:
2414     case Hexagon::L4_ior_memopw_io:
2415     case Hexagon::L4_iand_memopb_io:
2416     case Hexagon::L4_iand_memoph_io:
2417     case Hexagon::L4_iand_memopw_io:
2418     return true;
2419   }
2420   return false;
2421 }
2422 
2423 bool HexagonInstrInfo::isNewValue(const MachineInstr &MI) const {
2424   const uint64_t F = MI.getDesc().TSFlags;
2425   return (F >> HexagonII::NewValuePos) & HexagonII::NewValueMask;
2426 }
2427 
2428 bool HexagonInstrInfo::isNewValue(unsigned Opcode) const {
2429   const uint64_t F = get(Opcode).TSFlags;
2430   return (F >> HexagonII::NewValuePos) & HexagonII::NewValueMask;
2431 }
2432 
2433 bool HexagonInstrInfo::isNewValueInst(const MachineInstr &MI) const {
2434   return isNewValueJump(MI) || isNewValueStore(MI);
2435 }
2436 
2437 bool HexagonInstrInfo::isNewValueJump(const MachineInstr &MI) const {
2438   return isNewValue(MI) && MI.isBranch();
2439 }
2440 
2441 bool HexagonInstrInfo::isNewValueJump(unsigned Opcode) const {
2442   return isNewValue(Opcode) && get(Opcode).isBranch() && isPredicated(Opcode);
2443 }
2444 
2445 bool HexagonInstrInfo::isNewValueStore(const MachineInstr &MI) const {
2446   const uint64_t F = MI.getDesc().TSFlags;
2447   return (F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask;
2448 }
2449 
2450 bool HexagonInstrInfo::isNewValueStore(unsigned Opcode) const {
2451   const uint64_t F = get(Opcode).TSFlags;
2452   return (F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask;
2453 }
2454 
2455 // Returns true if a particular operand is extendable for an instruction.
2456 bool HexagonInstrInfo::isOperandExtended(const MachineInstr &MI,
2457     unsigned OperandNum) const {
2458   const uint64_t F = MI.getDesc().TSFlags;
2459   return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask)
2460           == OperandNum;
2461 }
2462 
2463 bool HexagonInstrInfo::isPredicatedNew(const MachineInstr &MI) const {
2464   const uint64_t F = MI.getDesc().TSFlags;
2465   assert(isPredicated(MI));
2466   return (F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask;
2467 }
2468 
2469 bool HexagonInstrInfo::isPredicatedNew(unsigned Opcode) const {
2470   const uint64_t F = get(Opcode).TSFlags;
2471   assert(isPredicated(Opcode));
2472   return (F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask;
2473 }
2474 
2475 bool HexagonInstrInfo::isPredicatedTrue(const MachineInstr &MI) const {
2476   const uint64_t F = MI.getDesc().TSFlags;
2477   return !((F >> HexagonII::PredicatedFalsePos) &
2478            HexagonII::PredicatedFalseMask);
2479 }
2480 
2481 bool HexagonInstrInfo::isPredicatedTrue(unsigned Opcode) const {
2482   const uint64_t F = get(Opcode).TSFlags;
2483   // Make sure that the instruction is predicated.
2484   assert((F>> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
2485   return !((F >> HexagonII::PredicatedFalsePos) &
2486            HexagonII::PredicatedFalseMask);
2487 }
2488 
2489 bool HexagonInstrInfo::isPredicated(unsigned Opcode) const {
2490   const uint64_t F = get(Opcode).TSFlags;
2491   return (F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask;
2492 }
2493 
2494 bool HexagonInstrInfo::isPredicateLate(unsigned Opcode) const {
2495   const uint64_t F = get(Opcode).TSFlags;
2496   return (F >> HexagonII::PredicateLatePos) & HexagonII::PredicateLateMask;
2497 }
2498 
2499 bool HexagonInstrInfo::isPredictedTaken(unsigned Opcode) const {
2500   const uint64_t F = get(Opcode).TSFlags;
2501   assert(get(Opcode).isBranch() &&
2502          (isPredicatedNew(Opcode) || isNewValue(Opcode)));
2503   return (F >> HexagonII::TakenPos) & HexagonII::TakenMask;
2504 }
2505 
2506 bool HexagonInstrInfo::isSaveCalleeSavedRegsCall(const MachineInstr &MI) const {
2507   return MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4 ||
2508          MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4_EXT ||
2509          MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4_PIC ||
2510          MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC;
2511 }
2512 
2513 bool HexagonInstrInfo::isSignExtendingLoad(const MachineInstr &MI) const {
2514   switch (MI.getOpcode()) {
2515   // Byte
2516   case Hexagon::L2_loadrb_io:
2517   case Hexagon::L4_loadrb_ur:
2518   case Hexagon::L4_loadrb_ap:
2519   case Hexagon::L2_loadrb_pr:
2520   case Hexagon::L2_loadrb_pbr:
2521   case Hexagon::L2_loadrb_pi:
2522   case Hexagon::L2_loadrb_pci:
2523   case Hexagon::L2_loadrb_pcr:
2524   case Hexagon::L2_loadbsw2_io:
2525   case Hexagon::L4_loadbsw2_ur:
2526   case Hexagon::L4_loadbsw2_ap:
2527   case Hexagon::L2_loadbsw2_pr:
2528   case Hexagon::L2_loadbsw2_pbr:
2529   case Hexagon::L2_loadbsw2_pi:
2530   case Hexagon::L2_loadbsw2_pci:
2531   case Hexagon::L2_loadbsw2_pcr:
2532   case Hexagon::L2_loadbsw4_io:
2533   case Hexagon::L4_loadbsw4_ur:
2534   case Hexagon::L4_loadbsw4_ap:
2535   case Hexagon::L2_loadbsw4_pr:
2536   case Hexagon::L2_loadbsw4_pbr:
2537   case Hexagon::L2_loadbsw4_pi:
2538   case Hexagon::L2_loadbsw4_pci:
2539   case Hexagon::L2_loadbsw4_pcr:
2540   case Hexagon::L4_loadrb_rr:
2541   case Hexagon::L2_ploadrbt_io:
2542   case Hexagon::L2_ploadrbt_pi:
2543   case Hexagon::L2_ploadrbf_io:
2544   case Hexagon::L2_ploadrbf_pi:
2545   case Hexagon::L2_ploadrbtnew_io:
2546   case Hexagon::L2_ploadrbfnew_io:
2547   case Hexagon::L4_ploadrbt_rr:
2548   case Hexagon::L4_ploadrbf_rr:
2549   case Hexagon::L4_ploadrbtnew_rr:
2550   case Hexagon::L4_ploadrbfnew_rr:
2551   case Hexagon::L2_ploadrbtnew_pi:
2552   case Hexagon::L2_ploadrbfnew_pi:
2553   case Hexagon::L4_ploadrbt_abs:
2554   case Hexagon::L4_ploadrbf_abs:
2555   case Hexagon::L4_ploadrbtnew_abs:
2556   case Hexagon::L4_ploadrbfnew_abs:
2557   case Hexagon::L2_loadrbgp:
2558   // Half
2559   case Hexagon::L2_loadrh_io:
2560   case Hexagon::L4_loadrh_ur:
2561   case Hexagon::L4_loadrh_ap:
2562   case Hexagon::L2_loadrh_pr:
2563   case Hexagon::L2_loadrh_pbr:
2564   case Hexagon::L2_loadrh_pi:
2565   case Hexagon::L2_loadrh_pci:
2566   case Hexagon::L2_loadrh_pcr:
2567   case Hexagon::L4_loadrh_rr:
2568   case Hexagon::L2_ploadrht_io:
2569   case Hexagon::L2_ploadrht_pi:
2570   case Hexagon::L2_ploadrhf_io:
2571   case Hexagon::L2_ploadrhf_pi:
2572   case Hexagon::L2_ploadrhtnew_io:
2573   case Hexagon::L2_ploadrhfnew_io:
2574   case Hexagon::L4_ploadrht_rr:
2575   case Hexagon::L4_ploadrhf_rr:
2576   case Hexagon::L4_ploadrhtnew_rr:
2577   case Hexagon::L4_ploadrhfnew_rr:
2578   case Hexagon::L2_ploadrhtnew_pi:
2579   case Hexagon::L2_ploadrhfnew_pi:
2580   case Hexagon::L4_ploadrht_abs:
2581   case Hexagon::L4_ploadrhf_abs:
2582   case Hexagon::L4_ploadrhtnew_abs:
2583   case Hexagon::L4_ploadrhfnew_abs:
2584   case Hexagon::L2_loadrhgp:
2585     return true;
2586   default:
2587     return false;
2588   }
2589 }
2590 
2591 bool HexagonInstrInfo::isSolo(const MachineInstr &MI) const {
2592   const uint64_t F = MI.getDesc().TSFlags;
2593   return (F >> HexagonII::SoloPos) & HexagonII::SoloMask;
2594 }
2595 
2596 bool HexagonInstrInfo::isSpillPredRegOp(const MachineInstr &MI) const {
2597   switch (MI.getOpcode()) {
2598   case Hexagon::STriw_pred:
2599   case Hexagon::LDriw_pred:
2600     return true;
2601   default:
2602     return false;
2603   }
2604 }
2605 
2606 bool HexagonInstrInfo::isTailCall(const MachineInstr &MI) const {
2607   if (!MI.isBranch())
2608     return false;
2609 
2610   for (auto &Op : MI.operands())
2611     if (Op.isGlobal() || Op.isSymbol())
2612       return true;
2613   return false;
2614 }
2615 
2616 // Returns true when SU has a timing class TC1.
2617 bool HexagonInstrInfo::isTC1(const MachineInstr &MI) const {
2618   unsigned SchedClass = MI.getDesc().getSchedClass();
2619   return is_TC1(SchedClass);
2620 }
2621 
2622 bool HexagonInstrInfo::isTC2(const MachineInstr &MI) const {
2623   unsigned SchedClass = MI.getDesc().getSchedClass();
2624   return is_TC2(SchedClass);
2625 }
2626 
2627 bool HexagonInstrInfo::isTC2Early(const MachineInstr &MI) const {
2628   unsigned SchedClass = MI.getDesc().getSchedClass();
2629   return is_TC2early(SchedClass);
2630 }
2631 
2632 bool HexagonInstrInfo::isTC4x(const MachineInstr &MI) const {
2633   unsigned SchedClass = MI.getDesc().getSchedClass();
2634   return is_TC4x(SchedClass);
2635 }
2636 
2637 // Schedule this ASAP.
2638 bool HexagonInstrInfo::isToBeScheduledASAP(const MachineInstr &MI1,
2639       const MachineInstr &MI2) const {
2640   if (mayBeCurLoad(MI1)) {
2641     // if (result of SU is used in Next) return true;
2642     Register DstReg = MI1.getOperand(0).getReg();
2643     int N = MI2.getNumOperands();
2644     for (int I = 0; I < N; I++)
2645       if (MI2.getOperand(I).isReg() && DstReg == MI2.getOperand(I).getReg())
2646         return true;
2647   }
2648   if (mayBeNewStore(MI2))
2649     if (MI2.getOpcode() == Hexagon::V6_vS32b_pi)
2650       if (MI1.getOperand(0).isReg() && MI2.getOperand(3).isReg() &&
2651           MI1.getOperand(0).getReg() == MI2.getOperand(3).getReg())
2652         return true;
2653   return false;
2654 }
2655 
2656 bool HexagonInstrInfo::isHVXVec(const MachineInstr &MI) const {
2657   const uint64_t V = getType(MI);
2658   return HexagonII::TypeCVI_FIRST <= V && V <= HexagonII::TypeCVI_LAST;
2659 }
2660 
2661 // Check if the Offset is a valid auto-inc imm by Load/Store Type.
2662 bool HexagonInstrInfo::isValidAutoIncImm(const EVT VT, int Offset) const {
2663   int Size = VT.getSizeInBits() / 8;
2664   if (Offset % Size != 0)
2665     return false;
2666   int Count = Offset / Size;
2667 
2668   switch (VT.getSimpleVT().SimpleTy) {
2669     // For scalars the auto-inc is s4
2670     case MVT::i8:
2671     case MVT::i16:
2672     case MVT::i32:
2673     case MVT::i64:
2674     case MVT::f32:
2675     case MVT::f64:
2676     case MVT::v2i16:
2677     case MVT::v2i32:
2678     case MVT::v4i8:
2679     case MVT::v4i16:
2680     case MVT::v8i8:
2681       return isInt<4>(Count);
2682     // For HVX vectors the auto-inc is s3
2683     case MVT::v64i8:
2684     case MVT::v32i16:
2685     case MVT::v16i32:
2686     case MVT::v8i64:
2687     case MVT::v128i8:
2688     case MVT::v64i16:
2689     case MVT::v32i32:
2690     case MVT::v16i64:
2691       return isInt<3>(Count);
2692     default:
2693       break;
2694   }
2695 
2696   llvm_unreachable("Not an valid type!");
2697 }
2698 
2699 bool HexagonInstrInfo::isValidOffset(unsigned Opcode, int Offset,
2700       const TargetRegisterInfo *TRI, bool Extend) const {
2701   // This function is to check whether the "Offset" is in the correct range of
2702   // the given "Opcode". If "Offset" is not in the correct range, "A2_addi" is
2703   // inserted to calculate the final address. Due to this reason, the function
2704   // assumes that the "Offset" has correct alignment.
2705   // We used to assert if the offset was not properly aligned, however,
2706   // there are cases where a misaligned pointer recast can cause this
2707   // problem, and we need to allow for it. The front end warns of such
2708   // misaligns with respect to load size.
2709   switch (Opcode) {
2710   case Hexagon::PS_vstorerq_ai:
2711   case Hexagon::PS_vstorerv_ai:
2712   case Hexagon::PS_vstorerw_ai:
2713   case Hexagon::PS_vstorerw_nt_ai:
2714   case Hexagon::PS_vloadrq_ai:
2715   case Hexagon::PS_vloadrv_ai:
2716   case Hexagon::PS_vloadrw_ai:
2717   case Hexagon::PS_vloadrw_nt_ai:
2718   case Hexagon::V6_vL32b_ai:
2719   case Hexagon::V6_vS32b_ai:
2720   case Hexagon::V6_vL32b_nt_ai:
2721   case Hexagon::V6_vS32b_nt_ai:
2722   case Hexagon::V6_vL32Ub_ai:
2723   case Hexagon::V6_vS32Ub_ai: {
2724     unsigned VectorSize = TRI->getSpillSize(Hexagon::HvxVRRegClass);
2725     assert(isPowerOf2_32(VectorSize));
2726     if (Offset & (VectorSize-1))
2727       return false;
2728     return isInt<4>(Offset >> Log2_32(VectorSize));
2729   }
2730 
2731   case Hexagon::J2_loop0i:
2732   case Hexagon::J2_loop1i:
2733     return isUInt<10>(Offset);
2734 
2735   case Hexagon::S4_storeirb_io:
2736   case Hexagon::S4_storeirbt_io:
2737   case Hexagon::S4_storeirbf_io:
2738     return isUInt<6>(Offset);
2739 
2740   case Hexagon::S4_storeirh_io:
2741   case Hexagon::S4_storeirht_io:
2742   case Hexagon::S4_storeirhf_io:
2743     return isShiftedUInt<6,1>(Offset);
2744 
2745   case Hexagon::S4_storeiri_io:
2746   case Hexagon::S4_storeirit_io:
2747   case Hexagon::S4_storeirif_io:
2748     return isShiftedUInt<6,2>(Offset);
2749   }
2750 
2751   if (Extend)
2752     return true;
2753 
2754   switch (Opcode) {
2755   case Hexagon::L2_loadri_io:
2756   case Hexagon::S2_storeri_io:
2757     return (Offset >= Hexagon_MEMW_OFFSET_MIN) &&
2758       (Offset <= Hexagon_MEMW_OFFSET_MAX);
2759 
2760   case Hexagon::L2_loadrd_io:
2761   case Hexagon::S2_storerd_io:
2762     return (Offset >= Hexagon_MEMD_OFFSET_MIN) &&
2763       (Offset <= Hexagon_MEMD_OFFSET_MAX);
2764 
2765   case Hexagon::L2_loadrh_io:
2766   case Hexagon::L2_loadruh_io:
2767   case Hexagon::S2_storerh_io:
2768   case Hexagon::S2_storerf_io:
2769     return (Offset >= Hexagon_MEMH_OFFSET_MIN) &&
2770       (Offset <= Hexagon_MEMH_OFFSET_MAX);
2771 
2772   case Hexagon::L2_loadrb_io:
2773   case Hexagon::L2_loadrub_io:
2774   case Hexagon::S2_storerb_io:
2775     return (Offset >= Hexagon_MEMB_OFFSET_MIN) &&
2776       (Offset <= Hexagon_MEMB_OFFSET_MAX);
2777 
2778   case Hexagon::A2_addi:
2779     return (Offset >= Hexagon_ADDI_OFFSET_MIN) &&
2780       (Offset <= Hexagon_ADDI_OFFSET_MAX);
2781 
2782   case Hexagon::L4_iadd_memopw_io:
2783   case Hexagon::L4_isub_memopw_io:
2784   case Hexagon::L4_add_memopw_io:
2785   case Hexagon::L4_sub_memopw_io:
2786   case Hexagon::L4_and_memopw_io:
2787   case Hexagon::L4_or_memopw_io:
2788     return (0 <= Offset && Offset <= 255);
2789 
2790   case Hexagon::L4_iadd_memoph_io:
2791   case Hexagon::L4_isub_memoph_io:
2792   case Hexagon::L4_add_memoph_io:
2793   case Hexagon::L4_sub_memoph_io:
2794   case Hexagon::L4_and_memoph_io:
2795   case Hexagon::L4_or_memoph_io:
2796     return (0 <= Offset && Offset <= 127);
2797 
2798   case Hexagon::L4_iadd_memopb_io:
2799   case Hexagon::L4_isub_memopb_io:
2800   case Hexagon::L4_add_memopb_io:
2801   case Hexagon::L4_sub_memopb_io:
2802   case Hexagon::L4_and_memopb_io:
2803   case Hexagon::L4_or_memopb_io:
2804     return (0 <= Offset && Offset <= 63);
2805 
2806   // LDriw_xxx and STriw_xxx are pseudo operations, so it has to take offset of
2807   // any size. Later pass knows how to handle it.
2808   case Hexagon::STriw_pred:
2809   case Hexagon::LDriw_pred:
2810   case Hexagon::STriw_ctr:
2811   case Hexagon::LDriw_ctr:
2812     return true;
2813 
2814   case Hexagon::PS_fi:
2815   case Hexagon::PS_fia:
2816   case Hexagon::INLINEASM:
2817     return true;
2818 
2819   case Hexagon::L2_ploadrbt_io:
2820   case Hexagon::L2_ploadrbf_io:
2821   case Hexagon::L2_ploadrubt_io:
2822   case Hexagon::L2_ploadrubf_io:
2823   case Hexagon::S2_pstorerbt_io:
2824   case Hexagon::S2_pstorerbf_io:
2825     return isUInt<6>(Offset);
2826 
2827   case Hexagon::L2_ploadrht_io:
2828   case Hexagon::L2_ploadrhf_io:
2829   case Hexagon::L2_ploadruht_io:
2830   case Hexagon::L2_ploadruhf_io:
2831   case Hexagon::S2_pstorerht_io:
2832   case Hexagon::S2_pstorerhf_io:
2833     return isShiftedUInt<6,1>(Offset);
2834 
2835   case Hexagon::L2_ploadrit_io:
2836   case Hexagon::L2_ploadrif_io:
2837   case Hexagon::S2_pstorerit_io:
2838   case Hexagon::S2_pstorerif_io:
2839     return isShiftedUInt<6,2>(Offset);
2840 
2841   case Hexagon::L2_ploadrdt_io:
2842   case Hexagon::L2_ploadrdf_io:
2843   case Hexagon::S2_pstorerdt_io:
2844   case Hexagon::S2_pstorerdf_io:
2845     return isShiftedUInt<6,3>(Offset);
2846   } // switch
2847 
2848   llvm_unreachable("No offset range is defined for this opcode. "
2849                    "Please define it in the above switch statement!");
2850 }
2851 
2852 bool HexagonInstrInfo::isVecAcc(const MachineInstr &MI) const {
2853   return isHVXVec(MI) && isAccumulator(MI);
2854 }
2855 
2856 bool HexagonInstrInfo::isVecALU(const MachineInstr &MI) const {
2857   const uint64_t F = get(MI.getOpcode()).TSFlags;
2858   const uint64_t V = ((F >> HexagonII::TypePos) & HexagonII::TypeMask);
2859   return
2860     V == HexagonII::TypeCVI_VA         ||
2861     V == HexagonII::TypeCVI_VA_DV;
2862 }
2863 
2864 bool HexagonInstrInfo::isVecUsableNextPacket(const MachineInstr &ProdMI,
2865       const MachineInstr &ConsMI) const {
2866   if (EnableACCForwarding && isVecAcc(ProdMI) && isVecAcc(ConsMI))
2867     return true;
2868 
2869   if (EnableALUForwarding && (isVecALU(ConsMI) || isLateSourceInstr(ConsMI)))
2870     return true;
2871 
2872   if (mayBeNewStore(ConsMI))
2873     return true;
2874 
2875   return false;
2876 }
2877 
2878 bool HexagonInstrInfo::isZeroExtendingLoad(const MachineInstr &MI) const {
2879   switch (MI.getOpcode()) {
2880   // Byte
2881   case Hexagon::L2_loadrub_io:
2882   case Hexagon::L4_loadrub_ur:
2883   case Hexagon::L4_loadrub_ap:
2884   case Hexagon::L2_loadrub_pr:
2885   case Hexagon::L2_loadrub_pbr:
2886   case Hexagon::L2_loadrub_pi:
2887   case Hexagon::L2_loadrub_pci:
2888   case Hexagon::L2_loadrub_pcr:
2889   case Hexagon::L2_loadbzw2_io:
2890   case Hexagon::L4_loadbzw2_ur:
2891   case Hexagon::L4_loadbzw2_ap:
2892   case Hexagon::L2_loadbzw2_pr:
2893   case Hexagon::L2_loadbzw2_pbr:
2894   case Hexagon::L2_loadbzw2_pi:
2895   case Hexagon::L2_loadbzw2_pci:
2896   case Hexagon::L2_loadbzw2_pcr:
2897   case Hexagon::L2_loadbzw4_io:
2898   case Hexagon::L4_loadbzw4_ur:
2899   case Hexagon::L4_loadbzw4_ap:
2900   case Hexagon::L2_loadbzw4_pr:
2901   case Hexagon::L2_loadbzw4_pbr:
2902   case Hexagon::L2_loadbzw4_pi:
2903   case Hexagon::L2_loadbzw4_pci:
2904   case Hexagon::L2_loadbzw4_pcr:
2905   case Hexagon::L4_loadrub_rr:
2906   case Hexagon::L2_ploadrubt_io:
2907   case Hexagon::L2_ploadrubt_pi:
2908   case Hexagon::L2_ploadrubf_io:
2909   case Hexagon::L2_ploadrubf_pi:
2910   case Hexagon::L2_ploadrubtnew_io:
2911   case Hexagon::L2_ploadrubfnew_io:
2912   case Hexagon::L4_ploadrubt_rr:
2913   case Hexagon::L4_ploadrubf_rr:
2914   case Hexagon::L4_ploadrubtnew_rr:
2915   case Hexagon::L4_ploadrubfnew_rr:
2916   case Hexagon::L2_ploadrubtnew_pi:
2917   case Hexagon::L2_ploadrubfnew_pi:
2918   case Hexagon::L4_ploadrubt_abs:
2919   case Hexagon::L4_ploadrubf_abs:
2920   case Hexagon::L4_ploadrubtnew_abs:
2921   case Hexagon::L4_ploadrubfnew_abs:
2922   case Hexagon::L2_loadrubgp:
2923   // Half
2924   case Hexagon::L2_loadruh_io:
2925   case Hexagon::L4_loadruh_ur:
2926   case Hexagon::L4_loadruh_ap:
2927   case Hexagon::L2_loadruh_pr:
2928   case Hexagon::L2_loadruh_pbr:
2929   case Hexagon::L2_loadruh_pi:
2930   case Hexagon::L2_loadruh_pci:
2931   case Hexagon::L2_loadruh_pcr:
2932   case Hexagon::L4_loadruh_rr:
2933   case Hexagon::L2_ploadruht_io:
2934   case Hexagon::L2_ploadruht_pi:
2935   case Hexagon::L2_ploadruhf_io:
2936   case Hexagon::L2_ploadruhf_pi:
2937   case Hexagon::L2_ploadruhtnew_io:
2938   case Hexagon::L2_ploadruhfnew_io:
2939   case Hexagon::L4_ploadruht_rr:
2940   case Hexagon::L4_ploadruhf_rr:
2941   case Hexagon::L4_ploadruhtnew_rr:
2942   case Hexagon::L4_ploadruhfnew_rr:
2943   case Hexagon::L2_ploadruhtnew_pi:
2944   case Hexagon::L2_ploadruhfnew_pi:
2945   case Hexagon::L4_ploadruht_abs:
2946   case Hexagon::L4_ploadruhf_abs:
2947   case Hexagon::L4_ploadruhtnew_abs:
2948   case Hexagon::L4_ploadruhfnew_abs:
2949   case Hexagon::L2_loadruhgp:
2950     return true;
2951   default:
2952     return false;
2953   }
2954 }
2955 
2956 // Add latency to instruction.
2957 bool HexagonInstrInfo::addLatencyToSchedule(const MachineInstr &MI1,
2958       const MachineInstr &MI2) const {
2959   if (isHVXVec(MI1) && isHVXVec(MI2))
2960     if (!isVecUsableNextPacket(MI1, MI2))
2961       return true;
2962   return false;
2963 }
2964 
2965 /// Get the base register and byte offset of a load/store instr.
2966 bool HexagonInstrInfo::getMemOperandsWithOffset(
2967     const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
2968     int64_t &Offset, bool &OffsetIsScalable, const TargetRegisterInfo *TRI) const {
2969   unsigned AccessSize = 0;
2970   OffsetIsScalable = false;
2971   const MachineOperand *BaseOp = getBaseAndOffset(LdSt, Offset, AccessSize);
2972   if (!BaseOp || !BaseOp->isReg())
2973     return false;
2974   BaseOps.push_back(BaseOp);
2975   return true;
2976 }
2977 
2978 /// Can these instructions execute at the same time in a bundle.
2979 bool HexagonInstrInfo::canExecuteInBundle(const MachineInstr &First,
2980       const MachineInstr &Second) const {
2981   if (Second.mayStore() && First.getOpcode() == Hexagon::S2_allocframe) {
2982     const MachineOperand &Op = Second.getOperand(0);
2983     if (Op.isReg() && Op.isUse() && Op.getReg() == Hexagon::R29)
2984       return true;
2985   }
2986   if (DisableNVSchedule)
2987     return false;
2988   if (mayBeNewStore(Second)) {
2989     // Make sure the definition of the first instruction is the value being
2990     // stored.
2991     const MachineOperand &Stored =
2992       Second.getOperand(Second.getNumOperands() - 1);
2993     if (!Stored.isReg())
2994       return false;
2995     for (unsigned i = 0, e = First.getNumOperands(); i < e; ++i) {
2996       const MachineOperand &Op = First.getOperand(i);
2997       if (Op.isReg() && Op.isDef() && Op.getReg() == Stored.getReg())
2998         return true;
2999     }
3000   }
3001   return false;
3002 }
3003 
3004 bool HexagonInstrInfo::doesNotReturn(const MachineInstr &CallMI) const {
3005   unsigned Opc = CallMI.getOpcode();
3006   return Opc == Hexagon::PS_call_nr || Opc == Hexagon::PS_callr_nr;
3007 }
3008 
3009 bool HexagonInstrInfo::hasEHLabel(const MachineBasicBlock *B) const {
3010   for (auto &I : *B)
3011     if (I.isEHLabel())
3012       return true;
3013   return false;
3014 }
3015 
3016 // Returns true if an instruction can be converted into a non-extended
3017 // equivalent instruction.
3018 bool HexagonInstrInfo::hasNonExtEquivalent(const MachineInstr &MI) const {
3019   short NonExtOpcode;
3020   // Check if the instruction has a register form that uses register in place
3021   // of the extended operand, if so return that as the non-extended form.
3022   if (Hexagon::getRegForm(MI.getOpcode()) >= 0)
3023     return true;
3024 
3025   if (MI.getDesc().mayLoad() || MI.getDesc().mayStore()) {
3026     // Check addressing mode and retrieve non-ext equivalent instruction.
3027 
3028     switch (getAddrMode(MI)) {
3029     case HexagonII::Absolute:
3030       // Load/store with absolute addressing mode can be converted into
3031       // base+offset mode.
3032       NonExtOpcode = Hexagon::changeAddrMode_abs_io(MI.getOpcode());
3033       break;
3034     case HexagonII::BaseImmOffset:
3035       // Load/store with base+offset addressing mode can be converted into
3036       // base+register offset addressing mode. However left shift operand should
3037       // be set to 0.
3038       NonExtOpcode = Hexagon::changeAddrMode_io_rr(MI.getOpcode());
3039       break;
3040     case HexagonII::BaseLongOffset:
3041       NonExtOpcode = Hexagon::changeAddrMode_ur_rr(MI.getOpcode());
3042       break;
3043     default:
3044       return false;
3045     }
3046     if (NonExtOpcode < 0)
3047       return false;
3048     return true;
3049   }
3050   return false;
3051 }
3052 
3053 bool HexagonInstrInfo::hasPseudoInstrPair(const MachineInstr &MI) const {
3054   return Hexagon::getRealHWInstr(MI.getOpcode(),
3055                                  Hexagon::InstrType_Pseudo) >= 0;
3056 }
3057 
3058 bool HexagonInstrInfo::hasUncondBranch(const MachineBasicBlock *B)
3059       const {
3060   MachineBasicBlock::const_iterator I = B->getFirstTerminator(), E = B->end();
3061   while (I != E) {
3062     if (I->isBarrier())
3063       return true;
3064     ++I;
3065   }
3066   return false;
3067 }
3068 
3069 // Returns true, if a LD insn can be promoted to a cur load.
3070 bool HexagonInstrInfo::mayBeCurLoad(const MachineInstr &MI) const {
3071   const uint64_t F = MI.getDesc().TSFlags;
3072   return ((F >> HexagonII::mayCVLoadPos) & HexagonII::mayCVLoadMask) &&
3073          Subtarget.hasV60Ops();
3074 }
3075 
3076 // Returns true, if a ST insn can be promoted to a new-value store.
3077 bool HexagonInstrInfo::mayBeNewStore(const MachineInstr &MI) const {
3078   if (MI.mayStore() && !Subtarget.useNewValueStores())
3079     return false;
3080 
3081   const uint64_t F = MI.getDesc().TSFlags;
3082   return (F >> HexagonII::mayNVStorePos) & HexagonII::mayNVStoreMask;
3083 }
3084 
3085 bool HexagonInstrInfo::producesStall(const MachineInstr &ProdMI,
3086       const MachineInstr &ConsMI) const {
3087   // There is no stall when ProdMI is not a V60 vector.
3088   if (!isHVXVec(ProdMI))
3089     return false;
3090 
3091   // There is no stall when ProdMI and ConsMI are not dependent.
3092   if (!isDependent(ProdMI, ConsMI))
3093     return false;
3094 
3095   // When Forward Scheduling is enabled, there is no stall if ProdMI and ConsMI
3096   // are scheduled in consecutive packets.
3097   if (isVecUsableNextPacket(ProdMI, ConsMI))
3098     return false;
3099 
3100   return true;
3101 }
3102 
3103 bool HexagonInstrInfo::producesStall(const MachineInstr &MI,
3104       MachineBasicBlock::const_instr_iterator BII) const {
3105   // There is no stall when I is not a V60 vector.
3106   if (!isHVXVec(MI))
3107     return false;
3108 
3109   MachineBasicBlock::const_instr_iterator MII = BII;
3110   MachineBasicBlock::const_instr_iterator MIE = MII->getParent()->instr_end();
3111 
3112   if (!MII->isBundle())
3113     return producesStall(*MII, MI);
3114 
3115   for (++MII; MII != MIE && MII->isInsideBundle(); ++MII) {
3116     const MachineInstr &J = *MII;
3117     if (producesStall(J, MI))
3118       return true;
3119   }
3120   return false;
3121 }
3122 
3123 bool HexagonInstrInfo::predCanBeUsedAsDotNew(const MachineInstr &MI,
3124       unsigned PredReg) const {
3125   for (const MachineOperand &MO : MI.operands()) {
3126     // Predicate register must be explicitly defined.
3127     if (MO.isRegMask() && MO.clobbersPhysReg(PredReg))
3128       return false;
3129     if (MO.isReg() && MO.isDef() && MO.isImplicit() && (MO.getReg() == PredReg))
3130       return false;
3131   }
3132 
3133   // Instruction that produce late predicate cannot be used as sources of
3134   // dot-new.
3135   switch (MI.getOpcode()) {
3136     case Hexagon::A4_addp_c:
3137     case Hexagon::A4_subp_c:
3138     case Hexagon::A4_tlbmatch:
3139     case Hexagon::A5_ACS:
3140     case Hexagon::F2_sfinvsqrta:
3141     case Hexagon::F2_sfrecipa:
3142     case Hexagon::J2_endloop0:
3143     case Hexagon::J2_endloop01:
3144     case Hexagon::J2_ploop1si:
3145     case Hexagon::J2_ploop1sr:
3146     case Hexagon::J2_ploop2si:
3147     case Hexagon::J2_ploop2sr:
3148     case Hexagon::J2_ploop3si:
3149     case Hexagon::J2_ploop3sr:
3150     case Hexagon::S2_cabacdecbin:
3151     case Hexagon::S2_storew_locked:
3152     case Hexagon::S4_stored_locked:
3153       return false;
3154   }
3155   return true;
3156 }
3157 
3158 bool HexagonInstrInfo::PredOpcodeHasJMP_c(unsigned Opcode) const {
3159   return Opcode == Hexagon::J2_jumpt      ||
3160          Opcode == Hexagon::J2_jumptpt    ||
3161          Opcode == Hexagon::J2_jumpf      ||
3162          Opcode == Hexagon::J2_jumpfpt    ||
3163          Opcode == Hexagon::J2_jumptnew   ||
3164          Opcode == Hexagon::J2_jumpfnew   ||
3165          Opcode == Hexagon::J2_jumptnewpt ||
3166          Opcode == Hexagon::J2_jumpfnewpt;
3167 }
3168 
3169 bool HexagonInstrInfo::predOpcodeHasNot(ArrayRef<MachineOperand> Cond) const {
3170   if (Cond.empty() || !isPredicated(Cond[0].getImm()))
3171     return false;
3172   return !isPredicatedTrue(Cond[0].getImm());
3173 }
3174 
3175 unsigned HexagonInstrInfo::getAddrMode(const MachineInstr &MI) const {
3176   const uint64_t F = MI.getDesc().TSFlags;
3177   return (F >> HexagonII::AddrModePos) & HexagonII::AddrModeMask;
3178 }
3179 
3180 // Returns the base register in a memory access (load/store). The offset is
3181 // returned in Offset and the access size is returned in AccessSize.
3182 // If the base operand has a subregister or the offset field does not contain
3183 // an immediate value, return nullptr.
3184 MachineOperand *HexagonInstrInfo::getBaseAndOffset(const MachineInstr &MI,
3185                                                    int64_t &Offset,
3186                                                    unsigned &AccessSize) const {
3187   // Return if it is not a base+offset type instruction or a MemOp.
3188   if (getAddrMode(MI) != HexagonII::BaseImmOffset &&
3189       getAddrMode(MI) != HexagonII::BaseLongOffset &&
3190       !isMemOp(MI) && !isPostIncrement(MI))
3191     return nullptr;
3192 
3193   AccessSize = getMemAccessSize(MI);
3194 
3195   unsigned BasePos = 0, OffsetPos = 0;
3196   if (!getBaseAndOffsetPosition(MI, BasePos, OffsetPos))
3197     return nullptr;
3198 
3199   // Post increment updates its EA after the mem access,
3200   // so we need to treat its offset as zero.
3201   if (isPostIncrement(MI)) {
3202     Offset = 0;
3203   } else {
3204     const MachineOperand &OffsetOp = MI.getOperand(OffsetPos);
3205     if (!OffsetOp.isImm())
3206       return nullptr;
3207     Offset = OffsetOp.getImm();
3208   }
3209 
3210   const MachineOperand &BaseOp = MI.getOperand(BasePos);
3211   if (BaseOp.getSubReg() != 0)
3212     return nullptr;
3213   return &const_cast<MachineOperand&>(BaseOp);
3214 }
3215 
3216 /// Return the position of the base and offset operands for this instruction.
3217 bool HexagonInstrInfo::getBaseAndOffsetPosition(const MachineInstr &MI,
3218       unsigned &BasePos, unsigned &OffsetPos) const {
3219   if (!isAddrModeWithOffset(MI) && !isPostIncrement(MI))
3220     return false;
3221 
3222   // Deal with memops first.
3223   if (isMemOp(MI)) {
3224     BasePos = 0;
3225     OffsetPos = 1;
3226   } else if (MI.mayStore()) {
3227     BasePos = 0;
3228     OffsetPos = 1;
3229   } else if (MI.mayLoad()) {
3230     BasePos = 1;
3231     OffsetPos = 2;
3232   } else
3233     return false;
3234 
3235   if (isPredicated(MI)) {
3236     BasePos++;
3237     OffsetPos++;
3238   }
3239   if (isPostIncrement(MI)) {
3240     BasePos++;
3241     OffsetPos++;
3242   }
3243 
3244   if (!MI.getOperand(BasePos).isReg() || !MI.getOperand(OffsetPos).isImm())
3245     return false;
3246 
3247   return true;
3248 }
3249 
3250 // Inserts branching instructions in reverse order of their occurrence.
3251 // e.g. jump_t t1 (i1)
3252 // jump t2        (i2)
3253 // Jumpers = {i2, i1}
3254 SmallVector<MachineInstr*, 2> HexagonInstrInfo::getBranchingInstrs(
3255       MachineBasicBlock& MBB) const {
3256   SmallVector<MachineInstr*, 2> Jumpers;
3257   // If the block has no terminators, it just falls into the block after it.
3258   MachineBasicBlock::instr_iterator I = MBB.instr_end();
3259   if (I == MBB.instr_begin())
3260     return Jumpers;
3261 
3262   // A basic block may looks like this:
3263   //
3264   //  [   insn
3265   //     EH_LABEL
3266   //      insn
3267   //      insn
3268   //      insn
3269   //     EH_LABEL
3270   //      insn     ]
3271   //
3272   // It has two succs but does not have a terminator
3273   // Don't know how to handle it.
3274   do {
3275     --I;
3276     if (I->isEHLabel())
3277       return Jumpers;
3278   } while (I != MBB.instr_begin());
3279 
3280   I = MBB.instr_end();
3281   --I;
3282 
3283   while (I->isDebugInstr()) {
3284     if (I == MBB.instr_begin())
3285       return Jumpers;
3286     --I;
3287   }
3288   if (!isUnpredicatedTerminator(*I))
3289     return Jumpers;
3290 
3291   // Get the last instruction in the block.
3292   MachineInstr *LastInst = &*I;
3293   Jumpers.push_back(LastInst);
3294   MachineInstr *SecondLastInst = nullptr;
3295   // Find one more terminator if present.
3296   do {
3297     if (&*I != LastInst && !I->isBundle() && isUnpredicatedTerminator(*I)) {
3298       if (!SecondLastInst) {
3299         SecondLastInst = &*I;
3300         Jumpers.push_back(SecondLastInst);
3301       } else // This is a third branch.
3302         return Jumpers;
3303     }
3304     if (I == MBB.instr_begin())
3305       break;
3306     --I;
3307   } while (true);
3308   return Jumpers;
3309 }
3310 
3311 // Returns Operand Index for the constant extended instruction.
3312 unsigned HexagonInstrInfo::getCExtOpNum(const MachineInstr &MI) const {
3313   const uint64_t F = MI.getDesc().TSFlags;
3314   return (F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask;
3315 }
3316 
3317 // See if instruction could potentially be a duplex candidate.
3318 // If so, return its group. Zero otherwise.
3319 HexagonII::CompoundGroup HexagonInstrInfo::getCompoundCandidateGroup(
3320       const MachineInstr &MI) const {
3321   unsigned DstReg, SrcReg, Src1Reg, Src2Reg;
3322 
3323   switch (MI.getOpcode()) {
3324   default:
3325     return HexagonII::HCG_None;
3326   //
3327   // Compound pairs.
3328   // "p0=cmp.eq(Rs16,Rt16); if (p0.new) jump:nt #r9:2"
3329   // "Rd16=#U6 ; jump #r9:2"
3330   // "Rd16=Rs16 ; jump #r9:2"
3331   //
3332   case Hexagon::C2_cmpeq:
3333   case Hexagon::C2_cmpgt:
3334   case Hexagon::C2_cmpgtu:
3335     DstReg = MI.getOperand(0).getReg();
3336     Src1Reg = MI.getOperand(1).getReg();
3337     Src2Reg = MI.getOperand(2).getReg();
3338     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
3339         (Hexagon::P0 == DstReg || Hexagon::P1 == DstReg) &&
3340         isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg))
3341       return HexagonII::HCG_A;
3342     break;
3343   case Hexagon::C2_cmpeqi:
3344   case Hexagon::C2_cmpgti:
3345   case Hexagon::C2_cmpgtui:
3346     // P0 = cmp.eq(Rs,#u2)
3347     DstReg = MI.getOperand(0).getReg();
3348     SrcReg = MI.getOperand(1).getReg();
3349     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
3350         (Hexagon::P0 == DstReg || Hexagon::P1 == DstReg) &&
3351         isIntRegForSubInst(SrcReg) && MI.getOperand(2).isImm() &&
3352         ((isUInt<5>(MI.getOperand(2).getImm())) ||
3353          (MI.getOperand(2).getImm() == -1)))
3354       return HexagonII::HCG_A;
3355     break;
3356   case Hexagon::A2_tfr:
3357     // Rd = Rs
3358     DstReg = MI.getOperand(0).getReg();
3359     SrcReg = MI.getOperand(1).getReg();
3360     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg))
3361       return HexagonII::HCG_A;
3362     break;
3363   case Hexagon::A2_tfrsi:
3364     // Rd = #u6
3365     // Do not test for #u6 size since the const is getting extended
3366     // regardless and compound could be formed.
3367     DstReg = MI.getOperand(0).getReg();
3368     if (isIntRegForSubInst(DstReg))
3369       return HexagonII::HCG_A;
3370     break;
3371   case Hexagon::S2_tstbit_i:
3372     DstReg = MI.getOperand(0).getReg();
3373     Src1Reg = MI.getOperand(1).getReg();
3374     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
3375         (Hexagon::P0 == DstReg || Hexagon::P1 == DstReg) &&
3376         MI.getOperand(2).isImm() &&
3377         isIntRegForSubInst(Src1Reg) && (MI.getOperand(2).getImm() == 0))
3378       return HexagonII::HCG_A;
3379     break;
3380   // The fact that .new form is used pretty much guarantees
3381   // that predicate register will match. Nevertheless,
3382   // there could be some false positives without additional
3383   // checking.
3384   case Hexagon::J2_jumptnew:
3385   case Hexagon::J2_jumpfnew:
3386   case Hexagon::J2_jumptnewpt:
3387   case Hexagon::J2_jumpfnewpt:
3388     Src1Reg = MI.getOperand(0).getReg();
3389     if (Hexagon::PredRegsRegClass.contains(Src1Reg) &&
3390         (Hexagon::P0 == Src1Reg || Hexagon::P1 == Src1Reg))
3391       return HexagonII::HCG_B;
3392     break;
3393   // Transfer and jump:
3394   // Rd=#U6 ; jump #r9:2
3395   // Rd=Rs ; jump #r9:2
3396   // Do not test for jump range here.
3397   case Hexagon::J2_jump:
3398   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
3399   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
3400     return HexagonII::HCG_C;
3401   }
3402 
3403   return HexagonII::HCG_None;
3404 }
3405 
3406 // Returns -1 when there is no opcode found.
3407 unsigned HexagonInstrInfo::getCompoundOpcode(const MachineInstr &GA,
3408       const MachineInstr &GB) const {
3409   assert(getCompoundCandidateGroup(GA) == HexagonII::HCG_A);
3410   assert(getCompoundCandidateGroup(GB) == HexagonII::HCG_B);
3411   if ((GA.getOpcode() != Hexagon::C2_cmpeqi) ||
3412       (GB.getOpcode() != Hexagon::J2_jumptnew))
3413     return -1u;
3414   Register DestReg = GA.getOperand(0).getReg();
3415   if (!GB.readsRegister(DestReg))
3416     return -1u;
3417   if (DestReg != Hexagon::P0 && DestReg != Hexagon::P1)
3418     return -1u;
3419   // The value compared against must be either u5 or -1.
3420   const MachineOperand &CmpOp = GA.getOperand(2);
3421   if (!CmpOp.isImm())
3422     return -1u;
3423   int V = CmpOp.getImm();
3424   if (V == -1)
3425     return DestReg == Hexagon::P0 ? Hexagon::J4_cmpeqn1_tp0_jump_nt
3426                                   : Hexagon::J4_cmpeqn1_tp1_jump_nt;
3427   if (!isUInt<5>(V))
3428     return -1u;
3429   return DestReg == Hexagon::P0 ? Hexagon::J4_cmpeqi_tp0_jump_nt
3430                                 : Hexagon::J4_cmpeqi_tp1_jump_nt;
3431 }
3432 
3433 // Returns -1 if there is no opcode found.
3434 int HexagonInstrInfo::getDuplexOpcode(const MachineInstr &MI,
3435                                       bool ForBigCore) const {
3436   // Static table to switch the opcodes across Tiny Core and Big Core.
3437   // dup_ opcodes are Big core opcodes.
3438   // NOTE: There are special instructions that need to handled later.
3439   // L4_return* instructions, they will only occupy SLOT0 (on big core too).
3440   // PS_jmpret - This pseudo translates to J2_jumpr which occupies only SLOT2.
3441   // The compiler need to base the root instruction to L6_return_map_to_raw
3442   // which can go any slot.
3443   static const std::map<unsigned, unsigned> DupMap = {
3444       {Hexagon::A2_add, Hexagon::dup_A2_add},
3445       {Hexagon::A2_addi, Hexagon::dup_A2_addi},
3446       {Hexagon::A2_andir, Hexagon::dup_A2_andir},
3447       {Hexagon::A2_combineii, Hexagon::dup_A2_combineii},
3448       {Hexagon::A2_sxtb, Hexagon::dup_A2_sxtb},
3449       {Hexagon::A2_sxth, Hexagon::dup_A2_sxth},
3450       {Hexagon::A2_tfr, Hexagon::dup_A2_tfr},
3451       {Hexagon::A2_tfrsi, Hexagon::dup_A2_tfrsi},
3452       {Hexagon::A2_zxtb, Hexagon::dup_A2_zxtb},
3453       {Hexagon::A2_zxth, Hexagon::dup_A2_zxth},
3454       {Hexagon::A4_combineii, Hexagon::dup_A4_combineii},
3455       {Hexagon::A4_combineir, Hexagon::dup_A4_combineir},
3456       {Hexagon::A4_combineri, Hexagon::dup_A4_combineri},
3457       {Hexagon::C2_cmoveif, Hexagon::dup_C2_cmoveif},
3458       {Hexagon::C2_cmoveit, Hexagon::dup_C2_cmoveit},
3459       {Hexagon::C2_cmovenewif, Hexagon::dup_C2_cmovenewif},
3460       {Hexagon::C2_cmovenewit, Hexagon::dup_C2_cmovenewit},
3461       {Hexagon::C2_cmpeqi, Hexagon::dup_C2_cmpeqi},
3462       {Hexagon::L2_deallocframe, Hexagon::dup_L2_deallocframe},
3463       {Hexagon::L2_loadrb_io, Hexagon::dup_L2_loadrb_io},
3464       {Hexagon::L2_loadrd_io, Hexagon::dup_L2_loadrd_io},
3465       {Hexagon::L2_loadrh_io, Hexagon::dup_L2_loadrh_io},
3466       {Hexagon::L2_loadri_io, Hexagon::dup_L2_loadri_io},
3467       {Hexagon::L2_loadrub_io, Hexagon::dup_L2_loadrub_io},
3468       {Hexagon::L2_loadruh_io, Hexagon::dup_L2_loadruh_io},
3469       {Hexagon::S2_allocframe, Hexagon::dup_S2_allocframe},
3470       {Hexagon::S2_storerb_io, Hexagon::dup_S2_storerb_io},
3471       {Hexagon::S2_storerd_io, Hexagon::dup_S2_storerd_io},
3472       {Hexagon::S2_storerh_io, Hexagon::dup_S2_storerh_io},
3473       {Hexagon::S2_storeri_io, Hexagon::dup_S2_storeri_io},
3474       {Hexagon::S4_storeirb_io, Hexagon::dup_S4_storeirb_io},
3475       {Hexagon::S4_storeiri_io, Hexagon::dup_S4_storeiri_io},
3476   };
3477   unsigned OpNum = MI.getOpcode();
3478   // Conversion to Big core.
3479   if (ForBigCore) {
3480     auto Iter = DupMap.find(OpNum);
3481     if (Iter != DupMap.end())
3482       return Iter->second;
3483   } else { // Conversion to Tiny core.
3484     for (auto Iter = DupMap.begin(), End = DupMap.end(); Iter != End; ++Iter)
3485       if (Iter->second == OpNum)
3486         return Iter->first;
3487   }
3488   return -1;
3489 }
3490 
3491 int HexagonInstrInfo::getCondOpcode(int Opc, bool invertPredicate) const {
3492   enum Hexagon::PredSense inPredSense;
3493   inPredSense = invertPredicate ? Hexagon::PredSense_false :
3494                                   Hexagon::PredSense_true;
3495   int CondOpcode = Hexagon::getPredOpcode(Opc, inPredSense);
3496   if (CondOpcode >= 0) // Valid Conditional opcode/instruction
3497     return CondOpcode;
3498 
3499   llvm_unreachable("Unexpected predicable instruction");
3500 }
3501 
3502 // Return the cur value instruction for a given store.
3503 int HexagonInstrInfo::getDotCurOp(const MachineInstr &MI) const {
3504   switch (MI.getOpcode()) {
3505   default: llvm_unreachable("Unknown .cur type");
3506   case Hexagon::V6_vL32b_pi:
3507     return Hexagon::V6_vL32b_cur_pi;
3508   case Hexagon::V6_vL32b_ai:
3509     return Hexagon::V6_vL32b_cur_ai;
3510   case Hexagon::V6_vL32b_nt_pi:
3511     return Hexagon::V6_vL32b_nt_cur_pi;
3512   case Hexagon::V6_vL32b_nt_ai:
3513     return Hexagon::V6_vL32b_nt_cur_ai;
3514   }
3515   return 0;
3516 }
3517 
3518 // Return the regular version of the .cur instruction.
3519 int HexagonInstrInfo::getNonDotCurOp(const MachineInstr &MI) const {
3520   switch (MI.getOpcode()) {
3521   default: llvm_unreachable("Unknown .cur type");
3522   case Hexagon::V6_vL32b_cur_pi:
3523     return Hexagon::V6_vL32b_pi;
3524   case Hexagon::V6_vL32b_cur_ai:
3525     return Hexagon::V6_vL32b_ai;
3526   case Hexagon::V6_vL32b_nt_cur_pi:
3527     return Hexagon::V6_vL32b_nt_pi;
3528   case Hexagon::V6_vL32b_nt_cur_ai:
3529     return Hexagon::V6_vL32b_nt_ai;
3530   }
3531   return 0;
3532 }
3533 
3534 // The diagram below shows the steps involved in the conversion of a predicated
3535 // store instruction to its .new predicated new-value form.
3536 //
3537 // Note: It doesn't include conditional new-value stores as they can't be
3538 // converted to .new predicate.
3539 //
3540 //               p.new NV store [ if(p0.new)memw(R0+#0)=R2.new ]
3541 //                ^           ^
3542 //               /             \ (not OK. it will cause new-value store to be
3543 //              /               X conditional on p0.new while R2 producer is
3544 //             /                 \ on p0)
3545 //            /                   \.
3546 //     p.new store                 p.old NV store
3547 // [if(p0.new)memw(R0+#0)=R2]    [if(p0)memw(R0+#0)=R2.new]
3548 //            ^                  ^
3549 //             \                /
3550 //              \              /
3551 //               \            /
3552 //                 p.old store
3553 //             [if (p0)memw(R0+#0)=R2]
3554 //
3555 // The following set of instructions further explains the scenario where
3556 // conditional new-value store becomes invalid when promoted to .new predicate
3557 // form.
3558 //
3559 // { 1) if (p0) r0 = add(r1, r2)
3560 //   2) p0 = cmp.eq(r3, #0) }
3561 //
3562 //   3) if (p0) memb(r1+#0) = r0  --> this instruction can't be grouped with
3563 // the first two instructions because in instr 1, r0 is conditional on old value
3564 // of p0 but its use in instr 3 is conditional on p0 modified by instr 2 which
3565 // is not valid for new-value stores.
3566 // Predicated new value stores (i.e. if (p0) memw(..)=r0.new) are excluded
3567 // from the "Conditional Store" list. Because a predicated new value store
3568 // would NOT be promoted to a double dot new store. See diagram below:
3569 // This function returns yes for those stores that are predicated but not
3570 // yet promoted to predicate dot new instructions.
3571 //
3572 //                          +---------------------+
3573 //                    /-----| if (p0) memw(..)=r0 |---------\~
3574 //                   ||     +---------------------+         ||
3575 //          promote  ||       /\       /\                   ||  promote
3576 //                   ||      /||\     /||\                  ||
3577 //                  \||/    demote     ||                  \||/
3578 //                   \/       ||       ||                   \/
3579 //       +-------------------------+   ||   +-------------------------+
3580 //       | if (p0.new) memw(..)=r0 |   ||   | if (p0) memw(..)=r0.new |
3581 //       +-------------------------+   ||   +-------------------------+
3582 //                        ||           ||         ||
3583 //                        ||         demote      \||/
3584 //                      promote        ||         \/ NOT possible
3585 //                        ||           ||         /\~
3586 //                       \||/          ||        /||\~
3587 //                        \/           ||         ||
3588 //                      +-----------------------------+
3589 //                      | if (p0.new) memw(..)=r0.new |
3590 //                      +-----------------------------+
3591 //                           Double Dot New Store
3592 //
3593 // Returns the most basic instruction for the .new predicated instructions and
3594 // new-value stores.
3595 // For example, all of the following instructions will be converted back to the
3596 // same instruction:
3597 // 1) if (p0.new) memw(R0+#0) = R1.new  --->
3598 // 2) if (p0) memw(R0+#0)= R1.new      -------> if (p0) memw(R0+#0) = R1
3599 // 3) if (p0.new) memw(R0+#0) = R1      --->
3600 //
3601 // To understand the translation of instruction 1 to its original form, consider
3602 // a packet with 3 instructions.
3603 // { p0 = cmp.eq(R0,R1)
3604 //   if (p0.new) R2 = add(R3, R4)
3605 //   R5 = add (R3, R1)
3606 // }
3607 // if (p0) memw(R5+#0) = R2 <--- trying to include it in the previous packet
3608 //
3609 // This instruction can be part of the previous packet only if both p0 and R2
3610 // are promoted to .new values. This promotion happens in steps, first
3611 // predicate register is promoted to .new and in the next iteration R2 is
3612 // promoted. Therefore, in case of dependence check failure (due to R5) during
3613 // next iteration, it should be converted back to its most basic form.
3614 
3615 // Return the new value instruction for a given store.
3616 int HexagonInstrInfo::getDotNewOp(const MachineInstr &MI) const {
3617   int NVOpcode = Hexagon::getNewValueOpcode(MI.getOpcode());
3618   if (NVOpcode >= 0) // Valid new-value store instruction.
3619     return NVOpcode;
3620 
3621   switch (MI.getOpcode()) {
3622   default:
3623     report_fatal_error(std::string("Unknown .new type: ") +
3624       std::to_string(MI.getOpcode()));
3625   case Hexagon::S4_storerb_ur:
3626     return Hexagon::S4_storerbnew_ur;
3627 
3628   case Hexagon::S2_storerb_pci:
3629     return Hexagon::S2_storerb_pci;
3630 
3631   case Hexagon::S2_storeri_pci:
3632     return Hexagon::S2_storeri_pci;
3633 
3634   case Hexagon::S2_storerh_pci:
3635     return Hexagon::S2_storerh_pci;
3636 
3637   case Hexagon::S2_storerd_pci:
3638     return Hexagon::S2_storerd_pci;
3639 
3640   case Hexagon::S2_storerf_pci:
3641     return Hexagon::S2_storerf_pci;
3642 
3643   case Hexagon::V6_vS32b_ai:
3644     return Hexagon::V6_vS32b_new_ai;
3645 
3646   case Hexagon::V6_vS32b_pi:
3647     return Hexagon::V6_vS32b_new_pi;
3648   }
3649   return 0;
3650 }
3651 
3652 // Returns the opcode to use when converting MI, which is a conditional jump,
3653 // into a conditional instruction which uses the .new value of the predicate.
3654 // We also use branch probabilities to add a hint to the jump.
3655 // If MBPI is null, all edges will be treated as equally likely for the
3656 // purposes of establishing a predication hint.
3657 int HexagonInstrInfo::getDotNewPredJumpOp(const MachineInstr &MI,
3658       const MachineBranchProbabilityInfo *MBPI) const {
3659   // We assume that block can have at most two successors.
3660   const MachineBasicBlock *Src = MI.getParent();
3661   const MachineOperand &BrTarget = MI.getOperand(1);
3662   bool Taken = false;
3663   const BranchProbability OneHalf(1, 2);
3664 
3665   auto getEdgeProbability = [MBPI] (const MachineBasicBlock *Src,
3666                                     const MachineBasicBlock *Dst) {
3667     if (MBPI)
3668       return MBPI->getEdgeProbability(Src, Dst);
3669     return BranchProbability(1, Src->succ_size());
3670   };
3671 
3672   if (BrTarget.isMBB()) {
3673     const MachineBasicBlock *Dst = BrTarget.getMBB();
3674     Taken = getEdgeProbability(Src, Dst) >= OneHalf;
3675   } else {
3676     // The branch target is not a basic block (most likely a function).
3677     // Since BPI only gives probabilities for targets that are basic blocks,
3678     // try to identify another target of this branch (potentially a fall-
3679     // -through) and check the probability of that target.
3680     //
3681     // The only handled branch combinations are:
3682     // - one conditional branch,
3683     // - one conditional branch followed by one unconditional branch.
3684     // Otherwise, assume not-taken.
3685     assert(MI.isConditionalBranch());
3686     const MachineBasicBlock &B = *MI.getParent();
3687     bool SawCond = false, Bad = false;
3688     for (const MachineInstr &I : B) {
3689       if (!I.isBranch())
3690         continue;
3691       if (I.isConditionalBranch()) {
3692         SawCond = true;
3693         if (&I != &MI) {
3694           Bad = true;
3695           break;
3696         }
3697       }
3698       if (I.isUnconditionalBranch() && !SawCond) {
3699         Bad = true;
3700         break;
3701       }
3702     }
3703     if (!Bad) {
3704       MachineBasicBlock::const_instr_iterator It(MI);
3705       MachineBasicBlock::const_instr_iterator NextIt = std::next(It);
3706       if (NextIt == B.instr_end()) {
3707         // If this branch is the last, look for the fall-through block.
3708         for (const MachineBasicBlock *SB : B.successors()) {
3709           if (!B.isLayoutSuccessor(SB))
3710             continue;
3711           Taken = getEdgeProbability(Src, SB) < OneHalf;
3712           break;
3713         }
3714       } else {
3715         assert(NextIt->isUnconditionalBranch());
3716         // Find the first MBB operand and assume it's the target.
3717         const MachineBasicBlock *BT = nullptr;
3718         for (const MachineOperand &Op : NextIt->operands()) {
3719           if (!Op.isMBB())
3720             continue;
3721           BT = Op.getMBB();
3722           break;
3723         }
3724         Taken = BT && getEdgeProbability(Src, BT) < OneHalf;
3725       }
3726     } // if (!Bad)
3727   }
3728 
3729   // The Taken flag should be set to something reasonable by this point.
3730 
3731   switch (MI.getOpcode()) {
3732   case Hexagon::J2_jumpt:
3733     return Taken ? Hexagon::J2_jumptnewpt : Hexagon::J2_jumptnew;
3734   case Hexagon::J2_jumpf:
3735     return Taken ? Hexagon::J2_jumpfnewpt : Hexagon::J2_jumpfnew;
3736 
3737   default:
3738     llvm_unreachable("Unexpected jump instruction.");
3739   }
3740 }
3741 
3742 // Return .new predicate version for an instruction.
3743 int HexagonInstrInfo::getDotNewPredOp(const MachineInstr &MI,
3744       const MachineBranchProbabilityInfo *MBPI) const {
3745   switch (MI.getOpcode()) {
3746   // Condtional Jumps
3747   case Hexagon::J2_jumpt:
3748   case Hexagon::J2_jumpf:
3749     return getDotNewPredJumpOp(MI, MBPI);
3750   }
3751 
3752   int NewOpcode = Hexagon::getPredNewOpcode(MI.getOpcode());
3753   if (NewOpcode >= 0)
3754     return NewOpcode;
3755   return 0;
3756 }
3757 
3758 int HexagonInstrInfo::getDotOldOp(const MachineInstr &MI) const {
3759   int NewOp = MI.getOpcode();
3760   if (isPredicated(NewOp) && isPredicatedNew(NewOp)) { // Get predicate old form
3761     NewOp = Hexagon::getPredOldOpcode(NewOp);
3762     // All Hexagon architectures have prediction bits on dot-new branches,
3763     // but only Hexagon V60+ has prediction bits on dot-old ones. Make sure
3764     // to pick the right opcode when converting back to dot-old.
3765     if (!Subtarget.getFeatureBits()[Hexagon::ArchV60]) {
3766       switch (NewOp) {
3767       case Hexagon::J2_jumptpt:
3768         NewOp = Hexagon::J2_jumpt;
3769         break;
3770       case Hexagon::J2_jumpfpt:
3771         NewOp = Hexagon::J2_jumpf;
3772         break;
3773       case Hexagon::J2_jumprtpt:
3774         NewOp = Hexagon::J2_jumprt;
3775         break;
3776       case Hexagon::J2_jumprfpt:
3777         NewOp = Hexagon::J2_jumprf;
3778         break;
3779       }
3780     }
3781     assert(NewOp >= 0 &&
3782            "Couldn't change predicate new instruction to its old form.");
3783   }
3784 
3785   if (isNewValueStore(NewOp)) { // Convert into non-new-value format
3786     NewOp = Hexagon::getNonNVStore(NewOp);
3787     assert(NewOp >= 0 && "Couldn't change new-value store to its old form.");
3788   }
3789 
3790   if (Subtarget.hasV60Ops())
3791     return NewOp;
3792 
3793   // Subtargets prior to V60 didn't support 'taken' forms of predicated jumps.
3794   switch (NewOp) {
3795   case Hexagon::J2_jumpfpt:
3796     return Hexagon::J2_jumpf;
3797   case Hexagon::J2_jumptpt:
3798     return Hexagon::J2_jumpt;
3799   case Hexagon::J2_jumprfpt:
3800     return Hexagon::J2_jumprf;
3801   case Hexagon::J2_jumprtpt:
3802     return Hexagon::J2_jumprt;
3803   }
3804   return NewOp;
3805 }
3806 
3807 // See if instruction could potentially be a duplex candidate.
3808 // If so, return its group. Zero otherwise.
3809 HexagonII::SubInstructionGroup HexagonInstrInfo::getDuplexCandidateGroup(
3810       const MachineInstr &MI) const {
3811   unsigned DstReg, SrcReg, Src1Reg, Src2Reg;
3812   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
3813 
3814   switch (MI.getOpcode()) {
3815   default:
3816     return HexagonII::HSIG_None;
3817   //
3818   // Group L1:
3819   //
3820   // Rd = memw(Rs+#u4:2)
3821   // Rd = memub(Rs+#u4:0)
3822   case Hexagon::L2_loadri_io:
3823   case Hexagon::dup_L2_loadri_io:
3824     DstReg = MI.getOperand(0).getReg();
3825     SrcReg = MI.getOperand(1).getReg();
3826     // Special case this one from Group L2.
3827     // Rd = memw(r29+#u5:2)
3828     if (isIntRegForSubInst(DstReg)) {
3829       if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
3830           HRI.getStackRegister() == SrcReg &&
3831           MI.getOperand(2).isImm() &&
3832           isShiftedUInt<5,2>(MI.getOperand(2).getImm()))
3833         return HexagonII::HSIG_L2;
3834       // Rd = memw(Rs+#u4:2)
3835       if (isIntRegForSubInst(SrcReg) &&
3836           (MI.getOperand(2).isImm() &&
3837           isShiftedUInt<4,2>(MI.getOperand(2).getImm())))
3838         return HexagonII::HSIG_L1;
3839     }
3840     break;
3841   case Hexagon::L2_loadrub_io:
3842   case Hexagon::dup_L2_loadrub_io:
3843     // Rd = memub(Rs+#u4:0)
3844     DstReg = MI.getOperand(0).getReg();
3845     SrcReg = MI.getOperand(1).getReg();
3846     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3847         MI.getOperand(2).isImm() && isUInt<4>(MI.getOperand(2).getImm()))
3848       return HexagonII::HSIG_L1;
3849     break;
3850   //
3851   // Group L2:
3852   //
3853   // Rd = memh/memuh(Rs+#u3:1)
3854   // Rd = memb(Rs+#u3:0)
3855   // Rd = memw(r29+#u5:2) - Handled above.
3856   // Rdd = memd(r29+#u5:3)
3857   // deallocframe
3858   // [if ([!]p0[.new])] dealloc_return
3859   // [if ([!]p0[.new])] jumpr r31
3860   case Hexagon::L2_loadrh_io:
3861   case Hexagon::L2_loadruh_io:
3862   case Hexagon::dup_L2_loadrh_io:
3863   case Hexagon::dup_L2_loadruh_io:
3864     // Rd = memh/memuh(Rs+#u3:1)
3865     DstReg = MI.getOperand(0).getReg();
3866     SrcReg = MI.getOperand(1).getReg();
3867     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3868         MI.getOperand(2).isImm() &&
3869         isShiftedUInt<3,1>(MI.getOperand(2).getImm()))
3870       return HexagonII::HSIG_L2;
3871     break;
3872   case Hexagon::L2_loadrb_io:
3873   case Hexagon::dup_L2_loadrb_io:
3874     // Rd = memb(Rs+#u3:0)
3875     DstReg = MI.getOperand(0).getReg();
3876     SrcReg = MI.getOperand(1).getReg();
3877     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3878         MI.getOperand(2).isImm() &&
3879         isUInt<3>(MI.getOperand(2).getImm()))
3880       return HexagonII::HSIG_L2;
3881     break;
3882   case Hexagon::L2_loadrd_io:
3883   case Hexagon::dup_L2_loadrd_io:
3884     // Rdd = memd(r29+#u5:3)
3885     DstReg = MI.getOperand(0).getReg();
3886     SrcReg = MI.getOperand(1).getReg();
3887     if (isDblRegForSubInst(DstReg, HRI) &&
3888         Hexagon::IntRegsRegClass.contains(SrcReg) &&
3889         HRI.getStackRegister() == SrcReg &&
3890         MI.getOperand(2).isImm() &&
3891         isShiftedUInt<5,3>(MI.getOperand(2).getImm()))
3892       return HexagonII::HSIG_L2;
3893     break;
3894   // dealloc_return is not documented in Hexagon Manual, but marked
3895   // with A_SUBINSN attribute in iset_v4classic.py.
3896   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
3897   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
3898   case Hexagon::L4_return:
3899   case Hexagon::L2_deallocframe:
3900   case Hexagon::dup_L2_deallocframe:
3901     return HexagonII::HSIG_L2;
3902   case Hexagon::EH_RETURN_JMPR:
3903   case Hexagon::PS_jmpret:
3904   case Hexagon::SL2_jumpr31:
3905     // jumpr r31
3906     // Actual form JMPR implicit-def %pc, implicit %r31, implicit internal %r0
3907     DstReg = MI.getOperand(0).getReg();
3908     if (Hexagon::IntRegsRegClass.contains(DstReg) && (Hexagon::R31 == DstReg))
3909       return HexagonII::HSIG_L2;
3910     break;
3911   case Hexagon::PS_jmprett:
3912   case Hexagon::PS_jmpretf:
3913   case Hexagon::PS_jmprettnewpt:
3914   case Hexagon::PS_jmpretfnewpt:
3915   case Hexagon::PS_jmprettnew:
3916   case Hexagon::PS_jmpretfnew:
3917   case Hexagon::SL2_jumpr31_t:
3918   case Hexagon::SL2_jumpr31_f:
3919   case Hexagon::SL2_jumpr31_tnew:
3920   case Hexagon::SL2_jumpr31_fnew:
3921     DstReg = MI.getOperand(1).getReg();
3922     SrcReg = MI.getOperand(0).getReg();
3923     // [if ([!]p0[.new])] jumpr r31
3924     if ((Hexagon::PredRegsRegClass.contains(SrcReg) &&
3925         (Hexagon::P0 == SrcReg)) &&
3926         (Hexagon::IntRegsRegClass.contains(DstReg) && (Hexagon::R31 == DstReg)))
3927       return HexagonII::HSIG_L2;
3928     break;
3929   case Hexagon::L4_return_t:
3930   case Hexagon::L4_return_f:
3931   case Hexagon::L4_return_tnew_pnt:
3932   case Hexagon::L4_return_fnew_pnt:
3933   case Hexagon::L4_return_tnew_pt:
3934   case Hexagon::L4_return_fnew_pt:
3935     // [if ([!]p0[.new])] dealloc_return
3936     SrcReg = MI.getOperand(0).getReg();
3937     if (Hexagon::PredRegsRegClass.contains(SrcReg) && (Hexagon::P0 == SrcReg))
3938       return HexagonII::HSIG_L2;
3939     break;
3940   //
3941   // Group S1:
3942   //
3943   // memw(Rs+#u4:2) = Rt
3944   // memb(Rs+#u4:0) = Rt
3945   case Hexagon::S2_storeri_io:
3946   case Hexagon::dup_S2_storeri_io:
3947     // Special case this one from Group S2.
3948     // memw(r29+#u5:2) = Rt
3949     Src1Reg = MI.getOperand(0).getReg();
3950     Src2Reg = MI.getOperand(2).getReg();
3951     if (Hexagon::IntRegsRegClass.contains(Src1Reg) &&
3952         isIntRegForSubInst(Src2Reg) &&
3953         HRI.getStackRegister() == Src1Reg && MI.getOperand(1).isImm() &&
3954         isShiftedUInt<5,2>(MI.getOperand(1).getImm()))
3955       return HexagonII::HSIG_S2;
3956     // memw(Rs+#u4:2) = Rt
3957     if (isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg) &&
3958         MI.getOperand(1).isImm() &&
3959         isShiftedUInt<4,2>(MI.getOperand(1).getImm()))
3960       return HexagonII::HSIG_S1;
3961     break;
3962   case Hexagon::S2_storerb_io:
3963   case Hexagon::dup_S2_storerb_io:
3964     // memb(Rs+#u4:0) = Rt
3965     Src1Reg = MI.getOperand(0).getReg();
3966     Src2Reg = MI.getOperand(2).getReg();
3967     if (isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg) &&
3968         MI.getOperand(1).isImm() && isUInt<4>(MI.getOperand(1).getImm()))
3969       return HexagonII::HSIG_S1;
3970     break;
3971   //
3972   // Group S2:
3973   //
3974   // memh(Rs+#u3:1) = Rt
3975   // memw(r29+#u5:2) = Rt
3976   // memd(r29+#s6:3) = Rtt
3977   // memw(Rs+#u4:2) = #U1
3978   // memb(Rs+#u4) = #U1
3979   // allocframe(#u5:3)
3980   case Hexagon::S2_storerh_io:
3981   case Hexagon::dup_S2_storerh_io:
3982     // memh(Rs+#u3:1) = Rt
3983     Src1Reg = MI.getOperand(0).getReg();
3984     Src2Reg = MI.getOperand(2).getReg();
3985     if (isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg) &&
3986         MI.getOperand(1).isImm() &&
3987         isShiftedUInt<3,1>(MI.getOperand(1).getImm()))
3988       return HexagonII::HSIG_S1;
3989     break;
3990   case Hexagon::S2_storerd_io:
3991   case Hexagon::dup_S2_storerd_io:
3992     // memd(r29+#s6:3) = Rtt
3993     Src1Reg = MI.getOperand(0).getReg();
3994     Src2Reg = MI.getOperand(2).getReg();
3995     if (isDblRegForSubInst(Src2Reg, HRI) &&
3996         Hexagon::IntRegsRegClass.contains(Src1Reg) &&
3997         HRI.getStackRegister() == Src1Reg && MI.getOperand(1).isImm() &&
3998         isShiftedInt<6,3>(MI.getOperand(1).getImm()))
3999       return HexagonII::HSIG_S2;
4000     break;
4001   case Hexagon::S4_storeiri_io:
4002   case Hexagon::dup_S4_storeiri_io:
4003     // memw(Rs+#u4:2) = #U1
4004     Src1Reg = MI.getOperand(0).getReg();
4005     if (isIntRegForSubInst(Src1Reg) && MI.getOperand(1).isImm() &&
4006         isShiftedUInt<4,2>(MI.getOperand(1).getImm()) &&
4007         MI.getOperand(2).isImm() && isUInt<1>(MI.getOperand(2).getImm()))
4008       return HexagonII::HSIG_S2;
4009     break;
4010   case Hexagon::S4_storeirb_io:
4011   case Hexagon::dup_S4_storeirb_io:
4012     // memb(Rs+#u4) = #U1
4013     Src1Reg = MI.getOperand(0).getReg();
4014     if (isIntRegForSubInst(Src1Reg) &&
4015         MI.getOperand(1).isImm() && isUInt<4>(MI.getOperand(1).getImm()) &&
4016         MI.getOperand(2).isImm() && isUInt<1>(MI.getOperand(2).getImm()))
4017       return HexagonII::HSIG_S2;
4018     break;
4019   case Hexagon::S2_allocframe:
4020   case Hexagon::dup_S2_allocframe:
4021     if (MI.getOperand(2).isImm() &&
4022         isShiftedUInt<5,3>(MI.getOperand(2).getImm()))
4023       return HexagonII::HSIG_S1;
4024     break;
4025   //
4026   // Group A:
4027   //
4028   // Rx = add(Rx,#s7)
4029   // Rd = Rs
4030   // Rd = #u6
4031   // Rd = #-1
4032   // if ([!]P0[.new]) Rd = #0
4033   // Rd = add(r29,#u6:2)
4034   // Rx = add(Rx,Rs)
4035   // P0 = cmp.eq(Rs,#u2)
4036   // Rdd = combine(#0,Rs)
4037   // Rdd = combine(Rs,#0)
4038   // Rdd = combine(#u2,#U2)
4039   // Rd = add(Rs,#1)
4040   // Rd = add(Rs,#-1)
4041   // Rd = sxth/sxtb/zxtb/zxth(Rs)
4042   // Rd = and(Rs,#1)
4043   case Hexagon::A2_addi:
4044   case Hexagon::dup_A2_addi:
4045     DstReg = MI.getOperand(0).getReg();
4046     SrcReg = MI.getOperand(1).getReg();
4047     if (isIntRegForSubInst(DstReg)) {
4048       // Rd = add(r29,#u6:2)
4049       if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
4050         HRI.getStackRegister() == SrcReg && MI.getOperand(2).isImm() &&
4051         isShiftedUInt<6,2>(MI.getOperand(2).getImm()))
4052         return HexagonII::HSIG_A;
4053       // Rx = add(Rx,#s7)
4054       if ((DstReg == SrcReg) && MI.getOperand(2).isImm() &&
4055           isInt<7>(MI.getOperand(2).getImm()))
4056         return HexagonII::HSIG_A;
4057       // Rd = add(Rs,#1)
4058       // Rd = add(Rs,#-1)
4059       if (isIntRegForSubInst(SrcReg) && MI.getOperand(2).isImm() &&
4060           ((MI.getOperand(2).getImm() == 1) ||
4061           (MI.getOperand(2).getImm() == -1)))
4062         return HexagonII::HSIG_A;
4063     }
4064     break;
4065   case Hexagon::A2_add:
4066   case Hexagon::dup_A2_add:
4067     // Rx = add(Rx,Rs)
4068     DstReg = MI.getOperand(0).getReg();
4069     Src1Reg = MI.getOperand(1).getReg();
4070     Src2Reg = MI.getOperand(2).getReg();
4071     if (isIntRegForSubInst(DstReg) && (DstReg == Src1Reg) &&
4072         isIntRegForSubInst(Src2Reg))
4073       return HexagonII::HSIG_A;
4074     break;
4075   case Hexagon::A2_andir:
4076   case Hexagon::dup_A2_andir:
4077     // Same as zxtb.
4078     // Rd16=and(Rs16,#255)
4079     // Rd16=and(Rs16,#1)
4080     DstReg = MI.getOperand(0).getReg();
4081     SrcReg = MI.getOperand(1).getReg();
4082     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
4083         MI.getOperand(2).isImm() &&
4084         ((MI.getOperand(2).getImm() == 1) ||
4085         (MI.getOperand(2).getImm() == 255)))
4086       return HexagonII::HSIG_A;
4087     break;
4088   case Hexagon::A2_tfr:
4089   case Hexagon::dup_A2_tfr:
4090     // Rd = Rs
4091     DstReg = MI.getOperand(0).getReg();
4092     SrcReg = MI.getOperand(1).getReg();
4093     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg))
4094       return HexagonII::HSIG_A;
4095     break;
4096   case Hexagon::A2_tfrsi:
4097   case Hexagon::dup_A2_tfrsi:
4098     // Rd = #u6
4099     // Do not test for #u6 size since the const is getting extended
4100     // regardless and compound could be formed.
4101     // Rd = #-1
4102     DstReg = MI.getOperand(0).getReg();
4103     if (isIntRegForSubInst(DstReg))
4104       return HexagonII::HSIG_A;
4105     break;
4106   case Hexagon::C2_cmoveit:
4107   case Hexagon::C2_cmovenewit:
4108   case Hexagon::C2_cmoveif:
4109   case Hexagon::C2_cmovenewif:
4110   case Hexagon::dup_C2_cmoveit:
4111   case Hexagon::dup_C2_cmovenewit:
4112   case Hexagon::dup_C2_cmoveif:
4113   case Hexagon::dup_C2_cmovenewif:
4114     // if ([!]P0[.new]) Rd = #0
4115     // Actual form:
4116     // %r16 = C2_cmovenewit internal %p0, 0, implicit undef %r16;
4117     DstReg = MI.getOperand(0).getReg();
4118     SrcReg = MI.getOperand(1).getReg();
4119     if (isIntRegForSubInst(DstReg) &&
4120         Hexagon::PredRegsRegClass.contains(SrcReg) && Hexagon::P0 == SrcReg &&
4121         MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0)
4122       return HexagonII::HSIG_A;
4123     break;
4124   case Hexagon::C2_cmpeqi:
4125   case Hexagon::dup_C2_cmpeqi:
4126     // P0 = cmp.eq(Rs,#u2)
4127     DstReg = MI.getOperand(0).getReg();
4128     SrcReg = MI.getOperand(1).getReg();
4129     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
4130         Hexagon::P0 == DstReg && isIntRegForSubInst(SrcReg) &&
4131         MI.getOperand(2).isImm() && isUInt<2>(MI.getOperand(2).getImm()))
4132       return HexagonII::HSIG_A;
4133     break;
4134   case Hexagon::A2_combineii:
4135   case Hexagon::A4_combineii:
4136   case Hexagon::dup_A2_combineii:
4137   case Hexagon::dup_A4_combineii:
4138     // Rdd = combine(#u2,#U2)
4139     DstReg = MI.getOperand(0).getReg();
4140     if (isDblRegForSubInst(DstReg, HRI) &&
4141         ((MI.getOperand(1).isImm() && isUInt<2>(MI.getOperand(1).getImm())) ||
4142         (MI.getOperand(1).isGlobal() &&
4143         isUInt<2>(MI.getOperand(1).getOffset()))) &&
4144         ((MI.getOperand(2).isImm() && isUInt<2>(MI.getOperand(2).getImm())) ||
4145         (MI.getOperand(2).isGlobal() &&
4146         isUInt<2>(MI.getOperand(2).getOffset()))))
4147       return HexagonII::HSIG_A;
4148     break;
4149   case Hexagon::A4_combineri:
4150   case Hexagon::dup_A4_combineri:
4151     // Rdd = combine(Rs,#0)
4152     // Rdd = combine(Rs,#0)
4153     DstReg = MI.getOperand(0).getReg();
4154     SrcReg = MI.getOperand(1).getReg();
4155     if (isDblRegForSubInst(DstReg, HRI) && isIntRegForSubInst(SrcReg) &&
4156         ((MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) ||
4157         (MI.getOperand(2).isGlobal() && MI.getOperand(2).getOffset() == 0)))
4158       return HexagonII::HSIG_A;
4159     break;
4160   case Hexagon::A4_combineir:
4161   case Hexagon::dup_A4_combineir:
4162     // Rdd = combine(#0,Rs)
4163     DstReg = MI.getOperand(0).getReg();
4164     SrcReg = MI.getOperand(2).getReg();
4165     if (isDblRegForSubInst(DstReg, HRI) && isIntRegForSubInst(SrcReg) &&
4166         ((MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) ||
4167         (MI.getOperand(1).isGlobal() && MI.getOperand(1).getOffset() == 0)))
4168       return HexagonII::HSIG_A;
4169     break;
4170   case Hexagon::A2_sxtb:
4171   case Hexagon::A2_sxth:
4172   case Hexagon::A2_zxtb:
4173   case Hexagon::A2_zxth:
4174   case Hexagon::dup_A2_sxtb:
4175   case Hexagon::dup_A2_sxth:
4176   case Hexagon::dup_A2_zxtb:
4177   case Hexagon::dup_A2_zxth:
4178     // Rd = sxth/sxtb/zxtb/zxth(Rs)
4179     DstReg = MI.getOperand(0).getReg();
4180     SrcReg = MI.getOperand(1).getReg();
4181     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg))
4182       return HexagonII::HSIG_A;
4183     break;
4184   }
4185 
4186   return HexagonII::HSIG_None;
4187 }
4188 
4189 short HexagonInstrInfo::getEquivalentHWInstr(const MachineInstr &MI) const {
4190   return Hexagon::getRealHWInstr(MI.getOpcode(), Hexagon::InstrType_Real);
4191 }
4192 
4193 unsigned HexagonInstrInfo::getInstrTimingClassLatency(
4194       const InstrItineraryData *ItinData, const MachineInstr &MI) const {
4195   // Default to one cycle for no itinerary. However, an "empty" itinerary may
4196   // still have a MinLatency property, which getStageLatency checks.
4197   if (!ItinData)
4198     return getInstrLatency(ItinData, MI);
4199 
4200   if (MI.isTransient())
4201     return 0;
4202   return ItinData->getStageLatency(MI.getDesc().getSchedClass());
4203 }
4204 
4205 /// getOperandLatency - Compute and return the use operand latency of a given
4206 /// pair of def and use.
4207 /// In most cases, the static scheduling itinerary was enough to determine the
4208 /// operand latency. But it may not be possible for instructions with variable
4209 /// number of defs / uses.
4210 ///
4211 /// This is a raw interface to the itinerary that may be directly overriden by
4212 /// a target. Use computeOperandLatency to get the best estimate of latency.
4213 int HexagonInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
4214                                         const MachineInstr &DefMI,
4215                                         unsigned DefIdx,
4216                                         const MachineInstr &UseMI,
4217                                         unsigned UseIdx) const {
4218   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
4219 
4220   // Get DefIdx and UseIdx for super registers.
4221   const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
4222 
4223   if (DefMO.isReg() && Register::isPhysicalRegister(DefMO.getReg())) {
4224     if (DefMO.isImplicit()) {
4225       for (MCSuperRegIterator SR(DefMO.getReg(), &HRI); SR.isValid(); ++SR) {
4226         int Idx = DefMI.findRegisterDefOperandIdx(*SR, false, false, &HRI);
4227         if (Idx != -1) {
4228           DefIdx = Idx;
4229           break;
4230         }
4231       }
4232     }
4233 
4234     const MachineOperand &UseMO = UseMI.getOperand(UseIdx);
4235     if (UseMO.isImplicit()) {
4236       for (MCSuperRegIterator SR(UseMO.getReg(), &HRI); SR.isValid(); ++SR) {
4237         int Idx = UseMI.findRegisterUseOperandIdx(*SR, false, &HRI);
4238         if (Idx != -1) {
4239           UseIdx = Idx;
4240           break;
4241         }
4242       }
4243     }
4244   }
4245 
4246   int Latency = TargetInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
4247                                                    UseMI, UseIdx);
4248   if (!Latency)
4249     // We should never have 0 cycle latency between two instructions unless
4250     // they can be packetized together. However, this decision can't be made
4251     // here.
4252     Latency = 1;
4253   return Latency;
4254 }
4255 
4256 // inverts the predication logic.
4257 // p -> NotP
4258 // NotP -> P
4259 bool HexagonInstrInfo::getInvertedPredSense(
4260       SmallVectorImpl<MachineOperand> &Cond) const {
4261   if (Cond.empty())
4262     return false;
4263   unsigned Opc = getInvertedPredicatedOpcode(Cond[0].getImm());
4264   Cond[0].setImm(Opc);
4265   return true;
4266 }
4267 
4268 unsigned HexagonInstrInfo::getInvertedPredicatedOpcode(const int Opc) const {
4269   int InvPredOpcode;
4270   InvPredOpcode = isPredicatedTrue(Opc) ? Hexagon::getFalsePredOpcode(Opc)
4271                                         : Hexagon::getTruePredOpcode(Opc);
4272   if (InvPredOpcode >= 0) // Valid instruction with the inverted predicate.
4273     return InvPredOpcode;
4274 
4275   llvm_unreachable("Unexpected predicated instruction");
4276 }
4277 
4278 // Returns the max value that doesn't need to be extended.
4279 int HexagonInstrInfo::getMaxValue(const MachineInstr &MI) const {
4280   const uint64_t F = MI.getDesc().TSFlags;
4281   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
4282                     & HexagonII::ExtentSignedMask;
4283   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
4284                     & HexagonII::ExtentBitsMask;
4285 
4286   if (isSigned) // if value is signed
4287     return ~(-1U << (bits - 1));
4288   else
4289     return ~(-1U << bits);
4290 }
4291 
4292 
4293 bool HexagonInstrInfo::isAddrModeWithOffset(const MachineInstr &MI) const {
4294   switch (MI.getOpcode()) {
4295   case Hexagon::L2_loadrbgp:
4296   case Hexagon::L2_loadrdgp:
4297   case Hexagon::L2_loadrhgp:
4298   case Hexagon::L2_loadrigp:
4299   case Hexagon::L2_loadrubgp:
4300   case Hexagon::L2_loadruhgp:
4301   case Hexagon::S2_storerbgp:
4302   case Hexagon::S2_storerbnewgp:
4303   case Hexagon::S2_storerhgp:
4304   case Hexagon::S2_storerhnewgp:
4305   case Hexagon::S2_storerigp:
4306   case Hexagon::S2_storerinewgp:
4307   case Hexagon::S2_storerdgp:
4308   case Hexagon::S2_storerfgp:
4309     return true;
4310   }
4311   const uint64_t F = MI.getDesc().TSFlags;
4312   unsigned addrMode =
4313     ((F >> HexagonII::AddrModePos) & HexagonII::AddrModeMask);
4314   // Disallow any base+offset instruction. The assembler does not yet reorder
4315   // based up any zero offset instruction.
4316   return (addrMode == HexagonII::BaseRegOffset ||
4317           addrMode == HexagonII::BaseImmOffset ||
4318           addrMode == HexagonII::BaseLongOffset);
4319 }
4320 
4321 bool HexagonInstrInfo::isPureSlot0(const MachineInstr &MI) const {
4322   // Workaround for the Global Scheduler. Sometimes, it creates
4323   // A4_ext as a Pseudo instruction and calls this function to see if
4324   // it can be added to an existing bundle. Since the instruction doesn't
4325   // belong to any BB yet, we can't use getUnits API.
4326   if (MI.getOpcode() == Hexagon::A4_ext)
4327     return false;
4328 
4329   unsigned FuncUnits = getUnits(MI);
4330   return HexagonFUnits::isSlot0Only(FuncUnits);
4331 }
4332 
4333 bool HexagonInstrInfo::isRestrictNoSlot1Store(const MachineInstr &MI) const {
4334   const uint64_t F = MI.getDesc().TSFlags;
4335   return ((F >> HexagonII::RestrictNoSlot1StorePos) &
4336           HexagonII::RestrictNoSlot1StoreMask);
4337 }
4338 
4339 void HexagonInstrInfo::changeDuplexOpcode(MachineBasicBlock::instr_iterator MII,
4340                                           bool ToBigInstrs) const {
4341   int Opcode = -1;
4342   if (ToBigInstrs) { // To BigCore Instr.
4343     // Check if the instruction can form a Duplex.
4344     if (getDuplexCandidateGroup(*MII))
4345       // Get the opcode marked "dup_*" tag.
4346       Opcode = getDuplexOpcode(*MII, ToBigInstrs);
4347   } else // To TinyCore Instr.
4348     Opcode = getDuplexOpcode(*MII, ToBigInstrs);
4349 
4350   // Change the opcode of the instruction.
4351   if (Opcode >= 0)
4352     MII->setDesc(get(Opcode));
4353 }
4354 
4355 // This function is used to translate instructions to facilitate generating
4356 // Duplexes on TinyCore.
4357 void HexagonInstrInfo::translateInstrsForDup(MachineFunction &MF,
4358                                              bool ToBigInstrs) const {
4359   for (auto &MB : MF)
4360     for (MachineBasicBlock::instr_iterator Instr = MB.instr_begin(),
4361                                            End = MB.instr_end();
4362          Instr != End; ++Instr)
4363       changeDuplexOpcode(Instr, ToBigInstrs);
4364 }
4365 
4366 // This is a specialized form of above function.
4367 void HexagonInstrInfo::translateInstrsForDup(
4368     MachineBasicBlock::instr_iterator MII, bool ToBigInstrs) const {
4369   MachineBasicBlock *MBB = MII->getParent();
4370   while ((MII != MBB->instr_end()) && MII->isInsideBundle()) {
4371     changeDuplexOpcode(MII, ToBigInstrs);
4372     ++MII;
4373   }
4374 }
4375 
4376 unsigned HexagonInstrInfo::getMemAccessSize(const MachineInstr &MI) const {
4377   using namespace HexagonII;
4378 
4379   const uint64_t F = MI.getDesc().TSFlags;
4380   unsigned S = (F >> MemAccessSizePos) & MemAccesSizeMask;
4381   unsigned Size = getMemAccessSizeInBytes(MemAccessSize(S));
4382   if (Size != 0)
4383     return Size;
4384 
4385   // Handle vector access sizes.
4386   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
4387   switch (S) {
4388     case HexagonII::HVXVectorAccess:
4389       return HRI.getSpillSize(Hexagon::HvxVRRegClass);
4390     default:
4391       llvm_unreachable("Unexpected instruction");
4392   }
4393 }
4394 
4395 // Returns the min value that doesn't need to be extended.
4396 int HexagonInstrInfo::getMinValue(const MachineInstr &MI) const {
4397   const uint64_t F = MI.getDesc().TSFlags;
4398   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
4399                     & HexagonII::ExtentSignedMask;
4400   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
4401                     & HexagonII::ExtentBitsMask;
4402 
4403   if (isSigned) // if value is signed
4404     return -1U << (bits - 1);
4405   else
4406     return 0;
4407 }
4408 
4409 // Returns opcode of the non-extended equivalent instruction.
4410 short HexagonInstrInfo::getNonExtOpcode(const MachineInstr &MI) const {
4411   // Check if the instruction has a register form that uses register in place
4412   // of the extended operand, if so return that as the non-extended form.
4413   short NonExtOpcode = Hexagon::getRegForm(MI.getOpcode());
4414     if (NonExtOpcode >= 0)
4415       return NonExtOpcode;
4416 
4417   if (MI.getDesc().mayLoad() || MI.getDesc().mayStore()) {
4418     // Check addressing mode and retrieve non-ext equivalent instruction.
4419     switch (getAddrMode(MI)) {
4420     case HexagonII::Absolute:
4421       return Hexagon::changeAddrMode_abs_io(MI.getOpcode());
4422     case HexagonII::BaseImmOffset:
4423       return Hexagon::changeAddrMode_io_rr(MI.getOpcode());
4424     case HexagonII::BaseLongOffset:
4425       return Hexagon::changeAddrMode_ur_rr(MI.getOpcode());
4426 
4427     default:
4428       return -1;
4429     }
4430   }
4431   return -1;
4432 }
4433 
4434 bool HexagonInstrInfo::getPredReg(ArrayRef<MachineOperand> Cond,
4435       unsigned &PredReg, unsigned &PredRegPos, unsigned &PredRegFlags) const {
4436   if (Cond.empty())
4437     return false;
4438   assert(Cond.size() == 2);
4439   if (isNewValueJump(Cond[0].getImm()) || Cond[1].isMBB()) {
4440     LLVM_DEBUG(dbgs() << "No predregs for new-value jumps/endloop");
4441     return false;
4442   }
4443   PredReg = Cond[1].getReg();
4444   PredRegPos = 1;
4445   // See IfConversion.cpp why we add RegState::Implicit | RegState::Undef
4446   PredRegFlags = 0;
4447   if (Cond[1].isImplicit())
4448     PredRegFlags = RegState::Implicit;
4449   if (Cond[1].isUndef())
4450     PredRegFlags |= RegState::Undef;
4451   return true;
4452 }
4453 
4454 short HexagonInstrInfo::getPseudoInstrPair(const MachineInstr &MI) const {
4455   return Hexagon::getRealHWInstr(MI.getOpcode(), Hexagon::InstrType_Pseudo);
4456 }
4457 
4458 short HexagonInstrInfo::getRegForm(const MachineInstr &MI) const {
4459   return Hexagon::getRegForm(MI.getOpcode());
4460 }
4461 
4462 // Return the number of bytes required to encode the instruction.
4463 // Hexagon instructions are fixed length, 4 bytes, unless they
4464 // use a constant extender, which requires another 4 bytes.
4465 // For debug instructions and prolog labels, return 0.
4466 unsigned HexagonInstrInfo::getSize(const MachineInstr &MI) const {
4467   if (MI.isDebugInstr() || MI.isPosition())
4468     return 0;
4469 
4470   unsigned Size = MI.getDesc().getSize();
4471   if (!Size)
4472     // Assume the default insn size in case it cannot be determined
4473     // for whatever reason.
4474     Size = HEXAGON_INSTR_SIZE;
4475 
4476   if (isConstExtended(MI) || isExtended(MI))
4477     Size += HEXAGON_INSTR_SIZE;
4478 
4479   // Try and compute number of instructions in asm.
4480   if (BranchRelaxAsmLarge && MI.getOpcode() == Hexagon::INLINEASM) {
4481     const MachineBasicBlock &MBB = *MI.getParent();
4482     const MachineFunction *MF = MBB.getParent();
4483     const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
4484 
4485     // Count the number of register definitions to find the asm string.
4486     unsigned NumDefs = 0;
4487     for (; MI.getOperand(NumDefs).isReg() && MI.getOperand(NumDefs).isDef();
4488          ++NumDefs)
4489       assert(NumDefs != MI.getNumOperands()-2 && "No asm string?");
4490 
4491     assert(MI.getOperand(NumDefs).isSymbol() && "No asm string?");
4492     // Disassemble the AsmStr and approximate number of instructions.
4493     const char *AsmStr = MI.getOperand(NumDefs).getSymbolName();
4494     Size = getInlineAsmLength(AsmStr, *MAI);
4495   }
4496 
4497   return Size;
4498 }
4499 
4500 uint64_t HexagonInstrInfo::getType(const MachineInstr &MI) const {
4501   const uint64_t F = MI.getDesc().TSFlags;
4502   return (F >> HexagonII::TypePos) & HexagonII::TypeMask;
4503 }
4504 
4505 InstrStage::FuncUnits HexagonInstrInfo::getUnits(const MachineInstr &MI) const {
4506   const InstrItineraryData &II = *Subtarget.getInstrItineraryData();
4507   const InstrStage &IS = *II.beginStage(MI.getDesc().getSchedClass());
4508 
4509   return IS.getUnits();
4510 }
4511 
4512 // Calculate size of the basic block without debug instructions.
4513 unsigned HexagonInstrInfo::nonDbgBBSize(const MachineBasicBlock *BB) const {
4514   return nonDbgMICount(BB->instr_begin(), BB->instr_end());
4515 }
4516 
4517 unsigned HexagonInstrInfo::nonDbgBundleSize(
4518       MachineBasicBlock::const_iterator BundleHead) const {
4519   assert(BundleHead->isBundle() && "Not a bundle header");
4520   auto MII = BundleHead.getInstrIterator();
4521   // Skip the bundle header.
4522   return nonDbgMICount(++MII, getBundleEnd(BundleHead.getInstrIterator()));
4523 }
4524 
4525 /// immediateExtend - Changes the instruction in place to one using an immediate
4526 /// extender.
4527 void HexagonInstrInfo::immediateExtend(MachineInstr &MI) const {
4528   assert((isExtendable(MI)||isConstExtended(MI)) &&
4529                                "Instruction must be extendable");
4530   // Find which operand is extendable.
4531   short ExtOpNum = getCExtOpNum(MI);
4532   MachineOperand &MO = MI.getOperand(ExtOpNum);
4533   // This needs to be something we understand.
4534   assert((MO.isMBB() || MO.isImm()) &&
4535          "Branch with unknown extendable field type");
4536   // Mark given operand as extended.
4537   MO.addTargetFlag(HexagonII::HMOTF_ConstExtended);
4538 }
4539 
4540 bool HexagonInstrInfo::invertAndChangeJumpTarget(
4541       MachineInstr &MI, MachineBasicBlock *NewTarget) const {
4542   LLVM_DEBUG(dbgs() << "\n[invertAndChangeJumpTarget] to "
4543                     << printMBBReference(*NewTarget);
4544              MI.dump(););
4545   assert(MI.isBranch());
4546   unsigned NewOpcode = getInvertedPredicatedOpcode(MI.getOpcode());
4547   int TargetPos = MI.getNumOperands() - 1;
4548   // In general branch target is the last operand,
4549   // but some implicit defs added at the end might change it.
4550   while ((TargetPos > -1) && !MI.getOperand(TargetPos).isMBB())
4551     --TargetPos;
4552   assert((TargetPos >= 0) && MI.getOperand(TargetPos).isMBB());
4553   MI.getOperand(TargetPos).setMBB(NewTarget);
4554   if (EnableBranchPrediction && isPredicatedNew(MI)) {
4555     NewOpcode = reversePrediction(NewOpcode);
4556   }
4557   MI.setDesc(get(NewOpcode));
4558   return true;
4559 }
4560 
4561 void HexagonInstrInfo::genAllInsnTimingClasses(MachineFunction &MF) const {
4562   /* +++ The code below is used to generate complete set of Hexagon Insn +++ */
4563   MachineFunction::iterator A = MF.begin();
4564   MachineBasicBlock &B = *A;
4565   MachineBasicBlock::iterator I = B.begin();
4566   DebugLoc DL = I->getDebugLoc();
4567   MachineInstr *NewMI;
4568 
4569   for (unsigned insn = TargetOpcode::GENERIC_OP_END+1;
4570        insn < Hexagon::INSTRUCTION_LIST_END; ++insn) {
4571     NewMI = BuildMI(B, I, DL, get(insn));
4572     LLVM_DEBUG(dbgs() << "\n"
4573                       << getName(NewMI->getOpcode())
4574                       << "  Class: " << NewMI->getDesc().getSchedClass());
4575     NewMI->eraseFromParent();
4576   }
4577   /* --- The code above is used to generate complete set of Hexagon Insn --- */
4578 }
4579 
4580 // inverts the predication logic.
4581 // p -> NotP
4582 // NotP -> P
4583 bool HexagonInstrInfo::reversePredSense(MachineInstr &MI) const {
4584   LLVM_DEBUG(dbgs() << "\nTrying to reverse pred. sense of:"; MI.dump());
4585   MI.setDesc(get(getInvertedPredicatedOpcode(MI.getOpcode())));
4586   return true;
4587 }
4588 
4589 // Reverse the branch prediction.
4590 unsigned HexagonInstrInfo::reversePrediction(unsigned Opcode) const {
4591   int PredRevOpcode = -1;
4592   if (isPredictedTaken(Opcode))
4593     PredRevOpcode = Hexagon::notTakenBranchPrediction(Opcode);
4594   else
4595     PredRevOpcode = Hexagon::takenBranchPrediction(Opcode);
4596   assert(PredRevOpcode > 0);
4597   return PredRevOpcode;
4598 }
4599 
4600 // TODO: Add more rigorous validation.
4601 bool HexagonInstrInfo::validateBranchCond(const ArrayRef<MachineOperand> &Cond)
4602       const {
4603   return Cond.empty() || (Cond[0].isImm() && (Cond.size() != 1));
4604 }
4605 
4606 void HexagonInstrInfo::
4607 setBundleNoShuf(MachineBasicBlock::instr_iterator MIB) const {
4608   assert(MIB->isBundle());
4609   MachineOperand &Operand = MIB->getOperand(0);
4610   if (Operand.isImm())
4611     Operand.setImm(Operand.getImm() | memShufDisabledMask);
4612   else
4613     MIB->addOperand(MachineOperand::CreateImm(memShufDisabledMask));
4614 }
4615 
4616 bool HexagonInstrInfo::getBundleNoShuf(const MachineInstr &MIB) const {
4617   assert(MIB.isBundle());
4618   const MachineOperand &Operand = MIB.getOperand(0);
4619   return (Operand.isImm() && (Operand.getImm() & memShufDisabledMask) != 0);
4620 }
4621 
4622 // Addressing mode relations.
4623 short HexagonInstrInfo::changeAddrMode_abs_io(short Opc) const {
4624   return Opc >= 0 ? Hexagon::changeAddrMode_abs_io(Opc) : Opc;
4625 }
4626 
4627 short HexagonInstrInfo::changeAddrMode_io_abs(short Opc) const {
4628   return Opc >= 0 ? Hexagon::changeAddrMode_io_abs(Opc) : Opc;
4629 }
4630 
4631 short HexagonInstrInfo::changeAddrMode_io_pi(short Opc) const {
4632   return Opc >= 0 ? Hexagon::changeAddrMode_io_pi(Opc) : Opc;
4633 }
4634 
4635 short HexagonInstrInfo::changeAddrMode_io_rr(short Opc) const {
4636   return Opc >= 0 ? Hexagon::changeAddrMode_io_rr(Opc) : Opc;
4637 }
4638 
4639 short HexagonInstrInfo::changeAddrMode_pi_io(short Opc) const {
4640   return Opc >= 0 ? Hexagon::changeAddrMode_pi_io(Opc) : Opc;
4641 }
4642 
4643 short HexagonInstrInfo::changeAddrMode_rr_io(short Opc) const {
4644   return Opc >= 0 ? Hexagon::changeAddrMode_rr_io(Opc) : Opc;
4645 }
4646 
4647 short HexagonInstrInfo::changeAddrMode_rr_ur(short Opc) const {
4648   return Opc >= 0 ? Hexagon::changeAddrMode_rr_ur(Opc) : Opc;
4649 }
4650 
4651 short HexagonInstrInfo::changeAddrMode_ur_rr(short Opc) const {
4652   return Opc >= 0 ? Hexagon::changeAddrMode_ur_rr(Opc) : Opc;
4653 }
4654