2ebbc0d81ae3c5521f57576acd0315e6022c31eb
[oota-llvm.git] / lib / Target / SystemZ / SystemZInstrInfo.cpp
1 //===-- SystemZInstrInfo.cpp - SystemZ 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 SystemZ implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SystemZInstrInfo.h"
15 #include "SystemZTargetMachine.h"
16 #include "SystemZInstrBuilder.h"
17 #include "llvm/CodeGen/LiveVariables.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19
20 #define GET_INSTRINFO_CTOR
21 #define GET_INSTRMAP_INFO
22 #include "SystemZGenInstrInfo.inc"
23
24 using namespace llvm;
25
26 // Return a mask with Count low bits set.
27 static uint64_t allOnes(unsigned int Count) {
28   return Count == 0 ? 0 : (uint64_t(1) << (Count - 1) << 1) - 1;
29 }
30
31 // Reg should be a 32-bit GPR.  Return true if it is a high register rather
32 // than a low register.
33 static bool isHighReg(unsigned int Reg) {
34   if (SystemZ::GRH32BitRegClass.contains(Reg))
35     return true;
36   assert(SystemZ::GR32BitRegClass.contains(Reg) && "Invalid GRX32");
37   return false;
38 }
39
40 SystemZInstrInfo::SystemZInstrInfo(SystemZTargetMachine &tm)
41   : SystemZGenInstrInfo(SystemZ::ADJCALLSTACKDOWN, SystemZ::ADJCALLSTACKUP),
42     RI(tm), TM(tm) {
43 }
44
45 // MI is a 128-bit load or store.  Split it into two 64-bit loads or stores,
46 // each having the opcode given by NewOpcode.
47 void SystemZInstrInfo::splitMove(MachineBasicBlock::iterator MI,
48                                  unsigned NewOpcode) const {
49   MachineBasicBlock *MBB = MI->getParent();
50   MachineFunction &MF = *MBB->getParent();
51
52   // Get two load or store instructions.  Use the original instruction for one
53   // of them (arbitarily the second here) and create a clone for the other.
54   MachineInstr *EarlierMI = MF.CloneMachineInstr(MI);
55   MBB->insert(MI, EarlierMI);
56
57   // Set up the two 64-bit registers.
58   MachineOperand &HighRegOp = EarlierMI->getOperand(0);
59   MachineOperand &LowRegOp = MI->getOperand(0);
60   HighRegOp.setReg(RI.getSubReg(HighRegOp.getReg(), SystemZ::subreg_h64));
61   LowRegOp.setReg(RI.getSubReg(LowRegOp.getReg(), SystemZ::subreg_l64));
62
63   // The address in the first (high) instruction is already correct.
64   // Adjust the offset in the second (low) instruction.
65   MachineOperand &HighOffsetOp = EarlierMI->getOperand(2);
66   MachineOperand &LowOffsetOp = MI->getOperand(2);
67   LowOffsetOp.setImm(LowOffsetOp.getImm() + 8);
68
69   // Set the opcodes.
70   unsigned HighOpcode = getOpcodeForOffset(NewOpcode, HighOffsetOp.getImm());
71   unsigned LowOpcode = getOpcodeForOffset(NewOpcode, LowOffsetOp.getImm());
72   assert(HighOpcode && LowOpcode && "Both offsets should be in range");
73
74   EarlierMI->setDesc(get(HighOpcode));
75   MI->setDesc(get(LowOpcode));
76 }
77
78 // Split ADJDYNALLOC instruction MI.
79 void SystemZInstrInfo::splitAdjDynAlloc(MachineBasicBlock::iterator MI) const {
80   MachineBasicBlock *MBB = MI->getParent();
81   MachineFunction &MF = *MBB->getParent();
82   MachineFrameInfo *MFFrame = MF.getFrameInfo();
83   MachineOperand &OffsetMO = MI->getOperand(2);
84
85   uint64_t Offset = (MFFrame->getMaxCallFrameSize() +
86                      SystemZMC::CallFrameSize +
87                      OffsetMO.getImm());
88   unsigned NewOpcode = getOpcodeForOffset(SystemZ::LA, Offset);
89   assert(NewOpcode && "No support for huge argument lists yet");
90   MI->setDesc(get(NewOpcode));
91   OffsetMO.setImm(Offset);
92 }
93
94 // MI is an RI-style pseudo instruction.  Replace it with LowOpcode
95 // if the first operand is a low GR32 and HighOpcode if the first operand
96 // is a high GR32.  ConvertHigh is true if LowOpcode takes a signed operand
97 // and HighOpcode takes an unsigned 32-bit operand.  In those cases,
98 // MI has the same kind of operand as LowOpcode, so needs to be converted
99 // if HighOpcode is used.
100 void SystemZInstrInfo::expandRIPseudo(MachineInstr *MI, unsigned LowOpcode,
101                                       unsigned HighOpcode,
102                                       bool ConvertHigh) const {
103   unsigned Reg = MI->getOperand(0).getReg();
104   bool IsHigh = isHighReg(Reg);
105   MI->setDesc(get(IsHigh ? HighOpcode : LowOpcode));
106   if (IsHigh && ConvertHigh)
107     MI->getOperand(1).setImm(uint32_t(MI->getOperand(1).getImm()));
108 }
109
110 // MI is a three-operand RIE-style pseudo instruction.  Replace it with
111 // LowOpcode3 if the registers are both low GR32s, otherwise use a move
112 // followed by HighOpcode or LowOpcode, depending on whether the target
113 // is a high or low GR32.
114 void SystemZInstrInfo::expandRIEPseudo(MachineInstr *MI, unsigned LowOpcode,
115                                        unsigned LowOpcodeK,
116                                        unsigned HighOpcode) const {
117   unsigned DestReg = MI->getOperand(0).getReg();
118   unsigned SrcReg = MI->getOperand(1).getReg();
119   bool DestIsHigh = isHighReg(DestReg);
120   bool SrcIsHigh = isHighReg(SrcReg);
121   if (!DestIsHigh && !SrcIsHigh)
122     MI->setDesc(get(LowOpcodeK));
123   else {
124     emitGRX32Move(*MI->getParent(), MI, MI->getDebugLoc(),
125                   DestReg, SrcReg, SystemZ::LR, 32,
126                   MI->getOperand(1).isKill());
127     MI->setDesc(get(DestIsHigh ? HighOpcode : LowOpcode));
128     MI->getOperand(1).setReg(DestReg);
129   }
130 }
131
132 // MI is an RXY-style pseudo instruction.  Replace it with LowOpcode
133 // if the first operand is a low GR32 and HighOpcode if the first operand
134 // is a high GR32.
135 void SystemZInstrInfo::expandRXYPseudo(MachineInstr *MI, unsigned LowOpcode,
136                                        unsigned HighOpcode) const {
137   unsigned Reg = MI->getOperand(0).getReg();
138   unsigned Opcode = getOpcodeForOffset(isHighReg(Reg) ? HighOpcode : LowOpcode,
139                                        MI->getOperand(2).getImm());
140   MI->setDesc(get(Opcode));
141 }
142
143 // MI is an RR-style pseudo instruction that zero-extends the low Size bits
144 // of one GRX32 into another.  Replace it with LowOpcode if both operands
145 // are low registers, otherwise use RISB[LH]G.
146 void SystemZInstrInfo::expandZExtPseudo(MachineInstr *MI, unsigned LowOpcode,
147                                         unsigned Size) const {
148   emitGRX32Move(*MI->getParent(), MI, MI->getDebugLoc(),
149                 MI->getOperand(0).getReg(), MI->getOperand(1).getReg(),
150                 LowOpcode, Size, MI->getOperand(1).isKill());
151   MI->eraseFromParent();
152 }
153
154 // Emit a zero-extending move from 32-bit GPR SrcReg to 32-bit GPR
155 // DestReg before MBBI in MBB.  Use LowLowOpcode when both DestReg and SrcReg
156 // are low registers, otherwise use RISB[LH]G.  Size is the number of bits
157 // taken from the low end of SrcReg (8 for LLCR, 16 for LLHR and 32 for LR).
158 // KillSrc is true if this move is the last use of SrcReg.
159 void SystemZInstrInfo::emitGRX32Move(MachineBasicBlock &MBB,
160                                      MachineBasicBlock::iterator MBBI,
161                                      DebugLoc DL, unsigned DestReg,
162                                      unsigned SrcReg, unsigned LowLowOpcode,
163                                      unsigned Size, bool KillSrc) const {
164   unsigned Opcode;
165   bool DestIsHigh = isHighReg(DestReg);
166   bool SrcIsHigh = isHighReg(SrcReg);
167   if (DestIsHigh && SrcIsHigh)
168     Opcode = SystemZ::RISBHH;
169   else if (DestIsHigh && !SrcIsHigh)
170     Opcode = SystemZ::RISBHL;
171   else if (!DestIsHigh && SrcIsHigh)
172     Opcode = SystemZ::RISBLH;
173   else {
174     BuildMI(MBB, MBBI, DL, get(LowLowOpcode), DestReg)
175       .addReg(SrcReg, getKillRegState(KillSrc));
176     return;
177   }
178   unsigned Rotate = (DestIsHigh != SrcIsHigh ? 32 : 0);
179   BuildMI(MBB, MBBI, DL, get(Opcode), DestReg)
180     .addReg(DestReg, RegState::Undef)
181     .addReg(SrcReg, getKillRegState(KillSrc))
182     .addImm(32 - Size).addImm(128 + 31).addImm(Rotate);
183 }
184
185 // If MI is a simple load or store for a frame object, return the register
186 // it loads or stores and set FrameIndex to the index of the frame object.
187 // Return 0 otherwise.
188 //
189 // Flag is SimpleBDXLoad for loads and SimpleBDXStore for stores.
190 static int isSimpleMove(const MachineInstr *MI, int &FrameIndex,
191                         unsigned Flag) {
192   const MCInstrDesc &MCID = MI->getDesc();
193   if ((MCID.TSFlags & Flag) &&
194       MI->getOperand(1).isFI() &&
195       MI->getOperand(2).getImm() == 0 &&
196       MI->getOperand(3).getReg() == 0) {
197     FrameIndex = MI->getOperand(1).getIndex();
198     return MI->getOperand(0).getReg();
199   }
200   return 0;
201 }
202
203 unsigned SystemZInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
204                                                int &FrameIndex) const {
205   return isSimpleMove(MI, FrameIndex, SystemZII::SimpleBDXLoad);
206 }
207
208 unsigned SystemZInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
209                                               int &FrameIndex) const {
210   return isSimpleMove(MI, FrameIndex, SystemZII::SimpleBDXStore);
211 }
212
213 bool SystemZInstrInfo::isStackSlotCopy(const MachineInstr *MI,
214                                        int &DestFrameIndex,
215                                        int &SrcFrameIndex) const {
216   // Check for MVC 0(Length,FI1),0(FI2)
217   const MachineFrameInfo *MFI = MI->getParent()->getParent()->getFrameInfo();
218   if (MI->getOpcode() != SystemZ::MVC ||
219       !MI->getOperand(0).isFI() ||
220       MI->getOperand(1).getImm() != 0 ||
221       !MI->getOperand(3).isFI() ||
222       MI->getOperand(4).getImm() != 0)
223     return false;
224
225   // Check that Length covers the full slots.
226   int64_t Length = MI->getOperand(2).getImm();
227   unsigned FI1 = MI->getOperand(0).getIndex();
228   unsigned FI2 = MI->getOperand(3).getIndex();
229   if (MFI->getObjectSize(FI1) != Length ||
230       MFI->getObjectSize(FI2) != Length)
231     return false;
232
233   DestFrameIndex = FI1;
234   SrcFrameIndex = FI2;
235   return true;
236 }
237
238 bool SystemZInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
239                                      MachineBasicBlock *&TBB,
240                                      MachineBasicBlock *&FBB,
241                                      SmallVectorImpl<MachineOperand> &Cond,
242                                      bool AllowModify) const {
243   // Most of the code and comments here are boilerplate.
244
245   // Start from the bottom of the block and work up, examining the
246   // terminator instructions.
247   MachineBasicBlock::iterator I = MBB.end();
248   while (I != MBB.begin()) {
249     --I;
250     if (I->isDebugValue())
251       continue;
252
253     // Working from the bottom, when we see a non-terminator instruction, we're
254     // done.
255     if (!isUnpredicatedTerminator(I))
256       break;
257
258     // A terminator that isn't a branch can't easily be handled by this
259     // analysis.
260     if (!I->isBranch())
261       return true;
262
263     // Can't handle indirect branches.
264     SystemZII::Branch Branch(getBranchInfo(I));
265     if (!Branch.Target->isMBB())
266       return true;
267
268     // Punt on compound branches.
269     if (Branch.Type != SystemZII::BranchNormal)
270       return true;
271
272     if (Branch.CCMask == SystemZ::CCMASK_ANY) {
273       // Handle unconditional branches.
274       if (!AllowModify) {
275         TBB = Branch.Target->getMBB();
276         continue;
277       }
278
279       // If the block has any instructions after a JMP, delete them.
280       while (llvm::next(I) != MBB.end())
281         llvm::next(I)->eraseFromParent();
282
283       Cond.clear();
284       FBB = 0;
285
286       // Delete the JMP if it's equivalent to a fall-through.
287       if (MBB.isLayoutSuccessor(Branch.Target->getMBB())) {
288         TBB = 0;
289         I->eraseFromParent();
290         I = MBB.end();
291         continue;
292       }
293
294       // TBB is used to indicate the unconditinal destination.
295       TBB = Branch.Target->getMBB();
296       continue;
297     }
298
299     // Working from the bottom, handle the first conditional branch.
300     if (Cond.empty()) {
301       // FIXME: add X86-style branch swap
302       FBB = TBB;
303       TBB = Branch.Target->getMBB();
304       Cond.push_back(MachineOperand::CreateImm(Branch.CCValid));
305       Cond.push_back(MachineOperand::CreateImm(Branch.CCMask));
306       continue;
307     }
308
309     // Handle subsequent conditional branches.
310     assert(Cond.size() == 2 && TBB && "Should have seen a conditional branch");
311
312     // Only handle the case where all conditional branches branch to the same
313     // destination.
314     if (TBB != Branch.Target->getMBB())
315       return true;
316
317     // If the conditions are the same, we can leave them alone.
318     unsigned OldCCValid = Cond[0].getImm();
319     unsigned OldCCMask = Cond[1].getImm();
320     if (OldCCValid == Branch.CCValid && OldCCMask == Branch.CCMask)
321       continue;
322
323     // FIXME: Try combining conditions like X86 does.  Should be easy on Z!
324     return false;
325   }
326
327   return false;
328 }
329
330 unsigned SystemZInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
331   // Most of the code and comments here are boilerplate.
332   MachineBasicBlock::iterator I = MBB.end();
333   unsigned Count = 0;
334
335   while (I != MBB.begin()) {
336     --I;
337     if (I->isDebugValue())
338       continue;
339     if (!I->isBranch())
340       break;
341     if (!getBranchInfo(I).Target->isMBB())
342       break;
343     // Remove the branch.
344     I->eraseFromParent();
345     I = MBB.end();
346     ++Count;
347   }
348
349   return Count;
350 }
351
352 bool SystemZInstrInfo::
353 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
354   assert(Cond.size() == 2 && "Invalid condition");
355   Cond[1].setImm(Cond[1].getImm() ^ Cond[0].getImm());
356   return false;
357 }
358
359 unsigned
360 SystemZInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
361                                MachineBasicBlock *FBB,
362                                const SmallVectorImpl<MachineOperand> &Cond,
363                                DebugLoc DL) const {
364   // In this function we output 32-bit branches, which should always
365   // have enough range.  They can be shortened and relaxed by later code
366   // in the pipeline, if desired.
367
368   // Shouldn't be a fall through.
369   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
370   assert((Cond.size() == 2 || Cond.size() == 0) &&
371          "SystemZ branch conditions have one component!");
372
373   if (Cond.empty()) {
374     // Unconditional branch?
375     assert(!FBB && "Unconditional branch with multiple successors!");
376     BuildMI(&MBB, DL, get(SystemZ::J)).addMBB(TBB);
377     return 1;
378   }
379
380   // Conditional branch.
381   unsigned Count = 0;
382   unsigned CCValid = Cond[0].getImm();
383   unsigned CCMask = Cond[1].getImm();
384   BuildMI(&MBB, DL, get(SystemZ::BRC))
385     .addImm(CCValid).addImm(CCMask).addMBB(TBB);
386   ++Count;
387
388   if (FBB) {
389     // Two-way Conditional branch. Insert the second branch.
390     BuildMI(&MBB, DL, get(SystemZ::J)).addMBB(FBB);
391     ++Count;
392   }
393   return Count;
394 }
395
396 bool SystemZInstrInfo::analyzeCompare(const MachineInstr *MI,
397                                       unsigned &SrcReg, unsigned &SrcReg2,
398                                       int &Mask, int &Value) const {
399   assert(MI->isCompare() && "Caller should have checked for a comparison");
400
401   if (MI->getNumExplicitOperands() == 2 &&
402       MI->getOperand(0).isReg() &&
403       MI->getOperand(1).isImm()) {
404     SrcReg = MI->getOperand(0).getReg();
405     SrcReg2 = 0;
406     Value = MI->getOperand(1).getImm();
407     Mask = ~0;
408     return true;
409   }
410
411   return false;
412 }
413
414 // If Reg is a virtual register, return its definition, otherwise return null.
415 static MachineInstr *getDef(unsigned Reg,
416                             const MachineRegisterInfo *MRI) {
417   if (TargetRegisterInfo::isPhysicalRegister(Reg))
418     return 0;
419   return MRI->getUniqueVRegDef(Reg);
420 }
421
422 // Return true if MI is a shift of type Opcode by Imm bits.
423 static bool isShift(MachineInstr *MI, int Opcode, int64_t Imm) {
424   return (MI->getOpcode() == Opcode &&
425           !MI->getOperand(2).getReg() &&
426           MI->getOperand(3).getImm() == Imm);
427 }
428
429 // If the destination of MI has no uses, delete it as dead.
430 static void eraseIfDead(MachineInstr *MI, const MachineRegisterInfo *MRI) {
431   if (MRI->use_nodbg_empty(MI->getOperand(0).getReg()))
432     MI->eraseFromParent();
433 }
434
435 // Compare compares SrcReg against zero.  Check whether SrcReg contains
436 // the result of an IPM sequence whose input CC survives until Compare,
437 // and whether Compare is therefore redundant.  Delete it and return
438 // true if so.
439 static bool removeIPMBasedCompare(MachineInstr *Compare, unsigned SrcReg,
440                                   const MachineRegisterInfo *MRI,
441                                   const TargetRegisterInfo *TRI) {
442   MachineInstr *LGFR = 0;
443   MachineInstr *RLL = getDef(SrcReg, MRI);
444   if (RLL && RLL->getOpcode() == SystemZ::LGFR) {
445     LGFR = RLL;
446     RLL = getDef(LGFR->getOperand(1).getReg(), MRI);
447   }
448   if (!RLL || !isShift(RLL, SystemZ::RLL, 31))
449     return false;
450
451   MachineInstr *SRL = getDef(RLL->getOperand(1).getReg(), MRI);
452   if (!SRL || !isShift(SRL, SystemZ::SRL, SystemZ::IPM_CC))
453     return false;
454
455   MachineInstr *IPM = getDef(SRL->getOperand(1).getReg(), MRI);
456   if (!IPM || IPM->getOpcode() != SystemZ::IPM)
457     return false;
458
459   // Check that there are no assignments to CC between the IPM and Compare,
460   if (IPM->getParent() != Compare->getParent())
461     return false;
462   MachineBasicBlock::iterator MBBI = IPM, MBBE = Compare;
463   for (++MBBI; MBBI != MBBE; ++MBBI) {
464     MachineInstr *MI = MBBI;
465     if (MI->modifiesRegister(SystemZ::CC, TRI))
466       return false;
467   }
468
469   Compare->eraseFromParent();
470   if (LGFR)
471     eraseIfDead(LGFR, MRI);
472   eraseIfDead(RLL, MRI);
473   eraseIfDead(SRL, MRI);
474   eraseIfDead(IPM, MRI);
475
476   return true;
477 }
478
479 bool
480 SystemZInstrInfo::optimizeCompareInstr(MachineInstr *Compare,
481                                        unsigned SrcReg, unsigned SrcReg2,
482                                        int Mask, int Value,
483                                        const MachineRegisterInfo *MRI) const {
484   assert(!SrcReg2 && "Only optimizing constant comparisons so far");
485   bool IsLogical = (Compare->getDesc().TSFlags & SystemZII::IsLogical) != 0;
486   if (Value == 0 &&
487       !IsLogical &&
488       removeIPMBasedCompare(Compare, SrcReg, MRI, TM.getRegisterInfo()))
489     return true;
490   return false;
491 }
492
493 // If Opcode is a move that has a conditional variant, return that variant,
494 // otherwise return 0.
495 static unsigned getConditionalMove(unsigned Opcode) {
496   switch (Opcode) {
497   case SystemZ::LR:  return SystemZ::LOCR;
498   case SystemZ::LGR: return SystemZ::LOCGR;
499   default:           return 0;
500   }
501 }
502
503 bool SystemZInstrInfo::isPredicable(MachineInstr *MI) const {
504   unsigned Opcode = MI->getOpcode();
505   if (TM.getSubtargetImpl()->hasLoadStoreOnCond() &&
506       getConditionalMove(Opcode))
507     return true;
508   return false;
509 }
510
511 bool SystemZInstrInfo::
512 isProfitableToIfCvt(MachineBasicBlock &MBB,
513                     unsigned NumCycles, unsigned ExtraPredCycles,
514                     const BranchProbability &Probability) const {
515   // For now only convert single instructions.
516   return NumCycles == 1;
517 }
518
519 bool SystemZInstrInfo::
520 isProfitableToIfCvt(MachineBasicBlock &TMBB,
521                     unsigned NumCyclesT, unsigned ExtraPredCyclesT,
522                     MachineBasicBlock &FMBB,
523                     unsigned NumCyclesF, unsigned ExtraPredCyclesF,
524                     const BranchProbability &Probability) const {
525   // For now avoid converting mutually-exclusive cases.
526   return false;
527 }
528
529 bool SystemZInstrInfo::
530 PredicateInstruction(MachineInstr *MI,
531                      const SmallVectorImpl<MachineOperand> &Pred) const {
532   assert(Pred.size() == 2 && "Invalid condition");
533   unsigned CCValid = Pred[0].getImm();
534   unsigned CCMask = Pred[1].getImm();
535   assert(CCMask > 0 && CCMask < 15 && "Invalid predicate");
536   unsigned Opcode = MI->getOpcode();
537   if (TM.getSubtargetImpl()->hasLoadStoreOnCond()) {
538     if (unsigned CondOpcode = getConditionalMove(Opcode)) {
539       MI->setDesc(get(CondOpcode));
540       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
541         .addImm(CCValid).addImm(CCMask)
542         .addReg(SystemZ::CC, RegState::Implicit);;
543       return true;
544     }
545   }
546   return false;
547 }
548
549 void
550 SystemZInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
551                               MachineBasicBlock::iterator MBBI, DebugLoc DL,
552                               unsigned DestReg, unsigned SrcReg,
553                               bool KillSrc) const {
554   // Split 128-bit GPR moves into two 64-bit moves.  This handles ADDR128 too.
555   if (SystemZ::GR128BitRegClass.contains(DestReg, SrcReg)) {
556     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_h64),
557                 RI.getSubReg(SrcReg, SystemZ::subreg_h64), KillSrc);
558     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_l64),
559                 RI.getSubReg(SrcReg, SystemZ::subreg_l64), KillSrc);
560     return;
561   }
562
563   if (SystemZ::GRX32BitRegClass.contains(DestReg, SrcReg)) {
564     emitGRX32Move(MBB, MBBI, DL, DestReg, SrcReg, SystemZ::LR, 32, KillSrc);
565     return;
566   }
567
568   // Everything else needs only one instruction.
569   unsigned Opcode;
570   if (SystemZ::GR64BitRegClass.contains(DestReg, SrcReg))
571     Opcode = SystemZ::LGR;
572   else if (SystemZ::FP32BitRegClass.contains(DestReg, SrcReg))
573     Opcode = SystemZ::LER;
574   else if (SystemZ::FP64BitRegClass.contains(DestReg, SrcReg))
575     Opcode = SystemZ::LDR;
576   else if (SystemZ::FP128BitRegClass.contains(DestReg, SrcReg))
577     Opcode = SystemZ::LXR;
578   else
579     llvm_unreachable("Impossible reg-to-reg copy");
580
581   BuildMI(MBB, MBBI, DL, get(Opcode), DestReg)
582     .addReg(SrcReg, getKillRegState(KillSrc));
583 }
584
585 void
586 SystemZInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
587                                       MachineBasicBlock::iterator MBBI,
588                                       unsigned SrcReg, bool isKill,
589                                       int FrameIdx,
590                                       const TargetRegisterClass *RC,
591                                       const TargetRegisterInfo *TRI) const {
592   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
593
594   // Callers may expect a single instruction, so keep 128-bit moves
595   // together for now and lower them after register allocation.
596   unsigned LoadOpcode, StoreOpcode;
597   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
598   addFrameReference(BuildMI(MBB, MBBI, DL, get(StoreOpcode))
599                     .addReg(SrcReg, getKillRegState(isKill)), FrameIdx);
600 }
601
602 void
603 SystemZInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
604                                        MachineBasicBlock::iterator MBBI,
605                                        unsigned DestReg, int FrameIdx,
606                                        const TargetRegisterClass *RC,
607                                        const TargetRegisterInfo *TRI) const {
608   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
609
610   // Callers may expect a single instruction, so keep 128-bit moves
611   // together for now and lower them after register allocation.
612   unsigned LoadOpcode, StoreOpcode;
613   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
614   addFrameReference(BuildMI(MBB, MBBI, DL, get(LoadOpcode), DestReg),
615                     FrameIdx);
616 }
617
618 // Return true if MI is a simple load or store with a 12-bit displacement
619 // and no index.  Flag is SimpleBDXLoad for loads and SimpleBDXStore for stores.
620 static bool isSimpleBD12Move(const MachineInstr *MI, unsigned Flag) {
621   const MCInstrDesc &MCID = MI->getDesc();
622   return ((MCID.TSFlags & Flag) &&
623           isUInt<12>(MI->getOperand(2).getImm()) &&
624           MI->getOperand(3).getReg() == 0);
625 }
626
627 namespace {
628   struct LogicOp {
629     LogicOp() : RegSize(0), ImmLSB(0), ImmSize(0) {}
630     LogicOp(unsigned regSize, unsigned immLSB, unsigned immSize)
631       : RegSize(regSize), ImmLSB(immLSB), ImmSize(immSize) {}
632
633     operator bool() const { return RegSize; }
634
635     unsigned RegSize, ImmLSB, ImmSize;
636   };
637 }
638
639 static LogicOp interpretAndImmediate(unsigned Opcode) {
640   switch (Opcode) {
641   case SystemZ::NILMux: return LogicOp(32,  0, 16);
642   case SystemZ::NIHMux: return LogicOp(32, 16, 16);
643   case SystemZ::NILL64: return LogicOp(64,  0, 16);
644   case SystemZ::NILH64: return LogicOp(64, 16, 16);
645   case SystemZ::NIHL64: return LogicOp(64, 32, 16);
646   case SystemZ::NIHH64: return LogicOp(64, 48, 16);
647   case SystemZ::NIFMux: return LogicOp(32,  0, 32);
648   case SystemZ::NILF64: return LogicOp(64,  0, 32);
649   case SystemZ::NIHF64: return LogicOp(64, 32, 32);
650   default:              return LogicOp();
651   }
652 }
653
654 // Used to return from convertToThreeAddress after replacing two-address
655 // instruction OldMI with three-address instruction NewMI.
656 static MachineInstr *finishConvertToThreeAddress(MachineInstr *OldMI,
657                                                  MachineInstr *NewMI,
658                                                  LiveVariables *LV) {
659   if (LV) {
660     unsigned NumOps = OldMI->getNumOperands();
661     for (unsigned I = 1; I < NumOps; ++I) {
662       MachineOperand &Op = OldMI->getOperand(I);
663       if (Op.isReg() && Op.isKill())
664         LV->replaceKillInstruction(Op.getReg(), OldMI, NewMI);
665     }
666   }
667   return NewMI;
668 }
669
670 MachineInstr *
671 SystemZInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
672                                         MachineBasicBlock::iterator &MBBI,
673                                         LiveVariables *LV) const {
674   MachineInstr *MI = MBBI;
675   MachineBasicBlock *MBB = MI->getParent();
676   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
677
678   unsigned Opcode = MI->getOpcode();
679   unsigned NumOps = MI->getNumOperands();
680
681   // Try to convert something like SLL into SLLK, if supported.
682   // We prefer to keep the two-operand form where possible both
683   // because it tends to be shorter and because some instructions
684   // have memory forms that can be used during spilling.
685   if (TM.getSubtargetImpl()->hasDistinctOps()) {
686     MachineOperand &Dest = MI->getOperand(0);
687     MachineOperand &Src = MI->getOperand(1);
688     unsigned DestReg = Dest.getReg();
689     unsigned SrcReg = Src.getReg();
690     // AHIMux is only really a three-operand instruction when both operands
691     // are low registers.  Try to constrain both operands to be low if
692     // possible.
693     if (Opcode == SystemZ::AHIMux &&
694         TargetRegisterInfo::isVirtualRegister(DestReg) &&
695         TargetRegisterInfo::isVirtualRegister(SrcReg) &&
696         MRI.getRegClass(DestReg)->contains(SystemZ::R1L) &&
697         MRI.getRegClass(SrcReg)->contains(SystemZ::R1L)) {
698       MRI.constrainRegClass(DestReg, &SystemZ::GR32BitRegClass);
699       MRI.constrainRegClass(SrcReg, &SystemZ::GR32BitRegClass);
700     }
701     int ThreeOperandOpcode = SystemZ::getThreeOperandOpcode(Opcode);
702     if (ThreeOperandOpcode >= 0) {
703       MachineInstrBuilder MIB =
704         BuildMI(*MBB, MBBI, MI->getDebugLoc(), get(ThreeOperandOpcode))
705         .addOperand(Dest);
706       // Keep the kill state, but drop the tied flag.
707       MIB.addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg());
708       // Keep the remaining operands as-is.
709       for (unsigned I = 2; I < NumOps; ++I)
710         MIB.addOperand(MI->getOperand(I));
711       return finishConvertToThreeAddress(MI, MIB, LV);
712     }
713   }
714
715   // Try to convert an AND into an RISBG-type instruction.
716   if (LogicOp And = interpretAndImmediate(Opcode)) {
717     uint64_t Imm = MI->getOperand(2).getImm() << And.ImmLSB;
718     // AND IMMEDIATE leaves the other bits of the register unchanged.
719     Imm |= allOnes(And.RegSize) & ~(allOnes(And.ImmSize) << And.ImmLSB);
720     unsigned Start, End;
721     if (isRxSBGMask(Imm, And.RegSize, Start, End)) {
722       unsigned NewOpcode;
723       if (And.RegSize == 64)
724         NewOpcode = SystemZ::RISBG;
725       else {
726         NewOpcode = SystemZ::RISBMux;
727         Start &= 31;
728         End &= 31;
729       }
730       MachineOperand &Dest = MI->getOperand(0);
731       MachineOperand &Src = MI->getOperand(1);
732       MachineInstrBuilder MIB =
733         BuildMI(*MBB, MI, MI->getDebugLoc(), get(NewOpcode))
734         .addOperand(Dest).addReg(0)
735         .addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg())
736         .addImm(Start).addImm(End + 128).addImm(0);
737       return finishConvertToThreeAddress(MI, MIB, LV);
738     }
739   }
740   return 0;
741 }
742
743 MachineInstr *
744 SystemZInstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
745                                         MachineInstr *MI,
746                                         const SmallVectorImpl<unsigned> &Ops,
747                                         int FrameIndex) const {
748   const MachineFrameInfo *MFI = MF.getFrameInfo();
749   unsigned Size = MFI->getObjectSize(FrameIndex);
750   unsigned Opcode = MI->getOpcode();
751
752   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
753     if ((Opcode == SystemZ::LA || Opcode == SystemZ::LAY) &&
754         isInt<8>(MI->getOperand(2).getImm()) &&
755         !MI->getOperand(3).getReg()) {
756       // LA(Y) %reg, CONST(%reg) -> AGSI %mem, CONST
757       return BuildMI(MF, MI->getDebugLoc(), get(SystemZ::AGSI))
758         .addFrameIndex(FrameIndex).addImm(0)
759         .addImm(MI->getOperand(2).getImm());
760     }
761     return 0;
762   }
763
764   // All other cases require a single operand.
765   if (Ops.size() != 1)
766     return 0;
767
768   unsigned OpNum = Ops[0];
769   assert(Size == MF.getRegInfo()
770          .getRegClass(MI->getOperand(OpNum).getReg())->getSize() &&
771          "Invalid size combination");
772
773   if ((Opcode == SystemZ::AHI || Opcode == SystemZ::AGHI) &&
774       OpNum == 0 &&
775       isInt<8>(MI->getOperand(2).getImm())) {
776     // A(G)HI %reg, CONST -> A(G)SI %mem, CONST
777     Opcode = (Opcode == SystemZ::AHI ? SystemZ::ASI : SystemZ::AGSI);
778     return BuildMI(MF, MI->getDebugLoc(), get(Opcode))
779       .addFrameIndex(FrameIndex).addImm(0)
780       .addImm(MI->getOperand(2).getImm());
781   }
782
783   if (Opcode == SystemZ::LGDR || Opcode == SystemZ::LDGR) {
784     bool Op0IsGPR = (Opcode == SystemZ::LGDR);
785     bool Op1IsGPR = (Opcode == SystemZ::LDGR);
786     // If we're spilling the destination of an LDGR or LGDR, store the
787     // source register instead.
788     if (OpNum == 0) {
789       unsigned StoreOpcode = Op1IsGPR ? SystemZ::STG : SystemZ::STD;
790       return BuildMI(MF, MI->getDebugLoc(), get(StoreOpcode))
791         .addOperand(MI->getOperand(1)).addFrameIndex(FrameIndex)
792         .addImm(0).addReg(0);
793     }
794     // If we're spilling the source of an LDGR or LGDR, load the
795     // destination register instead.
796     if (OpNum == 1) {
797       unsigned LoadOpcode = Op0IsGPR ? SystemZ::LG : SystemZ::LD;
798       unsigned Dest = MI->getOperand(0).getReg();
799       return BuildMI(MF, MI->getDebugLoc(), get(LoadOpcode), Dest)
800         .addFrameIndex(FrameIndex).addImm(0).addReg(0);
801     }
802   }
803
804   // Look for cases where the source of a simple store or the destination
805   // of a simple load is being spilled.  Try to use MVC instead.
806   //
807   // Although MVC is in practice a fast choice in these cases, it is still
808   // logically a bytewise copy.  This means that we cannot use it if the
809   // load or store is volatile.  We also wouldn't be able to use MVC if
810   // the two memories partially overlap, but that case cannot occur here,
811   // because we know that one of the memories is a full frame index.
812   //
813   // For performance reasons, we also want to avoid using MVC if the addresses
814   // might be equal.  We don't worry about that case here, because spill slot
815   // coloring happens later, and because we have special code to remove
816   // MVCs that turn out to be redundant.
817   if (OpNum == 0 && MI->hasOneMemOperand()) {
818     MachineMemOperand *MMO = *MI->memoperands_begin();
819     if (MMO->getSize() == Size && !MMO->isVolatile()) {
820       // Handle conversion of loads.
821       if (isSimpleBD12Move(MI, SystemZII::SimpleBDXLoad)) {
822         return BuildMI(MF, MI->getDebugLoc(), get(SystemZ::MVC))
823           .addFrameIndex(FrameIndex).addImm(0).addImm(Size)
824           .addOperand(MI->getOperand(1)).addImm(MI->getOperand(2).getImm())
825           .addMemOperand(MMO);
826       }
827       // Handle conversion of stores.
828       if (isSimpleBD12Move(MI, SystemZII::SimpleBDXStore)) {
829         return BuildMI(MF, MI->getDebugLoc(), get(SystemZ::MVC))
830           .addOperand(MI->getOperand(1)).addImm(MI->getOperand(2).getImm())
831           .addImm(Size).addFrameIndex(FrameIndex).addImm(0)
832           .addMemOperand(MMO);
833       }
834     }
835   }
836
837   // If the spilled operand is the final one, try to change <INSN>R
838   // into <INSN>.
839   int MemOpcode = SystemZ::getMemOpcode(Opcode);
840   if (MemOpcode >= 0) {
841     unsigned NumOps = MI->getNumExplicitOperands();
842     if (OpNum == NumOps - 1) {
843       const MCInstrDesc &MemDesc = get(MemOpcode);
844       uint64_t AccessBytes = SystemZII::getAccessSize(MemDesc.TSFlags);
845       assert(AccessBytes != 0 && "Size of access should be known");
846       assert(AccessBytes <= Size && "Access outside the frame index");
847       uint64_t Offset = Size - AccessBytes;
848       MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), get(MemOpcode));
849       for (unsigned I = 0; I < OpNum; ++I)
850         MIB.addOperand(MI->getOperand(I));
851       MIB.addFrameIndex(FrameIndex).addImm(Offset);
852       if (MemDesc.TSFlags & SystemZII::HasIndex)
853         MIB.addReg(0);
854       return MIB;
855     }
856   }
857
858   return 0;
859 }
860
861 MachineInstr *
862 SystemZInstrInfo::foldMemoryOperandImpl(MachineFunction &MF, MachineInstr* MI,
863                                         const SmallVectorImpl<unsigned> &Ops,
864                                         MachineInstr* LoadMI) const {
865   return 0;
866 }
867
868 bool
869 SystemZInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
870   switch (MI->getOpcode()) {
871   case SystemZ::L128:
872     splitMove(MI, SystemZ::LG);
873     return true;
874
875   case SystemZ::ST128:
876     splitMove(MI, SystemZ::STG);
877     return true;
878
879   case SystemZ::LX:
880     splitMove(MI, SystemZ::LD);
881     return true;
882
883   case SystemZ::STX:
884     splitMove(MI, SystemZ::STD);
885     return true;
886
887   case SystemZ::LBMux:
888     expandRXYPseudo(MI, SystemZ::LB, SystemZ::LBH);
889     return true;
890
891   case SystemZ::LHMux:
892     expandRXYPseudo(MI, SystemZ::LH, SystemZ::LHH);
893     return true;
894
895   case SystemZ::LLCRMux:
896     expandZExtPseudo(MI, SystemZ::LLCR, 8);
897     return true;
898
899   case SystemZ::LLHRMux:
900     expandZExtPseudo(MI, SystemZ::LLHR, 16);
901     return true;
902
903   case SystemZ::LLCMux:
904     expandRXYPseudo(MI, SystemZ::LLC, SystemZ::LLCH);
905     return true;
906
907   case SystemZ::LLHMux:
908     expandRXYPseudo(MI, SystemZ::LLH, SystemZ::LLHH);
909     return true;
910
911   case SystemZ::LMux:
912     expandRXYPseudo(MI, SystemZ::L, SystemZ::LFH);
913     return true;
914
915   case SystemZ::STCMux:
916     expandRXYPseudo(MI, SystemZ::STC, SystemZ::STCH);
917     return true;
918
919   case SystemZ::STHMux:
920     expandRXYPseudo(MI, SystemZ::STH, SystemZ::STHH);
921     return true;
922
923   case SystemZ::STMux:
924     expandRXYPseudo(MI, SystemZ::ST, SystemZ::STFH);
925     return true;
926
927   case SystemZ::LHIMux:
928     expandRIPseudo(MI, SystemZ::LHI, SystemZ::IIHF, true);
929     return true;
930
931   case SystemZ::IIFMux:
932     expandRIPseudo(MI, SystemZ::IILF, SystemZ::IIHF, false);
933     return true;
934
935   case SystemZ::IILMux:
936     expandRIPseudo(MI, SystemZ::IILL, SystemZ::IIHL, false);
937     return true;
938
939   case SystemZ::IIHMux:
940     expandRIPseudo(MI, SystemZ::IILH, SystemZ::IIHH, false);
941     return true;
942
943   case SystemZ::NIFMux:
944     expandRIPseudo(MI, SystemZ::NILF, SystemZ::NIHF, false);
945     return true;
946
947   case SystemZ::NILMux:
948     expandRIPseudo(MI, SystemZ::NILL, SystemZ::NIHL, false);
949     return true;
950
951   case SystemZ::NIHMux:
952     expandRIPseudo(MI, SystemZ::NILH, SystemZ::NIHH, false);
953     return true;
954
955   case SystemZ::OIFMux:
956     expandRIPseudo(MI, SystemZ::OILF, SystemZ::OIHF, false);
957     return true;
958
959   case SystemZ::OILMux:
960     expandRIPseudo(MI, SystemZ::OILL, SystemZ::OIHL, false);
961     return true;
962
963   case SystemZ::OIHMux:
964     expandRIPseudo(MI, SystemZ::OILH, SystemZ::OIHH, false);
965     return true;
966
967   case SystemZ::XIFMux:
968     expandRIPseudo(MI, SystemZ::XILF, SystemZ::XIHF, false);
969     return true;
970
971   case SystemZ::TMLMux:
972     expandRIPseudo(MI, SystemZ::TMLL, SystemZ::TMHL, false);
973     return true;
974
975   case SystemZ::TMHMux:
976     expandRIPseudo(MI, SystemZ::TMLH, SystemZ::TMHH, false);
977     return true;
978
979   case SystemZ::AHIMux:
980     expandRIPseudo(MI, SystemZ::AHI, SystemZ::AIH, false);
981     return true;
982
983   case SystemZ::AHIMuxK:
984     expandRIEPseudo(MI, SystemZ::AHI, SystemZ::AHIK, SystemZ::AIH);
985     return true;
986
987   case SystemZ::AFIMux:
988     expandRIPseudo(MI, SystemZ::AFI, SystemZ::AIH, false);
989     return true;
990
991   case SystemZ::CFIMux:
992     expandRIPseudo(MI, SystemZ::CFI, SystemZ::CIH, false);
993     return true;
994
995   case SystemZ::CLFIMux:
996     expandRIPseudo(MI, SystemZ::CLFI, SystemZ::CLIH, false);
997     return true;
998
999   case SystemZ::CMux:
1000     expandRXYPseudo(MI, SystemZ::C, SystemZ::CHF);
1001     return true;
1002
1003   case SystemZ::CLMux:
1004     expandRXYPseudo(MI, SystemZ::CL, SystemZ::CLHF);
1005     return true;
1006
1007   case SystemZ::RISBMux: {
1008     bool DestIsHigh = isHighReg(MI->getOperand(0).getReg());
1009     bool SrcIsHigh = isHighReg(MI->getOperand(2).getReg());
1010     if (SrcIsHigh == DestIsHigh)
1011       MI->setDesc(get(DestIsHigh ? SystemZ::RISBHH : SystemZ::RISBLL));
1012     else {
1013       MI->setDesc(get(DestIsHigh ? SystemZ::RISBHL : SystemZ::RISBLH));
1014       MI->getOperand(5).setImm(MI->getOperand(5).getImm() ^ 32);
1015     }
1016     return true;
1017   }
1018
1019   case SystemZ::ADJDYNALLOC:
1020     splitAdjDynAlloc(MI);
1021     return true;
1022
1023   default:
1024     return false;
1025   }
1026 }
1027
1028 uint64_t SystemZInstrInfo::getInstSizeInBytes(const MachineInstr *MI) const {
1029   if (MI->getOpcode() == TargetOpcode::INLINEASM) {
1030     const MachineFunction *MF = MI->getParent()->getParent();
1031     const char *AsmStr = MI->getOperand(0).getSymbolName();
1032     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1033   }
1034   return MI->getDesc().getSize();
1035 }
1036
1037 SystemZII::Branch
1038 SystemZInstrInfo::getBranchInfo(const MachineInstr *MI) const {
1039   switch (MI->getOpcode()) {
1040   case SystemZ::BR:
1041   case SystemZ::J:
1042   case SystemZ::JG:
1043     return SystemZII::Branch(SystemZII::BranchNormal, SystemZ::CCMASK_ANY,
1044                              SystemZ::CCMASK_ANY, &MI->getOperand(0));
1045
1046   case SystemZ::BRC:
1047   case SystemZ::BRCL:
1048     return SystemZII::Branch(SystemZII::BranchNormal,
1049                              MI->getOperand(0).getImm(),
1050                              MI->getOperand(1).getImm(), &MI->getOperand(2));
1051
1052   case SystemZ::BRCT:
1053     return SystemZII::Branch(SystemZII::BranchCT, SystemZ::CCMASK_ICMP,
1054                              SystemZ::CCMASK_CMP_NE, &MI->getOperand(2));
1055
1056   case SystemZ::BRCTG:
1057     return SystemZII::Branch(SystemZII::BranchCTG, SystemZ::CCMASK_ICMP,
1058                              SystemZ::CCMASK_CMP_NE, &MI->getOperand(2));
1059
1060   case SystemZ::CIJ:
1061   case SystemZ::CRJ:
1062     return SystemZII::Branch(SystemZII::BranchC, SystemZ::CCMASK_ICMP,
1063                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1064
1065   case SystemZ::CLIJ:
1066   case SystemZ::CLRJ:
1067     return SystemZII::Branch(SystemZII::BranchCL, SystemZ::CCMASK_ICMP,
1068                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1069
1070   case SystemZ::CGIJ:
1071   case SystemZ::CGRJ:
1072     return SystemZII::Branch(SystemZII::BranchCG, SystemZ::CCMASK_ICMP,
1073                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1074
1075   case SystemZ::CLGIJ:
1076   case SystemZ::CLGRJ:
1077     return SystemZII::Branch(SystemZII::BranchCLG, SystemZ::CCMASK_ICMP,
1078                              MI->getOperand(2).getImm(), &MI->getOperand(3));
1079
1080   default:
1081     llvm_unreachable("Unrecognized branch opcode");
1082   }
1083 }
1084
1085 void SystemZInstrInfo::getLoadStoreOpcodes(const TargetRegisterClass *RC,
1086                                            unsigned &LoadOpcode,
1087                                            unsigned &StoreOpcode) const {
1088   if (RC == &SystemZ::GR32BitRegClass || RC == &SystemZ::ADDR32BitRegClass) {
1089     LoadOpcode = SystemZ::L;
1090     StoreOpcode = SystemZ::ST;
1091   } else if (RC == &SystemZ::GRH32BitRegClass) {
1092     LoadOpcode = SystemZ::LFH;
1093     StoreOpcode = SystemZ::STFH;
1094   } else if (RC == &SystemZ::GRX32BitRegClass) {
1095     LoadOpcode = SystemZ::LMux;
1096     StoreOpcode = SystemZ::STMux;
1097   } else if (RC == &SystemZ::GR64BitRegClass ||
1098              RC == &SystemZ::ADDR64BitRegClass) {
1099     LoadOpcode = SystemZ::LG;
1100     StoreOpcode = SystemZ::STG;
1101   } else if (RC == &SystemZ::GR128BitRegClass ||
1102              RC == &SystemZ::ADDR128BitRegClass) {
1103     LoadOpcode = SystemZ::L128;
1104     StoreOpcode = SystemZ::ST128;
1105   } else if (RC == &SystemZ::FP32BitRegClass) {
1106     LoadOpcode = SystemZ::LE;
1107     StoreOpcode = SystemZ::STE;
1108   } else if (RC == &SystemZ::FP64BitRegClass) {
1109     LoadOpcode = SystemZ::LD;
1110     StoreOpcode = SystemZ::STD;
1111   } else if (RC == &SystemZ::FP128BitRegClass) {
1112     LoadOpcode = SystemZ::LX;
1113     StoreOpcode = SystemZ::STX;
1114   } else
1115     llvm_unreachable("Unsupported regclass to load or store");
1116 }
1117
1118 unsigned SystemZInstrInfo::getOpcodeForOffset(unsigned Opcode,
1119                                               int64_t Offset) const {
1120   const MCInstrDesc &MCID = get(Opcode);
1121   int64_t Offset2 = (MCID.TSFlags & SystemZII::Is128Bit ? Offset + 8 : Offset);
1122   if (isUInt<12>(Offset) && isUInt<12>(Offset2)) {
1123     // Get the instruction to use for unsigned 12-bit displacements.
1124     int Disp12Opcode = SystemZ::getDisp12Opcode(Opcode);
1125     if (Disp12Opcode >= 0)
1126       return Disp12Opcode;
1127
1128     // All address-related instructions can use unsigned 12-bit
1129     // displacements.
1130     return Opcode;
1131   }
1132   if (isInt<20>(Offset) && isInt<20>(Offset2)) {
1133     // Get the instruction to use for signed 20-bit displacements.
1134     int Disp20Opcode = SystemZ::getDisp20Opcode(Opcode);
1135     if (Disp20Opcode >= 0)
1136       return Disp20Opcode;
1137
1138     // Check whether Opcode allows signed 20-bit displacements.
1139     if (MCID.TSFlags & SystemZII::Has20BitOffset)
1140       return Opcode;
1141   }
1142   return 0;
1143 }
1144
1145 unsigned SystemZInstrInfo::getLoadAndTest(unsigned Opcode) const {
1146   switch (Opcode) {
1147   case SystemZ::L:    return SystemZ::LT;
1148   case SystemZ::LY:   return SystemZ::LT;
1149   case SystemZ::LG:   return SystemZ::LTG;
1150   case SystemZ::LGF:  return SystemZ::LTGF;
1151   case SystemZ::LR:   return SystemZ::LTR;
1152   case SystemZ::LGFR: return SystemZ::LTGFR;
1153   case SystemZ::LGR:  return SystemZ::LTGR;
1154   case SystemZ::LER:  return SystemZ::LTEBR;
1155   case SystemZ::LDR:  return SystemZ::LTDBR;
1156   case SystemZ::LXR:  return SystemZ::LTXBR;
1157   default:            return 0;
1158   }
1159 }
1160
1161 // Return true if Mask matches the regexp 0*1+0*, given that zero masks
1162 // have already been filtered out.  Store the first set bit in LSB and
1163 // the number of set bits in Length if so.
1164 static bool isStringOfOnes(uint64_t Mask, unsigned &LSB, unsigned &Length) {
1165   unsigned First = findFirstSet(Mask);
1166   uint64_t Top = (Mask >> First) + 1;
1167   if ((Top & -Top) == Top) {
1168     LSB = First;
1169     Length = findFirstSet(Top);
1170     return true;
1171   }
1172   return false;
1173 }
1174
1175 bool SystemZInstrInfo::isRxSBGMask(uint64_t Mask, unsigned BitSize,
1176                                    unsigned &Start, unsigned &End) const {
1177   // Reject trivial all-zero masks.
1178   if (Mask == 0)
1179     return false;
1180
1181   // Handle the 1+0+ or 0+1+0* cases.  Start then specifies the index of
1182   // the msb and End specifies the index of the lsb.
1183   unsigned LSB, Length;
1184   if (isStringOfOnes(Mask, LSB, Length)) {
1185     Start = 63 - (LSB + Length - 1);
1186     End = 63 - LSB;
1187     return true;
1188   }
1189
1190   // Handle the wrap-around 1+0+1+ cases.  Start then specifies the msb
1191   // of the low 1s and End specifies the lsb of the high 1s.
1192   if (isStringOfOnes(Mask ^ allOnes(BitSize), LSB, Length)) {
1193     assert(LSB > 0 && "Bottom bit must be set");
1194     assert(LSB + Length < BitSize && "Top bit must be set");
1195     Start = 63 - (LSB - 1);
1196     End = 63 - (LSB + Length);
1197     return true;
1198   }
1199
1200   return false;
1201 }
1202
1203 unsigned SystemZInstrInfo::getCompareAndBranch(unsigned Opcode,
1204                                                const MachineInstr *MI) const {
1205   switch (Opcode) {
1206   case SystemZ::CR:
1207     return SystemZ::CRJ;
1208   case SystemZ::CGR:
1209     return SystemZ::CGRJ;
1210   case SystemZ::CHI:
1211     return MI && isInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CIJ : 0;
1212   case SystemZ::CGHI:
1213     return MI && isInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CGIJ : 0;
1214   case SystemZ::CLR:
1215     return SystemZ::CLRJ;
1216   case SystemZ::CLGR:
1217     return SystemZ::CLGRJ;
1218   case SystemZ::CLFI:
1219     return MI && isUInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CLIJ : 0;
1220   case SystemZ::CLGFI:
1221     return MI && isUInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CLGIJ : 0;
1222   default:
1223     return 0;
1224   }
1225 }
1226
1227 void SystemZInstrInfo::loadImmediate(MachineBasicBlock &MBB,
1228                                      MachineBasicBlock::iterator MBBI,
1229                                      unsigned Reg, uint64_t Value) const {
1230   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1231   unsigned Opcode;
1232   if (isInt<16>(Value))
1233     Opcode = SystemZ::LGHI;
1234   else if (SystemZ::isImmLL(Value))
1235     Opcode = SystemZ::LLILL;
1236   else if (SystemZ::isImmLH(Value)) {
1237     Opcode = SystemZ::LLILH;
1238     Value >>= 16;
1239   } else {
1240     assert(isInt<32>(Value) && "Huge values not handled yet");
1241     Opcode = SystemZ::LGFI;
1242   }
1243   BuildMI(MBB, MBBI, DL, get(Opcode), Reg).addImm(Value);
1244 }