Fix logic inversion for RI-mode address selection
[oota-llvm.git] / lib / Target / SystemZ / SystemZISelDAGToDAG.cpp
1 //==-- SystemZISelDAGToDAG.cpp - A dag to dag inst selector for SystemZ ---===//
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 defines an instruction selector for the SystemZ target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SystemZ.h"
15 #include "SystemZISelLowering.h"
16 #include "SystemZTargetMachine.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 using namespace llvm;
32
33 static const unsigned subreg_even32 = 1;
34 static const unsigned subreg_odd32  = 2;
35 static const unsigned subreg_even   = 3;
36 static const unsigned subreg_odd    = 4;
37
38 namespace {
39   /// SystemZRRIAddressMode - This corresponds to rriaddr, but uses SDValue's
40   /// instead of register numbers for the leaves of the matched tree.
41   struct SystemZRRIAddressMode {
42     enum {
43       RegBase,
44       FrameIndexBase
45     } BaseType;
46
47     struct {            // This is really a union, discriminated by BaseType!
48       SDValue Reg;
49       int FrameIndex;
50     } Base;
51
52     SDValue IndexReg;
53     int64_t Disp;
54     bool isRI;
55
56     SystemZRRIAddressMode(bool RI = false)
57       : BaseType(RegBase), IndexReg(), Disp(0), isRI(RI) {
58     }
59
60     void dump() {
61       cerr << "SystemZRRIAddressMode " << this << '\n';
62       if (BaseType == RegBase) {
63         cerr << "Base.Reg ";
64         if (Base.Reg.getNode() != 0) Base.Reg.getNode()->dump();
65         else cerr << "nul";
66         cerr << '\n';
67       } else {
68         cerr << " Base.FrameIndex " << Base.FrameIndex << '\n';
69       }
70       if (!isRI) {
71         cerr << "IndexReg ";
72         if (IndexReg.getNode() != 0) IndexReg.getNode()->dump();
73         else cerr << "nul";
74       }
75       cerr << " Disp " << Disp << '\n';
76     }
77   };
78 }
79
80 /// SystemZDAGToDAGISel - SystemZ specific code to select SystemZ machine
81 /// instructions for SelectionDAG operations.
82 ///
83 namespace {
84   class SystemZDAGToDAGISel : public SelectionDAGISel {
85     SystemZTargetLowering &Lowering;
86     const SystemZSubtarget &Subtarget;
87
88     void getAddressOperandsRI(const SystemZRRIAddressMode &AM,
89                             SDValue &Base, SDValue &Disp);
90     void getAddressOperands(const SystemZRRIAddressMode &AM,
91                             SDValue &Base, SDValue &Disp,
92                             SDValue &Index);
93
94   public:
95     SystemZDAGToDAGISel(SystemZTargetMachine &TM, CodeGenOpt::Level OptLevel)
96       : SelectionDAGISel(TM, OptLevel),
97         Lowering(*TM.getTargetLowering()),
98         Subtarget(*TM.getSubtargetImpl()) { }
99
100     virtual void InstructionSelect();
101
102     virtual const char *getPassName() const {
103       return "SystemZ DAG->DAG Pattern Instruction Selection";
104     }
105
106     /// getI8Imm - Return a target constant with the specified value, of type
107     /// i8.
108     inline SDValue getI8Imm(uint64_t Imm) {
109       return CurDAG->getTargetConstant(Imm, MVT::i8);
110     }
111
112     /// getI16Imm - Return a target constant with the specified value, of type
113     /// i16.
114     inline SDValue getI16Imm(uint64_t Imm) {
115       return CurDAG->getTargetConstant(Imm, MVT::i16);
116     }
117
118     /// getI32Imm - Return a target constant with the specified value, of type
119     /// i32.
120     inline SDValue getI32Imm(uint64_t Imm) {
121       return CurDAG->getTargetConstant(Imm, MVT::i32);
122     }
123
124     // Include the pieces autogenerated from the target description.
125     #include "SystemZGenDAGISel.inc"
126
127   private:
128     bool SelectAddrRI12Only(SDValue Op, SDValue& Addr,
129                             SDValue &Base, SDValue &Disp);
130     bool SelectAddrRI12(SDValue Op, SDValue& Addr,
131                         SDValue &Base, SDValue &Disp,
132                         bool is12BitOnly = false);
133     bool SelectAddrRI(SDValue Op, SDValue& Addr,
134                       SDValue &Base, SDValue &Disp);
135     bool SelectAddrRRI12(SDValue Op, SDValue Addr,
136                          SDValue &Base, SDValue &Disp, SDValue &Index);
137     bool SelectAddrRRI20(SDValue Op, SDValue Addr,
138                          SDValue &Base, SDValue &Disp, SDValue &Index);
139     bool SelectLAAddr(SDValue Op, SDValue Addr,
140                       SDValue &Base, SDValue &Disp, SDValue &Index);
141
142     SDNode *Select(SDValue Op);
143
144     bool TryFoldLoad(SDValue P, SDValue N,
145                      SDValue &Base, SDValue &Disp, SDValue &Index);
146
147     bool MatchAddress(SDValue N, SystemZRRIAddressMode &AM,
148                       bool is12Bit, unsigned Depth = 0);
149     bool MatchAddressBase(SDValue N, SystemZRRIAddressMode &AM);
150     bool MatchAddressRI(SDValue N, SystemZRRIAddressMode &AM,
151                         bool is12Bit);
152
153   #ifndef NDEBUG
154     unsigned Indent;
155   #endif
156   };
157 }  // end anonymous namespace
158
159 /// createSystemZISelDag - This pass converts a legalized DAG into a
160 /// SystemZ-specific DAG, ready for instruction scheduling.
161 ///
162 FunctionPass *llvm::createSystemZISelDag(SystemZTargetMachine &TM,
163                                         CodeGenOpt::Level OptLevel) {
164   return new SystemZDAGToDAGISel(TM, OptLevel);
165 }
166
167 /// isImmSExt20 - This method tests to see if the node is either a 32-bit
168 /// or 64-bit immediate, and if the value can be accurately represented as a
169 /// sign extension from a 20-bit value. If so, this returns true and the
170 /// immediate.
171 static bool isImmSExt20(int64_t Val, int64_t &Imm) {
172   if (Val >= -524288 && Val <= 524287) {
173     Imm = Val;
174     return true;
175   }
176   return false;
177 }
178
179 /// isImmZExt12 - This method tests to see if the node is either a 32-bit
180 /// or 64-bit immediate, and if the value can be accurately represented as a
181 /// zero extension from a 12-bit value. If so, this returns true and the
182 /// immediate.
183 static bool isImmZExt12(int64_t Val, int64_t &Imm) {
184   if (Val >= 0 && Val <= 0xFFF) {
185     Imm = Val;
186     return true;
187   }
188   return false;
189 }
190
191 /// MatchAddress - Add the specified node to the specified addressing mode,
192 /// returning true if it cannot be done.  This just pattern matches for the
193 /// addressing mode.
194 bool SystemZDAGToDAGISel::MatchAddress(SDValue N, SystemZRRIAddressMode &AM,
195                                        bool is12Bit, unsigned Depth) {
196   DebugLoc dl = N.getDebugLoc();
197   DOUT << "MatchAddress: "; DEBUG(AM.dump());
198   // Limit recursion.
199   if (Depth > 5)
200     return MatchAddressBase(N, AM);
201
202   // FIXME: We can perform better here. If we have something like
203   // (shift (add A, imm), N), we can try to reassociate stuff and fold shift of
204   // imm into addressing mode.
205   switch (N.getOpcode()) {
206   default: break;
207   case ISD::Constant: {
208     int64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
209     int64_t Imm;
210     bool Match = (is12Bit ?
211                   isImmZExt12(AM.Disp + Val, Imm) :
212                   isImmSExt20(AM.Disp + Val, Imm));
213     if (Match) {
214       AM.Disp = Imm;
215       return false;
216     }
217     break;
218   }
219
220   case ISD::FrameIndex:
221     if (AM.BaseType == SystemZRRIAddressMode::RegBase &&
222         AM.Base.Reg.getNode() == 0) {
223       AM.BaseType = SystemZRRIAddressMode::FrameIndexBase;
224       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
225       return false;
226     }
227     break;
228
229   case ISD::SUB: {
230     // Given A-B, if A can be completely folded into the address and
231     // the index field with the index field unused, use -B as the index.
232     // This is a win if a has multiple parts that can be folded into
233     // the address. Also, this saves a mov if the base register has
234     // other uses, since it avoids a two-address sub instruction, however
235     // it costs an additional mov if the index register has other uses.
236
237     // Test if the LHS of the sub can be folded.
238     SystemZRRIAddressMode Backup = AM;
239     if (MatchAddress(N.getNode()->getOperand(0), AM, is12Bit, Depth+1)) {
240       AM = Backup;
241       break;
242     }
243     // Test if the index field is free for use.
244     if (AM.IndexReg.getNode() || AM.isRI) {
245       AM = Backup;
246       break;
247     }
248
249     // If the base is a register with multiple uses, this transformation may
250     // save a mov. Otherwise it's probably better not to do it.
251     if (AM.BaseType == SystemZRRIAddressMode::RegBase &&
252         (!AM.Base.Reg.getNode() || AM.Base.Reg.getNode()->hasOneUse())) {
253       AM = Backup;
254       break;
255     }
256
257     // Ok, the transformation is legal and appears profitable. Go for it.
258     SDValue RHS = N.getNode()->getOperand(1);
259     SDValue Zero = CurDAG->getConstant(0, N.getValueType());
260     SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
261     AM.IndexReg = Neg;
262
263     // Insert the new nodes into the topological ordering.
264     if (Zero.getNode()->getNodeId() == -1 ||
265         Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
266       CurDAG->RepositionNode(N.getNode(), Zero.getNode());
267       Zero.getNode()->setNodeId(N.getNode()->getNodeId());
268     }
269     if (Neg.getNode()->getNodeId() == -1 ||
270         Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
271       CurDAG->RepositionNode(N.getNode(), Neg.getNode());
272       Neg.getNode()->setNodeId(N.getNode()->getNodeId());
273     }
274     return false;
275   }
276
277   case ISD::ADD: {
278     SystemZRRIAddressMode Backup = AM;
279     if (!MatchAddress(N.getNode()->getOperand(0), AM, is12Bit, Depth+1) &&
280         !MatchAddress(N.getNode()->getOperand(1), AM, is12Bit, Depth+1))
281       return false;
282     AM = Backup;
283     if (!MatchAddress(N.getNode()->getOperand(1), AM, is12Bit, Depth+1) &&
284         !MatchAddress(N.getNode()->getOperand(0), AM, is12Bit, Depth+1))
285       return false;
286     AM = Backup;
287
288     // If we couldn't fold both operands into the address at the same time,
289     // see if we can just put each operand into a register and fold at least
290     // the add.
291     if (!AM.isRI &&
292         AM.BaseType == SystemZRRIAddressMode::RegBase &&
293         !AM.Base.Reg.getNode() && !AM.IndexReg.getNode()) {
294       AM.Base.Reg = N.getNode()->getOperand(0);
295       AM.IndexReg = N.getNode()->getOperand(1);
296       return false;
297     }
298     break;
299   }
300
301   case ISD::OR:
302     // Handle "X | C" as "X + C" iff X is known to have C bits clear.
303     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
304       SystemZRRIAddressMode Backup = AM;
305       int64_t Offset = CN->getSExtValue();
306       int64_t Imm;
307       bool MatchOffset = (is12Bit ?
308                           isImmZExt12(AM.Disp + Offset, Imm) :
309                           isImmSExt20(AM.Disp + Offset, Imm));
310       // The resultant disp must fit in 12 or 20-bits.
311       if (MatchOffset &&
312           // LHS should be an addr mode.
313           !MatchAddress(N.getOperand(0), AM, is12Bit, Depth+1) &&
314           // Check to see if the LHS & C is zero.
315           CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
316         AM.Disp = Imm;
317         return false;
318       }
319       AM = Backup;
320     }
321     break;
322   }
323
324   return MatchAddressBase(N, AM);
325 }
326
327 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
328 /// specified addressing mode without any further recursion.
329 bool SystemZDAGToDAGISel::MatchAddressBase(SDValue N,
330                                            SystemZRRIAddressMode &AM) {
331   // Is the base register already occupied?
332   if (AM.BaseType != SystemZRRIAddressMode::RegBase || AM.Base.Reg.getNode()) {
333     // If so, check to see if the index register is set.
334     if (AM.IndexReg.getNode() == 0 && !AM.isRI) {
335       AM.IndexReg = N;
336       return false;
337     }
338
339     // Otherwise, we cannot select it.
340     return true;
341   }
342
343   // Default, generate it as a register.
344   AM.BaseType = SystemZRRIAddressMode::RegBase;
345   AM.Base.Reg = N;
346   return false;
347 }
348
349 void SystemZDAGToDAGISel::getAddressOperandsRI(const SystemZRRIAddressMode &AM,
350                                                SDValue &Base, SDValue &Disp) {
351   if (AM.BaseType == SystemZRRIAddressMode::RegBase)
352     Base = AM.Base.Reg;
353   else
354     Base = CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy());
355   Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i64);
356 }
357
358 void SystemZDAGToDAGISel::getAddressOperands(const SystemZRRIAddressMode &AM,
359                                              SDValue &Base, SDValue &Disp,
360                                              SDValue &Index) {
361   getAddressOperandsRI(AM, Base, Disp);
362   Index = AM.IndexReg;
363 }
364
365 /// Returns true if the address can be represented by a base register plus
366 /// an unsigned 12-bit displacement [r+imm].
367 bool SystemZDAGToDAGISel::SelectAddrRI12Only(SDValue Op, SDValue& Addr,
368                                              SDValue &Base, SDValue &Disp) {
369   return SelectAddrRI12(Op, Addr, Base, Disp, /*is12BitOnly*/true);
370 }
371
372 bool SystemZDAGToDAGISel::SelectAddrRI12(SDValue Op, SDValue& Addr,
373                                          SDValue &Base, SDValue &Disp,
374                                          bool is12BitOnly) {
375   SystemZRRIAddressMode AM20(/*isRI*/true), AM12(/*isRI*/true);
376   bool Done = false;
377
378   if (!Addr.hasOneUse()) {
379     unsigned Opcode = Addr.getOpcode();
380     if (Opcode != ISD::Constant && Opcode != ISD::FrameIndex) {
381       // If we are able to fold N into addressing mode, then we'll allow it even
382       // if N has multiple uses. In general, addressing computation is used as
383       // addresses by all of its uses. But watch out for CopyToReg uses, that
384       // means the address computation is liveout. It will be computed by a LA
385       // so we want to avoid computing the address twice.
386       for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
387              UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
388         if (UI->getOpcode() == ISD::CopyToReg) {
389           MatchAddressBase(Addr, AM12);
390           Done = true;
391           break;
392         }
393       }
394     }
395   }
396   if (!Done && MatchAddress(Addr, AM12, /* is12Bit */ true))
397     return false;
398
399   // Check, whether we can match stuff using 20-bit displacements
400   if (!Done && !is12BitOnly &&
401       !MatchAddress(Addr, AM20, /* is12Bit */ false))
402     if (AM12.Disp == 0 && AM20.Disp != 0)
403       return false;
404
405   DOUT << "MatchAddress (final): "; DEBUG(AM12.dump());
406
407   MVT VT = Addr.getValueType();
408   if (AM12.BaseType == SystemZRRIAddressMode::RegBase) {
409     if (!AM12.Base.Reg.getNode())
410       AM12.Base.Reg = CurDAG->getRegister(0, VT);
411   }
412
413   assert(AM12.IndexReg.getNode() == 0 && "Invalid reg-imm address mode!");
414
415   getAddressOperandsRI(AM12, Base, Disp);
416
417   return true;
418 }
419
420 /// Returns true if the address can be represented by a base register plus
421 /// a signed 20-bit displacement [r+imm].
422 bool SystemZDAGToDAGISel::SelectAddrRI(SDValue Op, SDValue& Addr,
423                                        SDValue &Base, SDValue &Disp) {
424   SystemZRRIAddressMode AM(/*isRI*/true);
425   bool Done = false;
426
427   if (!Addr.hasOneUse()) {
428     unsigned Opcode = Addr.getOpcode();
429     if (Opcode != ISD::Constant && Opcode != ISD::FrameIndex) {
430       // If we are able to fold N into addressing mode, then we'll allow it even
431       // if N has multiple uses. In general, addressing computation is used as
432       // addresses by all of its uses. But watch out for CopyToReg uses, that
433       // means the address computation is liveout. It will be computed by a LA
434       // so we want to avoid computing the address twice.
435       for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
436              UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
437         if (UI->getOpcode() == ISD::CopyToReg) {
438           MatchAddressBase(Addr, AM);
439           Done = true;
440           break;
441         }
442       }
443     }
444   }
445   if (!Done && MatchAddress(Addr, AM, /* is12Bit */ false))
446     return false;
447
448   DOUT << "MatchAddress (final): "; DEBUG(AM.dump());
449
450   MVT VT = Addr.getValueType();
451   if (AM.BaseType == SystemZRRIAddressMode::RegBase) {
452     if (!AM.Base.Reg.getNode())
453       AM.Base.Reg = CurDAG->getRegister(0, VT);
454   }
455
456   assert(AM.IndexReg.getNode() == 0 && "Invalid reg-imm address mode!");
457
458   getAddressOperandsRI(AM, Base, Disp);
459
460   return true;
461 }
462
463 /// Returns true if the address can be represented by a base register plus
464 /// index register plus an unsigned 12-bit displacement [base + idx + imm].
465 bool SystemZDAGToDAGISel::SelectAddrRRI12(SDValue Op, SDValue Addr,
466                                 SDValue &Base, SDValue &Disp, SDValue &Index) {
467   SystemZRRIAddressMode AM20, AM12;
468   bool Done = false;
469
470   if (!Addr.hasOneUse()) {
471     unsigned Opcode = Addr.getOpcode();
472     if (Opcode != ISD::Constant && Opcode != ISD::FrameIndex) {
473       // If we are able to fold N into addressing mode, then we'll allow it even
474       // if N has multiple uses. In general, addressing computation is used as
475       // addresses by all of its uses. But watch out for CopyToReg uses, that
476       // means the address computation is liveout. It will be computed by a LA
477       // so we want to avoid computing the address twice.
478       for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
479              UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
480         if (UI->getOpcode() == ISD::CopyToReg) {
481           MatchAddressBase(Addr, AM12);
482           Done = true;
483           break;
484         }
485       }
486     }
487   }
488   if (!Done && MatchAddress(Addr, AM12, /* is12Bit */ true))
489     return false;
490
491   // Check, whether we can match stuff using 20-bit displacements
492   if (!Done && !MatchAddress(Addr, AM20, /* is12Bit */ false))
493     if (AM12.Disp == 0 && AM20.Disp != 0)
494       return false;
495
496   DOUT << "MatchAddress (final): "; DEBUG(AM12.dump());
497
498   MVT VT = Addr.getValueType();
499   if (AM12.BaseType == SystemZRRIAddressMode::RegBase) {
500     if (!AM12.Base.Reg.getNode())
501       AM12.Base.Reg = CurDAG->getRegister(0, VT);
502   }
503
504   if (!AM12.IndexReg.getNode())
505     AM12.IndexReg = CurDAG->getRegister(0, VT);
506
507   getAddressOperands(AM12, Base, Disp, Index);
508
509   return true;
510 }
511
512 /// Returns true if the address can be represented by a base register plus
513 /// index register plus a signed 20-bit displacement [base + idx + imm].
514 bool SystemZDAGToDAGISel::SelectAddrRRI20(SDValue Op, SDValue Addr,
515                                 SDValue &Base, SDValue &Disp, SDValue &Index) {
516   SystemZRRIAddressMode AM;
517   bool Done = false;
518
519   if (!Addr.hasOneUse()) {
520     unsigned Opcode = Addr.getOpcode();
521     if (Opcode != ISD::Constant && Opcode != ISD::FrameIndex) {
522       // If we are able to fold N into addressing mode, then we'll allow it even
523       // if N has multiple uses. In general, addressing computation is used as
524       // addresses by all of its uses. But watch out for CopyToReg uses, that
525       // means the address computation is liveout. It will be computed by a LA
526       // so we want to avoid computing the address twice.
527       for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
528              UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
529         if (UI->getOpcode() == ISD::CopyToReg) {
530           MatchAddressBase(Addr, AM);
531           Done = true;
532           break;
533         }
534       }
535     }
536   }
537   if (!Done && MatchAddress(Addr, AM, /* is12Bit */ false))
538     return false;
539
540   DOUT << "MatchAddress (final): "; DEBUG(AM.dump());
541
542   MVT VT = Addr.getValueType();
543   if (AM.BaseType == SystemZRRIAddressMode::RegBase) {
544     if (!AM.Base.Reg.getNode())
545       AM.Base.Reg = CurDAG->getRegister(0, VT);
546   }
547
548   if (!AM.IndexReg.getNode())
549     AM.IndexReg = CurDAG->getRegister(0, VT);
550
551   getAddressOperands(AM, Base, Disp, Index);
552
553   return true;
554 }
555
556 /// SelectLAAddr - it calls SelectAddr and determines if the maximal addressing
557 /// mode it matches can be cost effectively emitted as an LA/LAY instruction.
558 bool SystemZDAGToDAGISel::SelectLAAddr(SDValue Op, SDValue Addr,
559                                   SDValue &Base, SDValue &Disp, SDValue &Index) {
560   SystemZRRIAddressMode AM;
561
562   if (MatchAddress(Addr, AM, false))
563     return false;
564
565   MVT VT = Addr.getValueType();
566   unsigned Complexity = 0;
567   if (AM.BaseType == SystemZRRIAddressMode::RegBase)
568     if (AM.Base.Reg.getNode())
569       Complexity = 1;
570     else
571       AM.Base.Reg = CurDAG->getRegister(0, VT);
572   else if (AM.BaseType == SystemZRRIAddressMode::FrameIndexBase)
573     Complexity = 4;
574
575   if (AM.IndexReg.getNode())
576     Complexity += 1;
577   else
578     AM.IndexReg = CurDAG->getRegister(0, VT);
579
580   if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
581     Complexity += 1;
582
583   if (Complexity > 2) {
584     getAddressOperands(AM, Base, Disp, Index);
585     return true;
586   }
587
588   return false;
589 }
590
591 bool SystemZDAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
592                                  SDValue &Base, SDValue &Disp, SDValue &Index) {
593   if (ISD::isNON_EXTLoad(N.getNode()) &&
594       N.hasOneUse() &&
595       IsLegalAndProfitableToFold(N.getNode(), P.getNode(), P.getNode()))
596     return SelectAddrRRI20(P, N.getOperand(1), Base, Disp, Index);
597   return false;
598 }
599
600 /// InstructionSelect - This callback is invoked by
601 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
602 void SystemZDAGToDAGISel::InstructionSelect() {
603   DEBUG(BB->dump());
604
605   // Codegen the basic block.
606 #ifndef NDEBUG
607   DOUT << "===== Instruction selection begins:\n";
608   Indent = 0;
609 #endif
610   SelectRoot(*CurDAG);
611 #ifndef NDEBUG
612   DOUT << "===== Instruction selection ends:\n";
613 #endif
614
615   CurDAG->RemoveDeadNodes();
616 }
617
618 SDNode *SystemZDAGToDAGISel::Select(SDValue Op) {
619   SDNode *Node = Op.getNode();
620   MVT NVT = Node->getValueType(0);
621   DebugLoc dl = Op.getDebugLoc();
622   unsigned Opcode = Node->getOpcode();
623
624   // Dump information about the Node being selected
625   #ifndef NDEBUG
626   DOUT << std::string(Indent, ' ') << "Selecting: ";
627   DEBUG(Node->dump(CurDAG));
628   DOUT << "\n";
629   Indent += 2;
630   #endif
631
632   // If we have a custom node, we already have selected!
633   if (Node->isMachineOpcode()) {
634     #ifndef NDEBUG
635     DOUT << std::string(Indent-2, ' ') << "== ";
636     DEBUG(Node->dump(CurDAG));
637     DOUT << "\n";
638     Indent -= 2;
639     #endif
640     return NULL; // Already selected.
641   }
642
643   switch (Opcode) {
644   default: break;
645   case ISD::SDIVREM: {
646     unsigned Opc, MOpc;
647     SDValue N0 = Node->getOperand(0);
648     SDValue N1 = Node->getOperand(1);
649
650     MVT ResVT;
651     bool is32Bit = false;
652     switch (NVT.getSimpleVT()) {
653       default: assert(0 && "Unsupported VT!");
654       case MVT::i32:
655         Opc = SystemZ::SDIVREM32r; MOpc = SystemZ::SDIVREM32m;
656         ResVT = MVT::v2i64;
657         is32Bit = true;
658         break;
659       case MVT::i64:
660         Opc = SystemZ::SDIVREM64r; MOpc = SystemZ::SDIVREM64m;
661         ResVT = MVT::v2i64;
662         break;
663     }
664
665     SDValue Tmp0, Tmp1, Tmp2;
666     bool foldedLoad = TryFoldLoad(Op, N1, Tmp0, Tmp1, Tmp2);
667
668     // Prepare the dividend
669     SDNode *Dividend;
670     if (is32Bit)
671       Dividend = CurDAG->getTargetNode(SystemZ::MOVSX64rr32, dl, MVT::i64, N0);
672     else
673       Dividend = N0.getNode();
674
675     // Insert prepared dividend into suitable 'subreg'
676     SDNode *Tmp = CurDAG->getTargetNode(TargetInstrInfo::IMPLICIT_DEF,
677                                         dl, ResVT);
678     Dividend =
679       CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG, dl, ResVT,
680                             SDValue(Tmp, 0), SDValue(Dividend, 0),
681                             CurDAG->getTargetConstant(subreg_odd, MVT::i32));
682
683     SDNode *Result;
684     SDValue DivVal = SDValue(Dividend, 0);
685     if (foldedLoad) {
686       SDValue Ops[] = { DivVal, Tmp0, Tmp1, Tmp2, N1.getOperand(0) };
687       Result = CurDAG->getTargetNode(MOpc, dl, ResVT, Ops, array_lengthof(Ops));
688       // Update the chain.
689       ReplaceUses(N1.getValue(1), SDValue(Result, 0));
690     } else {
691       Result = CurDAG->getTargetNode(Opc, dl, ResVT, SDValue(Dividend, 0), N1);
692     }
693
694     // Copy the division (odd subreg) result, if it is needed.
695     if (!Op.getValue(0).use_empty()) {
696       unsigned SubRegIdx = (is32Bit ? subreg_odd32 : subreg_odd);
697       SDNode *Div = CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,
698                                           dl, NVT,
699                                           SDValue(Result, 0),
700                                           CurDAG->getTargetConstant(SubRegIdx,
701                                                                     MVT::i32));
702
703       ReplaceUses(Op.getValue(0), SDValue(Div, 0));
704       #ifndef NDEBUG
705       DOUT << std::string(Indent-2, ' ') << "=> ";
706       DEBUG(Result->dump(CurDAG));
707       DOUT << "\n";
708       #endif
709     }
710
711     // Copy the remainder (even subreg) result, if it is needed.
712     if (!Op.getValue(1).use_empty()) {
713       unsigned SubRegIdx = (is32Bit ? subreg_even32 : subreg_even);
714       SDNode *Rem = CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,
715                                           dl, NVT,
716                                           SDValue(Result, 0),
717                                           CurDAG->getTargetConstant(SubRegIdx,
718                                                                     MVT::i32));
719
720       ReplaceUses(Op.getValue(1), SDValue(Rem, 0));
721       #ifndef NDEBUG
722       DOUT << std::string(Indent-2, ' ') << "=> ";
723       DEBUG(Result->dump(CurDAG));
724       DOUT << "\n";
725       #endif
726     }
727
728 #ifndef NDEBUG
729     Indent -= 2;
730 #endif
731
732     return NULL;
733   }
734   case ISD::UDIVREM: {
735     unsigned Opc, MOpc, ClrOpc;
736     SDValue N0 = Node->getOperand(0);
737     SDValue N1 = Node->getOperand(1);
738     MVT ResVT;
739
740     bool is32Bit = false;
741     switch (NVT.getSimpleVT()) {
742       default: assert(0 && "Unsupported VT!");
743       case MVT::i32:
744         Opc = SystemZ::UDIVREM32r; MOpc = SystemZ::UDIVREM32m;
745         ClrOpc = SystemZ::MOV64Pr0_even;
746         ResVT = MVT::v2i32;
747         is32Bit = true;
748         break;
749       case MVT::i64:
750         Opc = SystemZ::UDIVREM64r; MOpc = SystemZ::UDIVREM64m;
751         ClrOpc = SystemZ::MOV128r0_even;
752         ResVT = MVT::v2i64;
753         break;
754     }
755
756     SDValue Tmp0, Tmp1, Tmp2;
757     bool foldedLoad = TryFoldLoad(Op, N1, Tmp0, Tmp1, Tmp2);
758
759     // Prepare the dividend
760     SDNode *Dividend = N0.getNode();
761
762     // Insert prepared dividend into suitable 'subreg'
763     SDNode *Tmp = CurDAG->getTargetNode(TargetInstrInfo::IMPLICIT_DEF,
764                                         dl, ResVT);
765     {
766       unsigned SubRegIdx = (is32Bit ? subreg_odd32 : subreg_odd);
767       Dividend =
768         CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG, dl, ResVT,
769                               SDValue(Tmp, 0), SDValue(Dividend, 0),
770                               CurDAG->getTargetConstant(SubRegIdx, MVT::i32));
771     }
772
773     // Zero out even subreg
774     Dividend = CurDAG->getTargetNode(ClrOpc, dl, ResVT, SDValue(Dividend, 0));
775
776     SDValue DivVal = SDValue(Dividend, 0);
777     SDNode *Result;
778     if (foldedLoad) {
779       SDValue Ops[] = { DivVal, Tmp0, Tmp1, Tmp2, N1.getOperand(0) };
780       Result = CurDAG->getTargetNode(MOpc, dl,ResVT,
781                                      Ops, array_lengthof(Ops));
782       // Update the chain.
783       ReplaceUses(N1.getValue(1), SDValue(Result, 0));
784     } else {
785       Result = CurDAG->getTargetNode(Opc, dl, ResVT, DivVal, N1);
786     }
787
788     // Copy the division (odd subreg) result, if it is needed.
789     if (!Op.getValue(0).use_empty()) {
790       unsigned SubRegIdx = (is32Bit ? subreg_odd32 : subreg_odd);
791       SDNode *Div = CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,
792                                           dl, NVT,
793                                           SDValue(Result, 0),
794                                           CurDAG->getTargetConstant(SubRegIdx,
795                                                                     MVT::i32));
796       ReplaceUses(Op.getValue(0), SDValue(Div, 0));
797       #ifndef NDEBUG
798       DOUT << std::string(Indent-2, ' ') << "=> ";
799       DEBUG(Result->dump(CurDAG));
800       DOUT << "\n";
801       #endif
802     }
803
804     // Copy the remainder (even subreg) result, if it is needed.
805     if (!Op.getValue(1).use_empty()) {
806       unsigned SubRegIdx = (is32Bit ? subreg_even32 : subreg_even);
807       SDNode *Rem = CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,
808                                           dl, NVT,
809                                           SDValue(Result, 0),
810                                           CurDAG->getTargetConstant(SubRegIdx,
811                                                                     MVT::i32));
812       ReplaceUses(Op.getValue(1), SDValue(Rem, 0));
813       #ifndef NDEBUG
814       DOUT << std::string(Indent-2, ' ') << "=> ";
815       DEBUG(Result->dump(CurDAG));
816       DOUT << "\n";
817       #endif
818     }
819
820 #ifndef NDEBUG
821     Indent -= 2;
822 #endif
823
824     return NULL;
825   }
826   }
827
828   // Select the default instruction
829   SDNode *ResNode = SelectCode(Op);
830
831   #ifndef NDEBUG
832   DOUT << std::string(Indent-2, ' ') << "=> ";
833   if (ResNode == NULL || ResNode == Op.getNode())
834     DEBUG(Op.getNode()->dump(CurDAG));
835   else
836     DEBUG(ResNode->dump(CurDAG));
837   DOUT << "\n";
838   Indent -= 2;
839   #endif
840
841   return ResNode;
842 }