]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/SystemZ/SystemZInstrInfo.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r302418, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 "MCTargetDesc/SystemZMCTargetDesc.h"
15 #include "SystemZ.h"
16 #include "SystemZInstrBuilder.h"
17 #include "SystemZInstrInfo.h"
18 #include "SystemZSubtarget.h"
19 #include "llvm/CodeGen/LiveInterval.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SlotIndexes.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/Support/BranchProbability.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
38 #include <cassert>
39 #include <cstdint>
40 #include <iterator>
41
42 using namespace llvm;
43
44 #define GET_INSTRINFO_CTOR_DTOR
45 #define GET_INSTRMAP_INFO
46 #include "SystemZGenInstrInfo.inc"
47
48 // Return a mask with Count low bits set.
49 static uint64_t allOnes(unsigned int Count) {
50   return Count == 0 ? 0 : (uint64_t(1) << (Count - 1) << 1) - 1;
51 }
52
53 // Reg should be a 32-bit GPR.  Return true if it is a high register rather
54 // than a low register.
55 static bool isHighReg(unsigned int Reg) {
56   if (SystemZ::GRH32BitRegClass.contains(Reg))
57     return true;
58   assert(SystemZ::GR32BitRegClass.contains(Reg) && "Invalid GRX32");
59   return false;
60 }
61
62 // Pin the vtable to this file.
63 void SystemZInstrInfo::anchor() {}
64
65 SystemZInstrInfo::SystemZInstrInfo(SystemZSubtarget &sti)
66   : SystemZGenInstrInfo(SystemZ::ADJCALLSTACKDOWN, SystemZ::ADJCALLSTACKUP),
67     RI(), STI(sti) {
68 }
69
70 // MI is a 128-bit load or store.  Split it into two 64-bit loads or stores,
71 // each having the opcode given by NewOpcode.
72 void SystemZInstrInfo::splitMove(MachineBasicBlock::iterator MI,
73                                  unsigned NewOpcode) const {
74   MachineBasicBlock *MBB = MI->getParent();
75   MachineFunction &MF = *MBB->getParent();
76
77   // Get two load or store instructions.  Use the original instruction for one
78   // of them (arbitrarily the second here) and create a clone for the other.
79   MachineInstr *EarlierMI = MF.CloneMachineInstr(&*MI);
80   MBB->insert(MI, EarlierMI);
81
82   // Set up the two 64-bit registers and remember super reg and its flags.
83   MachineOperand &HighRegOp = EarlierMI->getOperand(0);
84   MachineOperand &LowRegOp = MI->getOperand(0);
85   unsigned Reg128 = LowRegOp.getReg();
86   unsigned Reg128Killed = getKillRegState(LowRegOp.isKill());
87   unsigned Reg128Undef  = getUndefRegState(LowRegOp.isUndef());
88   HighRegOp.setReg(RI.getSubReg(HighRegOp.getReg(), SystemZ::subreg_h64));
89   LowRegOp.setReg(RI.getSubReg(LowRegOp.getReg(), SystemZ::subreg_l64));
90
91   if (MI->mayStore()) {
92     // Add implicit uses of the super register in case one of the subregs is
93     // undefined. We could track liveness and skip storing an undefined
94     // subreg, but this is hopefully rare (discovered with llvm-stress).
95     // If Reg128 was killed, set kill flag on MI.
96     unsigned Reg128UndefImpl = (Reg128Undef | RegState::Implicit);
97     MachineInstrBuilder(MF, EarlierMI).addReg(Reg128, Reg128UndefImpl);
98     MachineInstrBuilder(MF, MI).addReg(Reg128, (Reg128UndefImpl | Reg128Killed));
99   }
100
101   // The address in the first (high) instruction is already correct.
102   // Adjust the offset in the second (low) instruction.
103   MachineOperand &HighOffsetOp = EarlierMI->getOperand(2);
104   MachineOperand &LowOffsetOp = MI->getOperand(2);
105   LowOffsetOp.setImm(LowOffsetOp.getImm() + 8);
106
107   // Clear the kill flags on the registers in the first instruction.
108   if (EarlierMI->getOperand(0).isReg() && EarlierMI->getOperand(0).isUse())
109     EarlierMI->getOperand(0).setIsKill(false);
110   EarlierMI->getOperand(1).setIsKill(false);
111   EarlierMI->getOperand(3).setIsKill(false);
112
113   // Set the opcodes.
114   unsigned HighOpcode = getOpcodeForOffset(NewOpcode, HighOffsetOp.getImm());
115   unsigned LowOpcode = getOpcodeForOffset(NewOpcode, LowOffsetOp.getImm());
116   assert(HighOpcode && LowOpcode && "Both offsets should be in range");
117
118   EarlierMI->setDesc(get(HighOpcode));
119   MI->setDesc(get(LowOpcode));
120 }
121
122 // Split ADJDYNALLOC instruction MI.
123 void SystemZInstrInfo::splitAdjDynAlloc(MachineBasicBlock::iterator MI) const {
124   MachineBasicBlock *MBB = MI->getParent();
125   MachineFunction &MF = *MBB->getParent();
126   MachineFrameInfo &MFFrame = MF.getFrameInfo();
127   MachineOperand &OffsetMO = MI->getOperand(2);
128
129   uint64_t Offset = (MFFrame.getMaxCallFrameSize() +
130                      SystemZMC::CallFrameSize +
131                      OffsetMO.getImm());
132   unsigned NewOpcode = getOpcodeForOffset(SystemZ::LA, Offset);
133   assert(NewOpcode && "No support for huge argument lists yet");
134   MI->setDesc(get(NewOpcode));
135   OffsetMO.setImm(Offset);
136 }
137
138 // MI is an RI-style pseudo instruction.  Replace it with LowOpcode
139 // if the first operand is a low GR32 and HighOpcode if the first operand
140 // is a high GR32.  ConvertHigh is true if LowOpcode takes a signed operand
141 // and HighOpcode takes an unsigned 32-bit operand.  In those cases,
142 // MI has the same kind of operand as LowOpcode, so needs to be converted
143 // if HighOpcode is used.
144 void SystemZInstrInfo::expandRIPseudo(MachineInstr &MI, unsigned LowOpcode,
145                                       unsigned HighOpcode,
146                                       bool ConvertHigh) const {
147   unsigned Reg = MI.getOperand(0).getReg();
148   bool IsHigh = isHighReg(Reg);
149   MI.setDesc(get(IsHigh ? HighOpcode : LowOpcode));
150   if (IsHigh && ConvertHigh)
151     MI.getOperand(1).setImm(uint32_t(MI.getOperand(1).getImm()));
152 }
153
154 // MI is a three-operand RIE-style pseudo instruction.  Replace it with
155 // LowOpcodeK if the registers are both low GR32s, otherwise use a move
156 // followed by HighOpcode or LowOpcode, depending on whether the target
157 // is a high or low GR32.
158 void SystemZInstrInfo::expandRIEPseudo(MachineInstr &MI, unsigned LowOpcode,
159                                        unsigned LowOpcodeK,
160                                        unsigned HighOpcode) const {
161   unsigned DestReg = MI.getOperand(0).getReg();
162   unsigned SrcReg = MI.getOperand(1).getReg();
163   bool DestIsHigh = isHighReg(DestReg);
164   bool SrcIsHigh = isHighReg(SrcReg);
165   if (!DestIsHigh && !SrcIsHigh)
166     MI.setDesc(get(LowOpcodeK));
167   else {
168     emitGRX32Move(*MI.getParent(), MI, MI.getDebugLoc(), DestReg, SrcReg,
169                   SystemZ::LR, 32, MI.getOperand(1).isKill(),
170                   MI.getOperand(1).isUndef());
171     MI.setDesc(get(DestIsHigh ? HighOpcode : LowOpcode));
172     MI.getOperand(1).setReg(DestReg);
173     MI.tieOperands(0, 1);
174   }
175 }
176
177 // MI is an RXY-style pseudo instruction.  Replace it with LowOpcode
178 // if the first operand is a low GR32 and HighOpcode if the first operand
179 // is a high GR32.
180 void SystemZInstrInfo::expandRXYPseudo(MachineInstr &MI, unsigned LowOpcode,
181                                        unsigned HighOpcode) const {
182   unsigned Reg = MI.getOperand(0).getReg();
183   unsigned Opcode = getOpcodeForOffset(isHighReg(Reg) ? HighOpcode : LowOpcode,
184                                        MI.getOperand(2).getImm());
185   MI.setDesc(get(Opcode));
186 }
187
188 // MI is a load-on-condition pseudo instruction with a single register
189 // (source or destination) operand.  Replace it with LowOpcode if the
190 // register is a low GR32 and HighOpcode if the register is a high GR32.
191 void SystemZInstrInfo::expandLOCPseudo(MachineInstr &MI, unsigned LowOpcode,
192                                        unsigned HighOpcode) const {
193   unsigned Reg = MI.getOperand(0).getReg();
194   unsigned Opcode = isHighReg(Reg) ? HighOpcode : LowOpcode;
195   MI.setDesc(get(Opcode));
196 }
197
198 // MI is a load-register-on-condition pseudo instruction.  Replace it with
199 // LowOpcode if source and destination are both low GR32s and HighOpcode if
200 // source and destination are both high GR32s.
201 void SystemZInstrInfo::expandLOCRPseudo(MachineInstr &MI, unsigned LowOpcode,
202                                         unsigned HighOpcode) const {
203   unsigned DestReg = MI.getOperand(0).getReg();
204   unsigned SrcReg = MI.getOperand(2).getReg();
205   bool DestIsHigh = isHighReg(DestReg);
206   bool SrcIsHigh = isHighReg(SrcReg);
207
208   if (!DestIsHigh && !SrcIsHigh)
209     MI.setDesc(get(LowOpcode));
210   else if (DestIsHigh && SrcIsHigh)
211     MI.setDesc(get(HighOpcode));
212
213   // If we were unable to implement the pseudo with a single instruction, we
214   // need to convert it back into a branch sequence.  This cannot be done here
215   // since the caller of expandPostRAPseudo does not handle changes to the CFG
216   // correctly.  This change is defered to the SystemZExpandPseudo pass.
217 }
218
219 // MI is an RR-style pseudo instruction that zero-extends the low Size bits
220 // of one GRX32 into another.  Replace it with LowOpcode if both operands
221 // are low registers, otherwise use RISB[LH]G.
222 void SystemZInstrInfo::expandZExtPseudo(MachineInstr &MI, unsigned LowOpcode,
223                                         unsigned Size) const {
224   MachineInstrBuilder MIB =
225     emitGRX32Move(*MI.getParent(), MI, MI.getDebugLoc(),
226                MI.getOperand(0).getReg(), MI.getOperand(1).getReg(), LowOpcode,
227                Size, MI.getOperand(1).isKill(), MI.getOperand(1).isUndef());
228
229   // Keep the remaining operands as-is.
230   for (unsigned I = 2; I < MI.getNumOperands(); ++I)
231     MIB.add(MI.getOperand(I));
232
233   MI.eraseFromParent();
234 }
235
236 void SystemZInstrInfo::expandLoadStackGuard(MachineInstr *MI) const {
237   MachineBasicBlock *MBB = MI->getParent();
238   MachineFunction &MF = *MBB->getParent();
239   const unsigned Reg = MI->getOperand(0).getReg();
240
241   // Conveniently, all 4 instructions are cloned from LOAD_STACK_GUARD,
242   // so they already have operand 0 set to reg.
243
244   // ear <reg>, %a0
245   MachineInstr *Ear1MI = MF.CloneMachineInstr(MI);
246   MBB->insert(MI, Ear1MI);
247   Ear1MI->setDesc(get(SystemZ::EAR));
248   MachineInstrBuilder(MF, Ear1MI).addReg(SystemZ::A0);
249
250   // sllg <reg>, <reg>, 32
251   MachineInstr *SllgMI = MF.CloneMachineInstr(MI);
252   MBB->insert(MI, SllgMI);
253   SllgMI->setDesc(get(SystemZ::SLLG));
254   MachineInstrBuilder(MF, SllgMI).addReg(Reg).addReg(0).addImm(32);
255
256   // ear <reg>, %a1
257   MachineInstr *Ear2MI = MF.CloneMachineInstr(MI);
258   MBB->insert(MI, Ear2MI);
259   Ear2MI->setDesc(get(SystemZ::EAR));
260   MachineInstrBuilder(MF, Ear2MI).addReg(SystemZ::A1);
261
262   // lg <reg>, 40(<reg>)
263   MI->setDesc(get(SystemZ::LG));
264   MachineInstrBuilder(MF, MI).addReg(Reg).addImm(40).addReg(0);
265 }
266
267 // Emit a zero-extending move from 32-bit GPR SrcReg to 32-bit GPR
268 // DestReg before MBBI in MBB.  Use LowLowOpcode when both DestReg and SrcReg
269 // are low registers, otherwise use RISB[LH]G.  Size is the number of bits
270 // taken from the low end of SrcReg (8 for LLCR, 16 for LLHR and 32 for LR).
271 // KillSrc is true if this move is the last use of SrcReg.
272 MachineInstrBuilder
273 SystemZInstrInfo::emitGRX32Move(MachineBasicBlock &MBB,
274                                 MachineBasicBlock::iterator MBBI,
275                                 const DebugLoc &DL, unsigned DestReg,
276                                 unsigned SrcReg, unsigned LowLowOpcode,
277                                 unsigned Size, bool KillSrc,
278                                 bool UndefSrc) const {
279   unsigned Opcode;
280   bool DestIsHigh = isHighReg(DestReg);
281   bool SrcIsHigh = isHighReg(SrcReg);
282   if (DestIsHigh && SrcIsHigh)
283     Opcode = SystemZ::RISBHH;
284   else if (DestIsHigh && !SrcIsHigh)
285     Opcode = SystemZ::RISBHL;
286   else if (!DestIsHigh && SrcIsHigh)
287     Opcode = SystemZ::RISBLH;
288   else {
289     return BuildMI(MBB, MBBI, DL, get(LowLowOpcode), DestReg)
290       .addReg(SrcReg, getKillRegState(KillSrc) | getUndefRegState(UndefSrc));
291   }
292   unsigned Rotate = (DestIsHigh != SrcIsHigh ? 32 : 0);
293   return BuildMI(MBB, MBBI, DL, get(Opcode), DestReg)
294     .addReg(DestReg, RegState::Undef)
295     .addReg(SrcReg, getKillRegState(KillSrc) | getUndefRegState(UndefSrc))
296     .addImm(32 - Size).addImm(128 + 31).addImm(Rotate);
297 }
298
299 MachineInstr *SystemZInstrInfo::commuteInstructionImpl(MachineInstr &MI,
300                                                        bool NewMI,
301                                                        unsigned OpIdx1,
302                                                        unsigned OpIdx2) const {
303   auto cloneIfNew = [NewMI](MachineInstr &MI) -> MachineInstr & {
304     if (NewMI)
305       return *MI.getParent()->getParent()->CloneMachineInstr(&MI);
306     return MI;
307   };
308
309   switch (MI.getOpcode()) {
310   case SystemZ::LOCRMux:
311   case SystemZ::LOCFHR:
312   case SystemZ::LOCR:
313   case SystemZ::LOCGR: {
314     auto &WorkingMI = cloneIfNew(MI);
315     // Invert condition.
316     unsigned CCValid = WorkingMI.getOperand(3).getImm();
317     unsigned CCMask = WorkingMI.getOperand(4).getImm();
318     WorkingMI.getOperand(4).setImm(CCMask ^ CCValid);
319     return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
320                                                    OpIdx1, OpIdx2);
321   }
322   default:
323     return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
324   }
325 }
326
327 // If MI is a simple load or store for a frame object, return the register
328 // it loads or stores and set FrameIndex to the index of the frame object.
329 // Return 0 otherwise.
330 //
331 // Flag is SimpleBDXLoad for loads and SimpleBDXStore for stores.
332 static int isSimpleMove(const MachineInstr &MI, int &FrameIndex,
333                         unsigned Flag) {
334   const MCInstrDesc &MCID = MI.getDesc();
335   if ((MCID.TSFlags & Flag) && MI.getOperand(1).isFI() &&
336       MI.getOperand(2).getImm() == 0 && MI.getOperand(3).getReg() == 0) {
337     FrameIndex = MI.getOperand(1).getIndex();
338     return MI.getOperand(0).getReg();
339   }
340   return 0;
341 }
342
343 unsigned SystemZInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
344                                                int &FrameIndex) const {
345   return isSimpleMove(MI, FrameIndex, SystemZII::SimpleBDXLoad);
346 }
347
348 unsigned SystemZInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
349                                               int &FrameIndex) const {
350   return isSimpleMove(MI, FrameIndex, SystemZII::SimpleBDXStore);
351 }
352
353 bool SystemZInstrInfo::isStackSlotCopy(const MachineInstr &MI,
354                                        int &DestFrameIndex,
355                                        int &SrcFrameIndex) const {
356   // Check for MVC 0(Length,FI1),0(FI2)
357   const MachineFrameInfo &MFI = MI.getParent()->getParent()->getFrameInfo();
358   if (MI.getOpcode() != SystemZ::MVC || !MI.getOperand(0).isFI() ||
359       MI.getOperand(1).getImm() != 0 || !MI.getOperand(3).isFI() ||
360       MI.getOperand(4).getImm() != 0)
361     return false;
362
363   // Check that Length covers the full slots.
364   int64_t Length = MI.getOperand(2).getImm();
365   unsigned FI1 = MI.getOperand(0).getIndex();
366   unsigned FI2 = MI.getOperand(3).getIndex();
367   if (MFI.getObjectSize(FI1) != Length ||
368       MFI.getObjectSize(FI2) != Length)
369     return false;
370
371   DestFrameIndex = FI1;
372   SrcFrameIndex = FI2;
373   return true;
374 }
375
376 bool SystemZInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
377                                      MachineBasicBlock *&TBB,
378                                      MachineBasicBlock *&FBB,
379                                      SmallVectorImpl<MachineOperand> &Cond,
380                                      bool AllowModify) const {
381   // Most of the code and comments here are boilerplate.
382
383   // Start from the bottom of the block and work up, examining the
384   // terminator instructions.
385   MachineBasicBlock::iterator I = MBB.end();
386   while (I != MBB.begin()) {
387     --I;
388     if (I->isDebugValue())
389       continue;
390
391     // Working from the bottom, when we see a non-terminator instruction, we're
392     // done.
393     if (!isUnpredicatedTerminator(*I))
394       break;
395
396     // A terminator that isn't a branch can't easily be handled by this
397     // analysis.
398     if (!I->isBranch())
399       return true;
400
401     // Can't handle indirect branches.
402     SystemZII::Branch Branch(getBranchInfo(*I));
403     if (!Branch.Target->isMBB())
404       return true;
405
406     // Punt on compound branches.
407     if (Branch.Type != SystemZII::BranchNormal)
408       return true;
409
410     if (Branch.CCMask == SystemZ::CCMASK_ANY) {
411       // Handle unconditional branches.
412       if (!AllowModify) {
413         TBB = Branch.Target->getMBB();
414         continue;
415       }
416
417       // If the block has any instructions after a JMP, delete them.
418       while (std::next(I) != MBB.end())
419         std::next(I)->eraseFromParent();
420
421       Cond.clear();
422       FBB = nullptr;
423
424       // Delete the JMP if it's equivalent to a fall-through.
425       if (MBB.isLayoutSuccessor(Branch.Target->getMBB())) {
426         TBB = nullptr;
427         I->eraseFromParent();
428         I = MBB.end();
429         continue;
430       }
431
432       // TBB is used to indicate the unconditinal destination.
433       TBB = Branch.Target->getMBB();
434       continue;
435     }
436
437     // Working from the bottom, handle the first conditional branch.
438     if (Cond.empty()) {
439       // FIXME: add X86-style branch swap
440       FBB = TBB;
441       TBB = Branch.Target->getMBB();
442       Cond.push_back(MachineOperand::CreateImm(Branch.CCValid));
443       Cond.push_back(MachineOperand::CreateImm(Branch.CCMask));
444       continue;
445     }
446
447     // Handle subsequent conditional branches.
448     assert(Cond.size() == 2 && TBB && "Should have seen a conditional branch");
449
450     // Only handle the case where all conditional branches branch to the same
451     // destination.
452     if (TBB != Branch.Target->getMBB())
453       return true;
454
455     // If the conditions are the same, we can leave them alone.
456     unsigned OldCCValid = Cond[0].getImm();
457     unsigned OldCCMask = Cond[1].getImm();
458     if (OldCCValid == Branch.CCValid && OldCCMask == Branch.CCMask)
459       continue;
460
461     // FIXME: Try combining conditions like X86 does.  Should be easy on Z!
462     return false;
463   }
464
465   return false;
466 }
467
468 unsigned SystemZInstrInfo::removeBranch(MachineBasicBlock &MBB,
469                                         int *BytesRemoved) const {
470   assert(!BytesRemoved && "code size not handled");
471
472   // Most of the code and comments here are boilerplate.
473   MachineBasicBlock::iterator I = MBB.end();
474   unsigned Count = 0;
475
476   while (I != MBB.begin()) {
477     --I;
478     if (I->isDebugValue())
479       continue;
480     if (!I->isBranch())
481       break;
482     if (!getBranchInfo(*I).Target->isMBB())
483       break;
484     // Remove the branch.
485     I->eraseFromParent();
486     I = MBB.end();
487     ++Count;
488   }
489
490   return Count;
491 }
492
493 bool SystemZInstrInfo::
494 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
495   assert(Cond.size() == 2 && "Invalid condition");
496   Cond[1].setImm(Cond[1].getImm() ^ Cond[0].getImm());
497   return false;
498 }
499
500 unsigned SystemZInstrInfo::insertBranch(MachineBasicBlock &MBB,
501                                         MachineBasicBlock *TBB,
502                                         MachineBasicBlock *FBB,
503                                         ArrayRef<MachineOperand> Cond,
504                                         const DebugLoc &DL,
505                                         int *BytesAdded) const {
506   // In this function we output 32-bit branches, which should always
507   // have enough range.  They can be shortened and relaxed by later code
508   // in the pipeline, if desired.
509
510   // Shouldn't be a fall through.
511   assert(TBB && "insertBranch must not be told to insert a fallthrough");
512   assert((Cond.size() == 2 || Cond.size() == 0) &&
513          "SystemZ branch conditions have one component!");
514   assert(!BytesAdded && "code size not handled");
515
516   if (Cond.empty()) {
517     // Unconditional branch?
518     assert(!FBB && "Unconditional branch with multiple successors!");
519     BuildMI(&MBB, DL, get(SystemZ::J)).addMBB(TBB);
520     return 1;
521   }
522
523   // Conditional branch.
524   unsigned Count = 0;
525   unsigned CCValid = Cond[0].getImm();
526   unsigned CCMask = Cond[1].getImm();
527   BuildMI(&MBB, DL, get(SystemZ::BRC))
528     .addImm(CCValid).addImm(CCMask).addMBB(TBB);
529   ++Count;
530
531   if (FBB) {
532     // Two-way Conditional branch. Insert the second branch.
533     BuildMI(&MBB, DL, get(SystemZ::J)).addMBB(FBB);
534     ++Count;
535   }
536   return Count;
537 }
538
539 bool SystemZInstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
540                                       unsigned &SrcReg2, int &Mask,
541                                       int &Value) const {
542   assert(MI.isCompare() && "Caller should have checked for a comparison");
543
544   if (MI.getNumExplicitOperands() == 2 && MI.getOperand(0).isReg() &&
545       MI.getOperand(1).isImm()) {
546     SrcReg = MI.getOperand(0).getReg();
547     SrcReg2 = 0;
548     Value = MI.getOperand(1).getImm();
549     Mask = ~0;
550     return true;
551   }
552
553   return false;
554 }
555
556 // If Reg is a virtual register, return its definition, otherwise return null.
557 static MachineInstr *getDef(unsigned Reg,
558                             const MachineRegisterInfo *MRI) {
559   if (TargetRegisterInfo::isPhysicalRegister(Reg))
560     return nullptr;
561   return MRI->getUniqueVRegDef(Reg);
562 }
563
564 // Return true if MI is a shift of type Opcode by Imm bits.
565 static bool isShift(MachineInstr *MI, unsigned Opcode, int64_t Imm) {
566   return (MI->getOpcode() == Opcode &&
567           !MI->getOperand(2).getReg() &&
568           MI->getOperand(3).getImm() == Imm);
569 }
570
571 // If the destination of MI has no uses, delete it as dead.
572 static void eraseIfDead(MachineInstr *MI, const MachineRegisterInfo *MRI) {
573   if (MRI->use_nodbg_empty(MI->getOperand(0).getReg()))
574     MI->eraseFromParent();
575 }
576
577 // Compare compares SrcReg against zero.  Check whether SrcReg contains
578 // the result of an IPM sequence whose input CC survives until Compare,
579 // and whether Compare is therefore redundant.  Delete it and return
580 // true if so.
581 static bool removeIPMBasedCompare(MachineInstr &Compare, unsigned SrcReg,
582                                   const MachineRegisterInfo *MRI,
583                                   const TargetRegisterInfo *TRI) {
584   MachineInstr *LGFR = nullptr;
585   MachineInstr *RLL = getDef(SrcReg, MRI);
586   if (RLL && RLL->getOpcode() == SystemZ::LGFR) {
587     LGFR = RLL;
588     RLL = getDef(LGFR->getOperand(1).getReg(), MRI);
589   }
590   if (!RLL || !isShift(RLL, SystemZ::RLL, 31))
591     return false;
592
593   MachineInstr *SRL = getDef(RLL->getOperand(1).getReg(), MRI);
594   if (!SRL || !isShift(SRL, SystemZ::SRL, SystemZ::IPM_CC))
595     return false;
596
597   MachineInstr *IPM = getDef(SRL->getOperand(1).getReg(), MRI);
598   if (!IPM || IPM->getOpcode() != SystemZ::IPM)
599     return false;
600
601   // Check that there are no assignments to CC between the IPM and Compare,
602   if (IPM->getParent() != Compare.getParent())
603     return false;
604   MachineBasicBlock::iterator MBBI = IPM, MBBE = Compare.getIterator();
605   for (++MBBI; MBBI != MBBE; ++MBBI) {
606     MachineInstr &MI = *MBBI;
607     if (MI.modifiesRegister(SystemZ::CC, TRI))
608       return false;
609   }
610
611   Compare.eraseFromParent();
612   if (LGFR)
613     eraseIfDead(LGFR, MRI);
614   eraseIfDead(RLL, MRI);
615   eraseIfDead(SRL, MRI);
616   eraseIfDead(IPM, MRI);
617
618   return true;
619 }
620
621 bool SystemZInstrInfo::optimizeCompareInstr(
622     MachineInstr &Compare, unsigned SrcReg, unsigned SrcReg2, int Mask,
623     int Value, const MachineRegisterInfo *MRI) const {
624   assert(!SrcReg2 && "Only optimizing constant comparisons so far");
625   bool IsLogical = (Compare.getDesc().TSFlags & SystemZII::IsLogical) != 0;
626   return Value == 0 && !IsLogical &&
627          removeIPMBasedCompare(Compare, SrcReg, MRI, &RI);
628 }
629
630 bool SystemZInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
631                                        ArrayRef<MachineOperand> Pred,
632                                        unsigned TrueReg, unsigned FalseReg,
633                                        int &CondCycles, int &TrueCycles,
634                                        int &FalseCycles) const {
635   // Not all subtargets have LOCR instructions.
636   if (!STI.hasLoadStoreOnCond())
637     return false;
638   if (Pred.size() != 2)
639     return false;
640
641   // Check register classes.
642   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
643   const TargetRegisterClass *RC =
644     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
645   if (!RC)
646     return false;
647
648   // We have LOCR instructions for 32 and 64 bit general purpose registers.
649   if ((STI.hasLoadStoreOnCond2() &&
650        SystemZ::GRX32BitRegClass.hasSubClassEq(RC)) ||
651       SystemZ::GR32BitRegClass.hasSubClassEq(RC) ||
652       SystemZ::GR64BitRegClass.hasSubClassEq(RC)) {
653     CondCycles = 2;
654     TrueCycles = 2;
655     FalseCycles = 2;
656     return true;
657   }
658
659   // Can't do anything else.
660   return false;
661 }
662
663 void SystemZInstrInfo::insertSelect(MachineBasicBlock &MBB,
664                                     MachineBasicBlock::iterator I,
665                                     const DebugLoc &DL, unsigned DstReg,
666                                     ArrayRef<MachineOperand> Pred,
667                                     unsigned TrueReg,
668                                     unsigned FalseReg) const {
669   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
670   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
671
672   assert(Pred.size() == 2 && "Invalid condition");
673   unsigned CCValid = Pred[0].getImm();
674   unsigned CCMask = Pred[1].getImm();
675
676   unsigned Opc;
677   if (SystemZ::GRX32BitRegClass.hasSubClassEq(RC)) {
678     if (STI.hasLoadStoreOnCond2())
679       Opc = SystemZ::LOCRMux;
680     else {
681       Opc = SystemZ::LOCR;
682       MRI.constrainRegClass(DstReg, &SystemZ::GR32BitRegClass);
683       unsigned TReg = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
684       unsigned FReg = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
685       BuildMI(MBB, I, DL, get(TargetOpcode::COPY), TReg).addReg(TrueReg);
686       BuildMI(MBB, I, DL, get(TargetOpcode::COPY), FReg).addReg(FalseReg);
687       TrueReg = TReg;
688       FalseReg = FReg;
689     }
690   } else if (SystemZ::GR64BitRegClass.hasSubClassEq(RC))
691     Opc = SystemZ::LOCGR;
692   else
693     llvm_unreachable("Invalid register class");
694
695   BuildMI(MBB, I, DL, get(Opc), DstReg)
696     .addReg(FalseReg).addReg(TrueReg)
697     .addImm(CCValid).addImm(CCMask);
698 }
699
700 bool SystemZInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
701                                      unsigned Reg,
702                                      MachineRegisterInfo *MRI) const {
703   unsigned DefOpc = DefMI.getOpcode();
704   if (DefOpc != SystemZ::LHIMux && DefOpc != SystemZ::LHI &&
705       DefOpc != SystemZ::LGHI)
706     return false;
707   if (DefMI.getOperand(0).getReg() != Reg)
708     return false;
709   int32_t ImmVal = (int32_t)DefMI.getOperand(1).getImm();
710
711   unsigned UseOpc = UseMI.getOpcode();
712   unsigned NewUseOpc;
713   unsigned UseIdx;
714   int CommuteIdx = -1;
715   switch (UseOpc) {
716   case SystemZ::LOCRMux:
717     if (!STI.hasLoadStoreOnCond2())
718       return false;
719     NewUseOpc = SystemZ::LOCHIMux;
720     if (UseMI.getOperand(2).getReg() == Reg)
721       UseIdx = 2;
722     else if (UseMI.getOperand(1).getReg() == Reg)
723       UseIdx = 2, CommuteIdx = 1;
724     else
725       return false;
726     break;
727   case SystemZ::LOCGR:
728     if (!STI.hasLoadStoreOnCond2())
729       return false;
730     NewUseOpc = SystemZ::LOCGHI;
731     if (UseMI.getOperand(2).getReg() == Reg)
732       UseIdx = 2;
733     else if (UseMI.getOperand(1).getReg() == Reg)
734       UseIdx = 2, CommuteIdx = 1;
735     else
736       return false;
737     break;
738   default:
739     return false;
740   }
741
742   if (CommuteIdx != -1)
743     if (!commuteInstruction(UseMI, false, CommuteIdx, UseIdx))
744       return false;
745
746   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
747   UseMI.setDesc(get(NewUseOpc));
748   UseMI.getOperand(UseIdx).ChangeToImmediate(ImmVal);
749   if (DeleteDef)
750     DefMI.eraseFromParent();
751
752   return true;
753 }
754
755 bool SystemZInstrInfo::isPredicable(const MachineInstr &MI) const {
756   unsigned Opcode = MI.getOpcode();
757   if (Opcode == SystemZ::Return ||
758       Opcode == SystemZ::Trap ||
759       Opcode == SystemZ::CallJG ||
760       Opcode == SystemZ::CallBR)
761     return true;
762   return false;
763 }
764
765 bool SystemZInstrInfo::
766 isProfitableToIfCvt(MachineBasicBlock &MBB,
767                     unsigned NumCycles, unsigned ExtraPredCycles,
768                     BranchProbability Probability) const {
769   // Avoid using conditional returns at the end of a loop (since then
770   // we'd need to emit an unconditional branch to the beginning anyway,
771   // making the loop body longer).  This doesn't apply for low-probability
772   // loops (eg. compare-and-swap retry), so just decide based on branch
773   // probability instead of looping structure.
774   // However, since Compare and Trap instructions cost the same as a regular
775   // Compare instruction, we should allow the if conversion to convert this
776   // into a Conditional Compare regardless of the branch probability.
777   if (MBB.getLastNonDebugInstr()->getOpcode() != SystemZ::Trap &&
778       MBB.succ_empty() && Probability < BranchProbability(1, 8))
779     return false;
780   // For now only convert single instructions.
781   return NumCycles == 1;
782 }
783
784 bool SystemZInstrInfo::
785 isProfitableToIfCvt(MachineBasicBlock &TMBB,
786                     unsigned NumCyclesT, unsigned ExtraPredCyclesT,
787                     MachineBasicBlock &FMBB,
788                     unsigned NumCyclesF, unsigned ExtraPredCyclesF,
789                     BranchProbability Probability) const {
790   // For now avoid converting mutually-exclusive cases.
791   return false;
792 }
793
794 bool SystemZInstrInfo::
795 isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
796                           BranchProbability Probability) const {
797   // For now only duplicate single instructions.
798   return NumCycles == 1;
799 }
800
801 bool SystemZInstrInfo::PredicateInstruction(
802     MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
803   assert(Pred.size() == 2 && "Invalid condition");
804   unsigned CCValid = Pred[0].getImm();
805   unsigned CCMask = Pred[1].getImm();
806   assert(CCMask > 0 && CCMask < 15 && "Invalid predicate");
807   unsigned Opcode = MI.getOpcode();
808   if (Opcode == SystemZ::Trap) {
809     MI.setDesc(get(SystemZ::CondTrap));
810     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
811       .addImm(CCValid).addImm(CCMask)
812       .addReg(SystemZ::CC, RegState::Implicit);
813     return true;
814   }
815   if (Opcode == SystemZ::Return) {
816     MI.setDesc(get(SystemZ::CondReturn));
817     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
818       .addImm(CCValid).addImm(CCMask)
819       .addReg(SystemZ::CC, RegState::Implicit);
820     return true;
821   }
822   if (Opcode == SystemZ::CallJG) {
823     MachineOperand FirstOp = MI.getOperand(0);
824     const uint32_t *RegMask = MI.getOperand(1).getRegMask();
825     MI.RemoveOperand(1);
826     MI.RemoveOperand(0);
827     MI.setDesc(get(SystemZ::CallBRCL));
828     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
829         .addImm(CCValid)
830         .addImm(CCMask)
831         .add(FirstOp)
832         .addRegMask(RegMask)
833         .addReg(SystemZ::CC, RegState::Implicit);
834     return true;
835   }
836   if (Opcode == SystemZ::CallBR) {
837     const uint32_t *RegMask = MI.getOperand(0).getRegMask();
838     MI.RemoveOperand(0);
839     MI.setDesc(get(SystemZ::CallBCR));
840     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
841       .addImm(CCValid).addImm(CCMask)
842       .addRegMask(RegMask)
843       .addReg(SystemZ::CC, RegState::Implicit);
844     return true;
845   }
846   return false;
847 }
848
849 void SystemZInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
850                                    MachineBasicBlock::iterator MBBI,
851                                    const DebugLoc &DL, unsigned DestReg,
852                                    unsigned SrcReg, bool KillSrc) const {
853   // Split 128-bit GPR moves into two 64-bit moves. Add implicit uses of the
854   // super register in case one of the subregs is undefined.
855   // This handles ADDR128 too.
856   if (SystemZ::GR128BitRegClass.contains(DestReg, SrcReg)) {
857     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_h64),
858                 RI.getSubReg(SrcReg, SystemZ::subreg_h64), KillSrc);
859     MachineInstrBuilder(*MBB.getParent(), std::prev(MBBI))
860       .addReg(SrcReg, RegState::Implicit);
861     copyPhysReg(MBB, MBBI, DL, RI.getSubReg(DestReg, SystemZ::subreg_l64),
862                 RI.getSubReg(SrcReg, SystemZ::subreg_l64), KillSrc);
863     MachineInstrBuilder(*MBB.getParent(), std::prev(MBBI))
864       .addReg(SrcReg, (getKillRegState(KillSrc) | RegState::Implicit));
865     return;
866   }
867
868   if (SystemZ::GRX32BitRegClass.contains(DestReg, SrcReg)) {
869     emitGRX32Move(MBB, MBBI, DL, DestReg, SrcReg, SystemZ::LR, 32, KillSrc,
870                   false);
871     return;
872   }
873
874   // Everything else needs only one instruction.
875   unsigned Opcode;
876   if (SystemZ::GR64BitRegClass.contains(DestReg, SrcReg))
877     Opcode = SystemZ::LGR;
878   else if (SystemZ::FP32BitRegClass.contains(DestReg, SrcReg))
879     // For z13 we prefer LDR over LER to avoid partial register dependencies.
880     Opcode = STI.hasVector() ? SystemZ::LDR32 : SystemZ::LER;
881   else if (SystemZ::FP64BitRegClass.contains(DestReg, SrcReg))
882     Opcode = SystemZ::LDR;
883   else if (SystemZ::FP128BitRegClass.contains(DestReg, SrcReg))
884     Opcode = SystemZ::LXR;
885   else if (SystemZ::VR32BitRegClass.contains(DestReg, SrcReg))
886     Opcode = SystemZ::VLR32;
887   else if (SystemZ::VR64BitRegClass.contains(DestReg, SrcReg))
888     Opcode = SystemZ::VLR64;
889   else if (SystemZ::VR128BitRegClass.contains(DestReg, SrcReg))
890     Opcode = SystemZ::VLR;
891   else if (SystemZ::AR32BitRegClass.contains(DestReg, SrcReg))
892     Opcode = SystemZ::CPYA;
893   else if (SystemZ::AR32BitRegClass.contains(DestReg) &&
894            SystemZ::GR32BitRegClass.contains(SrcReg))
895     Opcode = SystemZ::SAR;
896   else if (SystemZ::GR32BitRegClass.contains(DestReg) &&
897            SystemZ::AR32BitRegClass.contains(SrcReg))
898     Opcode = SystemZ::EAR;
899   else
900     llvm_unreachable("Impossible reg-to-reg copy");
901
902   BuildMI(MBB, MBBI, DL, get(Opcode), DestReg)
903     .addReg(SrcReg, getKillRegState(KillSrc));
904 }
905
906 void SystemZInstrInfo::storeRegToStackSlot(
907     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned SrcReg,
908     bool isKill, int FrameIdx, const TargetRegisterClass *RC,
909     const TargetRegisterInfo *TRI) const {
910   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
911
912   // Callers may expect a single instruction, so keep 128-bit moves
913   // together for now and lower them after register allocation.
914   unsigned LoadOpcode, StoreOpcode;
915   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
916   addFrameReference(BuildMI(MBB, MBBI, DL, get(StoreOpcode))
917                         .addReg(SrcReg, getKillRegState(isKill)),
918                     FrameIdx);
919 }
920
921 void SystemZInstrInfo::loadRegFromStackSlot(
922     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned DestReg,
923     int FrameIdx, const TargetRegisterClass *RC,
924     const TargetRegisterInfo *TRI) const {
925   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
926
927   // Callers may expect a single instruction, so keep 128-bit moves
928   // together for now and lower them after register allocation.
929   unsigned LoadOpcode, StoreOpcode;
930   getLoadStoreOpcodes(RC, LoadOpcode, StoreOpcode);
931   addFrameReference(BuildMI(MBB, MBBI, DL, get(LoadOpcode), DestReg),
932                     FrameIdx);
933 }
934
935 // Return true if MI is a simple load or store with a 12-bit displacement
936 // and no index.  Flag is SimpleBDXLoad for loads and SimpleBDXStore for stores.
937 static bool isSimpleBD12Move(const MachineInstr *MI, unsigned Flag) {
938   const MCInstrDesc &MCID = MI->getDesc();
939   return ((MCID.TSFlags & Flag) &&
940           isUInt<12>(MI->getOperand(2).getImm()) &&
941           MI->getOperand(3).getReg() == 0);
942 }
943
944 namespace {
945
946 struct LogicOp {
947   LogicOp() = default;
948   LogicOp(unsigned regSize, unsigned immLSB, unsigned immSize)
949     : RegSize(regSize), ImmLSB(immLSB), ImmSize(immSize) {}
950
951   explicit operator bool() const { return RegSize; }
952
953   unsigned RegSize = 0;
954   unsigned ImmLSB = 0;
955   unsigned ImmSize = 0;
956 };
957
958 } // end anonymous namespace
959
960 static LogicOp interpretAndImmediate(unsigned Opcode) {
961   switch (Opcode) {
962   case SystemZ::NILMux: return LogicOp(32,  0, 16);
963   case SystemZ::NIHMux: return LogicOp(32, 16, 16);
964   case SystemZ::NILL64: return LogicOp(64,  0, 16);
965   case SystemZ::NILH64: return LogicOp(64, 16, 16);
966   case SystemZ::NIHL64: return LogicOp(64, 32, 16);
967   case SystemZ::NIHH64: return LogicOp(64, 48, 16);
968   case SystemZ::NIFMux: return LogicOp(32,  0, 32);
969   case SystemZ::NILF64: return LogicOp(64,  0, 32);
970   case SystemZ::NIHF64: return LogicOp(64, 32, 32);
971   default:              return LogicOp();
972   }
973 }
974
975 static void transferDeadCC(MachineInstr *OldMI, MachineInstr *NewMI) {
976   if (OldMI->registerDefIsDead(SystemZ::CC)) {
977     MachineOperand *CCDef = NewMI->findRegisterDefOperand(SystemZ::CC);
978     if (CCDef != nullptr)
979       CCDef->setIsDead(true);
980   }
981 }
982
983 // Used to return from convertToThreeAddress after replacing two-address
984 // instruction OldMI with three-address instruction NewMI.
985 static MachineInstr *finishConvertToThreeAddress(MachineInstr *OldMI,
986                                                  MachineInstr *NewMI,
987                                                  LiveVariables *LV) {
988   if (LV) {
989     unsigned NumOps = OldMI->getNumOperands();
990     for (unsigned I = 1; I < NumOps; ++I) {
991       MachineOperand &Op = OldMI->getOperand(I);
992       if (Op.isReg() && Op.isKill())
993         LV->replaceKillInstruction(Op.getReg(), *OldMI, *NewMI);
994     }
995   }
996   transferDeadCC(OldMI, NewMI);
997   return NewMI;
998 }
999
1000 MachineInstr *SystemZInstrInfo::convertToThreeAddress(
1001     MachineFunction::iterator &MFI, MachineInstr &MI, LiveVariables *LV) const {
1002   MachineBasicBlock *MBB = MI.getParent();
1003   MachineFunction *MF = MBB->getParent();
1004   MachineRegisterInfo &MRI = MF->getRegInfo();
1005
1006   unsigned Opcode = MI.getOpcode();
1007   unsigned NumOps = MI.getNumOperands();
1008
1009   // Try to convert something like SLL into SLLK, if supported.
1010   // We prefer to keep the two-operand form where possible both
1011   // because it tends to be shorter and because some instructions
1012   // have memory forms that can be used during spilling.
1013   if (STI.hasDistinctOps()) {
1014     MachineOperand &Dest = MI.getOperand(0);
1015     MachineOperand &Src = MI.getOperand(1);
1016     unsigned DestReg = Dest.getReg();
1017     unsigned SrcReg = Src.getReg();
1018     // AHIMux is only really a three-operand instruction when both operands
1019     // are low registers.  Try to constrain both operands to be low if
1020     // possible.
1021     if (Opcode == SystemZ::AHIMux &&
1022         TargetRegisterInfo::isVirtualRegister(DestReg) &&
1023         TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1024         MRI.getRegClass(DestReg)->contains(SystemZ::R1L) &&
1025         MRI.getRegClass(SrcReg)->contains(SystemZ::R1L)) {
1026       MRI.constrainRegClass(DestReg, &SystemZ::GR32BitRegClass);
1027       MRI.constrainRegClass(SrcReg, &SystemZ::GR32BitRegClass);
1028     }
1029     int ThreeOperandOpcode = SystemZ::getThreeOperandOpcode(Opcode);
1030     if (ThreeOperandOpcode >= 0) {
1031       // Create three address instruction without adding the implicit
1032       // operands. Those will instead be copied over from the original
1033       // instruction by the loop below.
1034       MachineInstrBuilder MIB(
1035           *MF, MF->CreateMachineInstr(get(ThreeOperandOpcode), MI.getDebugLoc(),
1036                                       /*NoImplicit=*/true));
1037       MIB.add(Dest);
1038       // Keep the kill state, but drop the tied flag.
1039       MIB.addReg(Src.getReg(), getKillRegState(Src.isKill()), Src.getSubReg());
1040       // Keep the remaining operands as-is.
1041       for (unsigned I = 2; I < NumOps; ++I)
1042         MIB.add(MI.getOperand(I));
1043       MBB->insert(MI, MIB);
1044       return finishConvertToThreeAddress(&MI, MIB, LV);
1045     }
1046   }
1047
1048   // Try to convert an AND into an RISBG-type instruction.
1049   if (LogicOp And = interpretAndImmediate(Opcode)) {
1050     uint64_t Imm = MI.getOperand(2).getImm() << And.ImmLSB;
1051     // AND IMMEDIATE leaves the other bits of the register unchanged.
1052     Imm |= allOnes(And.RegSize) & ~(allOnes(And.ImmSize) << And.ImmLSB);
1053     unsigned Start, End;
1054     if (isRxSBGMask(Imm, And.RegSize, Start, End)) {
1055       unsigned NewOpcode;
1056       if (And.RegSize == 64) {
1057         NewOpcode = SystemZ::RISBG;
1058         // Prefer RISBGN if available, since it does not clobber CC.
1059         if (STI.hasMiscellaneousExtensions())
1060           NewOpcode = SystemZ::RISBGN;
1061       } else {
1062         NewOpcode = SystemZ::RISBMux;
1063         Start &= 31;
1064         End &= 31;
1065       }
1066       MachineOperand &Dest = MI.getOperand(0);
1067       MachineOperand &Src = MI.getOperand(1);
1068       MachineInstrBuilder MIB =
1069           BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpcode))
1070               .add(Dest)
1071               .addReg(0)
1072               .addReg(Src.getReg(), getKillRegState(Src.isKill()),
1073                       Src.getSubReg())
1074               .addImm(Start)
1075               .addImm(End + 128)
1076               .addImm(0);
1077       return finishConvertToThreeAddress(&MI, MIB, LV);
1078     }
1079   }
1080   return nullptr;
1081 }
1082
1083 MachineInstr *SystemZInstrInfo::foldMemoryOperandImpl(
1084     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
1085     MachineBasicBlock::iterator InsertPt, int FrameIndex,
1086     LiveIntervals *LIS) const {
1087   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1088   const MachineFrameInfo &MFI = MF.getFrameInfo();
1089   unsigned Size = MFI.getObjectSize(FrameIndex);
1090   unsigned Opcode = MI.getOpcode();
1091
1092   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
1093     if (LIS != nullptr && (Opcode == SystemZ::LA || Opcode == SystemZ::LAY) &&
1094         isInt<8>(MI.getOperand(2).getImm()) && !MI.getOperand(3).getReg()) {
1095
1096       // Check CC liveness, since new instruction introduces a dead
1097       // def of CC.
1098       MCRegUnitIterator CCUnit(SystemZ::CC, TRI);
1099       LiveRange &CCLiveRange = LIS->getRegUnit(*CCUnit);
1100       ++CCUnit;
1101       assert(!CCUnit.isValid() && "CC only has one reg unit.");
1102       SlotIndex MISlot =
1103           LIS->getSlotIndexes()->getInstructionIndex(MI).getRegSlot();
1104       if (!CCLiveRange.liveAt(MISlot)) {
1105         // LA(Y) %reg, CONST(%reg) -> AGSI %mem, CONST
1106         MachineInstr *BuiltMI = BuildMI(*InsertPt->getParent(), InsertPt,
1107                                         MI.getDebugLoc(), get(SystemZ::AGSI))
1108                                     .addFrameIndex(FrameIndex)
1109                                     .addImm(0)
1110                                     .addImm(MI.getOperand(2).getImm());
1111         BuiltMI->findRegisterDefOperand(SystemZ::CC)->setIsDead(true);
1112         CCLiveRange.createDeadDef(MISlot, LIS->getVNInfoAllocator());
1113         return BuiltMI;
1114       }
1115     }
1116     return nullptr;
1117   }
1118
1119   // All other cases require a single operand.
1120   if (Ops.size() != 1)
1121     return nullptr;
1122
1123   unsigned OpNum = Ops[0];
1124   assert(Size * 8 ==
1125            TRI->getRegSizeInBits(*MF.getRegInfo()
1126                                .getRegClass(MI.getOperand(OpNum).getReg())) &&
1127          "Invalid size combination");
1128
1129   if ((Opcode == SystemZ::AHI || Opcode == SystemZ::AGHI) && OpNum == 0 &&
1130       isInt<8>(MI.getOperand(2).getImm())) {
1131     // A(G)HI %reg, CONST -> A(G)SI %mem, CONST
1132     Opcode = (Opcode == SystemZ::AHI ? SystemZ::ASI : SystemZ::AGSI);
1133     MachineInstr *BuiltMI =
1134         BuildMI(*InsertPt->getParent(), InsertPt, MI.getDebugLoc(), get(Opcode))
1135             .addFrameIndex(FrameIndex)
1136             .addImm(0)
1137             .addImm(MI.getOperand(2).getImm());
1138     transferDeadCC(&MI, BuiltMI);
1139     return BuiltMI;
1140   }
1141
1142   if (Opcode == SystemZ::LGDR || Opcode == SystemZ::LDGR) {
1143     bool Op0IsGPR = (Opcode == SystemZ::LGDR);
1144     bool Op1IsGPR = (Opcode == SystemZ::LDGR);
1145     // If we're spilling the destination of an LDGR or LGDR, store the
1146     // source register instead.
1147     if (OpNum == 0) {
1148       unsigned StoreOpcode = Op1IsGPR ? SystemZ::STG : SystemZ::STD;
1149       return BuildMI(*InsertPt->getParent(), InsertPt, MI.getDebugLoc(),
1150                      get(StoreOpcode))
1151           .add(MI.getOperand(1))
1152           .addFrameIndex(FrameIndex)
1153           .addImm(0)
1154           .addReg(0);
1155     }
1156     // If we're spilling the source of an LDGR or LGDR, load the
1157     // destination register instead.
1158     if (OpNum == 1) {
1159       unsigned LoadOpcode = Op0IsGPR ? SystemZ::LG : SystemZ::LD;
1160       return BuildMI(*InsertPt->getParent(), InsertPt, MI.getDebugLoc(),
1161                      get(LoadOpcode))
1162         .add(MI.getOperand(0))
1163         .addFrameIndex(FrameIndex)
1164         .addImm(0)
1165         .addReg(0);
1166     }
1167   }
1168
1169   // Look for cases where the source of a simple store or the destination
1170   // of a simple load is being spilled.  Try to use MVC instead.
1171   //
1172   // Although MVC is in practice a fast choice in these cases, it is still
1173   // logically a bytewise copy.  This means that we cannot use it if the
1174   // load or store is volatile.  We also wouldn't be able to use MVC if
1175   // the two memories partially overlap, but that case cannot occur here,
1176   // because we know that one of the memories is a full frame index.
1177   //
1178   // For performance reasons, we also want to avoid using MVC if the addresses
1179   // might be equal.  We don't worry about that case here, because spill slot
1180   // coloring happens later, and because we have special code to remove
1181   // MVCs that turn out to be redundant.
1182   if (OpNum == 0 && MI.hasOneMemOperand()) {
1183     MachineMemOperand *MMO = *MI.memoperands_begin();
1184     if (MMO->getSize() == Size && !MMO->isVolatile()) {
1185       // Handle conversion of loads.
1186       if (isSimpleBD12Move(&MI, SystemZII::SimpleBDXLoad)) {
1187         return BuildMI(*InsertPt->getParent(), InsertPt, MI.getDebugLoc(),
1188                        get(SystemZ::MVC))
1189             .addFrameIndex(FrameIndex)
1190             .addImm(0)
1191             .addImm(Size)
1192             .add(MI.getOperand(1))
1193             .addImm(MI.getOperand(2).getImm())
1194             .addMemOperand(MMO);
1195       }
1196       // Handle conversion of stores.
1197       if (isSimpleBD12Move(&MI, SystemZII::SimpleBDXStore)) {
1198         return BuildMI(*InsertPt->getParent(), InsertPt, MI.getDebugLoc(),
1199                        get(SystemZ::MVC))
1200             .add(MI.getOperand(1))
1201             .addImm(MI.getOperand(2).getImm())
1202             .addImm(Size)
1203             .addFrameIndex(FrameIndex)
1204             .addImm(0)
1205             .addMemOperand(MMO);
1206       }
1207     }
1208   }
1209
1210   // If the spilled operand is the final one, try to change <INSN>R
1211   // into <INSN>.
1212   int MemOpcode = SystemZ::getMemOpcode(Opcode);
1213   if (MemOpcode >= 0) {
1214     unsigned NumOps = MI.getNumExplicitOperands();
1215     if (OpNum == NumOps - 1) {
1216       const MCInstrDesc &MemDesc = get(MemOpcode);
1217       uint64_t AccessBytes = SystemZII::getAccessSize(MemDesc.TSFlags);
1218       assert(AccessBytes != 0 && "Size of access should be known");
1219       assert(AccessBytes <= Size && "Access outside the frame index");
1220       uint64_t Offset = Size - AccessBytes;
1221       MachineInstrBuilder MIB = BuildMI(*InsertPt->getParent(), InsertPt,
1222                                         MI.getDebugLoc(), get(MemOpcode));
1223       for (unsigned I = 0; I < OpNum; ++I)
1224         MIB.add(MI.getOperand(I));
1225       MIB.addFrameIndex(FrameIndex).addImm(Offset);
1226       if (MemDesc.TSFlags & SystemZII::HasIndex)
1227         MIB.addReg(0);
1228       transferDeadCC(&MI, MIB);
1229       return MIB;
1230     }
1231   }
1232
1233   return nullptr;
1234 }
1235
1236 MachineInstr *SystemZInstrInfo::foldMemoryOperandImpl(
1237     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
1238     MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
1239     LiveIntervals *LIS) const {
1240   return nullptr;
1241 }
1242
1243 bool SystemZInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1244   switch (MI.getOpcode()) {
1245   case SystemZ::L128:
1246     splitMove(MI, SystemZ::LG);
1247     return true;
1248
1249   case SystemZ::ST128:
1250     splitMove(MI, SystemZ::STG);
1251     return true;
1252
1253   case SystemZ::LX:
1254     splitMove(MI, SystemZ::LD);
1255     return true;
1256
1257   case SystemZ::STX:
1258     splitMove(MI, SystemZ::STD);
1259     return true;
1260
1261   case SystemZ::LBMux:
1262     expandRXYPseudo(MI, SystemZ::LB, SystemZ::LBH);
1263     return true;
1264
1265   case SystemZ::LHMux:
1266     expandRXYPseudo(MI, SystemZ::LH, SystemZ::LHH);
1267     return true;
1268
1269   case SystemZ::LLCRMux:
1270     expandZExtPseudo(MI, SystemZ::LLCR, 8);
1271     return true;
1272
1273   case SystemZ::LLHRMux:
1274     expandZExtPseudo(MI, SystemZ::LLHR, 16);
1275     return true;
1276
1277   case SystemZ::LLCMux:
1278     expandRXYPseudo(MI, SystemZ::LLC, SystemZ::LLCH);
1279     return true;
1280
1281   case SystemZ::LLHMux:
1282     expandRXYPseudo(MI, SystemZ::LLH, SystemZ::LLHH);
1283     return true;
1284
1285   case SystemZ::LMux:
1286     expandRXYPseudo(MI, SystemZ::L, SystemZ::LFH);
1287     return true;
1288
1289   case SystemZ::LOCMux:
1290     expandLOCPseudo(MI, SystemZ::LOC, SystemZ::LOCFH);
1291     return true;
1292
1293   case SystemZ::LOCHIMux:
1294     expandLOCPseudo(MI, SystemZ::LOCHI, SystemZ::LOCHHI);
1295     return true;
1296
1297   case SystemZ::LOCRMux:
1298     expandLOCRPseudo(MI, SystemZ::LOCR, SystemZ::LOCFHR);
1299     return true;
1300
1301   case SystemZ::STCMux:
1302     expandRXYPseudo(MI, SystemZ::STC, SystemZ::STCH);
1303     return true;
1304
1305   case SystemZ::STHMux:
1306     expandRXYPseudo(MI, SystemZ::STH, SystemZ::STHH);
1307     return true;
1308
1309   case SystemZ::STMux:
1310     expandRXYPseudo(MI, SystemZ::ST, SystemZ::STFH);
1311     return true;
1312
1313   case SystemZ::STOCMux:
1314     expandLOCPseudo(MI, SystemZ::STOC, SystemZ::STOCFH);
1315     return true;
1316
1317   case SystemZ::LHIMux:
1318     expandRIPseudo(MI, SystemZ::LHI, SystemZ::IIHF, true);
1319     return true;
1320
1321   case SystemZ::IIFMux:
1322     expandRIPseudo(MI, SystemZ::IILF, SystemZ::IIHF, false);
1323     return true;
1324
1325   case SystemZ::IILMux:
1326     expandRIPseudo(MI, SystemZ::IILL, SystemZ::IIHL, false);
1327     return true;
1328
1329   case SystemZ::IIHMux:
1330     expandRIPseudo(MI, SystemZ::IILH, SystemZ::IIHH, false);
1331     return true;
1332
1333   case SystemZ::NIFMux:
1334     expandRIPseudo(MI, SystemZ::NILF, SystemZ::NIHF, false);
1335     return true;
1336
1337   case SystemZ::NILMux:
1338     expandRIPseudo(MI, SystemZ::NILL, SystemZ::NIHL, false);
1339     return true;
1340
1341   case SystemZ::NIHMux:
1342     expandRIPseudo(MI, SystemZ::NILH, SystemZ::NIHH, false);
1343     return true;
1344
1345   case SystemZ::OIFMux:
1346     expandRIPseudo(MI, SystemZ::OILF, SystemZ::OIHF, false);
1347     return true;
1348
1349   case SystemZ::OILMux:
1350     expandRIPseudo(MI, SystemZ::OILL, SystemZ::OIHL, false);
1351     return true;
1352
1353   case SystemZ::OIHMux:
1354     expandRIPseudo(MI, SystemZ::OILH, SystemZ::OIHH, false);
1355     return true;
1356
1357   case SystemZ::XIFMux:
1358     expandRIPseudo(MI, SystemZ::XILF, SystemZ::XIHF, false);
1359     return true;
1360
1361   case SystemZ::TMLMux:
1362     expandRIPseudo(MI, SystemZ::TMLL, SystemZ::TMHL, false);
1363     return true;
1364
1365   case SystemZ::TMHMux:
1366     expandRIPseudo(MI, SystemZ::TMLH, SystemZ::TMHH, false);
1367     return true;
1368
1369   case SystemZ::AHIMux:
1370     expandRIPseudo(MI, SystemZ::AHI, SystemZ::AIH, false);
1371     return true;
1372
1373   case SystemZ::AHIMuxK:
1374     expandRIEPseudo(MI, SystemZ::AHI, SystemZ::AHIK, SystemZ::AIH);
1375     return true;
1376
1377   case SystemZ::AFIMux:
1378     expandRIPseudo(MI, SystemZ::AFI, SystemZ::AIH, false);
1379     return true;
1380
1381   case SystemZ::CHIMux:
1382     expandRIPseudo(MI, SystemZ::CHI, SystemZ::CIH, false);
1383     return true;
1384
1385   case SystemZ::CFIMux:
1386     expandRIPseudo(MI, SystemZ::CFI, SystemZ::CIH, false);
1387     return true;
1388
1389   case SystemZ::CLFIMux:
1390     expandRIPseudo(MI, SystemZ::CLFI, SystemZ::CLIH, false);
1391     return true;
1392
1393   case SystemZ::CMux:
1394     expandRXYPseudo(MI, SystemZ::C, SystemZ::CHF);
1395     return true;
1396
1397   case SystemZ::CLMux:
1398     expandRXYPseudo(MI, SystemZ::CL, SystemZ::CLHF);
1399     return true;
1400
1401   case SystemZ::RISBMux: {
1402     bool DestIsHigh = isHighReg(MI.getOperand(0).getReg());
1403     bool SrcIsHigh = isHighReg(MI.getOperand(2).getReg());
1404     if (SrcIsHigh == DestIsHigh)
1405       MI.setDesc(get(DestIsHigh ? SystemZ::RISBHH : SystemZ::RISBLL));
1406     else {
1407       MI.setDesc(get(DestIsHigh ? SystemZ::RISBHL : SystemZ::RISBLH));
1408       MI.getOperand(5).setImm(MI.getOperand(5).getImm() ^ 32);
1409     }
1410     return true;
1411   }
1412
1413   case SystemZ::ADJDYNALLOC:
1414     splitAdjDynAlloc(MI);
1415     return true;
1416
1417   case TargetOpcode::LOAD_STACK_GUARD:
1418     expandLoadStackGuard(&MI);
1419     return true;
1420
1421   default:
1422     return false;
1423   }
1424 }
1425
1426 unsigned SystemZInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
1427   if (MI.getOpcode() == TargetOpcode::INLINEASM) {
1428     const MachineFunction *MF = MI.getParent()->getParent();
1429     const char *AsmStr = MI.getOperand(0).getSymbolName();
1430     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1431   }
1432   return MI.getDesc().getSize();
1433 }
1434
1435 SystemZII::Branch
1436 SystemZInstrInfo::getBranchInfo(const MachineInstr &MI) const {
1437   switch (MI.getOpcode()) {
1438   case SystemZ::BR:
1439   case SystemZ::J:
1440   case SystemZ::JG:
1441     return SystemZII::Branch(SystemZII::BranchNormal, SystemZ::CCMASK_ANY,
1442                              SystemZ::CCMASK_ANY, &MI.getOperand(0));
1443
1444   case SystemZ::BRC:
1445   case SystemZ::BRCL:
1446     return SystemZII::Branch(SystemZII::BranchNormal, MI.getOperand(0).getImm(),
1447                              MI.getOperand(1).getImm(), &MI.getOperand(2));
1448
1449   case SystemZ::BRCT:
1450   case SystemZ::BRCTH:
1451     return SystemZII::Branch(SystemZII::BranchCT, SystemZ::CCMASK_ICMP,
1452                              SystemZ::CCMASK_CMP_NE, &MI.getOperand(2));
1453
1454   case SystemZ::BRCTG:
1455     return SystemZII::Branch(SystemZII::BranchCTG, SystemZ::CCMASK_ICMP,
1456                              SystemZ::CCMASK_CMP_NE, &MI.getOperand(2));
1457
1458   case SystemZ::CIJ:
1459   case SystemZ::CRJ:
1460     return SystemZII::Branch(SystemZII::BranchC, SystemZ::CCMASK_ICMP,
1461                              MI.getOperand(2).getImm(), &MI.getOperand(3));
1462
1463   case SystemZ::CLIJ:
1464   case SystemZ::CLRJ:
1465     return SystemZII::Branch(SystemZII::BranchCL, SystemZ::CCMASK_ICMP,
1466                              MI.getOperand(2).getImm(), &MI.getOperand(3));
1467
1468   case SystemZ::CGIJ:
1469   case SystemZ::CGRJ:
1470     return SystemZII::Branch(SystemZII::BranchCG, SystemZ::CCMASK_ICMP,
1471                              MI.getOperand(2).getImm(), &MI.getOperand(3));
1472
1473   case SystemZ::CLGIJ:
1474   case SystemZ::CLGRJ:
1475     return SystemZII::Branch(SystemZII::BranchCLG, SystemZ::CCMASK_ICMP,
1476                              MI.getOperand(2).getImm(), &MI.getOperand(3));
1477
1478   default:
1479     llvm_unreachable("Unrecognized branch opcode");
1480   }
1481 }
1482
1483 void SystemZInstrInfo::getLoadStoreOpcodes(const TargetRegisterClass *RC,
1484                                            unsigned &LoadOpcode,
1485                                            unsigned &StoreOpcode) const {
1486   if (RC == &SystemZ::GR32BitRegClass || RC == &SystemZ::ADDR32BitRegClass) {
1487     LoadOpcode = SystemZ::L;
1488     StoreOpcode = SystemZ::ST;
1489   } else if (RC == &SystemZ::GRH32BitRegClass) {
1490     LoadOpcode = SystemZ::LFH;
1491     StoreOpcode = SystemZ::STFH;
1492   } else if (RC == &SystemZ::GRX32BitRegClass) {
1493     LoadOpcode = SystemZ::LMux;
1494     StoreOpcode = SystemZ::STMux;
1495   } else if (RC == &SystemZ::GR64BitRegClass ||
1496              RC == &SystemZ::ADDR64BitRegClass) {
1497     LoadOpcode = SystemZ::LG;
1498     StoreOpcode = SystemZ::STG;
1499   } else if (RC == &SystemZ::GR128BitRegClass ||
1500              RC == &SystemZ::ADDR128BitRegClass) {
1501     LoadOpcode = SystemZ::L128;
1502     StoreOpcode = SystemZ::ST128;
1503   } else if (RC == &SystemZ::FP32BitRegClass) {
1504     LoadOpcode = SystemZ::LE;
1505     StoreOpcode = SystemZ::STE;
1506   } else if (RC == &SystemZ::FP64BitRegClass) {
1507     LoadOpcode = SystemZ::LD;
1508     StoreOpcode = SystemZ::STD;
1509   } else if (RC == &SystemZ::FP128BitRegClass) {
1510     LoadOpcode = SystemZ::LX;
1511     StoreOpcode = SystemZ::STX;
1512   } else if (RC == &SystemZ::VR32BitRegClass) {
1513     LoadOpcode = SystemZ::VL32;
1514     StoreOpcode = SystemZ::VST32;
1515   } else if (RC == &SystemZ::VR64BitRegClass) {
1516     LoadOpcode = SystemZ::VL64;
1517     StoreOpcode = SystemZ::VST64;
1518   } else if (RC == &SystemZ::VF128BitRegClass ||
1519              RC == &SystemZ::VR128BitRegClass) {
1520     LoadOpcode = SystemZ::VL;
1521     StoreOpcode = SystemZ::VST;
1522   } else
1523     llvm_unreachable("Unsupported regclass to load or store");
1524 }
1525
1526 unsigned SystemZInstrInfo::getOpcodeForOffset(unsigned Opcode,
1527                                               int64_t Offset) const {
1528   const MCInstrDesc &MCID = get(Opcode);
1529   int64_t Offset2 = (MCID.TSFlags & SystemZII::Is128Bit ? Offset + 8 : Offset);
1530   if (isUInt<12>(Offset) && isUInt<12>(Offset2)) {
1531     // Get the instruction to use for unsigned 12-bit displacements.
1532     int Disp12Opcode = SystemZ::getDisp12Opcode(Opcode);
1533     if (Disp12Opcode >= 0)
1534       return Disp12Opcode;
1535
1536     // All address-related instructions can use unsigned 12-bit
1537     // displacements.
1538     return Opcode;
1539   }
1540   if (isInt<20>(Offset) && isInt<20>(Offset2)) {
1541     // Get the instruction to use for signed 20-bit displacements.
1542     int Disp20Opcode = SystemZ::getDisp20Opcode(Opcode);
1543     if (Disp20Opcode >= 0)
1544       return Disp20Opcode;
1545
1546     // Check whether Opcode allows signed 20-bit displacements.
1547     if (MCID.TSFlags & SystemZII::Has20BitOffset)
1548       return Opcode;
1549   }
1550   return 0;
1551 }
1552
1553 unsigned SystemZInstrInfo::getLoadAndTest(unsigned Opcode) const {
1554   switch (Opcode) {
1555   case SystemZ::L:      return SystemZ::LT;
1556   case SystemZ::LY:     return SystemZ::LT;
1557   case SystemZ::LG:     return SystemZ::LTG;
1558   case SystemZ::LGF:    return SystemZ::LTGF;
1559   case SystemZ::LR:     return SystemZ::LTR;
1560   case SystemZ::LGFR:   return SystemZ::LTGFR;
1561   case SystemZ::LGR:    return SystemZ::LTGR;
1562   case SystemZ::LER:    return SystemZ::LTEBR;
1563   case SystemZ::LDR:    return SystemZ::LTDBR;
1564   case SystemZ::LXR:    return SystemZ::LTXBR;
1565   case SystemZ::LCDFR:  return SystemZ::LCDBR;
1566   case SystemZ::LPDFR:  return SystemZ::LPDBR;
1567   case SystemZ::LNDFR:  return SystemZ::LNDBR;
1568   case SystemZ::LCDFR_32:  return SystemZ::LCEBR;
1569   case SystemZ::LPDFR_32:  return SystemZ::LPEBR;
1570   case SystemZ::LNDFR_32:  return SystemZ::LNEBR;
1571   // On zEC12 we prefer to use RISBGN.  But if there is a chance to
1572   // actually use the condition code, we may turn it back into RISGB.
1573   // Note that RISBG is not really a "load-and-test" instruction,
1574   // but sets the same condition code values, so is OK to use here.
1575   case SystemZ::RISBGN: return SystemZ::RISBG;
1576   default:              return 0;
1577   }
1578 }
1579
1580 // Return true if Mask matches the regexp 0*1+0*, given that zero masks
1581 // have already been filtered out.  Store the first set bit in LSB and
1582 // the number of set bits in Length if so.
1583 static bool isStringOfOnes(uint64_t Mask, unsigned &LSB, unsigned &Length) {
1584   unsigned First = findFirstSet(Mask);
1585   uint64_t Top = (Mask >> First) + 1;
1586   if ((Top & -Top) == Top) {
1587     LSB = First;
1588     Length = findFirstSet(Top);
1589     return true;
1590   }
1591   return false;
1592 }
1593
1594 bool SystemZInstrInfo::isRxSBGMask(uint64_t Mask, unsigned BitSize,
1595                                    unsigned &Start, unsigned &End) const {
1596   // Reject trivial all-zero masks.
1597   Mask &= allOnes(BitSize);
1598   if (Mask == 0)
1599     return false;
1600
1601   // Handle the 1+0+ or 0+1+0* cases.  Start then specifies the index of
1602   // the msb and End specifies the index of the lsb.
1603   unsigned LSB, Length;
1604   if (isStringOfOnes(Mask, LSB, Length)) {
1605     Start = 63 - (LSB + Length - 1);
1606     End = 63 - LSB;
1607     return true;
1608   }
1609
1610   // Handle the wrap-around 1+0+1+ cases.  Start then specifies the msb
1611   // of the low 1s and End specifies the lsb of the high 1s.
1612   if (isStringOfOnes(Mask ^ allOnes(BitSize), LSB, Length)) {
1613     assert(LSB > 0 && "Bottom bit must be set");
1614     assert(LSB + Length < BitSize && "Top bit must be set");
1615     Start = 63 - (LSB - 1);
1616     End = 63 - (LSB + Length);
1617     return true;
1618   }
1619
1620   return false;
1621 }
1622
1623 unsigned SystemZInstrInfo::getFusedCompare(unsigned Opcode,
1624                                            SystemZII::FusedCompareType Type,
1625                                            const MachineInstr *MI) const {
1626   switch (Opcode) {
1627   case SystemZ::CHI:
1628   case SystemZ::CGHI:
1629     if (!(MI && isInt<8>(MI->getOperand(1).getImm())))
1630       return 0;
1631     break;
1632   case SystemZ::CLFI:
1633   case SystemZ::CLGFI:
1634     if (!(MI && isUInt<8>(MI->getOperand(1).getImm())))
1635       return 0;
1636     break;
1637   case SystemZ::CL:
1638   case SystemZ::CLG:
1639     if (!STI.hasMiscellaneousExtensions())
1640       return 0;
1641     if (!(MI && MI->getOperand(3).getReg() == 0))
1642       return 0;
1643     break;
1644   }
1645   switch (Type) {
1646   case SystemZII::CompareAndBranch:
1647     switch (Opcode) {
1648     case SystemZ::CR:
1649       return SystemZ::CRJ;
1650     case SystemZ::CGR:
1651       return SystemZ::CGRJ;
1652     case SystemZ::CHI:
1653       return SystemZ::CIJ;
1654     case SystemZ::CGHI:
1655       return SystemZ::CGIJ;
1656     case SystemZ::CLR:
1657       return SystemZ::CLRJ;
1658     case SystemZ::CLGR:
1659       return SystemZ::CLGRJ;
1660     case SystemZ::CLFI:
1661       return SystemZ::CLIJ;
1662     case SystemZ::CLGFI:
1663       return SystemZ::CLGIJ;
1664     default:
1665       return 0;
1666     }
1667   case SystemZII::CompareAndReturn:
1668     switch (Opcode) {
1669     case SystemZ::CR:
1670       return SystemZ::CRBReturn;
1671     case SystemZ::CGR:
1672       return SystemZ::CGRBReturn;
1673     case SystemZ::CHI:
1674       return SystemZ::CIBReturn;
1675     case SystemZ::CGHI:
1676       return SystemZ::CGIBReturn;
1677     case SystemZ::CLR:
1678       return SystemZ::CLRBReturn;
1679     case SystemZ::CLGR:
1680       return SystemZ::CLGRBReturn;
1681     case SystemZ::CLFI:
1682       return SystemZ::CLIBReturn;
1683     case SystemZ::CLGFI:
1684       return SystemZ::CLGIBReturn;
1685     default:
1686       return 0;
1687     }
1688   case SystemZII::CompareAndSibcall:
1689     switch (Opcode) {
1690     case SystemZ::CR:
1691       return SystemZ::CRBCall;
1692     case SystemZ::CGR:
1693       return SystemZ::CGRBCall;
1694     case SystemZ::CHI:
1695       return SystemZ::CIBCall;
1696     case SystemZ::CGHI:
1697       return SystemZ::CGIBCall;
1698     case SystemZ::CLR:
1699       return SystemZ::CLRBCall;
1700     case SystemZ::CLGR:
1701       return SystemZ::CLGRBCall;
1702     case SystemZ::CLFI:
1703       return SystemZ::CLIBCall;
1704     case SystemZ::CLGFI:
1705       return SystemZ::CLGIBCall;
1706     default:
1707       return 0;
1708     }
1709   case SystemZII::CompareAndTrap:
1710     switch (Opcode) {
1711     case SystemZ::CR:
1712       return SystemZ::CRT;
1713     case SystemZ::CGR:
1714       return SystemZ::CGRT;
1715     case SystemZ::CHI:
1716       return SystemZ::CIT;
1717     case SystemZ::CGHI:
1718       return SystemZ::CGIT;
1719     case SystemZ::CLR:
1720       return SystemZ::CLRT;
1721     case SystemZ::CLGR:
1722       return SystemZ::CLGRT;
1723     case SystemZ::CLFI:
1724       return SystemZ::CLFIT;
1725     case SystemZ::CLGFI:
1726       return SystemZ::CLGIT;
1727     case SystemZ::CL:
1728       return SystemZ::CLT;
1729     case SystemZ::CLG:
1730       return SystemZ::CLGT;
1731     default:
1732       return 0;
1733     }
1734   }
1735   return 0;
1736 }
1737
1738 unsigned SystemZInstrInfo::getLoadAndTrap(unsigned Opcode) const {
1739   if (!STI.hasLoadAndTrap())
1740     return 0;
1741   switch (Opcode) {
1742   case SystemZ::L:
1743   case SystemZ::LY:
1744     return SystemZ::LAT;
1745   case SystemZ::LG:
1746     return SystemZ::LGAT;
1747   case SystemZ::LFH:
1748     return SystemZ::LFHAT;
1749   case SystemZ::LLGF:
1750     return SystemZ::LLGFAT;
1751   case SystemZ::LLGT:
1752     return SystemZ::LLGTAT;
1753   }
1754   return 0;
1755 }
1756
1757 void SystemZInstrInfo::loadImmediate(MachineBasicBlock &MBB,
1758                                      MachineBasicBlock::iterator MBBI,
1759                                      unsigned Reg, uint64_t Value) const {
1760   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1761   unsigned Opcode;
1762   if (isInt<16>(Value))
1763     Opcode = SystemZ::LGHI;
1764   else if (SystemZ::isImmLL(Value))
1765     Opcode = SystemZ::LLILL;
1766   else if (SystemZ::isImmLH(Value)) {
1767     Opcode = SystemZ::LLILH;
1768     Value >>= 16;
1769   } else {
1770     assert(isInt<32>(Value) && "Huge values not handled yet");
1771     Opcode = SystemZ::LGFI;
1772   }
1773   BuildMI(MBB, MBBI, DL, get(Opcode), Reg).addImm(Value);
1774 }
1775
1776 bool SystemZInstrInfo::
1777 areMemAccessesTriviallyDisjoint(MachineInstr &MIa, MachineInstr &MIb,
1778                                 AliasAnalysis *AA) const {
1779
1780   if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand())
1781     return false;
1782
1783   // If mem-operands show that the same address Value is used by both
1784   // instructions, check for non-overlapping offsets and widths. Not
1785   // sure if a register based analysis would be an improvement...
1786
1787   MachineMemOperand *MMOa = *MIa.memoperands_begin();
1788   MachineMemOperand *MMOb = *MIb.memoperands_begin();
1789   const Value *VALa = MMOa->getValue();
1790   const Value *VALb = MMOb->getValue();
1791   bool SameVal = (VALa && VALb && (VALa == VALb));
1792   if (!SameVal) {
1793     const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
1794     const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
1795     if (PSVa && PSVb && (PSVa == PSVb))
1796       SameVal = true;
1797   }
1798   if (SameVal) {
1799     int OffsetA = MMOa->getOffset(), OffsetB = MMOb->getOffset();
1800     int WidthA = MMOa->getSize(), WidthB = MMOb->getSize();
1801     int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1802     int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1803     int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1804     if (LowOffset + LowWidth <= HighOffset)
1805       return true;
1806   }
1807
1808   return false;
1809 }