[Hexagon] Handle ENDLOOP0 in InsertBranch and RemoveBranch
[oota-llvm.git] / 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 "HexagonInstrInfo.h"
15 #include "Hexagon.h"
16 #include "HexagonRegisterInfo.h"
17 #include "HexagonSubtarget.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/CodeGen/DFAPacketizer.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineMemOperand.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/raw_ostream.h"
29
30 using namespace llvm;
31
32 #define DEBUG_TYPE "hexagon-instrinfo"
33
34 #define GET_INSTRINFO_CTOR_DTOR
35 #define GET_INSTRMAP_INFO
36 #include "HexagonGenInstrInfo.inc"
37 #include "HexagonGenDFAPacketizer.inc"
38
39 ///
40 /// Constants for Hexagon instructions.
41 ///
42 const int Hexagon_MEMW_OFFSET_MAX = 4095;
43 const int Hexagon_MEMW_OFFSET_MIN = -4096;
44 const int Hexagon_MEMD_OFFSET_MAX = 8191;
45 const int Hexagon_MEMD_OFFSET_MIN = -8192;
46 const int Hexagon_MEMH_OFFSET_MAX = 2047;
47 const int Hexagon_MEMH_OFFSET_MIN = -2048;
48 const int Hexagon_MEMB_OFFSET_MAX = 1023;
49 const int Hexagon_MEMB_OFFSET_MIN = -1024;
50 const int Hexagon_ADDI_OFFSET_MAX = 32767;
51 const int Hexagon_ADDI_OFFSET_MIN = -32768;
52 const int Hexagon_MEMD_AUTOINC_MAX = 56;
53 const int Hexagon_MEMD_AUTOINC_MIN = -64;
54 const int Hexagon_MEMW_AUTOINC_MAX = 28;
55 const int Hexagon_MEMW_AUTOINC_MIN = -32;
56 const int Hexagon_MEMH_AUTOINC_MAX = 14;
57 const int Hexagon_MEMH_AUTOINC_MIN = -16;
58 const int Hexagon_MEMB_AUTOINC_MAX = 7;
59 const int Hexagon_MEMB_AUTOINC_MIN = -8;
60
61 // Pin the vtable to this file.
62 void HexagonInstrInfo::anchor() {}
63
64 HexagonInstrInfo::HexagonInstrInfo(HexagonSubtarget &ST)
65     : HexagonGenInstrInfo(Hexagon::ADJCALLSTACKDOWN, Hexagon::ADJCALLSTACKUP),
66       RI(), Subtarget(ST) {}
67
68 /// isLoadFromStackSlot - If the specified machine instruction is a direct
69 /// load from a stack slot, return the virtual or physical register number of
70 /// the destination along with the FrameIndex of the loaded stack slot.  If
71 /// not, return 0.  This predicate must return 0 if the instruction has
72 /// any side effects other than loading from the stack slot.
73 unsigned HexagonInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
74                                              int &FrameIndex) const {
75
76
77   switch (MI->getOpcode()) {
78   default: break;
79   case Hexagon::L2_loadri_io:
80   case Hexagon::L2_loadrd_io:
81   case Hexagon::L2_loadrh_io:
82   case Hexagon::L2_loadrb_io:
83   case Hexagon::L2_loadrub_io:
84     if (MI->getOperand(2).isFI() &&
85         MI->getOperand(1).isImm() && (MI->getOperand(1).getImm() == 0)) {
86       FrameIndex = MI->getOperand(2).getIndex();
87       return MI->getOperand(0).getReg();
88     }
89     break;
90   }
91   return 0;
92 }
93
94
95 /// isStoreToStackSlot - If the specified machine instruction is a direct
96 /// store to a stack slot, return the virtual or physical register number of
97 /// the source reg along with the FrameIndex of the loaded stack slot.  If
98 /// not, return 0.  This predicate must return 0 if the instruction has
99 /// any side effects other than storing to the stack slot.
100 unsigned HexagonInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
101                                             int &FrameIndex) const {
102   switch (MI->getOpcode()) {
103   default: break;
104   case Hexagon::S2_storeri_io:
105   case Hexagon::S2_storerd_io:
106   case Hexagon::S2_storerh_io:
107   case Hexagon::S2_storerb_io:
108     if (MI->getOperand(2).isFI() &&
109         MI->getOperand(1).isImm() && (MI->getOperand(1).getImm() == 0)) {
110       FrameIndex = MI->getOperand(0).getIndex();
111       return MI->getOperand(2).getReg();
112     }
113     break;
114   }
115   return 0;
116 }
117
118
119 unsigned
120 HexagonInstrInfo::InsertBranch(MachineBasicBlock &MBB,MachineBasicBlock *TBB,
121                              MachineBasicBlock *FBB,
122                              const SmallVectorImpl<MachineOperand> &Cond,
123                              DebugLoc DL) const{
124
125     int BOpc   = Hexagon::J2_jump;
126     int BccOpc = Hexagon::J2_jumpt;
127
128     assert(TBB && "InsertBranch must not be told to insert a fallthrough");
129
130     int regPos = 0;
131     // Check if ReverseBranchCondition has asked to reverse this branch
132     // If we want to reverse the branch an odd number of times, we want
133     // JMP_f.
134     if (!Cond.empty() && Cond[0].isImm() && Cond[0].getImm() == 0) {
135       BccOpc = Hexagon::J2_jumpf;
136       regPos = 1;
137     }
138
139     if (!FBB) {
140       if (Cond.empty()) {
141         // Due to a bug in TailMerging/CFG Optimization, we need to add a
142         // special case handling of a predicated jump followed by an
143         // unconditional jump. If not, Tail Merging and CFG Optimization go
144         // into an infinite loop.
145         MachineBasicBlock *NewTBB, *NewFBB;
146         SmallVector<MachineOperand, 4> Cond;
147         MachineInstr *Term = MBB.getFirstTerminator();
148         if (isPredicated(Term) && !AnalyzeBranch(MBB, NewTBB, NewFBB, Cond,
149                                                  false)) {
150           MachineBasicBlock *NextBB =
151             std::next(MachineFunction::iterator(&MBB));
152           if (NewTBB == NextBB) {
153             ReverseBranchCondition(Cond);
154             RemoveBranch(MBB);
155             return InsertBranch(MBB, TBB, nullptr, Cond, DL);
156           }
157         }
158         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
159       } else {
160         // If Cond[0] is a basic block, insert ENDLOOP0.
161         if (Cond[0].isMBB())
162           BuildMI(&MBB, DL, get(Hexagon::ENDLOOP0)).addMBB(Cond[0].getMBB());
163         else
164           BuildMI(&MBB, DL,
165                   get(BccOpc)).addReg(Cond[regPos].getReg()).addMBB(TBB);
166       }
167       return 1;
168     }
169
170     // We don't handle ENDLOOP0 with a conditional branch in AnalyzeBranch.
171     BuildMI(&MBB, DL, get(BccOpc)).addReg(Cond[regPos].getReg()).addMBB(TBB);
172     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
173     return 2;
174 }
175
176
177 bool HexagonInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
178                                      MachineBasicBlock *&TBB,
179                                  MachineBasicBlock *&FBB,
180                                  SmallVectorImpl<MachineOperand> &Cond,
181                                  bool AllowModify) const {
182   TBB = nullptr;
183   FBB = nullptr;
184
185   // If the block has no terminators, it just falls into the block after it.
186   MachineBasicBlock::instr_iterator I = MBB.instr_end();
187   if (I == MBB.instr_begin())
188     return false;
189
190   // A basic block may looks like this:
191   //
192   //  [   insn
193   //     EH_LABEL
194   //      insn
195   //      insn
196   //      insn
197   //     EH_LABEL
198   //      insn     ]
199   //
200   // It has two succs but does not have a terminator
201   // Don't know how to handle it.
202   do {
203     --I;
204     if (I->isEHLabel())
205       return true;
206   } while (I != MBB.instr_begin());
207
208   I = MBB.instr_end();
209   --I;
210
211   while (I->isDebugValue()) {
212     if (I == MBB.instr_begin())
213       return false;
214     --I;
215   }
216   
217   bool JumpToBlock = I->getOpcode() == Hexagon::J2_jump &&
218                      I->getOperand(0).isMBB();
219   // Delete the JMP if it's equivalent to a fall-through.
220   if (AllowModify && JumpToBlock &&
221       MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
222     DEBUG(dbgs()<< "\nErasing the jump to successor block\n";);
223     I->eraseFromParent();
224     I = MBB.instr_end();
225     if (I == MBB.instr_begin())
226       return false;
227     --I;
228   }
229   if (!isUnpredicatedTerminator(I))
230     return false;
231
232   // Get the last instruction in the block.
233   MachineInstr *LastInst = I;
234   MachineInstr *SecondLastInst = nullptr;
235   // Find one more terminator if present.
236   do {
237     if (&*I != LastInst && !I->isBundle() && isUnpredicatedTerminator(I)) {
238       if (!SecondLastInst)
239         SecondLastInst = I;
240       else
241         // This is a third branch.
242         return true;
243     }
244     if (I == MBB.instr_begin())
245       break;
246     --I;
247   } while(I);
248
249   int LastOpcode = LastInst->getOpcode();
250   int SecLastOpcode = SecondLastInst ? SecondLastInst->getOpcode() : 0;
251   // If the branch target is not a basic block, it could be a tail call.
252   // (It is, if the target is a function.)
253   if (LastOpcode == Hexagon::J2_jump && !LastInst->getOperand(0).isMBB())
254     return true;
255   if (SecLastOpcode == Hexagon::J2_jump &&
256       !SecondLastInst->getOperand(0).isMBB())
257     return true;
258
259   bool LastOpcodeHasJMP_c = PredOpcodeHasJMP_c(LastOpcode);
260   bool LastOpcodeHasNot = PredOpcodeHasNot(LastOpcode);
261
262   // If there is only one terminator instruction, process it.
263   if (LastInst && !SecondLastInst) {
264     if (LastOpcode == Hexagon::J2_jump) {
265       TBB = LastInst->getOperand(0).getMBB();
266       return false;
267     }
268     if (LastOpcode == Hexagon::ENDLOOP0) {
269       TBB = LastInst->getOperand(0).getMBB();
270       Cond.push_back(LastInst->getOperand(0));
271       return false;
272     }
273     if (LastOpcodeHasJMP_c) {
274       TBB = LastInst->getOperand(1).getMBB();
275       if (LastOpcodeHasNot) {
276         Cond.push_back(MachineOperand::CreateImm(0));
277       }
278       Cond.push_back(LastInst->getOperand(0));
279       return false;
280     }
281     // Otherwise, don't know what this is.
282     return true;
283   }
284
285   bool SecLastOpcodeHasJMP_c = PredOpcodeHasJMP_c(SecLastOpcode);
286   bool SecLastOpcodeHasNot = PredOpcodeHasNot(SecLastOpcode);
287   if (SecLastOpcodeHasJMP_c && (LastOpcode == Hexagon::J2_jump)) {
288     TBB =  SecondLastInst->getOperand(1).getMBB();
289     if (SecLastOpcodeHasNot)
290       Cond.push_back(MachineOperand::CreateImm(0));
291     Cond.push_back(SecondLastInst->getOperand(0));
292     FBB = LastInst->getOperand(0).getMBB();
293     return false;
294   }
295
296   // If the block ends with two Hexagon:JMPs, handle it.  The second one is not
297   // executed, so remove it.
298   if (SecLastOpcode == Hexagon::J2_jump && LastOpcode == Hexagon::J2_jump) {
299     TBB = SecondLastInst->getOperand(0).getMBB();
300     I = LastInst;
301     if (AllowModify)
302       I->eraseFromParent();
303     return false;
304   }
305
306   // If the block ends with an ENDLOOP, and JMP, handle it.
307   if (SecLastOpcode == Hexagon::ENDLOOP0 &&
308       LastOpcode == Hexagon::J2_jump) {
309     TBB = SecondLastInst->getOperand(0).getMBB();
310     Cond.push_back(SecondLastInst->getOperand(0));
311     FBB = LastInst->getOperand(0).getMBB();
312     return false;
313   }
314
315   // Otherwise, can't handle this.
316   return true;
317 }
318
319
320 unsigned HexagonInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
321   MachineBasicBlock::iterator I = MBB.end();
322   if (I == MBB.begin()) return 0;
323   --I;
324   unsigned Opc1 = I->getOpcode();
325   switch (Opc1) {
326     case Hexagon::J2_jump:
327     case Hexagon::J2_jumpt:
328     case Hexagon::J2_jumpf:
329     case Hexagon::ENDLOOP0:
330       I->eraseFromParent();
331       break;
332     default:
333       return 0;
334   }
335
336   I = MBB.end();
337
338   if (I == MBB.begin()) return 1;
339   --I;
340   unsigned Opc2 = I->getOpcode();
341   switch (Opc2) {
342     case Hexagon::J2_jumpt:
343     case Hexagon::J2_jumpf:
344     case Hexagon::ENDLOOP0:
345       I->eraseFromParent();
346       return 2;
347     default:
348       return 1;
349   }
350 }
351
352
353 /// \brief For a comparison instruction, return the source registers in
354 /// \p SrcReg and \p SrcReg2 if having two register operands, and the value it
355 /// compares against in CmpValue. Return true if the comparison instruction
356 /// can be analyzed.
357 bool HexagonInstrInfo::analyzeCompare(const MachineInstr *MI,
358                                       unsigned &SrcReg, unsigned &SrcReg2,
359                                       int &Mask, int &Value) const {
360   unsigned Opc = MI->getOpcode();
361
362   // Set mask and the first source register.
363   switch (Opc) {
364     case Hexagon::C2_cmpeqp:
365     case Hexagon::C2_cmpeqi:
366     case Hexagon::C2_cmpeq:
367     case Hexagon::C2_cmpgtp:
368     case Hexagon::C2_cmpgtup:
369     case Hexagon::C2_cmpgtui:
370     case Hexagon::C2_cmpgtu:
371     case Hexagon::C2_cmpgti:
372     case Hexagon::C2_cmpgt:
373       SrcReg = MI->getOperand(1).getReg();
374       Mask = ~0;
375       break;
376     case Hexagon::A4_cmpbeqi:
377     case Hexagon::A4_cmpbeq:
378     case Hexagon::A4_cmpbgtui:
379     case Hexagon::A4_cmpbgtu:
380     case Hexagon::A4_cmpbgt:
381       SrcReg = MI->getOperand(1).getReg();
382       Mask = 0xFF;
383       break;
384     case Hexagon::A4_cmpheqi:
385     case Hexagon::A4_cmpheq:
386     case Hexagon::A4_cmphgtui:
387     case Hexagon::A4_cmphgtu:
388     case Hexagon::A4_cmphgt:
389       SrcReg = MI->getOperand(1).getReg();
390       Mask = 0xFFFF;
391       break;
392   }
393
394   // Set the value/second source register.
395   switch (Opc) {
396     case Hexagon::C2_cmpeqp:
397     case Hexagon::C2_cmpeq:
398     case Hexagon::C2_cmpgtp:
399     case Hexagon::C2_cmpgtup:
400     case Hexagon::C2_cmpgtu:
401     case Hexagon::C2_cmpgt:
402     case Hexagon::A4_cmpbeq:
403     case Hexagon::A4_cmpbgtu:
404     case Hexagon::A4_cmpbgt:
405     case Hexagon::A4_cmpheq:
406     case Hexagon::A4_cmphgtu:
407     case Hexagon::A4_cmphgt:
408       SrcReg2 = MI->getOperand(2).getReg();
409       return true;
410
411     case Hexagon::C2_cmpeqi:
412     case Hexagon::C2_cmpgtui:
413     case Hexagon::C2_cmpgti:
414     case Hexagon::A4_cmpbeqi:
415     case Hexagon::A4_cmpbgtui:
416     case Hexagon::A4_cmpheqi:
417     case Hexagon::A4_cmphgtui:
418       SrcReg2 = 0;
419       Value = MI->getOperand(2).getImm();
420       return true;
421   }
422
423   return false;
424 }
425
426
427 void HexagonInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
428                                  MachineBasicBlock::iterator I, DebugLoc DL,
429                                  unsigned DestReg, unsigned SrcReg,
430                                  bool KillSrc) const {
431   if (Hexagon::IntRegsRegClass.contains(SrcReg, DestReg)) {
432     BuildMI(MBB, I, DL, get(Hexagon::A2_tfr), DestReg).addReg(SrcReg);
433     return;
434   }
435   if (Hexagon::DoubleRegsRegClass.contains(SrcReg, DestReg)) {
436     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrp), DestReg).addReg(SrcReg);
437     return;
438   }
439   if (Hexagon::PredRegsRegClass.contains(SrcReg, DestReg)) {
440     // Map Pd = Ps to Pd = or(Ps, Ps).
441     BuildMI(MBB, I, DL, get(Hexagon::C2_or),
442             DestReg).addReg(SrcReg).addReg(SrcReg);
443     return;
444   }
445   if (Hexagon::DoubleRegsRegClass.contains(DestReg) &&
446       Hexagon::IntRegsRegClass.contains(SrcReg)) {
447     // We can have an overlap between single and double reg: r1:0 = r0.
448     if(SrcReg == RI.getSubReg(DestReg, Hexagon::subreg_loreg)) {
449         // r1:0 = r0
450         BuildMI(MBB, I, DL, get(Hexagon::A2_tfrsi), (RI.getSubReg(DestReg,
451                 Hexagon::subreg_hireg))).addImm(0);
452     } else {
453         // r1:0 = r1 or no overlap.
454         BuildMI(MBB, I, DL, get(Hexagon::A2_tfr), (RI.getSubReg(DestReg,
455                 Hexagon::subreg_loreg))).addReg(SrcReg);
456         BuildMI(MBB, I, DL, get(Hexagon::A2_tfrsi), (RI.getSubReg(DestReg,
457                 Hexagon::subreg_hireg))).addImm(0);
458     }
459     return;
460   }
461   if (Hexagon::CtrRegsRegClass.contains(DestReg) &&
462       Hexagon::IntRegsRegClass.contains(SrcReg)) {
463     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrrcr), DestReg).addReg(SrcReg);
464     return;
465   }
466   if (Hexagon::PredRegsRegClass.contains(SrcReg) &&
467       Hexagon::IntRegsRegClass.contains(DestReg)) {
468     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrpr), DestReg).
469       addReg(SrcReg, getKillRegState(KillSrc));
470     return;
471   }
472   if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
473       Hexagon::PredRegsRegClass.contains(DestReg)) {
474     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrrp), DestReg).
475       addReg(SrcReg, getKillRegState(KillSrc));
476     return;
477   }
478
479   llvm_unreachable("Unimplemented");
480 }
481
482
483 void HexagonInstrInfo::
484 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
485                     unsigned SrcReg, bool isKill, int FI,
486                     const TargetRegisterClass *RC,
487                     const TargetRegisterInfo *TRI) const {
488
489   DebugLoc DL = MBB.findDebugLoc(I);
490   MachineFunction &MF = *MBB.getParent();
491   MachineFrameInfo &MFI = *MF.getFrameInfo();
492   unsigned Align = MFI.getObjectAlignment(FI);
493
494   MachineMemOperand *MMO =
495       MF.getMachineMemOperand(
496                       MachinePointerInfo(PseudoSourceValue::getFixedStack(FI)),
497                       MachineMemOperand::MOStore,
498                       MFI.getObjectSize(FI),
499                       Align);
500
501   if (Hexagon::IntRegsRegClass.hasSubClassEq(RC)) {
502     BuildMI(MBB, I, DL, get(Hexagon::S2_storeri_io))
503           .addFrameIndex(FI).addImm(0)
504           .addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
505   } else if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC)) {
506     BuildMI(MBB, I, DL, get(Hexagon::S2_storerd_io))
507           .addFrameIndex(FI).addImm(0)
508           .addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
509   } else if (Hexagon::PredRegsRegClass.hasSubClassEq(RC)) {
510     BuildMI(MBB, I, DL, get(Hexagon::STriw_pred))
511           .addFrameIndex(FI).addImm(0)
512           .addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
513   } else {
514     llvm_unreachable("Unimplemented");
515   }
516 }
517
518
519 void HexagonInstrInfo::storeRegToAddr(
520                                  MachineFunction &MF, unsigned SrcReg,
521                                  bool isKill,
522                                  SmallVectorImpl<MachineOperand> &Addr,
523                                  const TargetRegisterClass *RC,
524                                  SmallVectorImpl<MachineInstr*> &NewMIs) const
525 {
526   llvm_unreachable("Unimplemented");
527 }
528
529
530 void HexagonInstrInfo::
531 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
532                      unsigned DestReg, int FI,
533                      const TargetRegisterClass *RC,
534                      const TargetRegisterInfo *TRI) const {
535   DebugLoc DL = MBB.findDebugLoc(I);
536   MachineFunction &MF = *MBB.getParent();
537   MachineFrameInfo &MFI = *MF.getFrameInfo();
538   unsigned Align = MFI.getObjectAlignment(FI);
539
540   MachineMemOperand *MMO =
541       MF.getMachineMemOperand(
542                       MachinePointerInfo(PseudoSourceValue::getFixedStack(FI)),
543                       MachineMemOperand::MOLoad,
544                       MFI.getObjectSize(FI),
545                       Align);
546   if (RC == &Hexagon::IntRegsRegClass) {
547     BuildMI(MBB, I, DL, get(Hexagon::L2_loadri_io), DestReg)
548           .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
549   } else if (RC == &Hexagon::DoubleRegsRegClass) {
550     BuildMI(MBB, I, DL, get(Hexagon::L2_loadrd_io), DestReg)
551           .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
552   } else if (RC == &Hexagon::PredRegsRegClass) {
553     BuildMI(MBB, I, DL, get(Hexagon::LDriw_pred), DestReg)
554           .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
555   } else {
556     llvm_unreachable("Can't store this register to stack slot");
557   }
558 }
559
560
561 void HexagonInstrInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
562                                         SmallVectorImpl<MachineOperand> &Addr,
563                                         const TargetRegisterClass *RC,
564                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
565   llvm_unreachable("Unimplemented");
566 }
567 bool
568 HexagonInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
569   unsigned Opc = MI->getOpcode();
570
571   switch (Opc) {
572     case Hexagon::TCRETURNi:
573       MI->setDesc(get(Hexagon::J2_jump));
574       return true;
575     case Hexagon::TCRETURNr:
576       MI->setDesc(get(Hexagon::J2_jumpr));
577       return true;
578   }
579
580   return false;
581 }
582
583 MachineInstr *HexagonInstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
584                                                       MachineInstr *MI,
585                                                       ArrayRef<unsigned> Ops,
586                                                       int FI) const {
587   // Hexagon_TODO: Implement.
588   return nullptr;
589 }
590
591 unsigned HexagonInstrInfo::createVR(MachineFunction* MF, MVT VT) const {
592
593   MachineRegisterInfo &RegInfo = MF->getRegInfo();
594   const TargetRegisterClass *TRC;
595   if (VT == MVT::i1) {
596     TRC = &Hexagon::PredRegsRegClass;
597   } else if (VT == MVT::i32 || VT == MVT::f32) {
598     TRC = &Hexagon::IntRegsRegClass;
599   } else if (VT == MVT::i64 || VT == MVT::f64) {
600     TRC = &Hexagon::DoubleRegsRegClass;
601   } else {
602     llvm_unreachable("Cannot handle this register class");
603   }
604
605   unsigned NewReg = RegInfo.createVirtualRegister(TRC);
606   return NewReg;
607 }
608
609 bool HexagonInstrInfo::isExtendable(const MachineInstr *MI) const {
610   const MCInstrDesc &MID = MI->getDesc();
611   const uint64_t F = MID.TSFlags;
612   if ((F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask)
613     return true;
614
615   // TODO: This is largely obsolete now. Will need to be removed
616   // in consecutive patches.
617   switch(MI->getOpcode()) {
618     // TFR_FI Remains a special case.
619     case Hexagon::TFR_FI:
620       return true;
621     default:
622       return false;
623   }
624   return  false;
625 }
626
627 // This returns true in two cases:
628 // - The OP code itself indicates that this is an extended instruction.
629 // - One of MOs has been marked with HMOTF_ConstExtended flag.
630 bool HexagonInstrInfo::isExtended(const MachineInstr *MI) const {
631   // First check if this is permanently extended op code.
632   const uint64_t F = MI->getDesc().TSFlags;
633   if ((F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask)
634     return true;
635   // Use MO operand flags to determine if one of MI's operands
636   // has HMOTF_ConstExtended flag set.
637   for (MachineInstr::const_mop_iterator I = MI->operands_begin(),
638        E = MI->operands_end(); I != E; ++I) {
639     if (I->getTargetFlags() && HexagonII::HMOTF_ConstExtended)
640       return true;
641   }
642   return  false;
643 }
644
645 bool HexagonInstrInfo::isBranch (const MachineInstr *MI) const {
646   return MI->getDesc().isBranch();
647 }
648
649 bool HexagonInstrInfo::isNewValueInst(const MachineInstr *MI) const {
650   if (isNewValueJump(MI))
651     return true;
652
653   if (isNewValueStore(MI))
654     return true;
655
656   return false;
657 }
658
659 bool HexagonInstrInfo::isSaveCalleeSavedRegsCall(const MachineInstr *MI) const {
660   return MI->getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4;
661 }
662
663 bool HexagonInstrInfo::isPredicable(MachineInstr *MI) const {
664   bool isPred = MI->getDesc().isPredicable();
665
666   if (!isPred)
667     return false;
668
669   const int Opc = MI->getOpcode();
670
671   switch(Opc) {
672   case Hexagon::A2_tfrsi:
673     return (isOperandExtended(MI, 1) && isConstExtended(MI)) || isInt<12>(MI->getOperand(1).getImm());
674
675   case Hexagon::S2_storerd_io:
676     return isShiftedUInt<6,3>(MI->getOperand(1).getImm());
677
678   case Hexagon::S2_storeri_io:
679   case Hexagon::S2_storerinew_io:
680     return isShiftedUInt<6,2>(MI->getOperand(1).getImm());
681
682   case Hexagon::S2_storerh_io:
683   case Hexagon::S2_storerhnew_io:
684     return isShiftedUInt<6,1>(MI->getOperand(1).getImm());
685
686   case Hexagon::S2_storerb_io:
687   case Hexagon::S2_storerbnew_io:
688     return isUInt<6>(MI->getOperand(1).getImm());
689
690   case Hexagon::L2_loadrd_io:
691     return isShiftedUInt<6,3>(MI->getOperand(2).getImm());
692
693   case Hexagon::L2_loadri_io:
694     return isShiftedUInt<6,2>(MI->getOperand(2).getImm());
695
696   case Hexagon::L2_loadrh_io:
697   case Hexagon::L2_loadruh_io:
698     return isShiftedUInt<6,1>(MI->getOperand(2).getImm());
699
700   case Hexagon::L2_loadrb_io:
701   case Hexagon::L2_loadrub_io:
702     return isUInt<6>(MI->getOperand(2).getImm());
703
704   case Hexagon::L2_loadrd_pi:
705     return isShiftedInt<4,3>(MI->getOperand(3).getImm());
706
707   case Hexagon::L2_loadri_pi:
708     return isShiftedInt<4,2>(MI->getOperand(3).getImm());
709
710   case Hexagon::L2_loadrh_pi:
711   case Hexagon::L2_loadruh_pi:
712     return isShiftedInt<4,1>(MI->getOperand(3).getImm());
713
714   case Hexagon::L2_loadrb_pi:
715   case Hexagon::L2_loadrub_pi:
716     return isInt<4>(MI->getOperand(3).getImm());
717
718   case Hexagon::S4_storeirb_io:
719   case Hexagon::S4_storeirh_io:
720   case Hexagon::S4_storeiri_io:
721     return (isUInt<6>(MI->getOperand(1).getImm()) &&
722             isInt<6>(MI->getOperand(2).getImm()));
723
724   case Hexagon::A2_addi:
725     return isInt<8>(MI->getOperand(2).getImm());
726
727   case Hexagon::A2_aslh:
728   case Hexagon::A2_asrh:
729   case Hexagon::A2_sxtb:
730   case Hexagon::A2_sxth:
731   case Hexagon::A2_zxtb:
732   case Hexagon::A2_zxth:
733     return true;
734   }
735
736   return true;
737 }
738
739 // This function performs the following inversiones:
740 //
741 //  cPt    ---> cNotPt
742 //  cNotPt ---> cPt
743 //
744 unsigned HexagonInstrInfo::getInvertedPredicatedOpcode(const int Opc) const {
745   int InvPredOpcode;
746   InvPredOpcode = isPredicatedTrue(Opc) ? Hexagon::getFalsePredOpcode(Opc)
747                                         : Hexagon::getTruePredOpcode(Opc);
748   if (InvPredOpcode >= 0) // Valid instruction with the inverted predicate.
749     return InvPredOpcode;
750
751   switch(Opc) {
752     default: llvm_unreachable("Unexpected predicated instruction");
753     case Hexagon::C2_ccombinewt:
754       return Hexagon::C2_ccombinewf;
755     case Hexagon::C2_ccombinewf:
756       return Hexagon::C2_ccombinewt;
757
758       // Dealloc_return.
759     case Hexagon::L4_return_t:
760       return Hexagon::L4_return_f;
761     case Hexagon::L4_return_f:
762       return Hexagon::L4_return_t;
763   }
764 }
765
766 // New Value Store instructions.
767 bool HexagonInstrInfo::isNewValueStore(const MachineInstr *MI) const {
768   const uint64_t F = MI->getDesc().TSFlags;
769
770   return ((F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask);
771 }
772
773 bool HexagonInstrInfo::isNewValueStore(unsigned Opcode) const {
774   const uint64_t F = get(Opcode).TSFlags;
775
776   return ((F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask);
777 }
778
779 int HexagonInstrInfo::
780 getMatchingCondBranchOpcode(int Opc, bool invertPredicate) const {
781   enum Hexagon::PredSense inPredSense;
782   inPredSense = invertPredicate ? Hexagon::PredSense_false :
783                                   Hexagon::PredSense_true;
784   int CondOpcode = Hexagon::getPredOpcode(Opc, inPredSense);
785   if (CondOpcode >= 0) // Valid Conditional opcode/instruction
786     return CondOpcode;
787
788   // This switch case will be removed once all the instructions have been
789   // modified to use relation maps.
790   switch(Opc) {
791   case Hexagon::TFRI_f:
792     return !invertPredicate ? Hexagon::TFRI_cPt_f :
793                               Hexagon::TFRI_cNotPt_f;
794   case Hexagon::A2_combinew:
795     return !invertPredicate ? Hexagon::C2_ccombinewt :
796                               Hexagon::C2_ccombinewf;
797
798   // DEALLOC_RETURN.
799   case Hexagon::L4_return:
800     return !invertPredicate ? Hexagon::L4_return_t:
801                               Hexagon::L4_return_f;
802   }
803   llvm_unreachable("Unexpected predicable instruction");
804 }
805
806
807 bool HexagonInstrInfo::
808 PredicateInstruction(MachineInstr *MI,
809                      const SmallVectorImpl<MachineOperand> &Cond) const {
810   int Opc = MI->getOpcode();
811   assert (isPredicable(MI) && "Expected predicable instruction");
812   bool invertJump = (!Cond.empty() && Cond[0].isImm() &&
813                      (Cond[0].getImm() == 0));
814
815   // This will change MI's opcode to its predicate version.
816   // However, its operand list is still the old one, i.e. the
817   // non-predicate one.
818   MI->setDesc(get(getMatchingCondBranchOpcode(Opc, invertJump)));
819
820   int oper = -1;
821   unsigned int GAIdx = 0;
822
823   // Indicates whether the current MI has a GlobalAddress operand
824   bool hasGAOpnd = false;
825   std::vector<MachineOperand> tmpOpnds;
826
827   // Indicates whether we need to shift operands to right.
828   bool needShift = true;
829
830   // The predicate is ALWAYS the FIRST input operand !!!
831   if (MI->getNumOperands() == 0) {
832     // The non-predicate version of MI does not take any operands,
833     // i.e. no outs and no ins. In this condition, the predicate
834     // operand will be directly placed at Operands[0]. No operand
835     // shift is needed.
836     // Example: BARRIER
837     needShift = false;
838     oper = -1;
839   }
840   else if (   MI->getOperand(MI->getNumOperands()-1).isReg()
841            && MI->getOperand(MI->getNumOperands()-1).isDef()
842            && !MI->getOperand(MI->getNumOperands()-1).isImplicit()) {
843     // The non-predicate version of MI does not have any input operands.
844     // In this condition, we extend the length of Operands[] by one and
845     // copy the original last operand to the newly allocated slot.
846     // At this moment, it is just a place holder. Later, we will put
847     // predicate operand directly into it. No operand shift is needed.
848     // Example: r0=BARRIER (this is a faked insn used here for illustration)
849     MI->addOperand(MI->getOperand(MI->getNumOperands()-1));
850     needShift = false;
851     oper = MI->getNumOperands() - 2;
852   }
853   else {
854     // We need to right shift all input operands by one. Duplicate the
855     // last operand into the newly allocated slot.
856     MI->addOperand(MI->getOperand(MI->getNumOperands()-1));
857   }
858
859   if (needShift)
860   {
861     // Operands[ MI->getNumOperands() - 2 ] has been copied into
862     // Operands[ MI->getNumOperands() - 1 ], so we start from
863     // Operands[ MI->getNumOperands() - 3 ].
864     // oper is a signed int.
865     // It is ok if "MI->getNumOperands()-3" is -3, -2, or -1.
866     for (oper = MI->getNumOperands() - 3; oper >= 0; --oper)
867     {
868       MachineOperand &MO = MI->getOperand(oper);
869
870       // Opnd[0] Opnd[1] Opnd[2] Opnd[3] Opnd[4]   Opnd[5]   Opnd[6]   Opnd[7]
871       // <Def0>  <Def1>  <Use0>  <Use1>  <ImpDef0> <ImpDef1> <ImpUse0> <ImpUse1>
872       //               /\~
873       //              /||\~
874       //               ||
875       //        Predicate Operand here
876       if (MO.isReg() && !MO.isUse() && !MO.isImplicit()) {
877         break;
878       }
879       if (MO.isReg()) {
880         MI->getOperand(oper+1).ChangeToRegister(MO.getReg(), MO.isDef(),
881                                                 MO.isImplicit(), MO.isKill(),
882                                                 MO.isDead(), MO.isUndef(),
883                                                 MO.isDebug());
884       }
885       else if (MO.isImm()) {
886         MI->getOperand(oper+1).ChangeToImmediate(MO.getImm());
887       }
888       else if (MO.isGlobal()) {
889         // MI can not have more than one GlobalAddress operand.
890         assert(hasGAOpnd == false && "MI can only have one GlobalAddress opnd");
891
892         // There is no member function called "ChangeToGlobalAddress" in the
893         // MachineOperand class (not like "ChangeToRegister" and
894         // "ChangeToImmediate"). So we have to remove them from Operands[] list
895         // first, and then add them back after we have inserted the predicate
896         // operand. tmpOpnds[] is to remember these operands before we remove
897         // them.
898         tmpOpnds.push_back(MO);
899
900         // Operands[oper] is a GlobalAddress operand;
901         // Operands[oper+1] has been copied into Operands[oper+2];
902         hasGAOpnd = true;
903         GAIdx = oper;
904         continue;
905       }
906       else {
907         llvm_unreachable("Unexpected operand type");
908       }
909     }
910   }
911
912   int regPos = invertJump ? 1 : 0;
913   MachineOperand PredMO = Cond[regPos];
914
915   // [oper] now points to the last explicit Def. Predicate operand must be
916   // located at [oper+1]. See diagram above.
917   // This assumes that the predicate is always the first operand,
918   // i.e. Operands[0+numResults], in the set of inputs
919   // It is better to have an assert here to check this. But I don't know how
920   // to write this assert because findFirstPredOperandIdx() would return -1
921   if (oper < -1) oper = -1;
922
923   MI->getOperand(oper+1).ChangeToRegister(PredMO.getReg(), PredMO.isDef(),
924                                           PredMO.isImplicit(), false,
925                                           PredMO.isDead(), PredMO.isUndef(),
926                                           PredMO.isDebug());
927
928   MachineRegisterInfo &RegInfo = MI->getParent()->getParent()->getRegInfo();
929   RegInfo.clearKillFlags(PredMO.getReg());
930
931   if (hasGAOpnd)
932   {
933     unsigned int i;
934
935     // Operands[GAIdx] is the original GlobalAddress operand, which is
936     // already copied into tmpOpnds[0].
937     // Operands[GAIdx] now stores a copy of Operands[GAIdx-1]
938     // Operands[GAIdx+1] has already been copied into Operands[GAIdx+2],
939     // so we start from [GAIdx+2]
940     for (i = GAIdx + 2; i < MI->getNumOperands(); ++i)
941       tmpOpnds.push_back(MI->getOperand(i));
942
943     // Remove all operands in range [ (GAIdx+1) ... (MI->getNumOperands()-1) ]
944     // It is very important that we always remove from the end of Operands[]
945     // MI->getNumOperands() is at least 2 if program goes to here.
946     for (i = MI->getNumOperands() - 1; i > GAIdx; --i)
947       MI->RemoveOperand(i);
948
949     for (i = 0; i < tmpOpnds.size(); ++i)
950       MI->addOperand(tmpOpnds[i]);
951   }
952
953   return true;
954 }
955
956
957 bool
958 HexagonInstrInfo::
959 isProfitableToIfCvt(MachineBasicBlock &MBB,
960                     unsigned NumCycles,
961                     unsigned ExtraPredCycles,
962                     const BranchProbability &Probability) const {
963   return true;
964 }
965
966
967 bool
968 HexagonInstrInfo::
969 isProfitableToIfCvt(MachineBasicBlock &TMBB,
970                     unsigned NumTCycles,
971                     unsigned ExtraTCycles,
972                     MachineBasicBlock &FMBB,
973                     unsigned NumFCycles,
974                     unsigned ExtraFCycles,
975                     const BranchProbability &Probability) const {
976   return true;
977 }
978
979 // Returns true if an instruction is predicated irrespective of the predicate
980 // sense. For example, all of the following will return true.
981 // if (p0) R1 = add(R2, R3)
982 // if (!p0) R1 = add(R2, R3)
983 // if (p0.new) R1 = add(R2, R3)
984 // if (!p0.new) R1 = add(R2, R3)
985 bool HexagonInstrInfo::isPredicated(const MachineInstr *MI) const {
986   const uint64_t F = MI->getDesc().TSFlags;
987
988   return ((F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
989 }
990
991 bool HexagonInstrInfo::isPredicated(unsigned Opcode) const {
992   const uint64_t F = get(Opcode).TSFlags;
993
994   return ((F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
995 }
996
997 bool HexagonInstrInfo::isPredicatedTrue(const MachineInstr *MI) const {
998   const uint64_t F = MI->getDesc().TSFlags;
999
1000   assert(isPredicated(MI));
1001   return (!((F >> HexagonII::PredicatedFalsePos) &
1002             HexagonII::PredicatedFalseMask));
1003 }
1004
1005 bool HexagonInstrInfo::isPredicatedTrue(unsigned Opcode) const {
1006   const uint64_t F = get(Opcode).TSFlags;
1007
1008   // Make sure that the instruction is predicated.
1009   assert((F>> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
1010   return (!((F >> HexagonII::PredicatedFalsePos) &
1011             HexagonII::PredicatedFalseMask));
1012 }
1013
1014 bool HexagonInstrInfo::isPredicatedNew(const MachineInstr *MI) const {
1015   const uint64_t F = MI->getDesc().TSFlags;
1016
1017   assert(isPredicated(MI));
1018   return ((F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask);
1019 }
1020
1021 bool HexagonInstrInfo::isPredicatedNew(unsigned Opcode) const {
1022   const uint64_t F = get(Opcode).TSFlags;
1023
1024   assert(isPredicated(Opcode));
1025   return ((F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask);
1026 }
1027
1028 // Returns true, if a ST insn can be promoted to a new-value store.
1029 bool HexagonInstrInfo::mayBeNewStore(const MachineInstr *MI) const {
1030   const uint64_t F = MI->getDesc().TSFlags;
1031
1032   return ((F >> HexagonII::mayNVStorePos) &
1033            HexagonII::mayNVStoreMask);
1034 }
1035
1036 bool
1037 HexagonInstrInfo::DefinesPredicate(MachineInstr *MI,
1038                                    std::vector<MachineOperand> &Pred) const {
1039   for (unsigned oper = 0; oper < MI->getNumOperands(); ++oper) {
1040     MachineOperand MO = MI->getOperand(oper);
1041     if (MO.isReg() && MO.isDef()) {
1042       const TargetRegisterClass* RC = RI.getMinimalPhysRegClass(MO.getReg());
1043       if (RC == &Hexagon::PredRegsRegClass) {
1044         Pred.push_back(MO);
1045         return true;
1046       }
1047     }
1048   }
1049   return false;
1050 }
1051
1052
1053 bool
1054 HexagonInstrInfo::
1055 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
1056                   const SmallVectorImpl<MachineOperand> &Pred2) const {
1057   // TODO: Fix this
1058   return false;
1059 }
1060
1061
1062 //
1063 // We indicate that we want to reverse the branch by
1064 // inserting a 0 at the beginning of the Cond vector.
1065 //
1066 bool HexagonInstrInfo::
1067 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1068   if (!Cond.empty() && Cond[0].isImm() && Cond[0].getImm() == 0) {
1069     Cond.erase(Cond.begin());
1070   } else {
1071     Cond.insert(Cond.begin(), MachineOperand::CreateImm(0));
1072   }
1073   return false;
1074 }
1075
1076
1077 bool HexagonInstrInfo::
1078 isProfitableToDupForIfCvt(MachineBasicBlock &MBB,unsigned NumInstrs,
1079                           const BranchProbability &Probability) const {
1080   return (NumInstrs <= 4);
1081 }
1082
1083 bool HexagonInstrInfo::isDeallocRet(const MachineInstr *MI) const {
1084   switch (MI->getOpcode()) {
1085   default: return false;
1086   case Hexagon::L4_return:
1087   case Hexagon::L4_return_t:
1088   case Hexagon::L4_return_f:
1089   case Hexagon::L4_return_tnew_pnt:
1090   case Hexagon::L4_return_fnew_pnt:
1091   case Hexagon::L4_return_tnew_pt:
1092   case Hexagon::L4_return_fnew_pt:
1093    return true;
1094   }
1095 }
1096
1097
1098 bool HexagonInstrInfo::
1099 isValidOffset(const int Opcode, const int Offset) const {
1100   // This function is to check whether the "Offset" is in the correct range of
1101   // the given "Opcode". If "Offset" is not in the correct range, "ADD_ri" is
1102   // inserted to calculate the final address. Due to this reason, the function
1103   // assumes that the "Offset" has correct alignment.
1104   // We used to assert if the offset was not properly aligned, however,
1105   // there are cases where a misaligned pointer recast can cause this
1106   // problem, and we need to allow for it. The front end warns of such
1107   // misaligns with respect to load size.
1108
1109   switch(Opcode) {
1110
1111   case Hexagon::L2_loadri_io:
1112   case Hexagon::S2_storeri_io:
1113     return (Offset >= Hexagon_MEMW_OFFSET_MIN) &&
1114       (Offset <= Hexagon_MEMW_OFFSET_MAX);
1115
1116   case Hexagon::L2_loadrd_io:
1117   case Hexagon::S2_storerd_io:
1118     return (Offset >= Hexagon_MEMD_OFFSET_MIN) &&
1119       (Offset <= Hexagon_MEMD_OFFSET_MAX);
1120
1121   case Hexagon::L2_loadrh_io:
1122   case Hexagon::L2_loadruh_io:
1123   case Hexagon::S2_storerh_io:
1124     return (Offset >= Hexagon_MEMH_OFFSET_MIN) &&
1125       (Offset <= Hexagon_MEMH_OFFSET_MAX);
1126
1127   case Hexagon::L2_loadrb_io:
1128   case Hexagon::S2_storerb_io:
1129   case Hexagon::L2_loadrub_io:
1130     return (Offset >= Hexagon_MEMB_OFFSET_MIN) &&
1131       (Offset <= Hexagon_MEMB_OFFSET_MAX);
1132
1133   case Hexagon::A2_addi:
1134   case Hexagon::TFR_FI:
1135     return (Offset >= Hexagon_ADDI_OFFSET_MIN) &&
1136       (Offset <= Hexagon_ADDI_OFFSET_MAX);
1137
1138   case Hexagon::L4_iadd_memopw_io:
1139   case Hexagon::L4_isub_memopw_io:
1140   case Hexagon::L4_add_memopw_io:
1141   case Hexagon::L4_sub_memopw_io:
1142   case Hexagon::L4_and_memopw_io:
1143   case Hexagon::L4_or_memopw_io:
1144     return (0 <= Offset && Offset <= 255);
1145
1146   case Hexagon::L4_iadd_memoph_io:
1147   case Hexagon::L4_isub_memoph_io:
1148   case Hexagon::L4_add_memoph_io:
1149   case Hexagon::L4_sub_memoph_io:
1150   case Hexagon::L4_and_memoph_io:
1151   case Hexagon::L4_or_memoph_io:
1152     return (0 <= Offset && Offset <= 127);
1153
1154   case Hexagon::L4_iadd_memopb_io:
1155   case Hexagon::L4_isub_memopb_io:
1156   case Hexagon::L4_add_memopb_io:
1157   case Hexagon::L4_sub_memopb_io:
1158   case Hexagon::L4_and_memopb_io:
1159   case Hexagon::L4_or_memopb_io:
1160     return (0 <= Offset && Offset <= 63);
1161
1162   // LDri_pred and STriw_pred are pseudo operations, so it has to take offset of
1163   // any size. Later pass knows how to handle it.
1164   case Hexagon::STriw_pred:
1165   case Hexagon::LDriw_pred:
1166     return true;
1167
1168   case Hexagon::J2_loop0i:
1169     return isUInt<10>(Offset);
1170
1171   // INLINEASM is very special.
1172   case Hexagon::INLINEASM:
1173     return true;
1174   }
1175
1176   llvm_unreachable("No offset range is defined for this opcode. "
1177                    "Please define it in the above switch statement!");
1178 }
1179
1180
1181 //
1182 // Check if the Offset is a valid auto-inc imm by Load/Store Type.
1183 //
1184 bool HexagonInstrInfo::
1185 isValidAutoIncImm(const EVT VT, const int Offset) const {
1186
1187   if (VT == MVT::i64) {
1188       return (Offset >= Hexagon_MEMD_AUTOINC_MIN &&
1189               Offset <= Hexagon_MEMD_AUTOINC_MAX &&
1190               (Offset & 0x7) == 0);
1191   }
1192   if (VT == MVT::i32) {
1193       return (Offset >= Hexagon_MEMW_AUTOINC_MIN &&
1194               Offset <= Hexagon_MEMW_AUTOINC_MAX &&
1195               (Offset & 0x3) == 0);
1196   }
1197   if (VT == MVT::i16) {
1198       return (Offset >= Hexagon_MEMH_AUTOINC_MIN &&
1199               Offset <= Hexagon_MEMH_AUTOINC_MAX &&
1200               (Offset & 0x1) == 0);
1201   }
1202   if (VT == MVT::i8) {
1203       return (Offset >= Hexagon_MEMB_AUTOINC_MIN &&
1204               Offset <= Hexagon_MEMB_AUTOINC_MAX);
1205   }
1206   llvm_unreachable("Not an auto-inc opc!");
1207 }
1208
1209
1210 bool HexagonInstrInfo::
1211 isMemOp(const MachineInstr *MI) const {
1212 //  return MI->getDesc().mayLoad() && MI->getDesc().mayStore();
1213
1214   switch (MI->getOpcode())
1215   {
1216   default: return false;
1217   case Hexagon::L4_iadd_memopw_io:
1218   case Hexagon::L4_isub_memopw_io:
1219   case Hexagon::L4_add_memopw_io:
1220   case Hexagon::L4_sub_memopw_io:
1221   case Hexagon::L4_and_memopw_io:
1222   case Hexagon::L4_or_memopw_io:
1223   case Hexagon::L4_iadd_memoph_io:
1224   case Hexagon::L4_isub_memoph_io:
1225   case Hexagon::L4_add_memoph_io:
1226   case Hexagon::L4_sub_memoph_io:
1227   case Hexagon::L4_and_memoph_io:
1228   case Hexagon::L4_or_memoph_io:
1229   case Hexagon::L4_iadd_memopb_io:
1230   case Hexagon::L4_isub_memopb_io:
1231   case Hexagon::L4_add_memopb_io:
1232   case Hexagon::L4_sub_memopb_io:
1233   case Hexagon::L4_and_memopb_io:
1234   case Hexagon::L4_or_memopb_io:
1235   case Hexagon::L4_ior_memopb_io:
1236   case Hexagon::L4_ior_memoph_io:
1237   case Hexagon::L4_ior_memopw_io:
1238   case Hexagon::L4_iand_memopb_io:
1239   case Hexagon::L4_iand_memoph_io:
1240   case Hexagon::L4_iand_memopw_io:
1241     return true;
1242   }
1243   return false;
1244 }
1245
1246
1247 bool HexagonInstrInfo::
1248 isSpillPredRegOp(const MachineInstr *MI) const {
1249   switch (MI->getOpcode()) {
1250     default: return false;
1251     case Hexagon::STriw_pred :
1252     case Hexagon::LDriw_pred :
1253       return true;
1254   }
1255 }
1256
1257 bool HexagonInstrInfo::isNewValueJumpCandidate(const MachineInstr *MI) const {
1258   switch (MI->getOpcode()) {
1259     default: return false;
1260     case Hexagon::C2_cmpeq:
1261     case Hexagon::C2_cmpeqi:
1262     case Hexagon::C2_cmpgt:
1263     case Hexagon::C2_cmpgti:
1264     case Hexagon::C2_cmpgtu:
1265     case Hexagon::C2_cmpgtui:
1266       return true;
1267   }
1268 }
1269
1270 bool HexagonInstrInfo::
1271 isConditionalTransfer (const MachineInstr *MI) const {
1272   switch (MI->getOpcode()) {
1273     default: return false;
1274     case Hexagon::A2_tfrt:
1275     case Hexagon::A2_tfrf:
1276     case Hexagon::C2_cmoveit:
1277     case Hexagon::C2_cmoveif:
1278     case Hexagon::A2_tfrtnew:
1279     case Hexagon::A2_tfrfnew:
1280     case Hexagon::C2_cmovenewit:
1281     case Hexagon::C2_cmovenewif:
1282       return true;
1283   }
1284 }
1285
1286 bool HexagonInstrInfo::isConditionalALU32 (const MachineInstr* MI) const {
1287   switch (MI->getOpcode())
1288   {
1289     default: return false;
1290     case Hexagon::A2_paddf:
1291     case Hexagon::A2_paddfnew:
1292     case Hexagon::A2_paddt:
1293     case Hexagon::A2_paddtnew:
1294     case Hexagon::A2_pandf:
1295     case Hexagon::A2_pandfnew:
1296     case Hexagon::A2_pandt:
1297     case Hexagon::A2_pandtnew:
1298     case Hexagon::A4_paslhf:
1299     case Hexagon::A4_paslhfnew:
1300     case Hexagon::A4_paslht:
1301     case Hexagon::A4_paslhtnew:
1302     case Hexagon::A4_pasrhf:
1303     case Hexagon::A4_pasrhfnew:
1304     case Hexagon::A4_pasrht:
1305     case Hexagon::A4_pasrhtnew:
1306     case Hexagon::A2_porf:
1307     case Hexagon::A2_porfnew:
1308     case Hexagon::A2_port:
1309     case Hexagon::A2_portnew:
1310     case Hexagon::A2_psubf:
1311     case Hexagon::A2_psubfnew:
1312     case Hexagon::A2_psubt:
1313     case Hexagon::A2_psubtnew:
1314     case Hexagon::A2_pxorf:
1315     case Hexagon::A2_pxorfnew:
1316     case Hexagon::A2_pxort:
1317     case Hexagon::A2_pxortnew:
1318     case Hexagon::A4_psxthf:
1319     case Hexagon::A4_psxthfnew:
1320     case Hexagon::A4_psxtht:
1321     case Hexagon::A4_psxthtnew:
1322     case Hexagon::A4_psxtbf:
1323     case Hexagon::A4_psxtbfnew:
1324     case Hexagon::A4_psxtbt:
1325     case Hexagon::A4_psxtbtnew:
1326     case Hexagon::A4_pzxtbf:
1327     case Hexagon::A4_pzxtbfnew:
1328     case Hexagon::A4_pzxtbt:
1329     case Hexagon::A4_pzxtbtnew:
1330     case Hexagon::A4_pzxthf:
1331     case Hexagon::A4_pzxthfnew:
1332     case Hexagon::A4_pzxtht:
1333     case Hexagon::A4_pzxthtnew:
1334     case Hexagon::A2_paddit:
1335     case Hexagon::A2_paddif:
1336     case Hexagon::C2_ccombinewt:
1337     case Hexagon::C2_ccombinewf:
1338       return true;
1339   }
1340 }
1341
1342 bool HexagonInstrInfo::
1343 isConditionalLoad (const MachineInstr* MI) const {
1344   switch (MI->getOpcode())
1345   {
1346     default: return false;
1347     case Hexagon::L2_ploadrdt_io :
1348     case Hexagon::L2_ploadrdf_io:
1349     case Hexagon::L2_ploadrit_io:
1350     case Hexagon::L2_ploadrif_io:
1351     case Hexagon::L2_ploadrht_io:
1352     case Hexagon::L2_ploadrhf_io:
1353     case Hexagon::L2_ploadrbt_io:
1354     case Hexagon::L2_ploadrbf_io:
1355     case Hexagon::L2_ploadruht_io:
1356     case Hexagon::L2_ploadruhf_io:
1357     case Hexagon::L2_ploadrubt_io:
1358     case Hexagon::L2_ploadrubf_io:
1359     case Hexagon::L2_ploadrdt_pi:
1360     case Hexagon::L2_ploadrdf_pi:
1361     case Hexagon::L2_ploadrit_pi:
1362     case Hexagon::L2_ploadrif_pi:
1363     case Hexagon::L2_ploadrht_pi:
1364     case Hexagon::L2_ploadrhf_pi:
1365     case Hexagon::L2_ploadrbt_pi:
1366     case Hexagon::L2_ploadrbf_pi:
1367     case Hexagon::L2_ploadruht_pi:
1368     case Hexagon::L2_ploadruhf_pi:
1369     case Hexagon::L2_ploadrubt_pi:
1370     case Hexagon::L2_ploadrubf_pi:
1371     case Hexagon::L4_ploadrdt_rr:
1372     case Hexagon::L4_ploadrdf_rr:
1373     case Hexagon::L4_ploadrbt_rr:
1374     case Hexagon::L4_ploadrbf_rr:
1375     case Hexagon::L4_ploadrubt_rr:
1376     case Hexagon::L4_ploadrubf_rr:
1377     case Hexagon::L4_ploadrht_rr:
1378     case Hexagon::L4_ploadrhf_rr:
1379     case Hexagon::L4_ploadruht_rr:
1380     case Hexagon::L4_ploadruhf_rr:
1381     case Hexagon::L4_ploadrit_rr:
1382     case Hexagon::L4_ploadrif_rr:
1383       return true;
1384   }
1385 }
1386
1387 // Returns true if an instruction is a conditional store.
1388 //
1389 // Note: It doesn't include conditional new-value stores as they can't be
1390 // converted to .new predicate.
1391 //
1392 //               p.new NV store [ if(p0.new)memw(R0+#0)=R2.new ]
1393 //                ^           ^
1394 //               /             \ (not OK. it will cause new-value store to be
1395 //              /               X conditional on p0.new while R2 producer is
1396 //             /                 \ on p0)
1397 //            /                   \.
1398 //     p.new store                 p.old NV store
1399 // [if(p0.new)memw(R0+#0)=R2]    [if(p0)memw(R0+#0)=R2.new]
1400 //            ^                  ^
1401 //             \                /
1402 //              \              /
1403 //               \            /
1404 //                 p.old store
1405 //             [if (p0)memw(R0+#0)=R2]
1406 //
1407 // The above diagram shows the steps involoved in the conversion of a predicated
1408 // store instruction to its .new predicated new-value form.
1409 //
1410 // The following set of instructions further explains the scenario where
1411 // conditional new-value store becomes invalid when promoted to .new predicate
1412 // form.
1413 //
1414 // { 1) if (p0) r0 = add(r1, r2)
1415 //   2) p0 = cmp.eq(r3, #0) }
1416 //
1417 //   3) if (p0) memb(r1+#0) = r0  --> this instruction can't be grouped with
1418 // the first two instructions because in instr 1, r0 is conditional on old value
1419 // of p0 but its use in instr 3 is conditional on p0 modified by instr 2 which
1420 // is not valid for new-value stores.
1421 bool HexagonInstrInfo::
1422 isConditionalStore (const MachineInstr* MI) const {
1423   switch (MI->getOpcode())
1424   {
1425     default: return false;
1426     case Hexagon::S4_storeirbt_io:
1427     case Hexagon::S4_storeirbf_io:
1428     case Hexagon::S4_pstorerbt_rr:
1429     case Hexagon::S4_pstorerbf_rr:
1430     case Hexagon::S2_pstorerbt_io:
1431     case Hexagon::S2_pstorerbf_io:
1432     case Hexagon::S2_pstorerbt_pi:
1433     case Hexagon::S2_pstorerbf_pi:
1434     case Hexagon::S2_pstorerdt_io:
1435     case Hexagon::S2_pstorerdf_io:
1436     case Hexagon::S4_pstorerdt_rr:
1437     case Hexagon::S4_pstorerdf_rr:
1438     case Hexagon::S2_pstorerdt_pi:
1439     case Hexagon::S2_pstorerdf_pi:
1440     case Hexagon::S2_pstorerht_io:
1441     case Hexagon::S2_pstorerhf_io:
1442     case Hexagon::S4_storeirht_io:
1443     case Hexagon::S4_storeirhf_io:
1444     case Hexagon::S4_pstorerht_rr:
1445     case Hexagon::S4_pstorerhf_rr:
1446     case Hexagon::S2_pstorerht_pi:
1447     case Hexagon::S2_pstorerhf_pi:
1448     case Hexagon::S2_pstorerit_io:
1449     case Hexagon::S2_pstorerif_io:
1450     case Hexagon::S4_storeirit_io:
1451     case Hexagon::S4_storeirif_io:
1452     case Hexagon::S4_pstorerit_rr:
1453     case Hexagon::S4_pstorerif_rr:
1454     case Hexagon::S2_pstorerit_pi:
1455     case Hexagon::S2_pstorerif_pi:
1456
1457     // V4 global address store before promoting to dot new.
1458     case Hexagon::S4_pstorerdt_abs:
1459     case Hexagon::S4_pstorerdf_abs:
1460     case Hexagon::S4_pstorerbt_abs:
1461     case Hexagon::S4_pstorerbf_abs:
1462     case Hexagon::S4_pstorerht_abs:
1463     case Hexagon::S4_pstorerhf_abs:
1464     case Hexagon::S4_pstorerit_abs:
1465     case Hexagon::S4_pstorerif_abs:
1466       return true;
1467
1468     // Predicated new value stores (i.e. if (p0) memw(..)=r0.new) are excluded
1469     // from the "Conditional Store" list. Because a predicated new value store
1470     // would NOT be promoted to a double dot new store. See diagram below:
1471     // This function returns yes for those stores that are predicated but not
1472     // yet promoted to predicate dot new instructions.
1473     //
1474     //                          +---------------------+
1475     //                    /-----| if (p0) memw(..)=r0 |---------\~
1476     //                   ||     +---------------------+         ||
1477     //          promote  ||       /\       /\                   ||  promote
1478     //                   ||      /||\     /||\                  ||
1479     //                  \||/    demote     ||                  \||/
1480     //                   \/       ||       ||                   \/
1481     //       +-------------------------+   ||   +-------------------------+
1482     //       | if (p0.new) memw(..)=r0 |   ||   | if (p0) memw(..)=r0.new |
1483     //       +-------------------------+   ||   +-------------------------+
1484     //                        ||           ||         ||
1485     //                        ||         demote      \||/
1486     //                      promote        ||         \/ NOT possible
1487     //                        ||           ||         /\~
1488     //                       \||/          ||        /||\~
1489     //                        \/           ||         ||
1490     //                      +-----------------------------+
1491     //                      | if (p0.new) memw(..)=r0.new |
1492     //                      +-----------------------------+
1493     //                           Double Dot New Store
1494     //
1495   }
1496 }
1497
1498
1499 bool HexagonInstrInfo::isNewValueJump(const MachineInstr *MI) const {
1500   if (isNewValue(MI) && isBranch(MI))
1501     return true;
1502   return false;
1503 }
1504
1505 bool HexagonInstrInfo::isPostIncrement (const MachineInstr* MI) const {
1506   return (getAddrMode(MI) == HexagonII::PostInc);
1507 }
1508
1509 bool HexagonInstrInfo::isNewValue(const MachineInstr* MI) const {
1510   const uint64_t F = MI->getDesc().TSFlags;
1511   return ((F >> HexagonII::NewValuePos) & HexagonII::NewValueMask);
1512 }
1513
1514 // Returns true, if any one of the operands is a dot new
1515 // insn, whether it is predicated dot new or register dot new.
1516 bool HexagonInstrInfo::isDotNewInst (const MachineInstr* MI) const {
1517   return (isNewValueInst(MI) ||
1518      (isPredicated(MI) && isPredicatedNew(MI)));
1519 }
1520
1521 // Returns the most basic instruction for the .new predicated instructions and
1522 // new-value stores.
1523 // For example, all of the following instructions will be converted back to the
1524 // same instruction:
1525 // 1) if (p0.new) memw(R0+#0) = R1.new  --->
1526 // 2) if (p0) memw(R0+#0)= R1.new      -------> if (p0) memw(R0+#0) = R1
1527 // 3) if (p0.new) memw(R0+#0) = R1      --->
1528 //
1529
1530 int HexagonInstrInfo::GetDotOldOp(const int opc) const {
1531   int NewOp = opc;
1532   if (isPredicated(NewOp) && isPredicatedNew(NewOp)) { // Get predicate old form
1533     NewOp = Hexagon::getPredOldOpcode(NewOp);
1534     assert(NewOp >= 0 &&
1535            "Couldn't change predicate new instruction to its old form.");
1536   }
1537
1538   if (isNewValueStore(NewOp)) { // Convert into non-new-value format
1539     NewOp = Hexagon::getNonNVStore(NewOp);
1540     assert(NewOp >= 0 && "Couldn't change new-value store to its old form.");
1541   }
1542   return NewOp;
1543 }
1544
1545 // Return the new value instruction for a given store.
1546 int HexagonInstrInfo::GetDotNewOp(const MachineInstr* MI) const {
1547   int NVOpcode = Hexagon::getNewValueOpcode(MI->getOpcode());
1548   if (NVOpcode >= 0) // Valid new-value store instruction.
1549     return NVOpcode;
1550
1551   switch (MI->getOpcode()) {
1552   default: llvm_unreachable("Unknown .new type");
1553   // store new value byte
1554   case Hexagon::S4_storerb_ur:
1555     return Hexagon::S4_storerbnew_ur;
1556
1557   case Hexagon::S4_storerh_ur:
1558     return Hexagon::S4_storerhnew_ur;
1559
1560   case Hexagon::S4_storeri_ur:
1561     return Hexagon::S4_storerinew_ur;
1562
1563   }
1564   return 0;
1565 }
1566
1567 // Return .new predicate version for an instruction.
1568 int HexagonInstrInfo::GetDotNewPredOp(MachineInstr *MI,
1569                                       const MachineBranchProbabilityInfo
1570                                       *MBPI) const {
1571
1572   int NewOpcode = Hexagon::getPredNewOpcode(MI->getOpcode());
1573   if (NewOpcode >= 0) // Valid predicate new instruction
1574     return NewOpcode;
1575
1576   switch (MI->getOpcode()) {
1577   default: llvm_unreachable("Unknown .new type");
1578   // Condtional Jumps
1579   case Hexagon::J2_jumpt:
1580   case Hexagon::J2_jumpf:
1581     return getDotNewPredJumpOp(MI, MBPI);
1582
1583   case Hexagon::J2_jumprt:
1584     return Hexagon::J2_jumptnewpt;
1585
1586   case Hexagon::J2_jumprf:
1587     return Hexagon::J2_jumprfnewpt;
1588
1589   case Hexagon::JMPrett:
1590     return Hexagon::J2_jumprtnewpt;
1591
1592   case Hexagon::JMPretf:
1593     return Hexagon::J2_jumprfnewpt;
1594
1595
1596   // Conditional combine
1597   case Hexagon::C2_ccombinewt:
1598     return Hexagon::C2_ccombinewnewt;
1599   case Hexagon::C2_ccombinewf:
1600     return Hexagon::C2_ccombinewnewf;
1601   }
1602 }
1603
1604
1605 unsigned HexagonInstrInfo::getAddrMode(const MachineInstr* MI) const {
1606   const uint64_t F = MI->getDesc().TSFlags;
1607
1608   return((F >> HexagonII::AddrModePos) & HexagonII::AddrModeMask);
1609 }
1610
1611 /// immediateExtend - Changes the instruction in place to one using an immediate
1612 /// extender.
1613 void HexagonInstrInfo::immediateExtend(MachineInstr *MI) const {
1614   assert((isExtendable(MI)||isConstExtended(MI)) &&
1615                                "Instruction must be extendable");
1616   // Find which operand is extendable.
1617   short ExtOpNum = getCExtOpNum(MI);
1618   MachineOperand &MO = MI->getOperand(ExtOpNum);
1619   // This needs to be something we understand.
1620   assert((MO.isMBB() || MO.isImm()) &&
1621          "Branch with unknown extendable field type");
1622   // Mark given operand as extended.
1623   MO.addTargetFlag(HexagonII::HMOTF_ConstExtended);
1624 }
1625
1626 DFAPacketizer *HexagonInstrInfo::CreateTargetScheduleState(
1627     const TargetSubtargetInfo &STI) const {
1628   const InstrItineraryData *II = STI.getInstrItineraryData();
1629   return static_cast<const HexagonSubtarget &>(STI).createDFAPacketizer(II);
1630 }
1631
1632 bool HexagonInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1633                                             const MachineBasicBlock *MBB,
1634                                             const MachineFunction &MF) const {
1635   // Debug info is never a scheduling boundary. It's necessary to be explicit
1636   // due to the special treatment of IT instructions below, otherwise a
1637   // dbg_value followed by an IT will result in the IT instruction being
1638   // considered a scheduling hazard, which is wrong. It should be the actual
1639   // instruction preceding the dbg_value instruction(s), just like it is
1640   // when debug info is not present.
1641   if (MI->isDebugValue())
1642     return false;
1643
1644   // Terminators and labels can't be scheduled around.
1645   if (MI->getDesc().isTerminator() || MI->isPosition() || MI->isInlineAsm())
1646     return true;
1647
1648   return false;
1649 }
1650
1651 bool HexagonInstrInfo::isConstExtended(MachineInstr *MI) const {
1652   const uint64_t F = MI->getDesc().TSFlags;
1653   unsigned isExtended = (F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask;
1654   if (isExtended) // Instruction must be extended.
1655     return true;
1656
1657   unsigned isExtendable = (F >> HexagonII::ExtendablePos)
1658                           & HexagonII::ExtendableMask;
1659   if (!isExtendable)
1660     return false;
1661
1662   short ExtOpNum = getCExtOpNum(MI);
1663   const MachineOperand &MO = MI->getOperand(ExtOpNum);
1664   // Use MO operand flags to determine if MO
1665   // has the HMOTF_ConstExtended flag set.
1666   if (MO.getTargetFlags() && HexagonII::HMOTF_ConstExtended)
1667     return true;
1668   // If this is a Machine BB address we are talking about, and it is
1669   // not marked as extended, say so.
1670   if (MO.isMBB())
1671     return false;
1672
1673   // We could be using an instruction with an extendable immediate and shoehorn
1674   // a global address into it. If it is a global address it will be constant
1675   // extended. We do this for COMBINE.
1676   // We currently only handle isGlobal() because it is the only kind of
1677   // object we are going to end up with here for now.
1678   // In the future we probably should add isSymbol(), etc.
1679   if (MO.isGlobal() || MO.isSymbol() || MO.isBlockAddress())
1680     return true;
1681
1682   // If the extendable operand is not 'Immediate' type, the instruction should
1683   // have 'isExtended' flag set.
1684   assert(MO.isImm() && "Extendable operand must be Immediate type");
1685
1686   int MinValue = getMinValue(MI);
1687   int MaxValue = getMaxValue(MI);
1688   int ImmValue = MO.getImm();
1689
1690   return (ImmValue < MinValue || ImmValue > MaxValue);
1691 }
1692
1693 // Returns the opcode to use when converting MI, which is a conditional jump,
1694 // into a conditional instruction which uses the .new value of the predicate.
1695 // We also use branch probabilities to add a hint to the jump.
1696 int
1697 HexagonInstrInfo::getDotNewPredJumpOp(MachineInstr *MI,
1698                                   const
1699                                   MachineBranchProbabilityInfo *MBPI) const {
1700
1701   // We assume that block can have at most two successors.
1702   bool taken = false;
1703   MachineBasicBlock *Src = MI->getParent();
1704   MachineOperand *BrTarget = &MI->getOperand(1);
1705   MachineBasicBlock *Dst = BrTarget->getMBB();
1706
1707   const BranchProbability Prediction = MBPI->getEdgeProbability(Src, Dst);
1708   if (Prediction >= BranchProbability(1,2))
1709     taken = true;
1710
1711   switch (MI->getOpcode()) {
1712   case Hexagon::J2_jumpt:
1713     return taken ? Hexagon::J2_jumptnewpt : Hexagon::J2_jumptnew;
1714   case Hexagon::J2_jumpf:
1715     return taken ? Hexagon::J2_jumpfnewpt : Hexagon::J2_jumpfnew;
1716
1717   default:
1718     llvm_unreachable("Unexpected jump instruction.");
1719   }
1720 }
1721 // Returns true if a particular operand is extendable for an instruction.
1722 bool HexagonInstrInfo::isOperandExtended(const MachineInstr *MI,
1723                                          unsigned short OperandNum) const {
1724   const uint64_t F = MI->getDesc().TSFlags;
1725
1726   return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask)
1727           == OperandNum;
1728 }
1729
1730 // Returns Operand Index for the constant extended instruction.
1731 unsigned short HexagonInstrInfo::getCExtOpNum(const MachineInstr *MI) const {
1732   const uint64_t F = MI->getDesc().TSFlags;
1733   return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask);
1734 }
1735
1736 // Returns the min value that doesn't need to be extended.
1737 int HexagonInstrInfo::getMinValue(const MachineInstr *MI) const {
1738   const uint64_t F = MI->getDesc().TSFlags;
1739   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
1740                     & HexagonII::ExtentSignedMask;
1741   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
1742                     & HexagonII::ExtentBitsMask;
1743
1744   if (isSigned) // if value is signed
1745     return -1U << (bits - 1);
1746   else
1747     return 0;
1748 }
1749
1750 // Returns the max value that doesn't need to be extended.
1751 int HexagonInstrInfo::getMaxValue(const MachineInstr *MI) const {
1752   const uint64_t F = MI->getDesc().TSFlags;
1753   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
1754                     & HexagonII::ExtentSignedMask;
1755   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
1756                     & HexagonII::ExtentBitsMask;
1757
1758   if (isSigned) // if value is signed
1759     return ~(-1U << (bits - 1));
1760   else
1761     return ~(-1U << bits);
1762 }
1763
1764 // Returns true if an instruction can be converted into a non-extended
1765 // equivalent instruction.
1766 bool HexagonInstrInfo::NonExtEquivalentExists (const MachineInstr *MI) const {
1767
1768   short NonExtOpcode;
1769   // Check if the instruction has a register form that uses register in place
1770   // of the extended operand, if so return that as the non-extended form.
1771   if (Hexagon::getRegForm(MI->getOpcode()) >= 0)
1772     return true;
1773
1774   if (MI->getDesc().mayLoad() || MI->getDesc().mayStore()) {
1775     // Check addressing mode and retrieve non-ext equivalent instruction.
1776
1777     switch (getAddrMode(MI)) {
1778     case HexagonII::Absolute :
1779       // Load/store with absolute addressing mode can be converted into
1780       // base+offset mode.
1781       NonExtOpcode = Hexagon::getBasedWithImmOffset(MI->getOpcode());
1782       break;
1783     case HexagonII::BaseImmOffset :
1784       // Load/store with base+offset addressing mode can be converted into
1785       // base+register offset addressing mode. However left shift operand should
1786       // be set to 0.
1787       NonExtOpcode = Hexagon::getBaseWithRegOffset(MI->getOpcode());
1788       break;
1789     default:
1790       return false;
1791     }
1792     if (NonExtOpcode < 0)
1793       return false;
1794     return true;
1795   }
1796   return false;
1797 }
1798
1799 // Returns opcode of the non-extended equivalent instruction.
1800 short HexagonInstrInfo::getNonExtOpcode (const MachineInstr *MI) const {
1801
1802   // Check if the instruction has a register form that uses register in place
1803   // of the extended operand, if so return that as the non-extended form.
1804   short NonExtOpcode = Hexagon::getRegForm(MI->getOpcode());
1805     if (NonExtOpcode >= 0)
1806       return NonExtOpcode;
1807
1808   if (MI->getDesc().mayLoad() || MI->getDesc().mayStore()) {
1809     // Check addressing mode and retrieve non-ext equivalent instruction.
1810     switch (getAddrMode(MI)) {
1811     case HexagonII::Absolute :
1812       return Hexagon::getBasedWithImmOffset(MI->getOpcode());
1813     case HexagonII::BaseImmOffset :
1814       return Hexagon::getBaseWithRegOffset(MI->getOpcode());
1815     default:
1816       return -1;
1817     }
1818   }
1819   return -1;
1820 }
1821
1822 bool HexagonInstrInfo::PredOpcodeHasJMP_c(Opcode_t Opcode) const {
1823   return (Opcode == Hexagon::J2_jumpt) ||
1824          (Opcode == Hexagon::J2_jumpf) ||
1825          (Opcode == Hexagon::J2_jumptnewpt) ||
1826          (Opcode == Hexagon::J2_jumpfnewpt) ||
1827          (Opcode == Hexagon::J2_jumpt) ||
1828          (Opcode == Hexagon::J2_jumpf);
1829 }
1830
1831 bool HexagonInstrInfo::PredOpcodeHasNot(Opcode_t Opcode) const {
1832   return (Opcode == Hexagon::J2_jumpf) ||
1833          (Opcode == Hexagon::J2_jumpfnewpt) ||
1834          (Opcode == Hexagon::J2_jumpfnew);
1835 }