[SystemZ] Postpone NI->RISBG conversion to convertToThreeAddress()
[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 bool SystemZInstrInfo::analyzeCompare(const MachineInstr *MI,
286                                       unsigned &SrcReg, unsigned &SrcReg2,
287                                       int &Mask, int &Value) const {
288   assert(MI->isCompare() && "Caller should check that this is a compare");
289
290   // Ignore comparisons involving memory for now.
291   if (MI->getNumExplicitOperands() != 2)
292     return false;
293
294   SrcReg = MI->getOperand(0).getReg();
295   if (MI->getOperand(1).isReg()) {
296     SrcReg2 = MI->getOperand(1).getReg();
297     Value = 0;
298     Mask = ~0;
299     return true;
300   } else if (MI->getOperand(1).isImm()) {
301     SrcReg2 = 0;
302     Value = MI->getOperand(1).getImm();
303     Mask = ~0;
304     return true;
305   }
306   return false;
307 }
308
309 // Return true if CC is live after MBBI.  We can't rely on kill information
310 // because of the way InsertBranch is used.
311 static bool isCCLiveAfter(MachineBasicBlock::iterator MBBI,
312                           const TargetRegisterInfo *TRI) {
313   if (MBBI->killsRegister(SystemZ::CC, TRI))
314     return false;
315
316   MachineBasicBlock *MBB = MBBI->getParent();
317   MachineBasicBlock::iterator MBBE = MBB->end();
318   for (++MBBI; MBBI != MBBE; ++MBBI)
319     if (MBBI->readsRegister(SystemZ::CC, TRI))
320       return true;
321
322   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
323          SE = MBB->succ_end(); SI != SE; ++SI)
324     if ((*SI)->isLiveIn(SystemZ::CC))
325       return true;
326
327   return false;
328 }
329
330 bool
331 SystemZInstrInfo::optimizeCompareInstr(MachineInstr *Compare,
332                                        unsigned SrcReg, unsigned SrcReg2,
333                                        int Mask, int Value,
334                                        const MachineRegisterInfo *MRI) const {
335   MachineBasicBlock *MBB = Compare->getParent();
336   const TargetRegisterInfo *TRI = &getRegisterInfo();
337
338   // Try to fold a comparison into a following branch, if it is only used once.
339   if (unsigned FusedOpcode = getCompareAndBranch(Compare->getOpcode(),
340                                                  Compare)) {
341     MachineBasicBlock::iterator MBBI = Compare, MBBE = MBB->end();
342     for (++MBBI; MBBI != MBBE; ++MBBI) {
343       if (MBBI->getOpcode() == SystemZ::BRC && !isCCLiveAfter(MBBI, TRI)) {
344         // Read the branch mask and target.
345         MachineOperand CCMask(MBBI->getOperand(0));
346         MachineOperand Target(MBBI->getOperand(1));
347
348         // Clear out all current operands.
349         int CCUse = MBBI->findRegisterUseOperandIdx(SystemZ::CC, false, TRI);
350         assert(CCUse >= 0 && "BRC must use CC");
351         MBBI->RemoveOperand(CCUse);
352         MBBI->RemoveOperand(1);
353         MBBI->RemoveOperand(0);
354
355         // Rebuild MBBI as a fused compare and branch.
356         MBBI->setDesc(get(FusedOpcode));
357         MachineInstrBuilder(*MBB->getParent(), MBBI)
358           .addOperand(Compare->getOperand(0))
359           .addOperand(Compare->getOperand(1))
360           .addOperand(CCMask)
361           .addOperand(Target);
362
363         // Clear any intervening kills of SrcReg and SrcReg2.
364         MBBI = Compare;
365         for (++MBBI; MBBI != MBBE; ++MBBI) {
366           MBBI->clearRegisterKills(SrcReg, TRI);
367           if (SrcReg2)
368             MBBI->clearRegisterKills(SrcReg2, TRI);
369         }
370         Compare->removeFromParent();
371         return true;
372       }
373
374       // Stop if we find another reference to CC before a branch.
375       if (MBBI->readsRegister(SystemZ::CC, TRI) ||
376           MBBI->modifiesRegister(SystemZ::CC, TRI))
377         break;
378
379       // Stop if we find another assignment to the registers before the branch.
380       if (MBBI->modifiesRegister(SrcReg, TRI) ||
381           (SrcReg2 && MBBI->modifiesRegister(SrcReg2, TRI)))
382         break;
383     }
384   }
385   return false;
386 }
387
388 // If Opcode is a move that has a conditional variant, return that variant,
389 // otherwise return 0.
390 static unsigned getConditionalMove(unsigned Opcode) {
391   switch (Opcode) {
392   case SystemZ::LR:  return SystemZ::LOCR;
393   case SystemZ::LGR: return SystemZ::LOCGR;
394   default:           return 0;
395   }
396 }
397
398 bool SystemZInstrInfo::isPredicable(MachineInstr *MI) const {
399   unsigned Opcode = MI->getOpcode();
400   if (TM.getSubtargetImpl()->hasLoadStoreOnCond() &&
401       getConditionalMove(Opcode))
402     return true;
403   return false;
404 }
405
406 bool SystemZInstrInfo::
407 isProfitableToIfCvt(MachineBasicBlock &MBB,
408                     unsigned NumCycles, unsigned ExtraPredCycles,
409                     const BranchProbability &Probability) const {
410   // For now only convert single instructions.
411   return NumCycles == 1;
412 }
413
414 bool SystemZInstrInfo::
415 isProfitableToIfCvt(MachineBasicBlock &TMBB,
416                     unsigned NumCyclesT, unsigned ExtraPredCyclesT,
417                     MachineBasicBlock &FMBB,
418                     unsigned NumCyclesF, unsigned ExtraPredCyclesF,
419                     const BranchProbability &Probability) const {
420   // For now avoid converting mutually-exclusive cases.
421   return false;
422 }
423
424 bool SystemZInstrInfo::
425 PredicateInstruction(MachineInstr *MI,
426                      const SmallVectorImpl<MachineOperand> &Pred) const {
427   unsigned CCMask = Pred[0].getImm();
428   assert(CCMask > 0 && CCMask < 15 && "Invalid predicate");
429   unsigned Opcode = MI->getOpcode();
430   if (TM.getSubtargetImpl()->hasLoadStoreOnCond()) {
431     if (unsigned CondOpcode = getConditionalMove(Opcode)) {
432       MI->setDesc(get(CondOpcode));
433       MachineInstrBuilder(*MI->getParent()->getParent(), MI).addImm(CCMask);
434       return true;
435     }
436   }
437   return false;
438 }
439
440 void
441 SystemZInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
442                               MachineBasicBlock::iterator MBBI, DebugLoc DL,
443                               unsigned DestReg, unsigned SrcReg,
444                               bool KillSrc) const {
445   // Split 128-bit GPR moves into two 64-bit moves.  This handles ADDR128 too.
446   if (SystemZ::GR128BitRegClass.contains(DestReg, SrcReg)) {
447     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_high),
448                 RI.getSubReg(SrcReg, SystemZ::subreg_high), KillSrc);
449     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_low),
450                 RI.getSubReg(SrcReg, SystemZ::subreg_low), KillSrc);
451     return;
452   }
453
454   // Everything else needs only one instruction.
455   unsigned Opcode;
456   if (SystemZ::GR32BitRegClass.contains(DestReg, SrcReg))
457     Opcode = SystemZ::LR;
458   else if (SystemZ::GR64BitRegClass.contains(DestReg, SrcReg))
459     Opcode = SystemZ::LGR;
460   else if (SystemZ::FP32BitRegClass.contains(DestReg, SrcReg))
461     Opcode = SystemZ::LER;
462   else if (SystemZ::FP64BitRegClass.contains(DestReg, SrcReg))
463     Opcode = SystemZ::LDR;
464   else if (SystemZ::FP128BitRegClass.contains(DestReg, SrcReg))
465     Opcode = SystemZ::LXR;
466   else
467     llvm_unreachable("Impossible reg-to-reg copy");
468
469   BuildMI(MBB, MBBI, DL, get(Opcode), DestReg)
470     .addReg(SrcReg, getKillRegState(KillSrc));
471 }
472
473 void
474 SystemZInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
475                                       MachineBasicBlock::iterator MBBI,
476                                       unsigned SrcReg, bool isKill,
477                                       int FrameIdx,
478                                       const TargetRegisterClass *RC,
479                                       const TargetRegisterInfo *TRI) const {
480   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
481
482   // Callers may expect a single instruction, so keep 128-bit moves
483   // together for now and lower them after register allocation.
484   unsigned LoadOpcode, StoreOpcode;
485   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
486   addFrameReference(BuildMI(MBB, MBBI, DL, get(StoreOpcode))
487                     .addReg(SrcReg, getKillRegState(isKill)), FrameIdx);
488 }
489
490 void
491 SystemZInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
492                                        MachineBasicBlock::iterator MBBI,
493                                        unsigned DestReg, int FrameIdx,
494                                        const TargetRegisterClass *RC,
495                                        const TargetRegisterInfo *TRI) const {
496   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
497
498   // Callers may expect a single instruction, so keep 128-bit moves
499   // together for now and lower them after register allocation.
500   unsigned LoadOpcode, StoreOpcode;
501   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
502   addFrameReference(BuildMI(MBB, MBBI, DL, get(LoadOpcode), DestReg),
503                     FrameIdx);
504 }
505
506 // Return true if MI is a simple load or store with a 12-bit displacement
507 // and no index.  Flag is SimpleBDXLoad for loads and SimpleBDXStore for stores.
508 static bool isSimpleBD12Move(const MachineInstr *MI, unsigned Flag) {
509   const MCInstrDesc &MCID = MI->getDesc();
510   return ((MCID.TSFlags & Flag) &&
511           isUInt<12>(MI->getOperand(2).getImm()) &&
512           MI->getOperand(3).getReg() == 0);
513 }
514
515 namespace {
516   struct LogicOp {
517     LogicOp() : RegSize(0), ImmLSB(0), ImmSize(0) {}
518     LogicOp(unsigned regSize, unsigned immLSB, unsigned immSize)
519       : RegSize(regSize), ImmLSB(immLSB), ImmSize(immSize) {}
520
521     operator bool() const { return RegSize; }
522
523     unsigned RegSize, ImmLSB, ImmSize;
524   };
525 }
526
527 static LogicOp interpretAndImmediate(unsigned Opcode) {
528   switch (Opcode) {
529   case SystemZ::NILL32: return LogicOp(32,  0, 16);
530   case SystemZ::NILH32: return LogicOp(32, 16, 16);
531   case SystemZ::NILL:   return LogicOp(64,  0, 16);
532   case SystemZ::NILH:   return LogicOp(64, 16, 16);
533   case SystemZ::NIHL:   return LogicOp(64, 32, 16);
534   case SystemZ::NIHH:   return LogicOp(64, 48, 16);
535   case SystemZ::NILF32: return LogicOp(32,  0, 32);
536   case SystemZ::NILF:   return LogicOp(64,  0, 32);
537   case SystemZ::NIHF:   return LogicOp(64, 32, 32);
538   default:              return LogicOp();
539   }
540 }
541
542 // Used to return from convertToThreeAddress after replacing two-address
543 // instruction OldMI with three-address instruction NewMI.
544 static MachineInstr *finishConvertToThreeAddress(MachineInstr *OldMI,
545                                                  MachineInstr *NewMI,
546                                                  LiveVariables *LV) {
547   if (LV) {
548     unsigned NumOps = OldMI->getNumOperands();
549     for (unsigned I = 1; I < NumOps; ++I) {
550       MachineOperand &Op = OldMI->getOperand(I);
551       if (Op.isReg() && Op.isKill())
552         LV->replaceKillInstruction(Op.getReg(), OldMI, NewMI);
553     }
554   }
555   return NewMI;
556 }
557
558 MachineInstr *
559 SystemZInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
560                                         MachineBasicBlock::iterator &MBBI,
561                                         LiveVariables *LV) const {
562   MachineInstr *MI = MBBI;
563   MachineBasicBlock *MBB = MI->getParent();
564
565   unsigned Opcode = MI->getOpcode();
566   unsigned NumOps = MI->getNumOperands();
567
568   // Try to convert something like SLL into SLLK, if supported.
569   // We prefer to keep the two-operand form where possible both
570   // because it tends to be shorter and because some instructions
571   // have memory forms that can be used during spilling.
572   if (TM.getSubtargetImpl()->hasDistinctOps()) {
573     int ThreeOperandOpcode = SystemZ::getThreeOperandOpcode(Opcode);
574     if (ThreeOperandOpcode >= 0) {
575       MachineOperand &Dest = MI->getOperand(0);
576       MachineOperand &Src = MI->getOperand(1);
577       MachineInstrBuilder MIB =
578         BuildMI(*MBB, MBBI, MI->getDebugLoc(), get(ThreeOperandOpcode))
579         .addOperand(Dest);
580       // Keep the kill state, but drop the tied flag.
581       MIB.addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg());
582       // Keep the remaining operands as-is.
583       for (unsigned I = 2; I < NumOps; ++I)
584         MIB.addOperand(MI->getOperand(I));
585       return finishConvertToThreeAddress(MI, MIB, LV);
586     }
587   }
588
589   // Try to convert an AND into an RISBG-type instruction.
590   if (LogicOp And = interpretAndImmediate(Opcode)) {
591     unsigned NewOpcode;
592     if (And.RegSize == 64)
593       NewOpcode = SystemZ::RISBG;
594     else if (TM.getSubtargetImpl()->hasHighWord())
595       NewOpcode = SystemZ::RISBLG32;
596     else
597       // We can't use RISBG for 32-bit operations because it clobbers the
598       // high word of the destination too.
599       NewOpcode = 0;
600     if (NewOpcode) {
601       uint64_t Imm = MI->getOperand(2).getImm() << And.ImmLSB;
602       // AND IMMEDIATE leaves the other bits of the register unchanged.
603       Imm |= allOnes(And.RegSize) & ~(allOnes(And.ImmSize) << And.ImmLSB);
604       unsigned Start, End;
605       if (isRxSBGMask(Imm, And.RegSize, Start, End)) {
606         if (NewOpcode == SystemZ::RISBLG32) {
607           Start &= 31;
608           End &= 31;
609         }
610         MachineOperand &Dest = MI->getOperand(0);
611         MachineOperand &Src = MI->getOperand(1);
612         MachineInstrBuilder MIB =
613           BuildMI(*MBB, MI, MI->getDebugLoc(), get(NewOpcode))
614           .addOperand(Dest).addReg(0)
615           .addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg())
616           .addImm(Start).addImm(End + 128).addImm(0);
617         return finishConvertToThreeAddress(MI, MIB, LV);
618       }
619     }
620   }
621   return 0;
622 }
623
624 MachineInstr *
625 SystemZInstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
626                                         MachineInstr *MI,
627                                         const SmallVectorImpl<unsigned> &Ops,
628                                         int FrameIndex) const {
629   const MachineFrameInfo *MFI = MF.getFrameInfo();
630   unsigned Size = MFI->getObjectSize(FrameIndex);
631
632   // Eary exit for cases we don't care about
633   if (Ops.size() != 1)
634     return 0;
635
636   unsigned OpNum = Ops[0];
637   assert(Size == MF.getRegInfo()
638          .getRegClass(MI->getOperand(OpNum).getReg())->getSize() &&
639          "Invalid size combination");
640
641   unsigned Opcode = MI->getOpcode();
642   if (Opcode == SystemZ::LGDR || Opcode == SystemZ::LDGR) {
643     bool Op0IsGPR = (Opcode == SystemZ::LGDR);
644     bool Op1IsGPR = (Opcode == SystemZ::LDGR);
645     // If we're spilling the destination of an LDGR or LGDR, store the
646     // source register instead.
647     if (OpNum == 0) {
648       unsigned StoreOpcode = Op1IsGPR ? SystemZ::STG : SystemZ::STD;
649       return BuildMI(MF, MI->getDebugLoc(), get(StoreOpcode))
650         .addOperand(MI->getOperand(1)).addFrameIndex(FrameIndex)
651         .addImm(0).addReg(0);
652     }
653     // If we're spilling the source of an LDGR or LGDR, load the
654     // destination register instead.
655     if (OpNum == 1) {
656       unsigned LoadOpcode = Op0IsGPR ? SystemZ::LG : SystemZ::LD;
657       unsigned Dest = MI->getOperand(0).getReg();
658       return BuildMI(MF, MI->getDebugLoc(), get(LoadOpcode), Dest)
659         .addFrameIndex(FrameIndex).addImm(0).addReg(0);
660     }
661   }
662
663   // Look for cases where the source of a simple store or the destination
664   // of a simple load is being spilled.  Try to use MVC instead.
665   //
666   // Although MVC is in practice a fast choice in these cases, it is still
667   // logically a bytewise copy.  This means that we cannot use it if the
668   // load or store is volatile.  It also means that the transformation is
669   // not valid in cases where the two memories partially overlap; however,
670   // that is not a problem here, because we know that one of the memories
671   // is a full frame index.
672   if (OpNum == 0 && MI->hasOneMemOperand()) {
673     MachineMemOperand *MMO = *MI->memoperands_begin();
674     if (MMO->getSize() == Size && !MMO->isVolatile()) {
675       // Handle conversion of loads.
676       if (isSimpleBD12Move(MI, SystemZII::SimpleBDXLoad)) {
677         return BuildMI(MF, MI->getDebugLoc(), get(SystemZ::MVC))
678           .addFrameIndex(FrameIndex).addImm(0).addImm(Size)
679           .addOperand(MI->getOperand(1)).addImm(MI->getOperand(2).getImm())
680           .addMemOperand(MMO);
681       }
682       // Handle conversion of stores.
683       if (isSimpleBD12Move(MI, SystemZII::SimpleBDXStore)) {
684         return BuildMI(MF, MI->getDebugLoc(), get(SystemZ::MVC))
685           .addOperand(MI->getOperand(1)).addImm(MI->getOperand(2).getImm())
686           .addImm(Size).addFrameIndex(FrameIndex).addImm(0)
687           .addMemOperand(MMO);
688       }
689     }
690   }
691
692   // If the spilled operand is the final one, try to change <INSN>R
693   // into <INSN>.
694   int MemOpcode = SystemZ::getMemOpcode(Opcode);
695   if (MemOpcode >= 0) {
696     unsigned NumOps = MI->getNumExplicitOperands();
697     if (OpNum == NumOps - 1) {
698       const MCInstrDesc &MemDesc = get(MemOpcode);
699       uint64_t AccessBytes = SystemZII::getAccessSize(MemDesc.TSFlags);
700       assert(AccessBytes != 0 && "Size of access should be known");
701       assert(AccessBytes <= Size && "Access outside the frame index");
702       uint64_t Offset = Size - AccessBytes;
703       MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), get(MemOpcode));
704       for (unsigned I = 0; I < OpNum; ++I)
705         MIB.addOperand(MI->getOperand(I));
706       MIB.addFrameIndex(FrameIndex).addImm(Offset);
707       if (MemDesc.TSFlags & SystemZII::HasIndex)
708         MIB.addReg(0);
709       return MIB;
710     }
711   }
712
713   return 0;
714 }
715
716 MachineInstr *
717 SystemZInstrInfo::foldMemoryOperandImpl(MachineFunction &MF, MachineInstr* MI,
718                                         const SmallVectorImpl<unsigned> &Ops,
719                                         MachineInstr* LoadMI) const {
720   return 0;
721 }
722
723 bool
724 SystemZInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
725   switch (MI->getOpcode()) {
726   case SystemZ::L128:
727     splitMove(MI, SystemZ::LG);
728     return true;
729
730   case SystemZ::ST128:
731     splitMove(MI, SystemZ::STG);
732     return true;
733
734   case SystemZ::LX:
735     splitMove(MI, SystemZ::LD);
736     return true;
737
738   case SystemZ::STX:
739     splitMove(MI, SystemZ::STD);
740     return true;
741
742   case SystemZ::ADJDYNALLOC:
743     splitAdjDynAlloc(MI);
744     return true;
745
746   default:
747     return false;
748   }
749 }
750
751 bool SystemZInstrInfo::
752 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
753   assert(Cond.size() == 1 && "Invalid branch condition!");
754   Cond[0].setImm(Cond[0].getImm() ^ SystemZ::CCMASK_ANY);
755   return false;
756 }
757
758 uint64_t SystemZInstrInfo::getInstSizeInBytes(const MachineInstr *MI) const {
759   if (MI->getOpcode() == TargetOpcode::INLINEASM) {
760     const MachineFunction *MF = MI->getParent()->getParent();
761     const char *AsmStr = MI->getOperand(0).getSymbolName();
762     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
763   }
764   return MI->getDesc().getSize();
765 }
766
767 SystemZII::Branch
768 SystemZInstrInfo::getBranchInfo(const MachineInstr *MI) const {
769   switch (MI->getOpcode()) {
770   case SystemZ::BR:
771   case SystemZ::J:
772   case SystemZ::JG:
773     return SystemZII::Branch(SystemZII::BranchNormal, SystemZ::CCMASK_ANY,
774                              &MI->getOperand(0));
775
776   case SystemZ::BRC:
777   case SystemZ::BRCL:
778     return SystemZII::Branch(SystemZII::BranchNormal,
779                              MI->getOperand(0).getImm(), &MI->getOperand(1));
780
781   case SystemZ::CIJ:
782   case SystemZ::CRJ:
783     return SystemZII::Branch(SystemZII::BranchC, MI->getOperand(2).getImm(),
784                              &MI->getOperand(3));
785
786   case SystemZ::CGIJ:
787   case SystemZ::CGRJ:
788     return SystemZII::Branch(SystemZII::BranchCG, MI->getOperand(2).getImm(),
789                              &MI->getOperand(3));
790
791   default:
792     llvm_unreachable("Unrecognized branch opcode");
793   }
794 }
795
796 void SystemZInstrInfo::getLoadStoreOpcodes(const TargetRegisterClass *RC,
797                                            unsigned &LoadOpcode,
798                                            unsigned &StoreOpcode) const {
799   if (RC == &SystemZ::GR32BitRegClass || RC == &SystemZ::ADDR32BitRegClass) {
800     LoadOpcode = SystemZ::L;
801     StoreOpcode = SystemZ::ST32;
802   } else if (RC == &SystemZ::GR64BitRegClass ||
803              RC == &SystemZ::ADDR64BitRegClass) {
804     LoadOpcode = SystemZ::LG;
805     StoreOpcode = SystemZ::STG;
806   } else if (RC == &SystemZ::GR128BitRegClass ||
807              RC == &SystemZ::ADDR128BitRegClass) {
808     LoadOpcode = SystemZ::L128;
809     StoreOpcode = SystemZ::ST128;
810   } else if (RC == &SystemZ::FP32BitRegClass) {
811     LoadOpcode = SystemZ::LE;
812     StoreOpcode = SystemZ::STE;
813   } else if (RC == &SystemZ::FP64BitRegClass) {
814     LoadOpcode = SystemZ::LD;
815     StoreOpcode = SystemZ::STD;
816   } else if (RC == &SystemZ::FP128BitRegClass) {
817     LoadOpcode = SystemZ::LX;
818     StoreOpcode = SystemZ::STX;
819   } else
820     llvm_unreachable("Unsupported regclass to load or store");
821 }
822
823 unsigned SystemZInstrInfo::getOpcodeForOffset(unsigned Opcode,
824                                               int64_t Offset) const {
825   const MCInstrDesc &MCID = get(Opcode);
826   int64_t Offset2 = (MCID.TSFlags & SystemZII::Is128Bit ? Offset + 8 : Offset);
827   if (isUInt<12>(Offset) && isUInt<12>(Offset2)) {
828     // Get the instruction to use for unsigned 12-bit displacements.
829     int Disp12Opcode = SystemZ::getDisp12Opcode(Opcode);
830     if (Disp12Opcode >= 0)
831       return Disp12Opcode;
832
833     // All address-related instructions can use unsigned 12-bit
834     // displacements.
835     return Opcode;
836   }
837   if (isInt<20>(Offset) && isInt<20>(Offset2)) {
838     // Get the instruction to use for signed 20-bit displacements.
839     int Disp20Opcode = SystemZ::getDisp20Opcode(Opcode);
840     if (Disp20Opcode >= 0)
841       return Disp20Opcode;
842
843     // Check whether Opcode allows signed 20-bit displacements.
844     if (MCID.TSFlags & SystemZII::Has20BitOffset)
845       return Opcode;
846   }
847   return 0;
848 }
849
850 // Return true if Mask matches the regexp 0*1+0*, given that zero masks
851 // have already been filtered out.  Store the first set bit in LSB and
852 // the number of set bits in Length if so.
853 static bool isStringOfOnes(uint64_t Mask, unsigned &LSB, unsigned &Length) {
854   unsigned First = findFirstSet(Mask);
855   uint64_t Top = (Mask >> First) + 1;
856   if ((Top & -Top) == Top) {
857     LSB = First;
858     Length = findFirstSet(Top);
859     return true;
860   }
861   return false;
862 }
863
864 bool SystemZInstrInfo::isRxSBGMask(uint64_t Mask, unsigned BitSize,
865                                    unsigned &Start, unsigned &End) const {
866   // Reject trivial all-zero masks.
867   if (Mask == 0)
868     return false;
869
870   // Handle the 1+0+ or 0+1+0* cases.  Start then specifies the index of
871   // the msb and End specifies the index of the lsb.
872   unsigned LSB, Length;
873   if (isStringOfOnes(Mask, LSB, Length)) {
874     Start = 63 - (LSB + Length - 1);
875     End = 63 - LSB;
876     return true;
877   }
878
879   // Handle the wrap-around 1+0+1+ cases.  Start then specifies the msb
880   // of the low 1s and End specifies the lsb of the high 1s.
881   if (isStringOfOnes(Mask ^ allOnes(BitSize), LSB, Length)) {
882     assert(LSB > 0 && "Bottom bit must be set");
883     assert(LSB + Length < BitSize && "Top bit must be set");
884     Start = 63 - (LSB - 1);
885     End = 63 - (LSB + Length);
886     return true;
887   }
888
889   return false;
890 }
891
892 unsigned SystemZInstrInfo::getCompareAndBranch(unsigned Opcode,
893                                                const MachineInstr *MI) const {
894   switch (Opcode) {
895   case SystemZ::CR:
896     return SystemZ::CRJ;
897   case SystemZ::CGR:
898     return SystemZ::CGRJ;
899   case SystemZ::CHI:
900     return MI && isInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CIJ : 0;
901   case SystemZ::CGHI:
902     return MI && isInt<8>(MI->getOperand(1).getImm()) ? SystemZ::CGIJ : 0;
903   default:
904     return 0;
905   }
906 }
907
908 void SystemZInstrInfo::loadImmediate(MachineBasicBlock &MBB,
909                                      MachineBasicBlock::iterator MBBI,
910                                      unsigned Reg, uint64_t Value) const {
911   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
912   unsigned Opcode;
913   if (isInt<16>(Value))
914     Opcode = SystemZ::LGHI;
915   else if (SystemZ::isImmLL(Value))
916     Opcode = SystemZ::LLILL;
917   else if (SystemZ::isImmLH(Value)) {
918     Opcode = SystemZ::LLILH;
919     Value >>= 16;
920   } else {
921     assert(isInt<32>(Value) && "Huge values not handled yet");
922     Opcode = SystemZ::LGFI;
923   }
924   BuildMI(MBB, MBBI, DL, get(Opcode), Reg).addImm(Value);
925 }