ISelDAG: spot chain cycles involving MachineNodes
[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 "SystemZTargetMachine.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/CodeGen/SelectionDAGISel.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/raw_ostream.h"
19
20 using namespace llvm;
21
22 namespace {
23 // Used to build addressing modes.
24 struct SystemZAddressingMode {
25   // The shape of the address.
26   enum AddrForm {
27     // base+displacement
28     FormBD,
29
30     // base+displacement+index for load and store operands
31     FormBDXNormal,
32
33     // base+displacement+index for load address operands
34     FormBDXLA,
35
36     // base+displacement+index+ADJDYNALLOC
37     FormBDXDynAlloc
38   };
39   AddrForm Form;
40
41   // The type of displacement.  The enum names here correspond directly
42   // to the definitions in SystemZOperand.td.  We could split them into
43   // flags -- single/pair, 128-bit, etc. -- but it hardly seems worth it.
44   enum DispRange {
45     Disp12Only,
46     Disp12Pair,
47     Disp20Only,
48     Disp20Only128,
49     Disp20Pair
50   };
51   DispRange DR;
52
53   // The parts of the address.  The address is equivalent to:
54   //
55   //     Base + Disp + Index + (IncludesDynAlloc ? ADJDYNALLOC : 0)
56   SDValue Base;
57   int64_t Disp;
58   SDValue Index;
59   bool IncludesDynAlloc;
60
61   SystemZAddressingMode(AddrForm form, DispRange dr)
62     : Form(form), DR(dr), Base(), Disp(0), Index(),
63       IncludesDynAlloc(false) {}
64
65   // True if the address can have an index register.
66   bool hasIndexField() { return Form != FormBD; }
67
68   // True if the address can (and must) include ADJDYNALLOC.
69   bool isDynAlloc() { return Form == FormBDXDynAlloc; }
70
71   void dump() {
72     errs() << "SystemZAddressingMode " << this << '\n';
73
74     errs() << " Base ";
75     if (Base.getNode() != 0)
76       Base.getNode()->dump();
77     else
78       errs() << "null\n";
79
80     if (hasIndexField()) {
81       errs() << " Index ";
82       if (Index.getNode() != 0)
83         Index.getNode()->dump();
84       else
85         errs() << "null\n";
86     }
87
88     errs() << " Disp " << Disp;
89     if (IncludesDynAlloc)
90       errs() << " + ADJDYNALLOC";
91     errs() << '\n';
92   }
93 };
94
95 // Return a mask with Count low bits set.
96 static uint64_t allOnes(unsigned int Count) {
97   return Count == 0 ? 0 : (uint64_t(1) << (Count - 1) << 1) - 1;
98 }
99
100 // Represents operands 2 to 5 of the ROTATE AND ... SELECTED BITS operation
101 // given by Opcode.  The operands are: Input (R2), Start (I3), End (I4) and
102 // Rotate (I5).  The combined operand value is effectively:
103 //
104 //   (or (rotl Input, Rotate), ~Mask)
105 //
106 // for RNSBG and:
107 //
108 //   (and (rotl Input, Rotate), Mask)
109 //
110 // otherwise.  The value has BitSize bits.
111 struct RxSBGOperands {
112   RxSBGOperands(unsigned Op, SDValue N)
113     : Opcode(Op), BitSize(N.getValueType().getSizeInBits()),
114       Mask(allOnes(BitSize)), Input(N), Start(64 - BitSize), End(63),
115       Rotate(0) {}
116
117   unsigned Opcode;
118   unsigned BitSize;
119   uint64_t Mask;
120   SDValue Input;
121   unsigned Start;
122   unsigned End;
123   unsigned Rotate;
124 };
125
126 class SystemZDAGToDAGISel : public SelectionDAGISel {
127   const SystemZTargetLowering &Lowering;
128   const SystemZSubtarget &Subtarget;
129
130   // Used by SystemZOperands.td to create integer constants.
131   inline SDValue getImm(const SDNode *Node, uint64_t Imm) {
132     return CurDAG->getTargetConstant(Imm, Node->getValueType(0));
133   }
134
135   const SystemZTargetMachine &getTargetMachine() const {
136     return static_cast<const SystemZTargetMachine &>(TM);
137   }
138
139   const SystemZInstrInfo *getInstrInfo() const {
140     return getTargetMachine().getInstrInfo();
141   }
142
143   // Try to fold more of the base or index of AM into AM, where IsBase
144   // selects between the base and index.
145   bool expandAddress(SystemZAddressingMode &AM, bool IsBase);
146
147   // Try to describe N in AM, returning true on success.
148   bool selectAddress(SDValue N, SystemZAddressingMode &AM);
149
150   // Extract individual target operands from matched address AM.
151   void getAddressOperands(const SystemZAddressingMode &AM, EVT VT,
152                           SDValue &Base, SDValue &Disp);
153   void getAddressOperands(const SystemZAddressingMode &AM, EVT VT,
154                           SDValue &Base, SDValue &Disp, SDValue &Index);
155
156   // Try to match Addr as a FormBD address with displacement type DR.
157   // Return true on success, storing the base and displacement in
158   // Base and Disp respectively.
159   bool selectBDAddr(SystemZAddressingMode::DispRange DR, SDValue Addr,
160                     SDValue &Base, SDValue &Disp);
161
162   // Try to match Addr as a FormBDX address with displacement type DR.
163   // Return true on success and if the result had no index.  Store the
164   // base and displacement in Base and Disp respectively.
165   bool selectMVIAddr(SystemZAddressingMode::DispRange DR, SDValue Addr,
166                      SDValue &Base, SDValue &Disp);
167
168   // Try to match Addr as a FormBDX* address of form Form with
169   // displacement type DR.  Return true on success, storing the base,
170   // displacement and index in Base, Disp and Index respectively.
171   bool selectBDXAddr(SystemZAddressingMode::AddrForm Form,
172                      SystemZAddressingMode::DispRange DR, SDValue Addr,
173                      SDValue &Base, SDValue &Disp, SDValue &Index);
174
175   // PC-relative address matching routines used by SystemZOperands.td.
176   bool selectPCRelAddress(SDValue Addr, SDValue &Target) {
177     if (Addr.getOpcode() == SystemZISD::PCREL_WRAPPER) {
178       Target = Addr.getOperand(0);
179       return true;
180     }
181     return false;
182   }
183
184   // BD matching routines used by SystemZOperands.td.
185   bool selectBDAddr12Only(SDValue Addr, SDValue &Base, SDValue &Disp) {
186     return selectBDAddr(SystemZAddressingMode::Disp12Only, Addr, Base, Disp);
187   }
188   bool selectBDAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp) {
189     return selectBDAddr(SystemZAddressingMode::Disp12Pair, Addr, Base, Disp);
190   }
191   bool selectBDAddr20Only(SDValue Addr, SDValue &Base, SDValue &Disp) {
192     return selectBDAddr(SystemZAddressingMode::Disp20Only, Addr, Base, Disp);
193   }
194   bool selectBDAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp) {
195     return selectBDAddr(SystemZAddressingMode::Disp20Pair, Addr, Base, Disp);
196   }
197
198   // MVI matching routines used by SystemZOperands.td.
199   bool selectMVIAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp) {
200     return selectMVIAddr(SystemZAddressingMode::Disp12Pair, Addr, Base, Disp);
201   }
202   bool selectMVIAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp) {
203     return selectMVIAddr(SystemZAddressingMode::Disp20Pair, Addr, Base, Disp);
204   }
205
206   // BDX matching routines used by SystemZOperands.td.
207   bool selectBDXAddr12Only(SDValue Addr, SDValue &Base, SDValue &Disp,
208                            SDValue &Index) {
209     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
210                          SystemZAddressingMode::Disp12Only,
211                          Addr, Base, Disp, Index);
212   }
213   bool selectBDXAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
214                            SDValue &Index) {
215     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
216                          SystemZAddressingMode::Disp12Pair,
217                          Addr, Base, Disp, Index);
218   }
219   bool selectDynAlloc12Only(SDValue Addr, SDValue &Base, SDValue &Disp,
220                             SDValue &Index) {
221     return selectBDXAddr(SystemZAddressingMode::FormBDXDynAlloc,
222                          SystemZAddressingMode::Disp12Only,
223                          Addr, Base, Disp, Index);
224   }
225   bool selectBDXAddr20Only(SDValue Addr, SDValue &Base, SDValue &Disp,
226                            SDValue &Index) {
227     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
228                          SystemZAddressingMode::Disp20Only,
229                          Addr, Base, Disp, Index);
230   }
231   bool selectBDXAddr20Only128(SDValue Addr, SDValue &Base, SDValue &Disp,
232                               SDValue &Index) {
233     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
234                          SystemZAddressingMode::Disp20Only128,
235                          Addr, Base, Disp, Index);
236   }
237   bool selectBDXAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
238                            SDValue &Index) {
239     return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
240                          SystemZAddressingMode::Disp20Pair,
241                          Addr, Base, Disp, Index);
242   }
243   bool selectLAAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
244                           SDValue &Index) {
245     return selectBDXAddr(SystemZAddressingMode::FormBDXLA,
246                          SystemZAddressingMode::Disp12Pair,
247                          Addr, Base, Disp, Index);
248   }
249   bool selectLAAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
250                           SDValue &Index) {
251     return selectBDXAddr(SystemZAddressingMode::FormBDXLA,
252                          SystemZAddressingMode::Disp20Pair,
253                          Addr, Base, Disp, Index);
254   }
255
256   // Check whether (or Op (and X InsertMask)) is effectively an insertion
257   // of X into bits InsertMask of some Y != Op.  Return true if so and
258   // set Op to that Y.
259   bool detectOrAndInsertion(SDValue &Op, uint64_t InsertMask);
260
261   // Try to update RxSBG so that only the bits of RxSBG.Input in Mask are used.
262   // Return true on success.
263   bool refineRxSBGMask(RxSBGOperands &RxSBG, uint64_t Mask);
264
265   // Try to fold some of RxSBG.Input into other fields of RxSBG.
266   // Return true on success.
267   bool expandRxSBG(RxSBGOperands &RxSBG);
268
269   // Return an undefined i64 value.
270   SDValue getUNDEF64(SDLoc DL);
271
272   // Convert N to VT, if it isn't already.
273   SDValue convertTo(SDLoc DL, EVT VT, SDValue N);
274
275   // Try to implement AND or shift node N using RISBG with the zero flag set.
276   // Return the selected node on success, otherwise return null.
277   SDNode *tryRISBGZero(SDNode *N);
278
279   // Try to use RISBG or Opcode to implement OR or XOR node N.
280   // Return the selected node on success, otherwise return null.
281   SDNode *tryRxSBG(SDNode *N, unsigned Opcode);
282
283   // If Op0 is null, then Node is a constant that can be loaded using:
284   //
285   //   (Opcode UpperVal LowerVal)
286   //
287   // If Op0 is nonnull, then Node can be implemented using:
288   //
289   //   (Opcode (Opcode Op0 UpperVal) LowerVal)
290   SDNode *splitLargeImmediate(unsigned Opcode, SDNode *Node, SDValue Op0,
291                               uint64_t UpperVal, uint64_t LowerVal);
292
293   // N is a (store (load Y), X) pattern.  Return true if it can use an MVC
294   // from Y to X.
295   bool storeLoadCanUseMVC(SDNode *N) const;
296
297   // N is a (store (op (load A[0]), (load A[1])), X) pattern.  Return true
298   // if A[1 - I] == X and if N can use a block operation like NC from A[I]
299   // to X.
300   bool storeLoadCanUseBlockBinary(SDNode *N, unsigned I) const;
301
302 public:
303   SystemZDAGToDAGISel(SystemZTargetMachine &TM, CodeGenOpt::Level OptLevel)
304     : SelectionDAGISel(TM, OptLevel),
305       Lowering(*TM.getTargetLowering()),
306       Subtarget(*TM.getSubtargetImpl()) { }
307
308   // Override MachineFunctionPass.
309   virtual const char *getPassName() const LLVM_OVERRIDE {
310     return "SystemZ DAG->DAG Pattern Instruction Selection";
311   }
312
313   // Override SelectionDAGISel.
314   virtual SDNode *Select(SDNode *Node) LLVM_OVERRIDE;
315   virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
316                                             char ConstraintCode,
317                                             std::vector<SDValue> &OutOps)
318     LLVM_OVERRIDE;
319
320   // Include the pieces autogenerated from the target description.
321   #include "SystemZGenDAGISel.inc"
322 };
323 } // end anonymous namespace
324
325 FunctionPass *llvm::createSystemZISelDag(SystemZTargetMachine &TM,
326                                          CodeGenOpt::Level OptLevel) {
327   return new SystemZDAGToDAGISel(TM, OptLevel);
328 }
329
330 // Return true if Val should be selected as a displacement for an address
331 // with range DR.  Here we're interested in the range of both the instruction
332 // described by DR and of any pairing instruction.
333 static bool selectDisp(SystemZAddressingMode::DispRange DR, int64_t Val) {
334   switch (DR) {
335   case SystemZAddressingMode::Disp12Only:
336     return isUInt<12>(Val);
337
338   case SystemZAddressingMode::Disp12Pair:
339   case SystemZAddressingMode::Disp20Only:
340   case SystemZAddressingMode::Disp20Pair:
341     return isInt<20>(Val);
342
343   case SystemZAddressingMode::Disp20Only128:
344     return isInt<20>(Val) && isInt<20>(Val + 8);
345   }
346   llvm_unreachable("Unhandled displacement range");
347 }
348
349 // Change the base or index in AM to Value, where IsBase selects
350 // between the base and index.
351 static void changeComponent(SystemZAddressingMode &AM, bool IsBase,
352                             SDValue Value) {
353   if (IsBase)
354     AM.Base = Value;
355   else
356     AM.Index = Value;
357 }
358
359 // The base or index of AM is equivalent to Value + ADJDYNALLOC,
360 // where IsBase selects between the base and index.  Try to fold the
361 // ADJDYNALLOC into AM.
362 static bool expandAdjDynAlloc(SystemZAddressingMode &AM, bool IsBase,
363                               SDValue Value) {
364   if (AM.isDynAlloc() && !AM.IncludesDynAlloc) {
365     changeComponent(AM, IsBase, Value);
366     AM.IncludesDynAlloc = true;
367     return true;
368   }
369   return false;
370 }
371
372 // The base of AM is equivalent to Base + Index.  Try to use Index as
373 // the index register.
374 static bool expandIndex(SystemZAddressingMode &AM, SDValue Base,
375                         SDValue Index) {
376   if (AM.hasIndexField() && !AM.Index.getNode()) {
377     AM.Base = Base;
378     AM.Index = Index;
379     return true;
380   }
381   return false;
382 }
383
384 // The base or index of AM is equivalent to Op0 + Op1, where IsBase selects
385 // between the base and index.  Try to fold Op1 into AM's displacement.
386 static bool expandDisp(SystemZAddressingMode &AM, bool IsBase,
387                        SDValue Op0, ConstantSDNode *Op1) {
388   // First try adjusting the displacement.
389   int64_t TestDisp = AM.Disp + Op1->getSExtValue();
390   if (selectDisp(AM.DR, TestDisp)) {
391     changeComponent(AM, IsBase, Op0);
392     AM.Disp = TestDisp;
393     return true;
394   }
395
396   // We could consider forcing the displacement into a register and
397   // using it as an index, but it would need to be carefully tuned.
398   return false;
399 }
400
401 bool SystemZDAGToDAGISel::expandAddress(SystemZAddressingMode &AM,
402                                         bool IsBase) {
403   SDValue N = IsBase ? AM.Base : AM.Index;
404   unsigned Opcode = N.getOpcode();
405   if (Opcode == ISD::TRUNCATE) {
406     N = N.getOperand(0);
407     Opcode = N.getOpcode();
408   }
409   if (Opcode == ISD::ADD || CurDAG->isBaseWithConstantOffset(N)) {
410     SDValue Op0 = N.getOperand(0);
411     SDValue Op1 = N.getOperand(1);
412
413     unsigned Op0Code = Op0->getOpcode();
414     unsigned Op1Code = Op1->getOpcode();
415
416     if (Op0Code == SystemZISD::ADJDYNALLOC)
417       return expandAdjDynAlloc(AM, IsBase, Op1);
418     if (Op1Code == SystemZISD::ADJDYNALLOC)
419       return expandAdjDynAlloc(AM, IsBase, Op0);
420
421     if (Op0Code == ISD::Constant)
422       return expandDisp(AM, IsBase, Op1, cast<ConstantSDNode>(Op0));
423     if (Op1Code == ISD::Constant)
424       return expandDisp(AM, IsBase, Op0, cast<ConstantSDNode>(Op1));
425
426     if (IsBase && expandIndex(AM, Op0, Op1))
427       return true;
428   }
429   return false;
430 }
431
432 // Return true if an instruction with displacement range DR should be
433 // used for displacement value Val.  selectDisp(DR, Val) must already hold.
434 static bool isValidDisp(SystemZAddressingMode::DispRange DR, int64_t Val) {
435   assert(selectDisp(DR, Val) && "Invalid displacement");
436   switch (DR) {
437   case SystemZAddressingMode::Disp12Only:
438   case SystemZAddressingMode::Disp20Only:
439   case SystemZAddressingMode::Disp20Only128:
440     return true;
441
442   case SystemZAddressingMode::Disp12Pair:
443     // Use the other instruction if the displacement is too large.
444     return isUInt<12>(Val);
445
446   case SystemZAddressingMode::Disp20Pair:
447     // Use the other instruction if the displacement is small enough.
448     return !isUInt<12>(Val);
449   }
450   llvm_unreachable("Unhandled displacement range");
451 }
452
453 // Return true if Base + Disp + Index should be performed by LA(Y).
454 static bool shouldUseLA(SDNode *Base, int64_t Disp, SDNode *Index) {
455   // Don't use LA(Y) for constants.
456   if (!Base)
457     return false;
458
459   // Always use LA(Y) for frame addresses, since we know that the destination
460   // register is almost always (perhaps always) going to be different from
461   // the frame register.
462   if (Base->getOpcode() == ISD::FrameIndex)
463     return true;
464
465   if (Disp) {
466     // Always use LA(Y) if there is a base, displacement and index.
467     if (Index)
468       return true;
469
470     // Always use LA if the displacement is small enough.  It should always
471     // be no worse than AGHI (and better if it avoids a move).
472     if (isUInt<12>(Disp))
473       return true;
474
475     // For similar reasons, always use LAY if the constant is too big for AGHI.
476     // LAY should be no worse than AGFI.
477     if (!isInt<16>(Disp))
478       return true;
479   } else {
480     // Don't use LA for plain registers.
481     if (!Index)
482       return false;
483
484     // Don't use LA for plain addition if the index operand is only used
485     // once.  It should be a natural two-operand addition in that case.
486     if (Index->hasOneUse())
487       return false;
488
489     // Prefer addition if the second operation is sign-extended, in the
490     // hope of using AGF.
491     unsigned IndexOpcode = Index->getOpcode();
492     if (IndexOpcode == ISD::SIGN_EXTEND ||
493         IndexOpcode == ISD::SIGN_EXTEND_INREG)
494       return false;
495   }
496
497   // Don't use LA for two-operand addition if either operand is only
498   // used once.  The addition instructions are better in that case.
499   if (Base->hasOneUse())
500     return false;
501
502   return true;
503 }
504
505 // Return true if Addr is suitable for AM, updating AM if so.
506 bool SystemZDAGToDAGISel::selectAddress(SDValue Addr,
507                                         SystemZAddressingMode &AM) {
508   // Start out assuming that the address will need to be loaded separately,
509   // then try to extend it as much as we can.
510   AM.Base = Addr;
511
512   // First try treating the address as a constant.
513   if (Addr.getOpcode() == ISD::Constant &&
514       expandDisp(AM, true, SDValue(), cast<ConstantSDNode>(Addr)))
515     ;
516   else
517     // Otherwise try expanding each component.
518     while (expandAddress(AM, true) ||
519            (AM.Index.getNode() && expandAddress(AM, false)))
520       continue;
521
522   // Reject cases where it isn't profitable to use LA(Y).
523   if (AM.Form == SystemZAddressingMode::FormBDXLA &&
524       !shouldUseLA(AM.Base.getNode(), AM.Disp, AM.Index.getNode()))
525     return false;
526
527   // Reject cases where the other instruction in a pair should be used.
528   if (!isValidDisp(AM.DR, AM.Disp))
529     return false;
530
531   // Make sure that ADJDYNALLOC is included where necessary.
532   if (AM.isDynAlloc() && !AM.IncludesDynAlloc)
533     return false;
534
535   DEBUG(AM.dump());
536   return true;
537 }
538
539 // Insert a node into the DAG at least before Pos.  This will reposition
540 // the node as needed, and will assign it a node ID that is <= Pos's ID.
541 // Note that this does *not* preserve the uniqueness of node IDs!
542 // The selection DAG must no longer depend on their uniqueness when this
543 // function is used.
544 static void insertDAGNode(SelectionDAG *DAG, SDNode *Pos, SDValue N) {
545   if (N.getNode()->getNodeId() == -1 ||
546       N.getNode()->getNodeId() > Pos->getNodeId()) {
547     DAG->RepositionNode(Pos, N.getNode());
548     N.getNode()->setNodeId(Pos->getNodeId());
549   }
550 }
551
552 void SystemZDAGToDAGISel::getAddressOperands(const SystemZAddressingMode &AM,
553                                              EVT VT, SDValue &Base,
554                                              SDValue &Disp) {
555   Base = AM.Base;
556   if (!Base.getNode())
557     // Register 0 means "no base".  This is mostly useful for shifts.
558     Base = CurDAG->getRegister(0, VT);
559   else if (Base.getOpcode() == ISD::FrameIndex) {
560     // Lower a FrameIndex to a TargetFrameIndex.
561     int64_t FrameIndex = cast<FrameIndexSDNode>(Base)->getIndex();
562     Base = CurDAG->getTargetFrameIndex(FrameIndex, VT);
563   } else if (Base.getValueType() != VT) {
564     // Truncate values from i64 to i32, for shifts.
565     assert(VT == MVT::i32 && Base.getValueType() == MVT::i64 &&
566            "Unexpected truncation");
567     SDLoc DL(Base);
568     SDValue Trunc = CurDAG->getNode(ISD::TRUNCATE, DL, VT, Base);
569     insertDAGNode(CurDAG, Base.getNode(), Trunc);
570     Base = Trunc;
571   }
572
573   // Lower the displacement to a TargetConstant.
574   Disp = CurDAG->getTargetConstant(AM.Disp, VT);
575 }
576
577 void SystemZDAGToDAGISel::getAddressOperands(const SystemZAddressingMode &AM,
578                                              EVT VT, SDValue &Base,
579                                              SDValue &Disp, SDValue &Index) {
580   getAddressOperands(AM, VT, Base, Disp);
581
582   Index = AM.Index;
583   if (!Index.getNode())
584     // Register 0 means "no index".
585     Index = CurDAG->getRegister(0, VT);
586 }
587
588 bool SystemZDAGToDAGISel::selectBDAddr(SystemZAddressingMode::DispRange DR,
589                                        SDValue Addr, SDValue &Base,
590                                        SDValue &Disp) {
591   SystemZAddressingMode AM(SystemZAddressingMode::FormBD, DR);
592   if (!selectAddress(Addr, AM))
593     return false;
594
595   getAddressOperands(AM, Addr.getValueType(), Base, Disp);
596   return true;
597 }
598
599 bool SystemZDAGToDAGISel::selectMVIAddr(SystemZAddressingMode::DispRange DR,
600                                         SDValue Addr, SDValue &Base,
601                                         SDValue &Disp) {
602   SystemZAddressingMode AM(SystemZAddressingMode::FormBDXNormal, DR);
603   if (!selectAddress(Addr, AM) || AM.Index.getNode())
604     return false;
605
606   getAddressOperands(AM, Addr.getValueType(), Base, Disp);
607   return true;
608 }
609
610 bool SystemZDAGToDAGISel::selectBDXAddr(SystemZAddressingMode::AddrForm Form,
611                                         SystemZAddressingMode::DispRange DR,
612                                         SDValue Addr, SDValue &Base,
613                                         SDValue &Disp, SDValue &Index) {
614   SystemZAddressingMode AM(Form, DR);
615   if (!selectAddress(Addr, AM))
616     return false;
617
618   getAddressOperands(AM, Addr.getValueType(), Base, Disp, Index);
619   return true;
620 }
621
622 bool SystemZDAGToDAGISel::detectOrAndInsertion(SDValue &Op,
623                                                uint64_t InsertMask) {
624   // We're only interested in cases where the insertion is into some operand
625   // of Op, rather than into Op itself.  The only useful case is an AND.
626   if (Op.getOpcode() != ISD::AND)
627     return false;
628
629   // We need a constant mask.
630   ConstantSDNode *MaskNode =
631     dyn_cast<ConstantSDNode>(Op.getOperand(1).getNode());
632   if (!MaskNode)
633     return false;
634
635   // It's not an insertion of Op.getOperand(0) if the two masks overlap.
636   uint64_t AndMask = MaskNode->getZExtValue();
637   if (InsertMask & AndMask)
638     return false;
639
640   // It's only an insertion if all bits are covered or are known to be zero.
641   // The inner check covers all cases but is more expensive.
642   uint64_t Used = allOnes(Op.getValueType().getSizeInBits());
643   if (Used != (AndMask | InsertMask)) {
644     APInt KnownZero, KnownOne;
645     CurDAG->ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne);
646     if (Used != (AndMask | InsertMask | KnownZero.getZExtValue()))
647       return false;
648   }
649
650   Op = Op.getOperand(0);
651   return true;
652 }
653
654 bool SystemZDAGToDAGISel::refineRxSBGMask(RxSBGOperands &RxSBG, uint64_t Mask) {
655   const SystemZInstrInfo *TII = getInstrInfo();
656   if (RxSBG.Rotate != 0)
657     Mask = (Mask << RxSBG.Rotate) | (Mask >> (64 - RxSBG.Rotate));
658   Mask &= RxSBG.Mask;
659   if (TII->isRxSBGMask(Mask, RxSBG.BitSize, RxSBG.Start, RxSBG.End)) {
660     RxSBG.Mask = Mask;
661     return true;
662   }
663   return false;
664 }
665
666 // RxSBG.Input is a shift of Count bits in the direction given by IsLeft.
667 // Return true if the result depends on the signs or zeros that are
668 // shifted in.
669 static bool shiftedInBitsMatter(RxSBGOperands &RxSBG, uint64_t Count,
670                                 bool IsLeft) {
671   // Work out which bits of the shift result are zeros or sign copies.
672   uint64_t ShiftedIn = allOnes(Count);
673   if (!IsLeft)
674     ShiftedIn <<= RxSBG.BitSize - Count;
675
676   // Rotate that mask in the same way as RxSBG.Input is rotated.
677   if (RxSBG.Rotate != 0)
678     ShiftedIn = ((ShiftedIn << RxSBG.Rotate) |
679                  (ShiftedIn >> (64 - RxSBG.Rotate)));
680
681   // Fail if any of the zero or sign bits are used.
682   return (ShiftedIn & RxSBG.Mask) != 0;
683 }
684
685 bool SystemZDAGToDAGISel::expandRxSBG(RxSBGOperands &RxSBG) {
686   SDValue N = RxSBG.Input;
687   unsigned Opcode = N.getOpcode();
688   switch (Opcode) {
689   case ISD::AND: {
690     if (RxSBG.Opcode == SystemZ::RNSBG)
691       return false;
692
693     ConstantSDNode *MaskNode =
694       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
695     if (!MaskNode)
696       return false;
697
698     SDValue Input = N.getOperand(0);
699     uint64_t Mask = MaskNode->getZExtValue();
700     if (!refineRxSBGMask(RxSBG, Mask)) {
701       // If some bits of Input are already known zeros, those bits will have
702       // been removed from the mask.  See if adding them back in makes the
703       // mask suitable.
704       APInt KnownZero, KnownOne;
705       CurDAG->ComputeMaskedBits(Input, KnownZero, KnownOne);
706       Mask |= KnownZero.getZExtValue();
707       if (!refineRxSBGMask(RxSBG, Mask))
708         return false;
709     }
710     RxSBG.Input = Input;
711     return true;
712   }
713
714   case ISD::OR: {
715     if (RxSBG.Opcode != SystemZ::RNSBG)
716       return false;
717
718     ConstantSDNode *MaskNode =
719       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
720     if (!MaskNode)
721       return false;
722
723     SDValue Input = N.getOperand(0);
724     uint64_t Mask = ~MaskNode->getZExtValue();
725     if (!refineRxSBGMask(RxSBG, Mask)) {
726       // If some bits of Input are already known ones, those bits will have
727       // been removed from the mask.  See if adding them back in makes the
728       // mask suitable.
729       APInt KnownZero, KnownOne;
730       CurDAG->ComputeMaskedBits(Input, KnownZero, KnownOne);
731       Mask &= ~KnownOne.getZExtValue();
732       if (!refineRxSBGMask(RxSBG, Mask))
733         return false;
734     }
735     RxSBG.Input = Input;
736     return true;
737   }
738
739   case ISD::ROTL: {
740     // Any 64-bit rotate left can be merged into the RxSBG.
741     if (RxSBG.BitSize != 64)
742       return false;
743     ConstantSDNode *CountNode
744       = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
745     if (!CountNode)
746       return false;
747
748     RxSBG.Rotate = (RxSBG.Rotate + CountNode->getZExtValue()) & 63;
749     RxSBG.Input = N.getOperand(0);
750     return true;
751   }
752       
753   case ISD::SHL: {
754     ConstantSDNode *CountNode =
755       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
756     if (!CountNode)
757       return false;
758
759     uint64_t Count = CountNode->getZExtValue();
760     if (Count < 1 || Count >= RxSBG.BitSize)
761       return false;
762
763     if (RxSBG.Opcode == SystemZ::RNSBG) {
764       // Treat (shl X, count) as (rotl X, size-count) as long as the bottom
765       // count bits from RxSBG.Input are ignored.
766       if (shiftedInBitsMatter(RxSBG, Count, true))
767         return false;
768     } else {
769       // Treat (shl X, count) as (and (rotl X, count), ~0<<count).
770       if (!refineRxSBGMask(RxSBG, allOnes(RxSBG.BitSize - Count) << Count))
771         return false;
772     }
773
774     RxSBG.Rotate = (RxSBG.Rotate + Count) & 63;
775     RxSBG.Input = N.getOperand(0);
776     return true;
777   }
778
779   case ISD::SRL:
780   case ISD::SRA: {
781     ConstantSDNode *CountNode =
782       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
783     if (!CountNode)
784       return false;
785
786     uint64_t Count = CountNode->getZExtValue();
787     if (Count < 1 || Count >= RxSBG.BitSize)
788       return false;
789
790     if (RxSBG.Opcode == SystemZ::RNSBG || Opcode == ISD::SRA) {
791       // Treat (srl|sra X, count) as (rotl X, size-count) as long as the top
792       // count bits from RxSBG.Input are ignored.
793       if (shiftedInBitsMatter(RxSBG, Count, false))
794         return false;
795     } else {
796       // Treat (srl X, count), mask) as (and (rotl X, size-count), ~0>>count),
797       // which is similar to SLL above.
798       if (!refineRxSBGMask(RxSBG, allOnes(RxSBG.BitSize - Count)))
799         return false;
800     }
801
802     RxSBG.Rotate = (RxSBG.Rotate - Count) & 63;
803     RxSBG.Input = N.getOperand(0);
804     return true;
805   }
806   default:
807     return false;
808   }
809 }
810
811 SDValue SystemZDAGToDAGISel::getUNDEF64(SDLoc DL) {
812   SDNode *N = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64);
813   return SDValue(N, 0);
814 }
815
816 SDValue SystemZDAGToDAGISel::convertTo(SDLoc DL, EVT VT, SDValue N) {
817   if (N.getValueType() == MVT::i32 && VT == MVT::i64)
818     return CurDAG->getTargetInsertSubreg(SystemZ::subreg_32bit,
819                                          DL, VT, getUNDEF64(DL), N);
820   if (N.getValueType() == MVT::i64 && VT == MVT::i32)
821     return CurDAG->getTargetExtractSubreg(SystemZ::subreg_32bit, DL, VT, N);
822   assert(N.getValueType() == VT && "Unexpected value types");
823   return N;
824 }
825
826 SDNode *SystemZDAGToDAGISel::tryRISBGZero(SDNode *N) {
827   EVT VT = N->getValueType(0);
828   RxSBGOperands RISBG(SystemZ::RISBG, SDValue(N, 0));
829   unsigned Count = 0;
830   while (expandRxSBG(RISBG))
831     Count += 1;
832   if (Count == 0)
833     return 0;
834   if (Count == 1) {
835     // Prefer to use normal shift instructions over RISBG, since they can handle
836     // all cases and are sometimes shorter.
837     if (N->getOpcode() != ISD::AND)
838       return 0;
839
840     // Prefer register extensions like LLC over RISBG.  Also prefer to start
841     // out with normal ANDs if one instruction would be enough.  We can convert
842     // these ANDs into an RISBG later if a three-address instruction is useful.
843     if (VT == MVT::i32 ||
844         RISBG.Mask == 0xff ||
845         RISBG.Mask == 0xffff ||
846         SystemZ::isImmLF(~RISBG.Mask) ||
847         SystemZ::isImmHF(~RISBG.Mask)) {
848       // Force the new mask into the DAG, since it may include known-one bits.
849       ConstantSDNode *MaskN = cast<ConstantSDNode>(N->getOperand(1).getNode());
850       if (MaskN->getZExtValue() != RISBG.Mask) {
851         SDValue NewMask = CurDAG->getConstant(RISBG.Mask, VT);
852         N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), NewMask);
853         return SelectCode(N);
854       }
855       return 0;
856     }
857   }  
858
859   SDValue Ops[5] = {
860     getUNDEF64(SDLoc(N)),
861     convertTo(SDLoc(N), MVT::i64, RISBG.Input),
862     CurDAG->getTargetConstant(RISBG.Start, MVT::i32),
863     CurDAG->getTargetConstant(RISBG.End | 128, MVT::i32),
864     CurDAG->getTargetConstant(RISBG.Rotate, MVT::i32)
865   };
866   N = CurDAG->getMachineNode(SystemZ::RISBG, SDLoc(N), MVT::i64, Ops);
867   return convertTo(SDLoc(N), VT, SDValue(N, 0)).getNode();
868 }
869
870 SDNode *SystemZDAGToDAGISel::tryRxSBG(SDNode *N, unsigned Opcode) {
871   // Try treating each operand of N as the second operand of the RxSBG
872   // and see which goes deepest.
873   RxSBGOperands RxSBG[] = {
874     RxSBGOperands(Opcode, N->getOperand(0)),
875     RxSBGOperands(Opcode, N->getOperand(1))
876   };
877   unsigned Count[] = { 0, 0 };
878   for (unsigned I = 0; I < 2; ++I)
879     while (expandRxSBG(RxSBG[I]))
880       Count[I] += 1;
881
882   // Do nothing if neither operand is suitable.
883   if (Count[0] == 0 && Count[1] == 0)
884     return 0;
885
886   // Pick the deepest second operand.
887   unsigned I = Count[0] > Count[1] ? 0 : 1;
888   SDValue Op0 = N->getOperand(I ^ 1);
889
890   // Prefer IC for character insertions from memory.
891   if (Opcode == SystemZ::ROSBG && (RxSBG[I].Mask & 0xff) == 0)
892     if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Op0.getNode()))
893       if (Load->getMemoryVT() == MVT::i8)
894         return 0;
895
896   // See whether we can avoid an AND in the first operand by converting
897   // ROSBG to RISBG.
898   if (Opcode == SystemZ::ROSBG && detectOrAndInsertion(Op0, RxSBG[I].Mask))
899     Opcode = SystemZ::RISBG;
900            
901   EVT VT = N->getValueType(0);
902   SDValue Ops[5] = {
903     convertTo(SDLoc(N), MVT::i64, Op0),
904     convertTo(SDLoc(N), MVT::i64, RxSBG[I].Input),
905     CurDAG->getTargetConstant(RxSBG[I].Start, MVT::i32),
906     CurDAG->getTargetConstant(RxSBG[I].End, MVT::i32),
907     CurDAG->getTargetConstant(RxSBG[I].Rotate, MVT::i32)
908   };
909   N = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i64, Ops);
910   return convertTo(SDLoc(N), VT, SDValue(N, 0)).getNode();
911 }
912
913 SDNode *SystemZDAGToDAGISel::splitLargeImmediate(unsigned Opcode, SDNode *Node,
914                                                  SDValue Op0, uint64_t UpperVal,
915                                                  uint64_t LowerVal) {
916   EVT VT = Node->getValueType(0);
917   SDLoc DL(Node);
918   SDValue Upper = CurDAG->getConstant(UpperVal, VT);
919   if (Op0.getNode())
920     Upper = CurDAG->getNode(Opcode, DL, VT, Op0, Upper);
921   Upper = SDValue(Select(Upper.getNode()), 0);
922
923   SDValue Lower = CurDAG->getConstant(LowerVal, VT);
924   SDValue Or = CurDAG->getNode(Opcode, DL, VT, Upper, Lower);
925   return Or.getNode();
926 }
927
928 // Return true if Load and Store:
929 // - are loads and stores of the same size;
930 // - do not partially overlap; and
931 // - can be decomposed into what are logically individual character accesses
932 //   without changing the semantics.
933 static bool canUseBlockOperation(StoreSDNode *Store, LoadSDNode *Load,
934                                  AliasAnalysis *AA) {
935   // Check that the two memory operands have the same size.
936   if (Load->getMemoryVT() != Store->getMemoryVT())
937     return false;
938
939   // Volatility stops an access from being decomposed.
940   if (Load->isVolatile() || Store->isVolatile())
941     return false;
942
943   // There's no chance of overlap if the load is invariant.
944   if (Load->isInvariant())
945     return true;
946
947   // If both operands are aligned, they must be equal or not overlap.
948   uint64_t Size = Load->getMemoryVT().getStoreSize();
949   if (Load->getAlignment() >= Size && Store->getAlignment() >= Size)
950     return true;
951
952   // Otherwise we need to check whether there's an alias.
953   const Value *V1 = Load->getSrcValue();
954   const Value *V2 = Store->getSrcValue();
955   if (!V1 || !V2)
956     return false;
957
958   int64_t End1 = Load->getSrcValueOffset() + Size;
959   int64_t End2 = Store->getSrcValueOffset() + Size;
960   return !AA->alias(AliasAnalysis::Location(V1, End1, Load->getTBAAInfo()),
961                     AliasAnalysis::Location(V2, End2, Store->getTBAAInfo()));
962 }
963
964 bool SystemZDAGToDAGISel::storeLoadCanUseMVC(SDNode *N) const {
965   StoreSDNode *Store = cast<StoreSDNode>(N);
966   LoadSDNode *Load = cast<LoadSDNode>(Store->getValue());
967
968   // Prefer not to use MVC if either address can use ... RELATIVE LONG
969   // instructions.
970   uint64_t Size = Load->getMemoryVT().getStoreSize();
971   if (Size > 1 && Size <= 8) {
972     // Prefer LHRL, LRL and LGRL.
973     if (Load->getBasePtr().getOpcode() == SystemZISD::PCREL_WRAPPER)
974       return false;
975     // Prefer STHRL, STRL and STGRL.
976     if (Store->getBasePtr().getOpcode() == SystemZISD::PCREL_WRAPPER)
977       return false;
978   }
979
980   return canUseBlockOperation(Store, Load, AA);
981 }
982
983 bool SystemZDAGToDAGISel::storeLoadCanUseBlockBinary(SDNode *N,
984                                                      unsigned I) const {
985   StoreSDNode *StoreA = cast<StoreSDNode>(N);
986   LoadSDNode *LoadA = cast<LoadSDNode>(StoreA->getValue().getOperand(1 - I));
987   LoadSDNode *LoadB = cast<LoadSDNode>(StoreA->getValue().getOperand(I));
988   if (LoadA->isVolatile() ||
989       LoadA->getMemoryVT() != StoreA->getMemoryVT() ||
990       LoadA->getBasePtr() != StoreA->getBasePtr())
991     return false;
992   return canUseBlockOperation(StoreA, LoadB, AA);
993 }
994
995 SDNode *SystemZDAGToDAGISel::Select(SDNode *Node) {
996   // Dump information about the Node being selected
997   DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
998
999   // If we have a custom node, we already have selected!
1000   if (Node->isMachineOpcode()) {
1001     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
1002     Node->setNodeId(-1);
1003     return 0;
1004   }
1005
1006   unsigned Opcode = Node->getOpcode();
1007   SDNode *ResNode = 0;
1008   switch (Opcode) {
1009   case ISD::OR:
1010     if (Node->getOperand(1).getOpcode() != ISD::Constant)
1011       ResNode = tryRxSBG(Node, SystemZ::ROSBG);
1012     goto or_xor;
1013
1014   case ISD::XOR:
1015     if (Node->getOperand(1).getOpcode() != ISD::Constant)
1016       ResNode = tryRxSBG(Node, SystemZ::RXSBG);
1017     // Fall through.
1018   or_xor:
1019     // If this is a 64-bit operation in which both 32-bit halves are nonzero,
1020     // split the operation into two.
1021     if (!ResNode && Node->getValueType(0) == MVT::i64)
1022       if (ConstantSDNode *Op1 = dyn_cast<ConstantSDNode>(Node->getOperand(1))) {
1023         uint64_t Val = Op1->getZExtValue();
1024         if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val))
1025           Node = splitLargeImmediate(Opcode, Node, Node->getOperand(0),
1026                                      Val - uint32_t(Val), uint32_t(Val));
1027       }
1028     break;
1029
1030   case ISD::AND:
1031     if (Node->getOperand(1).getOpcode() != ISD::Constant)
1032       ResNode = tryRxSBG(Node, SystemZ::RNSBG);
1033     // Fall through.
1034   case ISD::ROTL:
1035   case ISD::SHL:
1036   case ISD::SRL:
1037     if (!ResNode)
1038       ResNode = tryRISBGZero(Node);
1039     break;
1040
1041   case ISD::Constant:
1042     // If this is a 64-bit constant that is out of the range of LLILF,
1043     // LLIHF and LGFI, split it into two 32-bit pieces.
1044     if (Node->getValueType(0) == MVT::i64) {
1045       uint64_t Val = cast<ConstantSDNode>(Node)->getZExtValue();
1046       if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val) && !isInt<32>(Val))
1047         Node = splitLargeImmediate(ISD::OR, Node, SDValue(),
1048                                    Val - uint32_t(Val), uint32_t(Val));
1049     }
1050     break;
1051
1052   case ISD::ATOMIC_LOAD_SUB:
1053     // Try to convert subtractions of constants to additions.
1054     if (ConstantSDNode *Op2 = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
1055       uint64_t Value = -Op2->getZExtValue();
1056       EVT VT = Node->getValueType(0);
1057       if (VT == MVT::i32 || isInt<32>(Value)) {
1058         SDValue Ops[] = { Node->getOperand(0), Node->getOperand(1),
1059                           CurDAG->getConstant(int32_t(Value), VT) };
1060         Node = CurDAG->MorphNodeTo(Node, ISD::ATOMIC_LOAD_ADD,
1061                                    Node->getVTList(), Ops, array_lengthof(Ops));
1062       }
1063     }
1064     break;
1065
1066   case SystemZISD::SELECT_CCMASK: {
1067     SDValue Op0 = Node->getOperand(0);
1068     SDValue Op1 = Node->getOperand(1);
1069     // Prefer to put any load first, so that it can be matched as a
1070     // conditional load.
1071     if (Op1.getOpcode() == ISD::LOAD && Op0.getOpcode() != ISD::LOAD) {
1072       SDValue CCValid = Node->getOperand(2);
1073       SDValue CCMask = Node->getOperand(3);
1074       uint64_t ConstCCValid =
1075         cast<ConstantSDNode>(CCValid.getNode())->getZExtValue();
1076       uint64_t ConstCCMask =
1077         cast<ConstantSDNode>(CCMask.getNode())->getZExtValue();
1078       // Invert the condition.
1079       CCMask = CurDAG->getConstant(ConstCCValid ^ ConstCCMask,
1080                                    CCMask.getValueType());
1081       SDValue Op4 = Node->getOperand(4);
1082       Node = CurDAG->UpdateNodeOperands(Node, Op1, Op0, CCValid, CCMask, Op4);
1083     }
1084     break;
1085   }
1086   }
1087
1088   // Select the default instruction
1089   if (!ResNode)
1090     ResNode = SelectCode(Node);
1091
1092   DEBUG(errs() << "=> ";
1093         if (ResNode == NULL || ResNode == Node)
1094           Node->dump(CurDAG);
1095         else
1096           ResNode->dump(CurDAG);
1097         errs() << "\n";
1098         );
1099   return ResNode;
1100 }
1101
1102 bool SystemZDAGToDAGISel::
1103 SelectInlineAsmMemoryOperand(const SDValue &Op,
1104                              char ConstraintCode,
1105                              std::vector<SDValue> &OutOps) {
1106   assert(ConstraintCode == 'm' && "Unexpected constraint code");
1107   // Accept addresses with short displacements, which are compatible
1108   // with Q, R, S and T.  But keep the index operand for future expansion.
1109   SDValue Base, Disp, Index;
1110   if (!selectBDXAddr(SystemZAddressingMode::FormBD,
1111                      SystemZAddressingMode::Disp12Only,
1112                      Op, Base, Disp, Index))
1113     return true;
1114   OutOps.push_back(Base);
1115   OutOps.push_back(Disp);
1116   OutOps.push_back(Index);
1117   return false;
1118 }