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