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