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