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 RISBGOperands {
105   RISBGOperands(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 Ops.Input into other fields of Ops.  Return true
231   // on success.
232   bool expandRISBG(RISBGOperands &Ops);
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 ROSBG to implement OR node N.  Return the selected
245   // node on success, otherwise return null.
246   SDNode *tryRISBGOrROSBG(SDNode *N);
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     {
609       LSB = First;
610       Length = findFirstSet(Top);
611       return true;
612     }
613   return false;
614 }
615 
616 // Try to update RISBG so that only the bits of Ops.Input in Mask are used.
617 // Return true on success.
618 static bool refineRISBGMask(RISBGOperands &RISBG, uint64_t Mask) {
619   if (RISBG.Rotate != 0)
620     Mask = (Mask << RISBG.Rotate) | (Mask >> (64 - RISBG.Rotate));
621   Mask &= RISBG.Mask;
622 
623   // Reject trivial all-zero masks.
624   if (Mask == 0)
625     return false;
626 
627   // Handle the 1+0+ or 0+1+0* cases.  Start then specifies the index of
628   // the msb and End specifies the index of the lsb.
629   unsigned LSB, Length;
630   if (isStringOfOnes(Mask, LSB, Length))
631     {
632       RISBG.Mask = Mask;
633       RISBG.Start = 63 - (LSB + Length - 1);
634       RISBG.End = 63 - LSB;
635       return true;
636     }
637 
638   // Handle the wrap-around 1+0+1+ cases.  Start then specifies the msb
639   // of the low 1s and End specifies the lsb of the high 1s.
640   if (isStringOfOnes(Mask ^ allOnes(RISBG.BitSize), LSB, Length))
641     {
642       assert(LSB > 0 && "Bottom bit must be set");
643       assert(LSB + Length < RISBG.BitSize && "Top bit must be set");
644       RISBG.Mask = Mask;
645       RISBG.Start = 63 - (LSB - 1);
646       RISBG.End = 63 - (LSB + Length);
647       return true;
648     }
649 
650   return false;
651 }
652 
653 bool SystemZDAGToDAGISel::expandRISBG(RISBGOperands &RISBG) {
654   SDValue N = RISBG.Input;
655   switch (N.getOpcode()) {
656   case ISD::AND: {
657     ConstantSDNode *MaskNode =
658       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
659     if (!MaskNode)
660       return false;
661 
662     SDValue Input = N.getOperand(0);
663     uint64_t Mask = MaskNode->getZExtValue();
664     if (!refineRISBGMask(RISBG, Mask)) {
665       // If some bits of Input are already known zeros, those bits will have
666       // been removed from the mask.  See if adding them back in makes the
667       // mask suitable.
668       APInt KnownZero, KnownOne;
669       CurDAG->ComputeMaskedBits(Input, KnownZero, KnownOne);
670       Mask |= KnownZero.getZExtValue();
671       if (!refineRISBGMask(RISBG, Mask))
672         return false;
673     }
674     RISBG.Input = Input;
675     return true;
676   }
677 
678   case ISD::ROTL: {
679     // Any 64-bit rotate left can be merged into the RISBG.
680     if (RISBG.BitSize != 64)
681       return false;
682     ConstantSDNode *CountNode
683       = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
684     if (!CountNode)
685       return false;
686 
687     RISBG.Rotate = (RISBG.Rotate + CountNode->getZExtValue()) & 63;
688     RISBG.Input = N.getOperand(0);
689     return true;
690   }
691 
692   case ISD::SHL: {
693     // Treat (shl X, count) as (and (rotl X, count), ~0<<count).
694     ConstantSDNode *CountNode =
695       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
696     if (!CountNode)
697       return false;
698 
699     uint64_t Count = CountNode->getZExtValue();
700     if (Count < 1 ||
701         Count >= RISBG.BitSize ||
702         !refineRISBGMask(RISBG, allOnes(RISBG.BitSize - Count) << Count))
703       return false;
704 
705     RISBG.Rotate = (RISBG.Rotate + Count) & 63;
706     RISBG.Input = N.getOperand(0);
707     return true;
708   }
709 
710   case ISD::SRL: {
711     // Treat (srl X, count), mask) as (and (rotl X, size-count), ~0>>count),
712     // which is similar to SLL above.
713     ConstantSDNode *CountNode =
714       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
715     if (!CountNode)
716       return false;
717 
718     uint64_t Count = CountNode->getZExtValue();
719     if (Count < 1 ||
720         Count >= RISBG.BitSize ||
721         !refineRISBGMask(RISBG, allOnes(RISBG.BitSize - Count)))
722       return false;
723 
724     RISBG.Rotate = (RISBG.Rotate - Count) & 63;
725     RISBG.Input = N.getOperand(0);
726     return true;
727   }
728 
729   case ISD::SRA: {
730     // Treat (sra X, count) as (rotl X, size-count) as long as the top
731     // count bits from Ops.Input are ignored.
732     ConstantSDNode *CountNode =
733       dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
734     if (!CountNode)
735       return false;
736 
737     uint64_t Count = CountNode->getZExtValue();
738     if (RISBG.Rotate != 0 ||
739         Count < 1 ||
740         Count >= RISBG.BitSize ||
741         RISBG.Start < 64 - (RISBG.BitSize - Count))
742       return false;
743 
744     RISBG.Rotate = -Count & 63;
745     RISBG.Input = N.getOperand(0);
746     return true;
747   }
748   default:
749     return false;
750   }
751 }
752 
753 SDValue SystemZDAGToDAGISel::getUNDEF64(SDLoc DL) {
754   SDNode *N = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64);
755   return SDValue(N, 0);
756 }
757 
758 SDValue SystemZDAGToDAGISel::convertTo(SDLoc DL, EVT VT, SDValue N) {
759   if (N.getValueType() == MVT::i32 && VT == MVT::i64) {
760     SDValue Index = CurDAG->getTargetConstant(SystemZ::subreg_32bit, MVT::i64);
761     SDNode *Insert = CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG,
762                                             DL, VT, getUNDEF64(DL), N, Index);
763     return SDValue(Insert, 0);
764   }
765   if (N.getValueType() == MVT::i64 && VT == MVT::i32) {
766     SDValue Index = CurDAG->getTargetConstant(SystemZ::subreg_32bit, MVT::i64);
767     SDNode *Extract = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
768                                              DL, VT, N, Index);
769     return SDValue(Extract, 0);
770   }
771   assert(N.getValueType() == VT && "Unexpected value types");
772   return N;
773 }
774 
775 SDNode *SystemZDAGToDAGISel::tryRISBGZero(SDNode *N) {
776   RISBGOperands RISBG(SDValue(N, 0));
777   unsigned Count = 0;
778   while (expandRISBG(RISBG))
779     Count += 1;
780   // Prefer to use normal shift instructions over RISBG, since they can handle
781   // all cases and are sometimes shorter.  Prefer to use RISBG for ANDs though,
782   // since it is effectively a three-operand instruction in this case,
783   // and since it can handle some masks that AND IMMEDIATE can't.
784   if (Count < (N->getOpcode() == ISD::AND ? 1 : 2))
785     return 0;
786 
787   // Prefer register extensions like LLC over RISBG.
788   if (RISBG.Rotate == 0 &&
789       (RISBG.Start == 32 || RISBG.Start == 48 || RISBG.Start == 56) &&
790       RISBG.End == 63)
791     return 0;
792 
793   EVT VT = N->getValueType(0);
794   SDValue Ops[5] = {
795     getUNDEF64(SDLoc(N)),
796     convertTo(SDLoc(N), MVT::i64, RISBG.Input),
797     CurDAG->getTargetConstant(RISBG.Start, MVT::i32),
798     CurDAG->getTargetConstant(RISBG.End | 128, MVT::i32),
799     CurDAG->getTargetConstant(RISBG.Rotate, MVT::i32)
800   };
801   N = CurDAG->getMachineNode(SystemZ::RISBG, SDLoc(N), MVT::i64, Ops);
802   return convertTo(SDLoc(N), VT, SDValue(N, 0)).getNode();
803 }
804 
805 SDNode *SystemZDAGToDAGISel::tryRISBGOrROSBG(SDNode *N) {
806   // Try treating each operand of N as the second operand of RISBG or ROSBG
807   // and see which goes deepest.
808   RISBGOperands RISBG[] = { N->getOperand(0), N->getOperand(1) };
809   unsigned Count[] = { 0, 0 };
810   for (unsigned I = 0; I < 2; ++I)
811     while (expandRISBG(RISBG[I]))
812       Count[I] += 1;
813 
814   // Do nothing if neither operand is suitable.
815   if (Count[0] == 0 && Count[1] == 0)
816     return 0;
817 
818   // Pick the deepest second operand.
819   unsigned I = Count[0] > Count[1] ? 0 : 1;
820   SDValue Op0 = N->getOperand(I ^ 1);
821 
822   // Prefer IC for character insertions from memory.
823   if ((RISBG[I].Mask & 0xff) == 0)
824     if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Op0.getNode()))
825       if (Load->getMemoryVT() == MVT::i8)
826         return 0;
827 
828   // See whether we can avoid an AND in the first operand by converting
829   // ROSBG to RISBG.
830   unsigned Opcode = SystemZ::ROSBG;
831   if (detectOrAndInsertion(Op0, RISBG[I].Mask))
832     Opcode = SystemZ::RISBG;
833 
834   EVT VT = N->getValueType(0);
835   SDValue Ops[5] = {
836     convertTo(SDLoc(N), MVT::i64, Op0),
837     convertTo(SDLoc(N), MVT::i64, RISBG[I].Input),
838     CurDAG->getTargetConstant(RISBG[I].Start, MVT::i32),
839     CurDAG->getTargetConstant(RISBG[I].End, MVT::i32),
840     CurDAG->getTargetConstant(RISBG[I].Rotate, MVT::i32)
841   };
842   N = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i64, Ops);
843   return convertTo(SDLoc(N), VT, SDValue(N, 0)).getNode();
844 }
845 
846 SDNode *SystemZDAGToDAGISel::splitLargeImmediate(unsigned Opcode, SDNode *Node,
847                                                  SDValue Op0, uint64_t UpperVal,
848                                                  uint64_t LowerVal) {
849   EVT VT = Node->getValueType(0);
850   SDLoc DL(Node);
851   SDValue Upper = CurDAG->getConstant(UpperVal, VT);
852   if (Op0.getNode())
853     Upper = CurDAG->getNode(Opcode, DL, VT, Op0, Upper);
854   Upper = SDValue(Select(Upper.getNode()), 0);
855 
856   SDValue Lower = CurDAG->getConstant(LowerVal, VT);
857   SDValue Or = CurDAG->getNode(Opcode, DL, VT, Upper, Lower);
858   return Or.getNode();
859 }
860 
861 // N is a (store (load ...), ...) pattern.  Return true if it can use MVC.
862 bool SystemZDAGToDAGISel::storeLoadCanUseMVC(SDNode *N) const {
863   StoreSDNode *Store = cast<StoreSDNode>(N);
864   LoadSDNode *Load = cast<LoadSDNode>(Store->getValue().getNode());
865 
866   // MVC is logically a bytewise copy, so can't be used for volatile accesses.
867   if (Load->isVolatile() || Store->isVolatile())
868     return false;
869 
870   // Prefer not to use MVC if either address can use ... RELATIVE LONG
871   // instructions.
872   assert(Load->getMemoryVT() == Store->getMemoryVT() &&
873          "Should already have checked that the types match");
874   uint64_t Size = Load->getMemoryVT().getStoreSize();
875   if (Size > 1 && Size <= 8) {
876     // Prefer LHRL, LRL and LGRL.
877     if (Load->getBasePtr().getOpcode() == SystemZISD::PCREL_WRAPPER)
878       return false;
879     // Prefer STHRL, STRL and STGRL.
880     if (Store->getBasePtr().getOpcode() == SystemZISD::PCREL_WRAPPER)
881       return false;
882   }
883 
884   // There's no chance of overlap if the load is invariant.
885   if (Load->isInvariant())
886     return true;
887 
888   // If both operands are aligned, they must be equal or not overlap.
889   if (Load->getAlignment() >= Size && Store->getAlignment() >= Size)
890     return true;
891 
892   // Otherwise we need to check whether there's an alias.
893   const Value *V1 = Load->getSrcValue();
894   const Value *V2 = Store->getSrcValue();
895   if (!V1 || !V2)
896     return false;
897 
898   int64_t End1 = Load->getSrcValueOffset() + Size;
899   int64_t End2 = Store->getSrcValueOffset() + Size;
900   return !AA->alias(AliasAnalysis::Location(V1, End1, Load->getTBAAInfo()),
901                     AliasAnalysis::Location(V2, End2, Store->getTBAAInfo()));
902 }
903 
904 SDNode *SystemZDAGToDAGISel::Select(SDNode *Node) {
905   // Dump information about the Node being selected
906   DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
907 
908   // If we have a custom node, we already have selected!
909   if (Node->isMachineOpcode()) {
910     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
911     return 0;
912   }
913 
914   unsigned Opcode = Node->getOpcode();
915   SDNode *ResNode = 0;
916   switch (Opcode) {
917   case ISD::OR:
918     if (Node->getOperand(1).getOpcode() != ISD::Constant)
919       ResNode = tryRISBGOrROSBG(Node);
920     // Fall through.
921   case ISD::XOR:
922     // If this is a 64-bit operation in which both 32-bit halves are nonzero,
923     // split the operation into two.
924     if (!ResNode && Node->getValueType(0) == MVT::i64)
925       if (ConstantSDNode *Op1 = dyn_cast<ConstantSDNode>(Node->getOperand(1))) {
926         uint64_t Val = Op1->getZExtValue();
927         if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val))
928           Node = splitLargeImmediate(Opcode, Node, Node->getOperand(0),
929                                      Val - uint32_t(Val), uint32_t(Val));
930       }
931     break;
932 
933   case ISD::AND:
934   case ISD::ROTL:
935   case ISD::SHL:
936   case ISD::SRL:
937     ResNode = tryRISBGZero(Node);
938     break;
939 
940   case ISD::Constant:
941     // If this is a 64-bit constant that is out of the range of LLILF,
942     // LLIHF and LGFI, split it into two 32-bit pieces.
943     if (Node->getValueType(0) == MVT::i64) {
944       uint64_t Val = cast<ConstantSDNode>(Node)->getZExtValue();
945       if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val) && !isInt<32>(Val))
946         Node = splitLargeImmediate(ISD::OR, Node, SDValue(),
947                                    Val - uint32_t(Val), uint32_t(Val));
948     }
949     break;
950 
951   case ISD::ATOMIC_LOAD_SUB:
952     // Try to convert subtractions of constants to additions.
953     if (ConstantSDNode *Op2 = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
954       uint64_t Value = -Op2->getZExtValue();
955       EVT VT = Node->getValueType(0);
956       if (VT == MVT::i32 || isInt<32>(Value)) {
957         SDValue Ops[] = { Node->getOperand(0), Node->getOperand(1),
958                           CurDAG->getConstant(int32_t(Value), VT) };
959         Node = CurDAG->MorphNodeTo(Node, ISD::ATOMIC_LOAD_ADD,
960                                    Node->getVTList(), Ops, array_lengthof(Ops));
961       }
962     }
963     break;
964   }
965 
966   // Select the default instruction
967   if (!ResNode)
968     ResNode = SelectCode(Node);
969 
970   DEBUG(errs() << "=> ";
971         if (ResNode == NULL || ResNode == Node)
972           Node->dump(CurDAG);
973         else
974           ResNode->dump(CurDAG);
975         errs() << "\n";
976         );
977   return ResNode;
978 }
979 
980 bool SystemZDAGToDAGISel::
981 SelectInlineAsmMemoryOperand(const SDValue &Op,
982                              char ConstraintCode,
983                              std::vector<SDValue> &OutOps) {
984   assert(ConstraintCode == 'm' && "Unexpected constraint code");
985   // Accept addresses with short displacements, which are compatible
986   // with Q, R, S and T.  But keep the index operand for future expansion.
987   SDValue Base, Disp, Index;
988   if (!selectBDXAddr(SystemZAddressingMode::FormBD,
989                      SystemZAddressingMode::Disp12Only,
990                      Op, Base, Disp, Index))
991     return true;
992   OutOps.push_back(Base);
993   OutOps.push_back(Disp);
994   OutOps.push_back(Index);
995   return false;
996 }
997