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