dfb5c0983ccb631c2e1b3735b86b1cf1d6c95940
[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 SystemZInstrInfo::SystemZInstrInfo(SystemZTargetMachine &tm)
32   : SystemZGenInstrInfo(SystemZ::ADJCALLSTACKDOWN, SystemZ::ADJCALLSTACKUP),
33     RI(tm), TM(tm) {
34 }
35
36 // MI is a 128-bit load or store.  Split it into two 64-bit loads or stores,
37 // each having the opcode given by NewOpcode.
38 void SystemZInstrInfo::splitMove(MachineBasicBlock::iterator MI,
39                                  unsigned NewOpcode) const {
40   MachineBasicBlock *MBB = MI->getParent();
41   MachineFunction &MF = *MBB->getParent();
42
43   // Get two load or store instructions.  Use the original instruction for one
44   // of them (arbitarily the second here) and create a clone for the other.
45   MachineInstr *EarlierMI = MF.CloneMachineInstr(MI);
46   MBB->insert(MI, EarlierMI);
47
48   // Set up the two 64-bit registers.
49   MachineOperand &HighRegOp = EarlierMI->getOperand(0);
50   MachineOperand &LowRegOp = MI->getOperand(0);
51   HighRegOp.setReg(RI.getSubReg(HighRegOp.getReg(), SystemZ::subreg_high));
52   LowRegOp.setReg(RI.getSubReg(LowRegOp.getReg(), SystemZ::subreg_low));
53
54   // The address in the first (high) instruction is already correct.
55   // Adjust the offset in the second (low) instruction.
56   MachineOperand &HighOffsetOp = EarlierMI->getOperand(2);
57   MachineOperand &LowOffsetOp = MI->getOperand(2);
58   LowOffsetOp.setImm(LowOffsetOp.getImm() + 8);
59
60   // Set the opcodes.
61   unsigned HighOpcode = getOpcodeForOffset(NewOpcode, HighOffsetOp.getImm());
62   unsigned LowOpcode = getOpcodeForOffset(NewOpcode, LowOffsetOp.getImm());
63   assert(HighOpcode && LowOpcode && "Both offsets should be in range");
64
65   EarlierMI->setDesc(get(HighOpcode));
66   MI->setDesc(get(LowOpcode));
67 }
68
69 // Split ADJDYNALLOC instruction MI.
70 void SystemZInstrInfo::splitAdjDynAlloc(MachineBasicBlock::iterator MI) const {
71   MachineBasicBlock *MBB = MI->getParent();
72   MachineFunction &MF = *MBB->getParent();
73   MachineFrameInfo *MFFrame = MF.getFrameInfo();
74   MachineOperand &OffsetMO = MI->getOperand(2);
75
76   uint64_t Offset = (MFFrame->getMaxCallFrameSize() +
77                      SystemZMC::CallFrameSize +
78                      OffsetMO.getImm());
79   unsigned NewOpcode = getOpcodeForOffset(SystemZ::LA, Offset);
80   assert(NewOpcode && "No support for huge argument lists yet");
81   MI->setDesc(get(NewOpcode));
82   OffsetMO.setImm(Offset);
83 }
84
85 // If MI is a simple load or store for a frame object, return the register
86 // it loads or stores and set FrameIndex to the index of the frame object.
87 // Return 0 otherwise.
88 //
89 // Flag is SimpleBDXLoad for loads and SimpleBDXStore for stores.
90 static int isSimpleMove(const MachineInstr *MI, int &FrameIndex,
91                         unsigned Flag) {
92   const MCInstrDesc &MCID = MI->getDesc();
93   if ((MCID.TSFlags & Flag) &&
94       MI->getOperand(1).isFI() &&
95       MI->getOperand(2).getImm() == 0 &&
96       MI->getOperand(3).getReg() == 0) {
97     FrameIndex = MI->getOperand(1).getIndex();
98     return MI->getOperand(0).getReg();
99   }
100   return 0;
101 }
102
103 unsigned SystemZInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
104                                                int &FrameIndex) const {
105   return isSimpleMove(MI, FrameIndex, SystemZII::SimpleBDXLoad);
106 }
107
108 unsigned SystemZInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
109                                               int &FrameIndex) const {
110   return isSimpleMove(MI, FrameIndex, SystemZII::SimpleBDXStore);
111 }
112
113 bool SystemZInstrInfo::isStackSlotCopy(const MachineInstr *MI,
114                                        int &DestFrameIndex,
115                                        int &SrcFrameIndex) const {
116   // Check for MVC 0(Length,FI1),0(FI2)
117   const MachineFrameInfo *MFI = MI->getParent()->getParent()->getFrameInfo();
118   if (MI->getOpcode() != SystemZ::MVC ||
119       !MI->getOperand(0).isFI() ||
120       MI->getOperand(1).getImm() != 0 ||
121       !MI->getOperand(3).isFI() ||
122       MI->getOperand(4).getImm() != 0)
123     return false;
124
125   // Check that Length covers the full slots.
126   int64_t Length = MI->getOperand(2).getImm();
127   unsigned FI1 = MI->getOperand(0).getIndex();
128   unsigned FI2 = MI->getOperand(3).getIndex();
129   if (MFI->getObjectSize(FI1) != Length ||
130       MFI->getObjectSize(FI2) != Length)
131     return false;
132
133   DestFrameIndex = FI1;
134   SrcFrameIndex = FI2;
135   return true;
136 }
137
138 bool SystemZInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
139                                      MachineBasicBlock *&TBB,
140                                      MachineBasicBlock *&FBB,
141                                      SmallVectorImpl<MachineOperand> &Cond,
142                                      bool AllowModify) const {
143   // Most of the code and comments here are boilerplate.
144
145   // Start from the bottom of the block and work up, examining the
146   // terminator instructions.
147   MachineBasicBlock::iterator I = MBB.end();
148   while (I != MBB.begin()) {
149     --I;
150     if (I->isDebugValue())
151       continue;
152
153     // Working from the bottom, when we see a non-terminator instruction, we're
154     // done.
155     if (!isUnpredicatedTerminator(I))
156       break;
157
158     // A terminator that isn't a branch can't easily be handled by this
159     // analysis.
160     if (!I->isBranch())
161       return true;
162
163     // Can't handle indirect branches.
164     SystemZII::Branch Branch(getBranchInfo(I));
165     if (!Branch.Target->isMBB())
166       return true;
167
168     // Punt on compound branches.
169     if (Branch.Type != SystemZII::BranchNormal)
170       return true;
171
172     if (Branch.CCMask == SystemZ::CCMASK_ANY) {
173       // Handle unconditional branches.
174       if (!AllowModify) {
175         TBB = Branch.Target->getMBB();
176         continue;
177       }
178
179       // If the block has any instructions after a JMP, delete them.
180       while (llvm::next(I) != MBB.end())
181         llvm::next(I)->eraseFromParent();
182
183       Cond.clear();
184       FBB = 0;
185
186       // Delete the JMP if it's equivalent to a fall-through.
187       if (MBB.isLayoutSuccessor(Branch.Target->getMBB())) {
188         TBB = 0;
189         I->eraseFromParent();
190         I = MBB.end();
191         continue;
192       }
193
194       // TBB is used to indicate the unconditinal destination.
195       TBB = Branch.Target->getMBB();
196       continue;
197     }
198
199     // Working from the bottom, handle the first conditional branch.
200     if (Cond.empty()) {
201       // FIXME: add X86-style branch swap
202       FBB = TBB;
203       TBB = Branch.Target->getMBB();
204       Cond.push_back(MachineOperand::CreateImm(Branch.CCMask));
205       continue;
206     }
207
208     // Handle subsequent conditional branches.
209     assert(Cond.size() == 1);
210     assert(TBB);
211
212     // Only handle the case where all conditional branches branch to the same
213     // destination.
214     if (TBB != Branch.Target->getMBB())
215       return true;
216
217     // If the conditions are the same, we can leave them alone.
218     unsigned OldCond = Cond[0].getImm();
219     if (OldCond == Branch.CCMask)
220       continue;
221
222     // FIXME: Try combining conditions like X86 does.  Should be easy on Z!
223   }
224
225   return false;
226 }
227
228 unsigned SystemZInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
229   // Most of the code and comments here are boilerplate.
230   MachineBasicBlock::iterator I = MBB.end();
231   unsigned Count = 0;
232
233   while (I != MBB.begin()) {
234     --I;
235     if (I->isDebugValue())
236       continue;
237     if (!I->isBranch())
238       break;
239     if (!getBranchInfo(I).Target->isMBB())
240       break;
241     // Remove the branch.
242     I->eraseFromParent();
243     I = MBB.end();
244     ++Count;
245   }
246
247   return Count;
248 }
249
250 unsigned
251 SystemZInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
252                                MachineBasicBlock *FBB,
253                                const SmallVectorImpl<MachineOperand> &Cond,
254                                DebugLoc DL) const {
255   // In this function we output 32-bit branches, which should always
256   // have enough range.  They can be shortened and relaxed by later code
257   // in the pipeline, if desired.
258
259   // Shouldn't be a fall through.
260   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
261   assert((Cond.size() == 1 || Cond.size() == 0) &&
262          "SystemZ branch conditions have one component!");
263
264   if (Cond.empty()) {
265     // Unconditional branch?
266     assert(!FBB && "Unconditional branch with multiple successors!");
267     BuildMI(&MBB, DL, get(SystemZ::J)).addMBB(TBB);
268     return 1;
269   }
270
271   // Conditional branch.
272   unsigned Count = 0;
273   unsigned CC = Cond[0].getImm();
274   BuildMI(&MBB, DL, get(SystemZ::BRC)).addImm(CC).addMBB(TBB);
275   ++Count;
276
277   if (FBB) {
278     // Two-way Conditional branch. Insert the second branch.
279     BuildMI(&MBB, DL, get(SystemZ::J)).addMBB(FBB);
280     ++Count;
281   }
282   return Count;
283 }
284
285 // If Opcode is a move that has a conditional variant, return that variant,
286 // otherwise return 0.
287 static unsigned getConditionalMove(unsigned Opcode) {
288   switch (Opcode) {
289   case SystemZ::LR:  return SystemZ::LOCR;
290   case SystemZ::LGR: return SystemZ::LOCGR;
291   default:           return 0;
292   }
293 }
294
295 bool SystemZInstrInfo::isPredicable(MachineInstr *MI) const {
296   unsigned Opcode = MI->getOpcode();
297   if (TM.getSubtargetImpl()->hasLoadStoreOnCond() &&
298       getConditionalMove(Opcode))
299     return true;
300   return false;
301 }
302
303 bool SystemZInstrInfo::
304 isProfitableToIfCvt(MachineBasicBlock &MBB,
305                     unsigned NumCycles, unsigned ExtraPredCycles,
306                     const BranchProbability &Probability) const {
307   // For now only convert single instructions.
308   return NumCycles == 1;
309 }
310
311 bool SystemZInstrInfo::
312 isProfitableToIfCvt(MachineBasicBlock &TMBB,
313                     unsigned NumCyclesT, unsigned ExtraPredCyclesT,
314                     MachineBasicBlock &FMBB,
315                     unsigned NumCyclesF, unsigned ExtraPredCyclesF,
316                     const BranchProbability &Probability) const {
317   // For now avoid converting mutually-exclusive cases.
318   return false;
319 }
320
321 bool SystemZInstrInfo::
322 PredicateInstruction(MachineInstr *MI,
323                      const SmallVectorImpl<MachineOperand> &Pred) const {
324   unsigned CCMask = Pred[0].getImm();
325   assert(CCMask > 0 && CCMask < 15 && "Invalid predicate");
326   unsigned Opcode = MI->getOpcode();
327   if (TM.getSubtargetImpl()->hasLoadStoreOnCond()) {
328     if (unsigned CondOpcode = getConditionalMove(Opcode)) {
329       MI->setDesc(get(CondOpcode));
330       MachineInstrBuilder(*MI->getParent()->getParent(), MI).addImm(CCMask);
331       return true;
332     }
333   }
334   return false;
335 }
336
337 void
338 SystemZInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
339                               MachineBasicBlock::iterator MBBI, DebugLoc DL,
340                               unsigned DestReg, unsigned SrcReg,
341                               bool KillSrc) const {
342   // Split 128-bit GPR moves into two 64-bit moves.  This handles ADDR128 too.
343   if (SystemZ::GR128BitRegClass.contains(DestReg, SrcReg)) {
344     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_high),
345                 RI.getSubReg(SrcReg, SystemZ::subreg_high), KillSrc);
346     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_low),
347                 RI.getSubReg(SrcReg, SystemZ::subreg_low), KillSrc);
348     return;
349   }
350
351   // Everything else needs only one instruction.
352   unsigned Opcode;
353   if (SystemZ::GR32BitRegClass.contains(DestReg, SrcReg))
354     Opcode = SystemZ::LR;
355   else if (SystemZ::GR64BitRegClass.contains(DestReg, SrcReg))
356     Opcode = SystemZ::LGR;
357   else if (SystemZ::FP32BitRegClass.contains(DestReg, SrcReg))
358     Opcode = SystemZ::LER;
359   else if (SystemZ::FP64BitRegClass.contains(DestReg, SrcReg))
360     Opcode = SystemZ::LDR;
361   else if (SystemZ::FP128BitRegClass.contains(DestReg, SrcReg))
362     Opcode = SystemZ::LXR;
363   else
364     llvm_unreachable("Impossible reg-to-reg copy");
365
366   BuildMI(MBB, MBBI, DL, get(Opcode), DestReg)
367     .addReg(SrcReg, getKillRegState(KillSrc));
368 }
369
370 void
371 SystemZInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
372                                       MachineBasicBlock::iterator MBBI,
373                                       unsigned SrcReg, bool isKill,
374                                       int FrameIdx,
375                                       const TargetRegisterClass *RC,
376                                       const TargetRegisterInfo *TRI) const {
377   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
378
379   // Callers may expect a single instruction, so keep 128-bit moves
380   // together for now and lower them after register allocation.
381   unsigned LoadOpcode, StoreOpcode;
382   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
383   addFrameReference(BuildMI(MBB, MBBI, DL, get(StoreOpcode))
384                     .addReg(SrcReg, getKillRegState(isKill)), FrameIdx);
385 }
386
387 void
388 SystemZInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
389                                        MachineBasicBlock::iterator MBBI,
390                                        unsigned DestReg, int FrameIdx,
391                                        const TargetRegisterClass *RC,
392                                        const TargetRegisterInfo *TRI) const {
393   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
394
395   // Callers may expect a single instruction, so keep 128-bit moves
396   // together for now and lower them after register allocation.
397   unsigned LoadOpcode, StoreOpcode;
398   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
399   addFrameReference(BuildMI(MBB, MBBI, DL, get(LoadOpcode), DestReg),
400                     FrameIdx);
401 }
402
403 // Return true if MI is a simple load or store with a 12-bit displacement
404 // and no index.  Flag is SimpleBDXLoad for loads and SimpleBDXStore for stores.
405 static bool isSimpleBD12Move(const MachineInstr *MI, unsigned Flag) {
406   const MCInstrDesc &MCID = MI->getDesc();
407   return ((MCID.TSFlags & Flag) &&
408           isUInt<12>(MI->getOperand(2).getImm()) &&
409           MI->getOperand(3).getReg() == 0);
410 }
411
412 namespace {
413   struct LogicOp {
414     LogicOp() : RegSize(0), ImmLSB(0), ImmSize(0) {}
415     LogicOp(unsigned regSize, unsigned immLSB, unsigned immSize)
416       : RegSize(regSize), ImmLSB(immLSB), ImmSize(immSize) {}
417
418     operator bool() const { return RegSize; }
419
420     unsigned RegSize, ImmLSB, ImmSize;
421   };
422 }
423
424 static LogicOp interpretAndImmediate(unsigned Opcode) {
425   switch (Opcode) {
426   case SystemZ::NILL32: return LogicOp(32,  0, 16);
427   case SystemZ::NILH32: return LogicOp(32, 16, 16);
428   case SystemZ::NILL:   return LogicOp(64,  0, 16);
429   case SystemZ::NILH:   return LogicOp(64, 16, 16);
430   case SystemZ::NIHL:   return LogicOp(64, 32, 16);
431   case SystemZ::NIHH:   return LogicOp(64, 48, 16);
432   case SystemZ::NILF32: return LogicOp(32,  0, 32);
433   case SystemZ::NILF:   return LogicOp(64,  0, 32);
434   case SystemZ::NIHF:   return LogicOp(64, 32, 32);
435   default:              return LogicOp();
436   }
437 }
438
439 // Used to return from convertToThreeAddress after replacing two-address
440 // instruction OldMI with three-address instruction NewMI.
441 static MachineInstr *finishConvertToThreeAddress(MachineInstr *OldMI,
442                                                  MachineInstr *NewMI,
443                                                  LiveVariables *LV) {
444   if (LV) {
445     unsigned NumOps = OldMI->getNumOperands();
446     for (unsigned I = 1; I < NumOps; ++I) {
447       MachineOperand &Op = OldMI->getOperand(I);
448       if (Op.isReg() && Op.isKill())
449         LV->replaceKillInstruction(Op.getReg(), OldMI, NewMI);
450     }
451   }
452   return NewMI;
453 }
454
455 MachineInstr *
456 SystemZInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
457                                         MachineBasicBlock::iterator &MBBI,
458                                         LiveVariables *LV) const {
459   MachineInstr *MI = MBBI;
460   MachineBasicBlock *MBB = MI->getParent();
461
462   unsigned Opcode = MI->getOpcode();
463   unsigned NumOps = MI->getNumOperands();
464
465   // Try to convert something like SLL into SLLK, if supported.
466   // We prefer to keep the two-operand form where possible both
467   // because it tends to be shorter and because some instructions
468   // have memory forms that can be used during spilling.
469   if (TM.getSubtargetImpl()->hasDistinctOps()) {
470     int ThreeOperandOpcode = SystemZ::getThreeOperandOpcode(Opcode);
471     if (ThreeOperandOpcode >= 0) {
472       MachineOperand &Dest = MI->getOperand(0);
473       MachineOperand &Src = MI->getOperand(1);
474       MachineInstrBuilder MIB =
475         BuildMI(*MBB, MBBI, MI->getDebugLoc(), get(ThreeOperandOpcode))
476         .addOperand(Dest);
477       // Keep the kill state, but drop the tied flag.
478       MIB.addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg());
479       // Keep the remaining operands as-is.
480       for (unsigned I = 2; I < NumOps; ++I)
481         MIB.addOperand(MI->getOperand(I));
482       return finishConvertToThreeAddress(MI, MIB, LV);
483     }
484   }
485
486   // Try to convert an AND into an RISBG-type instruction.
487   if (LogicOp And = interpretAndImmediate(Opcode)) {
488     unsigned NewOpcode;
489     if (And.RegSize == 64)
490       NewOpcode = SystemZ::RISBG;
491     else if (TM.getSubtargetImpl()->hasHighWord())
492       NewOpcode = SystemZ::RISBLG32;
493     else
494       // We can't use RISBG for 32-bit operations because it clobbers the
495       // high word of the destination too.
496       NewOpcode = 0;
497     if (NewOpcode) {
498       uint64_t Imm = MI->getOperand(2).getImm() << And.ImmLSB;
499       // AND IMMEDIATE leaves the other bits of the register unchanged.
500       Imm |= allOnes(And.RegSize) & ~(allOnes(And.ImmSize) << And.ImmLSB);
501       unsigned Start, End;
502       if (isRxSBGMask(Imm, And.RegSize, Start, End)) {
503         if (NewOpcode == SystemZ::RISBLG32) {
504           Start &= 31;
505           End &= 31;
506         }
507         MachineOperand &Dest = MI->getOperand(0);
508         MachineOperand &Src = MI->getOperand(1);
509         MachineInstrBuilder MIB =
510           BuildMI(*MBB, MI, MI->getDebugLoc(), get(NewOpcode))
511           .addOperand(Dest).addReg(0)
512           .addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg())
513           .addImm(Start).addImm(End + 128).addImm(0);
514         return finishConvertToThreeAddress(MI, MIB, LV);
515       }
516     }
517   }
518   return 0;
519 }
520
521 MachineInstr *
522 SystemZInstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
523                                         MachineInstr *MI,
524                                         const SmallVectorImpl<unsigned> &Ops,
525                                         int FrameIndex) const {
526   const MachineFrameInfo *MFI = MF.getFrameInfo();
527   unsigned Size = MFI->getObjectSize(FrameIndex);
528
529   // Eary exit for cases we don't care about
530   if (Ops.size() != 1)
531     return 0;
532
533   unsigned OpNum = Ops[0];
534   assert(Size == MF.getRegInfo()
535          .getRegClass(MI->getOperand(OpNum).getReg())->getSize() &&
536          "Invalid size combination");
537
538   unsigned Opcode = MI->getOpcode();
539   if (Opcode == SystemZ::LGDR || Opcode == SystemZ::LDGR) {
540     bool Op0IsGPR = (Opcode == SystemZ::LGDR);
541     bool Op1IsGPR = (Opcode == SystemZ::LDGR);
542     // If we're spilling the destination of an LDGR or LGDR, store the
543     // source register instead.
544     if (OpNum == 0) {
545       unsigned StoreOpcode = Op1IsGPR ? SystemZ::STG : SystemZ::STD;
546       return BuildMI(MF, MI->getDebugLoc(), get(StoreOpcode))
547         .addOperand(MI->getOperand(1)).addFrameIndex(FrameIndex)
548         .addImm(0).addReg(0);
549     }
550     // If we're spilling the source of an LDGR or LGDR, load the
551     // destination register instead.
552     if (OpNum == 1) {
553       unsigned LoadOpcode = Op0IsGPR ? SystemZ::LG : SystemZ::LD;
554       unsigned Dest = MI->getOperand(0).getReg();
555       return BuildMI(MF, MI->getDebugLoc(), get(LoadOpcode), Dest)
556         .addFrameIndex(FrameIndex).addImm(0).addReg(0);
557     }
558   }
559
560   // Look for cases where the source of a simple store or the destination
561   // of a simple load is being spilled.  Try to use MVC instead.
562   //
563   // Although MVC is in practice a fast choice in these cases, it is still
564   // logically a bytewise copy.  This means that we cannot use it if the
565   // load or store is volatile.  It also means that the transformation is
566   // not valid in cases where the two memories partially overlap; however,
567   // that is not a problem here, because we know that one of the memories
568   // is a full frame index.
569   if (OpNum == 0 && MI->hasOneMemOperand()) {
570     MachineMemOperand *MMO = *MI->memoperands_begin();
571     if (MMO->getSize() == Size && !MMO->isVolatile()) {
572       // Handle conversion of loads.
573       if (isSimpleBD12Move(MI, SystemZII::SimpleBDXLoad)) {
574         return BuildMI(MF, MI->getDebugLoc(), get(SystemZ::MVC))
575           .addFrameIndex(FrameIndex).addImm(0).addImm(Size)
576           .addOperand(MI->getOperand(1)).addImm(MI->getOperand(2).getImm())
577           .addMemOperand(MMO);
578       }
579       // Handle conversion of stores.
580       if (isSimpleBD12Move(MI, SystemZII::SimpleBDXStore)) {
581         return BuildMI(MF, MI->getDebugLoc(), get(SystemZ::MVC))
582           .addOperand(MI->getOperand(1)).addImm(MI->getOperand(2).getImm())
583           .addImm(Size).addFrameIndex(FrameIndex).addImm(0)
584           .addMemOperand(MMO);
585       }
586     }
587   }
588
589   // If the spilled operand is the final one, try to change <INSN>R
590   // into <INSN>.
591   int MemOpcode = SystemZ::getMemOpcode(Opcode);
592   if (MemOpcode >= 0) {
593     unsigned NumOps = MI->getNumExplicitOperands();
594     if (OpNum == NumOps - 1) {
595       const MCInstrDesc &MemDesc = get(MemOpcode);
596       uint64_t AccessBytes = SystemZII::getAccessSize(MemDesc.TSFlags);
597       assert(AccessBytes != 0 && "Size of access should be known");
598       assert(AccessBytes <= Size && "Access outside the frame index");
599       uint64_t Offset = Size - AccessBytes;
600       MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), get(MemOpcode));
601       for (unsigned I = 0; I < OpNum; ++I)
602         MIB.addOperand(MI->getOperand(I));
603       MIB.addFrameIndex(FrameIndex).addImm(Offset);
604       if (MemDesc.TSFlags & SystemZII::HasIndex)
605         MIB.addReg(0);
606       return MIB;
607     }
608   }
609
610   return 0;
611 }
612
613 MachineInstr *
614 SystemZInstrInfo::foldMemoryOperandImpl(MachineFunction &MF, MachineInstr* MI,
615                                         const SmallVectorImpl<unsigned> &Ops,
616                                         MachineInstr* LoadMI) const {
617   return 0;
618 }
619
620 bool
621 SystemZInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
622   switch (MI->getOpcode()) {
623   case SystemZ::L128:
624     splitMove(MI, SystemZ::LG);
625     return true;
626
627   case SystemZ::ST128:
628     splitMove(MI, SystemZ::STG);
629     return true;
630
631   case SystemZ::LX:
632     splitMove(MI, SystemZ::LD);
633     return true;
634
635   case SystemZ::STX:
636     splitMove(MI, SystemZ::STD);
637     return true;
638
639   case SystemZ::ADJDYNALLOC:
640     splitAdjDynAlloc(MI);
641     return true;
642
643   default:
644     return false;
645   }
646 }
647
648 bool SystemZInstrInfo::
649 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
650   assert(Cond.size() == 1 && "Invalid branch condition!");
651   Cond[0].setImm(Cond[0].getImm() ^ SystemZ::CCMASK_ANY);
652   return false;
653 }
654
655 uint64_t SystemZInstrInfo::getInstSizeInBytes(const MachineInstr *MI) const {
656   if (MI->getOpcode() == TargetOpcode::INLINEASM) {
657     const MachineFunction *MF = MI->getParent()->getParent();
658     const char *AsmStr = MI->getOperand(0).getSymbolName();
659     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
660   }
661   return MI->getDesc().getSize();
662 }
663
664 SystemZII::Branch
665 SystemZInstrInfo::getBranchInfo(const MachineInstr *MI) const {
666   switch (MI->getOpcode()) {
667   case SystemZ::BR:
668   case SystemZ::J:
669   case SystemZ::JG:
670     return SystemZII::Branch(SystemZII::BranchNormal, SystemZ::CCMASK_ANY,
671                              &MI->getOperand(0));
672
673   case SystemZ::BRC:
674   case SystemZ::BRCL:
675     return SystemZII::Branch(SystemZII::BranchNormal,
676                              MI->getOperand(0).getImm(), &MI->getOperand(1));
677
678   case SystemZ::CIJ:
679   case SystemZ::CRJ:
680     return SystemZII::Branch(SystemZII::BranchC, MI->getOperand(2).getImm(),
681                              &MI->getOperand(3));
682
683   case SystemZ::CGIJ:
684   case SystemZ::CGRJ:
685     return SystemZII::Branch(SystemZII::BranchCG, MI->getOperand(2).getImm(),
686                              &MI->getOperand(3));
687
688   default:
689     llvm_unreachable("Unrecognized branch opcode");
690   }
691 }
692
693 void SystemZInstrInfo::getLoadStoreOpcodes(const TargetRegisterClass *RC,
694                                            unsigned &LoadOpcode,
695                                            unsigned &StoreOpcode) const {
696   if (RC == &SystemZ::GR32BitRegClass || RC == &SystemZ::ADDR32BitRegClass) {
697     LoadOpcode = SystemZ::L;
698     StoreOpcode = SystemZ::ST32;
699   } else if (RC == &SystemZ::GR64BitRegClass ||
700              RC == &SystemZ::ADDR64BitRegClass) {
701     LoadOpcode = SystemZ::LG;
702     StoreOpcode = SystemZ::STG;
703   } else if (RC == &SystemZ::GR128BitRegClass ||
704              RC == &SystemZ::ADDR128BitRegClass) {
705     LoadOpcode = SystemZ::L128;
706     StoreOpcode = SystemZ::ST128;
707   } else if (RC == &SystemZ::FP32BitRegClass) {
708     LoadOpcode = SystemZ::LE;
709     StoreOpcode = SystemZ::STE;
710   } else if (RC == &SystemZ::FP64BitRegClass) {
711     LoadOpcode = SystemZ::LD;
712     StoreOpcode = SystemZ::STD;
713   } else if (RC == &SystemZ::FP128BitRegClass) {
714     LoadOpcode = SystemZ::LX;
715     StoreOpcode = SystemZ::STX;
716   } else
717     llvm_unreachable("Unsupported regclass to load or store");
718 }
719
720 unsigned SystemZInstrInfo::getOpcodeForOffset(unsigned Opcode,
721                                               int64_t Offset) const {
722   const MCInstrDesc &MCID = get(Opcode);
723   int64_t Offset2 = (MCID.TSFlags & SystemZII::Is128Bit ? Offset + 8 : Offset);
724   if (isUInt<12>(Offset) && isUInt<12>(Offset2)) {
725     // Get the instruction to use for unsigned 12-bit displacements.
726     int Disp12Opcode = SystemZ::getDisp12Opcode(Opcode);
727     if (Disp12Opcode >= 0)
728       return Disp12Opcode;
729
730     // All address-related instructions can use unsigned 12-bit
731     // displacements.
732     return Opcode;
733   }
734   if (isInt<20>(Offset) && isInt<20>(Offset2)) {
735     // Get the instruction to use for signed 20-bit displacements.
736     int Disp20Opcode = SystemZ::getDisp20Opcode(Opcode);
737     if (Disp20Opcode >= 0)
738       return Disp20Opcode;
739
740     // Check whether Opcode allows signed 20-bit displacements.
741     if (MCID.TSFlags & SystemZII::Has20BitOffset)
742       return Opcode;
743   }
744   return 0;
745 }
746
747 // Return true if Mask matches the regexp 0*1+0*, given that zero masks
748 // have already been filtered out.  Store the first set bit in LSB and
749 // the number of set bits in Length if so.
750 static bool isStringOfOnes(uint64_t Mask, unsigned &LSB, unsigned &Length) {
751   unsigned First = findFirstSet(Mask);
752   uint64_t Top = (Mask >> First) + 1;
753   if ((Top & -Top) == Top) {
754     LSB = First;
755     Length = findFirstSet(Top);
756     return true;
757   }
758   return false;
759 }
760
761 bool SystemZInstrInfo::isRxSBGMask(uint64_t Mask, unsigned BitSize,
762                                    unsigned &Start, unsigned &End) const {
763   // Reject trivial all-zero masks.
764   if (Mask == 0)
765     return false;
766
767   // Handle the 1+0+ or 0+1+0* cases.  Start then specifies the index of
768   // the msb and End specifies the index of the lsb.
769   unsigned LSB, Length;
770   if (isStringOfOnes(Mask, LSB, Length)) {
771     Start = 63 - (LSB + Length - 1);
772     End = 63 - LSB;
773     return true;
774   }
775
776   // Handle the wrap-around 1+0+1+ cases.  Start then specifies the msb
777   // of the low 1s and End specifies the lsb of the high 1s.
778   if (isStringOfOnes(Mask ^ allOnes(BitSize), LSB, Length)) {
779     assert(LSB > 0 && "Bottom bit must be set");
780     assert(LSB + Length < BitSize && "Top bit must be set");
781     Start = 63 - (LSB - 1);
782     End = 63 - (LSB + Length);
783     return true;
784   }
785
786   return false;
787 }
788
789 unsigned SystemZInstrInfo::getCompareAndBranch(unsigned Opcode,
790                                                const MachineInstr *MI) const {
791   switch (Opcode) {
792   case SystemZ::CR:
793     return SystemZ::CRJ;
794   case SystemZ::CGR:
795     return SystemZ::CGRJ;
796   case SystemZ::CHI:
797     return MI && isInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CIJ : 0;
798   case SystemZ::CGHI:
799     return MI && isInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CGIJ : 0;
800   default:
801     return 0;
802   }
803 }
804
805 void SystemZInstrInfo::loadImmediate(MachineBasicBlock &MBB,
806                                      MachineBasicBlock::iterator MBBI,
807                                      unsigned Reg, uint64_t Value) const {
808   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
809   unsigned Opcode;
810   if (isInt<16>(Value))
811     Opcode = SystemZ::LGHI;
812   else if (SystemZ::isImmLL(Value))
813     Opcode = SystemZ::LLILL;
814   else if (SystemZ::isImmLH(Value)) {
815     Opcode = SystemZ::LLILH;
816     Value >>= 16;
817   } else {
818     assert(isInt<32>(Value) && "Huge values not handled yet");
819     Opcode = SystemZ::LGFI;
820   }
821   BuildMI(MBB, MBBI, DL, get(Opcode), Reg).addImm(Value);
822 }