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