1 //===-- SystemZISelDAGToDAG.cpp - A dag to dag inst selector for SystemZ --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines an instruction selector for the SystemZ target.
12 //===----------------------------------------------------------------------===//
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"
22 #define DEBUG_TYPE "systemz-isel"
25 // Used to build addressing modes.
26 struct SystemZAddressingMode {
27 // The shape of the address.
32 // base+displacement+index for load and store operands
35 // base+displacement+index for load address operands
38 // base+displacement+index+ADJDYNALLOC
43 // The type of displacement. The enum names here correspond directly
44 // to the definitions in SystemZOperand.td. We could split them into
45 // flags -- single/pair, 128-bit, etc. -- but it hardly seems worth it.
55 // The parts of the address. The address is equivalent to:
57 // Base + Disp + Index + (IncludesDynAlloc ? ADJDYNALLOC : 0)
61 bool IncludesDynAlloc;
63 SystemZAddressingMode(AddrForm form, DispRange dr)
64 : Form(form), DR(dr), Base(), Disp(0), Index(),
65 IncludesDynAlloc(false) {}
67 // True if the address can have an index register.
68 bool hasIndexField() { return Form != FormBD; }
70 // True if the address can (and must) include ADJDYNALLOC.
71 bool isDynAlloc() { return Form == FormBDXDynAlloc; }
74 errs() << "SystemZAddressingMode " << this << '\n';
78 Base.getNode()->dump();
82 if (hasIndexField()) {
85 Index.getNode()->dump();
90 errs() << " Disp " << Disp;
92 errs() << " + ADJDYNALLOC";
97 // Return a mask with Count low bits set.
98 static uint64_t allOnes(unsigned int Count) {
99 return Count == 0 ? 0 : (uint64_t(1) << (Count - 1) << 1) - 1;
102 // Represents operands 2 to 5 of the ROTATE AND ... SELECTED BITS operation
103 // given by Opcode. The operands are: Input (R2), Start (I3), End (I4) and
104 // Rotate (I5). The combined operand value is effectively:
106 // (or (rotl Input, Rotate), ~Mask)
110 // (and (rotl Input, Rotate), Mask)
112 // otherwise. The output value has BitSize bits, although Input may be
113 // narrower (in which case the upper bits are don't care).
114 struct RxSBGOperands {
115 RxSBGOperands(unsigned Op, SDValue N)
116 : Opcode(Op), BitSize(N.getValueType().getSizeInBits()),
117 Mask(allOnes(BitSize)), Input(N), Start(64 - BitSize), End(63),
129 class SystemZDAGToDAGISel : public SelectionDAGISel {
130 const SystemZSubtarget *Subtarget;
132 // Used by SystemZOperands.td to create integer constants.
133 inline SDValue getImm(const SDNode *Node, uint64_t Imm) const {
134 return CurDAG->getTargetConstant(Imm, SDLoc(Node), Node->getValueType(0));
137 const SystemZTargetMachine &getTargetMachine() const {
138 return static_cast<const SystemZTargetMachine &>(TM);
141 const SystemZInstrInfo *getInstrInfo() const {
142 return Subtarget->getInstrInfo();
145 // Try to fold more of the base or index of AM into AM, where IsBase
146 // selects between the base and index.
147 bool expandAddress(SystemZAddressingMode &AM, bool IsBase) const;
149 // Try to describe N in AM, returning true on success.
150 bool selectAddress(SDValue N, SystemZAddressingMode &AM) const;
152 // Extract individual target operands from matched address AM.
153 void getAddressOperands(const SystemZAddressingMode &AM, EVT VT,
154 SDValue &Base, SDValue &Disp) const;
155 void getAddressOperands(const SystemZAddressingMode &AM, EVT VT,
156 SDValue &Base, SDValue &Disp, SDValue &Index) const;
158 // Try to match Addr as a FormBD address with displacement type DR.
159 // Return true on success, storing the base and displacement in
160 // Base and Disp respectively.
161 bool selectBDAddr(SystemZAddressingMode::DispRange DR, SDValue Addr,
162 SDValue &Base, SDValue &Disp) const;
164 // Try to match Addr as a FormBDX address with displacement type DR.
165 // Return true on success and if the result had no index. Store the
166 // base and displacement in Base and Disp respectively.
167 bool selectMVIAddr(SystemZAddressingMode::DispRange DR, SDValue Addr,
168 SDValue &Base, SDValue &Disp) const;
170 // Try to match Addr as a FormBDX* address of form Form with
171 // displacement type DR. Return true on success, storing the base,
172 // displacement and index in Base, Disp and Index respectively.
173 bool selectBDXAddr(SystemZAddressingMode::AddrForm Form,
174 SystemZAddressingMode::DispRange DR, SDValue Addr,
175 SDValue &Base, SDValue &Disp, SDValue &Index) const;
177 // PC-relative address matching routines used by SystemZOperands.td.
178 bool selectPCRelAddress(SDValue Addr, SDValue &Target) const {
179 if (SystemZISD::isPCREL(Addr.getOpcode())) {
180 Target = Addr.getOperand(0);
186 // BD matching routines used by SystemZOperands.td.
187 bool selectBDAddr12Only(SDValue Addr, SDValue &Base, SDValue &Disp) const {
188 return selectBDAddr(SystemZAddressingMode::Disp12Only, Addr, Base, Disp);
190 bool selectBDAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
191 return selectBDAddr(SystemZAddressingMode::Disp12Pair, Addr, Base, Disp);
193 bool selectBDAddr20Only(SDValue Addr, SDValue &Base, SDValue &Disp) const {
194 return selectBDAddr(SystemZAddressingMode::Disp20Only, Addr, Base, Disp);
196 bool selectBDAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
197 return selectBDAddr(SystemZAddressingMode::Disp20Pair, Addr, Base, Disp);
200 // MVI matching routines used by SystemZOperands.td.
201 bool selectMVIAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
202 return selectMVIAddr(SystemZAddressingMode::Disp12Pair, Addr, Base, Disp);
204 bool selectMVIAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp) const {
205 return selectMVIAddr(SystemZAddressingMode::Disp20Pair, Addr, Base, Disp);
208 // BDX matching routines used by SystemZOperands.td.
209 bool selectBDXAddr12Only(SDValue Addr, SDValue &Base, SDValue &Disp,
210 SDValue &Index) const {
211 return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
212 SystemZAddressingMode::Disp12Only,
213 Addr, Base, Disp, Index);
215 bool selectBDXAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
216 SDValue &Index) const {
217 return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
218 SystemZAddressingMode::Disp12Pair,
219 Addr, Base, Disp, Index);
221 bool selectDynAlloc12Only(SDValue Addr, SDValue &Base, SDValue &Disp,
222 SDValue &Index) const {
223 return selectBDXAddr(SystemZAddressingMode::FormBDXDynAlloc,
224 SystemZAddressingMode::Disp12Only,
225 Addr, Base, Disp, Index);
227 bool selectBDXAddr20Only(SDValue Addr, SDValue &Base, SDValue &Disp,
228 SDValue &Index) const {
229 return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
230 SystemZAddressingMode::Disp20Only,
231 Addr, Base, Disp, Index);
233 bool selectBDXAddr20Only128(SDValue Addr, SDValue &Base, SDValue &Disp,
234 SDValue &Index) const {
235 return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
236 SystemZAddressingMode::Disp20Only128,
237 Addr, Base, Disp, Index);
239 bool selectBDXAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
240 SDValue &Index) const {
241 return selectBDXAddr(SystemZAddressingMode::FormBDXNormal,
242 SystemZAddressingMode::Disp20Pair,
243 Addr, Base, Disp, Index);
245 bool selectLAAddr12Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
246 SDValue &Index) const {
247 return selectBDXAddr(SystemZAddressingMode::FormBDXLA,
248 SystemZAddressingMode::Disp12Pair,
249 Addr, Base, Disp, Index);
251 bool selectLAAddr20Pair(SDValue Addr, SDValue &Base, SDValue &Disp,
252 SDValue &Index) const {
253 return selectBDXAddr(SystemZAddressingMode::FormBDXLA,
254 SystemZAddressingMode::Disp20Pair,
255 Addr, Base, Disp, Index);
258 // Try to match Addr as an address with a base, 12-bit displacement
259 // and index, where the index is element Elem of a vector.
260 // Return true on success, storing the base, displacement and vector
261 // in Base, Disp and Index respectively.
262 bool selectBDVAddr12Only(SDValue Addr, SDValue Elem, SDValue &Base,
263 SDValue &Disp, SDValue &Index) const;
265 // Check whether (or Op (and X InsertMask)) is effectively an insertion
266 // of X into bits InsertMask of some Y != Op. Return true if so and
268 bool detectOrAndInsertion(SDValue &Op, uint64_t InsertMask) const;
270 // Try to update RxSBG so that only the bits of RxSBG.Input in Mask are used.
271 // Return true on success.
272 bool refineRxSBGMask(RxSBGOperands &RxSBG, uint64_t Mask) const;
274 // Try to fold some of RxSBG.Input into other fields of RxSBG.
275 // Return true on success.
276 bool expandRxSBG(RxSBGOperands &RxSBG) const;
278 // Return an undefined value of type VT.
279 SDValue getUNDEF(SDLoc DL, EVT VT) const;
281 // Convert N to VT, if it isn't already.
282 SDValue convertTo(SDLoc DL, EVT VT, SDValue N) const;
284 // Try to implement AND or shift node N using RISBG with the zero flag set.
285 // Return the selected node on success, otherwise return null.
286 SDNode *tryRISBGZero(SDNode *N);
288 // Try to use RISBG or Opcode to implement OR or XOR node N.
289 // Return the selected node on success, otherwise return null.
290 SDNode *tryRxSBG(SDNode *N, unsigned Opcode);
292 // If Op0 is null, then Node is a constant that can be loaded using:
294 // (Opcode UpperVal LowerVal)
296 // If Op0 is nonnull, then Node can be implemented using:
298 // (Opcode (Opcode Op0 UpperVal) LowerVal)
299 SDNode *splitLargeImmediate(unsigned Opcode, SDNode *Node, SDValue Op0,
300 uint64_t UpperVal, uint64_t LowerVal);
302 // Try to use gather instruction Opcode to implement vector insertion N.
303 SDNode *tryGather(SDNode *N, unsigned Opcode);
305 // Try to use scatter instruction Opcode to implement store Store.
306 SDNode *tryScatter(StoreSDNode *Store, unsigned Opcode);
308 // Return true if Load and Store are loads and stores of the same size
309 // and are guaranteed not to overlap. Such operations can be implemented
310 // using block (SS-format) instructions.
312 // Partial overlap would lead to incorrect code, since the block operations
313 // are logically bytewise, even though they have a fast path for the
314 // non-overlapping case. We also need to avoid full overlap (i.e. two
315 // addresses that might be equal at run time) because although that case
316 // would be handled correctly, it might be implemented by millicode.
317 bool canUseBlockOperation(StoreSDNode *Store, LoadSDNode *Load) const;
319 // N is a (store (load Y), X) pattern. Return true if it can use an MVC
321 bool storeLoadCanUseMVC(SDNode *N) const;
323 // N is a (store (op (load A[0]), (load A[1])), X) pattern. Return true
324 // if A[1 - I] == X and if N can use a block operation like NC from A[I]
326 bool storeLoadCanUseBlockBinary(SDNode *N, unsigned I) const;
329 SystemZDAGToDAGISel(SystemZTargetMachine &TM, CodeGenOpt::Level OptLevel)
330 : SelectionDAGISel(TM, OptLevel) {}
332 bool runOnMachineFunction(MachineFunction &MF) override {
333 Subtarget = &MF.getSubtarget<SystemZSubtarget>();
334 return SelectionDAGISel::runOnMachineFunction(MF);
337 // Override MachineFunctionPass.
338 const char *getPassName() const override {
339 return "SystemZ DAG->DAG Pattern Instruction Selection";
342 // Override SelectionDAGISel.
343 SDNode *Select(SDNode *Node) override;
344 bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
345 std::vector<SDValue> &OutOps) override;
347 // Include the pieces autogenerated from the target description.
348 #include "SystemZGenDAGISel.inc"
350 } // end anonymous namespace
352 FunctionPass *llvm::createSystemZISelDag(SystemZTargetMachine &TM,
353 CodeGenOpt::Level OptLevel) {
354 return new SystemZDAGToDAGISel(TM, OptLevel);
357 // Return true if Val should be selected as a displacement for an address
358 // with range DR. Here we're interested in the range of both the instruction
359 // described by DR and of any pairing instruction.
360 static bool selectDisp(SystemZAddressingMode::DispRange DR, int64_t Val) {
362 case SystemZAddressingMode::Disp12Only:
363 return isUInt<12>(Val);
365 case SystemZAddressingMode::Disp12Pair:
366 case SystemZAddressingMode::Disp20Only:
367 case SystemZAddressingMode::Disp20Pair:
368 return isInt<20>(Val);
370 case SystemZAddressingMode::Disp20Only128:
371 return isInt<20>(Val) && isInt<20>(Val + 8);
373 llvm_unreachable("Unhandled displacement range");
376 // Change the base or index in AM to Value, where IsBase selects
377 // between the base and index.
378 static void changeComponent(SystemZAddressingMode &AM, bool IsBase,
386 // The base or index of AM is equivalent to Value + ADJDYNALLOC,
387 // where IsBase selects between the base and index. Try to fold the
388 // ADJDYNALLOC into AM.
389 static bool expandAdjDynAlloc(SystemZAddressingMode &AM, bool IsBase,
391 if (AM.isDynAlloc() && !AM.IncludesDynAlloc) {
392 changeComponent(AM, IsBase, Value);
393 AM.IncludesDynAlloc = true;
399 // The base of AM is equivalent to Base + Index. Try to use Index as
400 // the index register.
401 static bool expandIndex(SystemZAddressingMode &AM, SDValue Base,
403 if (AM.hasIndexField() && !AM.Index.getNode()) {
411 // The base or index of AM is equivalent to Op0 + Op1, where IsBase selects
412 // between the base and index. Try to fold Op1 into AM's displacement.
413 static bool expandDisp(SystemZAddressingMode &AM, bool IsBase,
414 SDValue Op0, uint64_t Op1) {
415 // First try adjusting the displacement.
416 int64_t TestDisp = AM.Disp + Op1;
417 if (selectDisp(AM.DR, TestDisp)) {
418 changeComponent(AM, IsBase, Op0);
423 // We could consider forcing the displacement into a register and
424 // using it as an index, but it would need to be carefully tuned.
428 bool SystemZDAGToDAGISel::expandAddress(SystemZAddressingMode &AM,
430 SDValue N = IsBase ? AM.Base : AM.Index;
431 unsigned Opcode = N.getOpcode();
432 if (Opcode == ISD::TRUNCATE) {
434 Opcode = N.getOpcode();
436 if (Opcode == ISD::ADD || CurDAG->isBaseWithConstantOffset(N)) {
437 SDValue Op0 = N.getOperand(0);
438 SDValue Op1 = N.getOperand(1);
440 unsigned Op0Code = Op0->getOpcode();
441 unsigned Op1Code = Op1->getOpcode();
443 if (Op0Code == SystemZISD::ADJDYNALLOC)
444 return expandAdjDynAlloc(AM, IsBase, Op1);
445 if (Op1Code == SystemZISD::ADJDYNALLOC)
446 return expandAdjDynAlloc(AM, IsBase, Op0);
448 if (Op0Code == ISD::Constant)
449 return expandDisp(AM, IsBase, Op1,
450 cast<ConstantSDNode>(Op0)->getSExtValue());
451 if (Op1Code == ISD::Constant)
452 return expandDisp(AM, IsBase, Op0,
453 cast<ConstantSDNode>(Op1)->getSExtValue());
455 if (IsBase && expandIndex(AM, Op0, Op1))
458 if (Opcode == SystemZISD::PCREL_OFFSET) {
459 SDValue Full = N.getOperand(0);
460 SDValue Base = N.getOperand(1);
461 SDValue Anchor = Base.getOperand(0);
462 uint64_t Offset = (cast<GlobalAddressSDNode>(Full)->getOffset() -
463 cast<GlobalAddressSDNode>(Anchor)->getOffset());
464 return expandDisp(AM, IsBase, Base, Offset);
469 // Return true if an instruction with displacement range DR should be
470 // used for displacement value Val. selectDisp(DR, Val) must already hold.
471 static bool isValidDisp(SystemZAddressingMode::DispRange DR, int64_t Val) {
472 assert(selectDisp(DR, Val) && "Invalid displacement");
474 case SystemZAddressingMode::Disp12Only:
475 case SystemZAddressingMode::Disp20Only:
476 case SystemZAddressingMode::Disp20Only128:
479 case SystemZAddressingMode::Disp12Pair:
480 // Use the other instruction if the displacement is too large.
481 return isUInt<12>(Val);
483 case SystemZAddressingMode::Disp20Pair:
484 // Use the other instruction if the displacement is small enough.
485 return !isUInt<12>(Val);
487 llvm_unreachable("Unhandled displacement range");
490 // Return true if Base + Disp + Index should be performed by LA(Y).
491 static bool shouldUseLA(SDNode *Base, int64_t Disp, SDNode *Index) {
492 // Don't use LA(Y) for constants.
496 // Always use LA(Y) for frame addresses, since we know that the destination
497 // register is almost always (perhaps always) going to be different from
498 // the frame register.
499 if (Base->getOpcode() == ISD::FrameIndex)
503 // Always use LA(Y) if there is a base, displacement and index.
507 // Always use LA if the displacement is small enough. It should always
508 // be no worse than AGHI (and better if it avoids a move).
509 if (isUInt<12>(Disp))
512 // For similar reasons, always use LAY if the constant is too big for AGHI.
513 // LAY should be no worse than AGFI.
514 if (!isInt<16>(Disp))
517 // Don't use LA for plain registers.
521 // Don't use LA for plain addition if the index operand is only used
522 // once. It should be a natural two-operand addition in that case.
523 if (Index->hasOneUse())
526 // Prefer addition if the second operation is sign-extended, in the
527 // hope of using AGF.
528 unsigned IndexOpcode = Index->getOpcode();
529 if (IndexOpcode == ISD::SIGN_EXTEND ||
530 IndexOpcode == ISD::SIGN_EXTEND_INREG)
534 // Don't use LA for two-operand addition if either operand is only
535 // used once. The addition instructions are better in that case.
536 if (Base->hasOneUse())
542 // Return true if Addr is suitable for AM, updating AM if so.
543 bool SystemZDAGToDAGISel::selectAddress(SDValue Addr,
544 SystemZAddressingMode &AM) const {
545 // Start out assuming that the address will need to be loaded separately,
546 // then try to extend it as much as we can.
549 // First try treating the address as a constant.
550 if (Addr.getOpcode() == ISD::Constant &&
551 expandDisp(AM, true, SDValue(),
552 cast<ConstantSDNode>(Addr)->getSExtValue()))
555 // Otherwise try expanding each component.
556 while (expandAddress(AM, true) ||
557 (AM.Index.getNode() && expandAddress(AM, false)))
560 // Reject cases where it isn't profitable to use LA(Y).
561 if (AM.Form == SystemZAddressingMode::FormBDXLA &&
562 !shouldUseLA(AM.Base.getNode(), AM.Disp, AM.Index.getNode()))
565 // Reject cases where the other instruction in a pair should be used.
566 if (!isValidDisp(AM.DR, AM.Disp))
569 // Make sure that ADJDYNALLOC is included where necessary.
570 if (AM.isDynAlloc() && !AM.IncludesDynAlloc)
577 // Insert a node into the DAG at least before Pos. This will reposition
578 // the node as needed, and will assign it a node ID that is <= Pos's ID.
579 // Note that this does *not* preserve the uniqueness of node IDs!
580 // The selection DAG must no longer depend on their uniqueness when this
582 static void insertDAGNode(SelectionDAG *DAG, SDNode *Pos, SDValue N) {
583 if (N.getNode()->getNodeId() == -1 ||
584 N.getNode()->getNodeId() > Pos->getNodeId()) {
585 DAG->RepositionNode(Pos, N.getNode());
586 N.getNode()->setNodeId(Pos->getNodeId());
590 void SystemZDAGToDAGISel::getAddressOperands(const SystemZAddressingMode &AM,
591 EVT VT, SDValue &Base,
592 SDValue &Disp) const {
595 // Register 0 means "no base". This is mostly useful for shifts.
596 Base = CurDAG->getRegister(0, VT);
597 else if (Base.getOpcode() == ISD::FrameIndex) {
598 // Lower a FrameIndex to a TargetFrameIndex.
599 int64_t FrameIndex = cast<FrameIndexSDNode>(Base)->getIndex();
600 Base = CurDAG->getTargetFrameIndex(FrameIndex, VT);
601 } else if (Base.getValueType() != VT) {
602 // Truncate values from i64 to i32, for shifts.
603 assert(VT == MVT::i32 && Base.getValueType() == MVT::i64 &&
604 "Unexpected truncation");
606 SDValue Trunc = CurDAG->getNode(ISD::TRUNCATE, DL, VT, Base);
607 insertDAGNode(CurDAG, Base.getNode(), Trunc);
611 // Lower the displacement to a TargetConstant.
612 Disp = CurDAG->getTargetConstant(AM.Disp, SDLoc(Base), VT);
615 void SystemZDAGToDAGISel::getAddressOperands(const SystemZAddressingMode &AM,
616 EVT VT, SDValue &Base,
618 SDValue &Index) const {
619 getAddressOperands(AM, VT, Base, Disp);
622 if (!Index.getNode())
623 // Register 0 means "no index".
624 Index = CurDAG->getRegister(0, VT);
627 bool SystemZDAGToDAGISel::selectBDAddr(SystemZAddressingMode::DispRange DR,
628 SDValue Addr, SDValue &Base,
629 SDValue &Disp) const {
630 SystemZAddressingMode AM(SystemZAddressingMode::FormBD, DR);
631 if (!selectAddress(Addr, AM))
634 getAddressOperands(AM, Addr.getValueType(), Base, Disp);
638 bool SystemZDAGToDAGISel::selectMVIAddr(SystemZAddressingMode::DispRange DR,
639 SDValue Addr, SDValue &Base,
640 SDValue &Disp) const {
641 SystemZAddressingMode AM(SystemZAddressingMode::FormBDXNormal, DR);
642 if (!selectAddress(Addr, AM) || AM.Index.getNode())
645 getAddressOperands(AM, Addr.getValueType(), Base, Disp);
649 bool SystemZDAGToDAGISel::selectBDXAddr(SystemZAddressingMode::AddrForm Form,
650 SystemZAddressingMode::DispRange DR,
651 SDValue Addr, SDValue &Base,
652 SDValue &Disp, SDValue &Index) const {
653 SystemZAddressingMode AM(Form, DR);
654 if (!selectAddress(Addr, AM))
657 getAddressOperands(AM, Addr.getValueType(), Base, Disp, Index);
661 bool SystemZDAGToDAGISel::selectBDVAddr12Only(SDValue Addr, SDValue Elem,
664 SDValue &Index) const {
666 if (selectBDXAddr12Only(Addr, Regs[0], Disp, Regs[1]) &&
667 Regs[0].getNode() && Regs[1].getNode()) {
668 for (unsigned int I = 0; I < 2; ++I) {
671 // We can't tell here whether the index vector has the right type
672 // for the access; the caller needs to do that instead.
673 if (Index.getOpcode() == ISD::ZERO_EXTEND)
674 Index = Index.getOperand(0);
675 if (Index.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
676 Index.getOperand(1) == Elem) {
677 Index = Index.getOperand(0);
685 bool SystemZDAGToDAGISel::detectOrAndInsertion(SDValue &Op,
686 uint64_t InsertMask) const {
687 // We're only interested in cases where the insertion is into some operand
688 // of Op, rather than into Op itself. The only useful case is an AND.
689 if (Op.getOpcode() != ISD::AND)
692 // We need a constant mask.
693 auto *MaskNode = dyn_cast<ConstantSDNode>(Op.getOperand(1).getNode());
697 // It's not an insertion of Op.getOperand(0) if the two masks overlap.
698 uint64_t AndMask = MaskNode->getZExtValue();
699 if (InsertMask & AndMask)
702 // It's only an insertion if all bits are covered or are known to be zero.
703 // The inner check covers all cases but is more expensive.
704 uint64_t Used = allOnes(Op.getValueType().getSizeInBits());
705 if (Used != (AndMask | InsertMask)) {
706 APInt KnownZero, KnownOne;
707 CurDAG->computeKnownBits(Op.getOperand(0), KnownZero, KnownOne);
708 if (Used != (AndMask | InsertMask | KnownZero.getZExtValue()))
712 Op = Op.getOperand(0);
716 bool SystemZDAGToDAGISel::refineRxSBGMask(RxSBGOperands &RxSBG,
717 uint64_t Mask) const {
718 const SystemZInstrInfo *TII = getInstrInfo();
719 if (RxSBG.Rotate != 0)
720 Mask = (Mask << RxSBG.Rotate) | (Mask >> (64 - RxSBG.Rotate));
722 if (TII->isRxSBGMask(Mask, RxSBG.BitSize, RxSBG.Start, RxSBG.End)) {
729 // Return true if any bits of (RxSBG.Input & Mask) are significant.
730 static bool maskMatters(RxSBGOperands &RxSBG, uint64_t Mask) {
731 // Rotate the mask in the same way as RxSBG.Input is rotated.
732 if (RxSBG.Rotate != 0)
733 Mask = ((Mask << RxSBG.Rotate) | (Mask >> (64 - RxSBG.Rotate)));
734 return (Mask & RxSBG.Mask) != 0;
737 bool SystemZDAGToDAGISel::expandRxSBG(RxSBGOperands &RxSBG) const {
738 SDValue N = RxSBG.Input;
739 unsigned Opcode = N.getOpcode();
742 if (RxSBG.Opcode == SystemZ::RNSBG)
745 auto *MaskNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
749 SDValue Input = N.getOperand(0);
750 uint64_t Mask = MaskNode->getZExtValue();
751 if (!refineRxSBGMask(RxSBG, Mask)) {
752 // If some bits of Input are already known zeros, those bits will have
753 // been removed from the mask. See if adding them back in makes the
755 APInt KnownZero, KnownOne;
756 CurDAG->computeKnownBits(Input, KnownZero, KnownOne);
757 Mask |= KnownZero.getZExtValue();
758 if (!refineRxSBGMask(RxSBG, Mask))
766 if (RxSBG.Opcode != SystemZ::RNSBG)
769 auto *MaskNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
773 SDValue Input = N.getOperand(0);
774 uint64_t Mask = ~MaskNode->getZExtValue();
775 if (!refineRxSBGMask(RxSBG, Mask)) {
776 // If some bits of Input are already known ones, those bits will have
777 // been removed from the mask. See if adding them back in makes the
779 APInt KnownZero, KnownOne;
780 CurDAG->computeKnownBits(Input, KnownZero, KnownOne);
781 Mask &= ~KnownOne.getZExtValue();
782 if (!refineRxSBGMask(RxSBG, Mask))
790 // Any 64-bit rotate left can be merged into the RxSBG.
791 if (RxSBG.BitSize != 64 || N.getValueType() != MVT::i64)
793 auto *CountNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
797 RxSBG.Rotate = (RxSBG.Rotate + CountNode->getZExtValue()) & 63;
798 RxSBG.Input = N.getOperand(0);
802 case ISD::ANY_EXTEND:
803 // Bits above the extended operand are don't-care.
804 RxSBG.Input = N.getOperand(0);
807 case ISD::ZERO_EXTEND:
808 if (RxSBG.Opcode != SystemZ::RNSBG) {
809 // Restrict the mask to the extended operand.
810 unsigned InnerBitSize = N.getOperand(0).getValueType().getSizeInBits();
811 if (!refineRxSBGMask(RxSBG, allOnes(InnerBitSize)))
814 RxSBG.Input = N.getOperand(0);
819 case ISD::SIGN_EXTEND: {
820 // Check that the extension bits are don't-care (i.e. are masked out
821 // by the final mask).
822 unsigned InnerBitSize = N.getOperand(0).getValueType().getSizeInBits();
823 if (maskMatters(RxSBG, allOnes(RxSBG.BitSize) - allOnes(InnerBitSize)))
826 RxSBG.Input = N.getOperand(0);
831 auto *CountNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
835 uint64_t Count = CountNode->getZExtValue();
836 unsigned BitSize = N.getValueType().getSizeInBits();
837 if (Count < 1 || Count >= BitSize)
840 if (RxSBG.Opcode == SystemZ::RNSBG) {
841 // Treat (shl X, count) as (rotl X, size-count) as long as the bottom
842 // count bits from RxSBG.Input are ignored.
843 if (maskMatters(RxSBG, allOnes(Count)))
846 // Treat (shl X, count) as (and (rotl X, count), ~0<<count).
847 if (!refineRxSBGMask(RxSBG, allOnes(BitSize - Count) << Count))
851 RxSBG.Rotate = (RxSBG.Rotate + Count) & 63;
852 RxSBG.Input = N.getOperand(0);
858 auto *CountNode = dyn_cast<ConstantSDNode>(N.getOperand(1).getNode());
862 uint64_t Count = CountNode->getZExtValue();
863 unsigned BitSize = N.getValueType().getSizeInBits();
864 if (Count < 1 || Count >= BitSize)
867 if (RxSBG.Opcode == SystemZ::RNSBG || Opcode == ISD::SRA) {
868 // Treat (srl|sra X, count) as (rotl X, size-count) as long as the top
869 // count bits from RxSBG.Input are ignored.
870 if (maskMatters(RxSBG, allOnes(Count) << (BitSize - Count)))
873 // Treat (srl X, count), mask) as (and (rotl X, size-count), ~0>>count),
874 // which is similar to SLL above.
875 if (!refineRxSBGMask(RxSBG, allOnes(BitSize - Count)))
879 RxSBG.Rotate = (RxSBG.Rotate - Count) & 63;
880 RxSBG.Input = N.getOperand(0);
888 SDValue SystemZDAGToDAGISel::getUNDEF(SDLoc DL, EVT VT) const {
889 SDNode *N = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, VT);
890 return SDValue(N, 0);
893 SDValue SystemZDAGToDAGISel::convertTo(SDLoc DL, EVT VT, SDValue N) const {
894 if (N.getValueType() == MVT::i32 && VT == MVT::i64)
895 return CurDAG->getTargetInsertSubreg(SystemZ::subreg_l32,
896 DL, VT, getUNDEF(DL, MVT::i64), N);
897 if (N.getValueType() == MVT::i64 && VT == MVT::i32)
898 return CurDAG->getTargetExtractSubreg(SystemZ::subreg_l32, DL, VT, N);
899 assert(N.getValueType() == VT && "Unexpected value types");
903 SDNode *SystemZDAGToDAGISel::tryRISBGZero(SDNode *N) {
905 EVT VT = N->getValueType(0);
906 RxSBGOperands RISBG(SystemZ::RISBG, SDValue(N, 0));
908 while (expandRxSBG(RISBG))
909 if (RISBG.Input.getOpcode() != ISD::ANY_EXTEND)
914 // Prefer to use normal shift instructions over RISBG, since they can handle
915 // all cases and are sometimes shorter.
916 if (N->getOpcode() != ISD::AND)
919 // Prefer register extensions like LLC over RISBG. Also prefer to start
920 // out with normal ANDs if one instruction would be enough. We can convert
921 // these ANDs into an RISBG later if a three-address instruction is useful.
922 if (VT == MVT::i32 ||
923 RISBG.Mask == 0xff ||
924 RISBG.Mask == 0xffff ||
925 SystemZ::isImmLF(~RISBG.Mask) ||
926 SystemZ::isImmHF(~RISBG.Mask)) {
927 // Force the new mask into the DAG, since it may include known-one bits.
928 auto *MaskN = cast<ConstantSDNode>(N->getOperand(1).getNode());
929 if (MaskN->getZExtValue() != RISBG.Mask) {
930 SDValue NewMask = CurDAG->getConstant(RISBG.Mask, DL, VT);
931 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), NewMask);
932 return SelectCode(N);
938 unsigned Opcode = SystemZ::RISBG;
939 // Prefer RISBGN if available, since it does not clobber CC.
940 if (Subtarget->hasMiscellaneousExtensions())
941 Opcode = SystemZ::RISBGN;
942 EVT OpcodeVT = MVT::i64;
943 if (VT == MVT::i32 && Subtarget->hasHighWord()) {
944 Opcode = SystemZ::RISBMux;
950 getUNDEF(DL, OpcodeVT),
951 convertTo(DL, OpcodeVT, RISBG.Input),
952 CurDAG->getTargetConstant(RISBG.Start, DL, MVT::i32),
953 CurDAG->getTargetConstant(RISBG.End | 128, DL, MVT::i32),
954 CurDAG->getTargetConstant(RISBG.Rotate, DL, MVT::i32)
956 N = CurDAG->getMachineNode(Opcode, DL, OpcodeVT, Ops);
957 return convertTo(DL, VT, SDValue(N, 0)).getNode();
960 SDNode *SystemZDAGToDAGISel::tryRxSBG(SDNode *N, unsigned Opcode) {
961 // Try treating each operand of N as the second operand of the RxSBG
962 // and see which goes deepest.
963 RxSBGOperands RxSBG[] = {
964 RxSBGOperands(Opcode, N->getOperand(0)),
965 RxSBGOperands(Opcode, N->getOperand(1))
967 unsigned Count[] = { 0, 0 };
968 for (unsigned I = 0; I < 2; ++I)
969 while (expandRxSBG(RxSBG[I]))
970 if (RxSBG[I].Input.getOpcode() != ISD::ANY_EXTEND)
973 // Do nothing if neither operand is suitable.
974 if (Count[0] == 0 && Count[1] == 0)
977 // Pick the deepest second operand.
978 unsigned I = Count[0] > Count[1] ? 0 : 1;
979 SDValue Op0 = N->getOperand(I ^ 1);
981 // Prefer IC for character insertions from memory.
982 if (Opcode == SystemZ::ROSBG && (RxSBG[I].Mask & 0xff) == 0)
983 if (auto *Load = dyn_cast<LoadSDNode>(Op0.getNode()))
984 if (Load->getMemoryVT() == MVT::i8)
987 // See whether we can avoid an AND in the first operand by converting
989 if (Opcode == SystemZ::ROSBG && detectOrAndInsertion(Op0, RxSBG[I].Mask)) {
990 Opcode = SystemZ::RISBG;
991 // Prefer RISBGN if available, since it does not clobber CC.
992 if (Subtarget->hasMiscellaneousExtensions())
993 Opcode = SystemZ::RISBGN;
997 EVT VT = N->getValueType(0);
999 convertTo(DL, MVT::i64, Op0),
1000 convertTo(DL, MVT::i64, RxSBG[I].Input),
1001 CurDAG->getTargetConstant(RxSBG[I].Start, DL, MVT::i32),
1002 CurDAG->getTargetConstant(RxSBG[I].End, DL, MVT::i32),
1003 CurDAG->getTargetConstant(RxSBG[I].Rotate, DL, MVT::i32)
1005 N = CurDAG->getMachineNode(Opcode, DL, MVT::i64, Ops);
1006 return convertTo(DL, VT, SDValue(N, 0)).getNode();
1009 SDNode *SystemZDAGToDAGISel::splitLargeImmediate(unsigned Opcode, SDNode *Node,
1010 SDValue Op0, uint64_t UpperVal,
1011 uint64_t LowerVal) {
1012 EVT VT = Node->getValueType(0);
1014 SDValue Upper = CurDAG->getConstant(UpperVal, DL, VT);
1016 Upper = CurDAG->getNode(Opcode, DL, VT, Op0, Upper);
1017 Upper = SDValue(Select(Upper.getNode()), 0);
1019 SDValue Lower = CurDAG->getConstant(LowerVal, DL, VT);
1020 SDValue Or = CurDAG->getNode(Opcode, DL, VT, Upper, Lower);
1021 return Or.getNode();
1024 SDNode *SystemZDAGToDAGISel::tryGather(SDNode *N, unsigned Opcode) {
1025 SDValue ElemV = N->getOperand(2);
1026 auto *ElemN = dyn_cast<ConstantSDNode>(ElemV);
1030 unsigned Elem = ElemN->getZExtValue();
1031 EVT VT = N->getValueType(0);
1032 if (Elem >= VT.getVectorNumElements())
1035 auto *Load = dyn_cast<LoadSDNode>(N->getOperand(1));
1036 if (!Load || !Load->hasOneUse())
1038 if (Load->getMemoryVT().getSizeInBits() !=
1039 Load->getValueType(0).getSizeInBits())
1042 SDValue Base, Disp, Index;
1043 if (!selectBDVAddr12Only(Load->getBasePtr(), ElemV, Base, Disp, Index) ||
1044 Index.getValueType() != VT.changeVectorElementTypeToInteger())
1049 N->getOperand(0), Base, Disp, Index,
1050 CurDAG->getTargetConstant(Elem, DL, MVT::i32), Load->getChain()
1052 SDNode *Res = CurDAG->getMachineNode(Opcode, DL, VT, MVT::Other, Ops);
1053 ReplaceUses(SDValue(Load, 1), SDValue(Res, 1));
1057 SDNode *SystemZDAGToDAGISel::tryScatter(StoreSDNode *Store, unsigned Opcode) {
1058 SDValue Value = Store->getValue();
1059 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1061 if (Store->getMemoryVT().getSizeInBits() !=
1062 Value.getValueType().getSizeInBits())
1065 SDValue ElemV = Value.getOperand(1);
1066 auto *ElemN = dyn_cast<ConstantSDNode>(ElemV);
1070 SDValue Vec = Value.getOperand(0);
1071 EVT VT = Vec.getValueType();
1072 unsigned Elem = ElemN->getZExtValue();
1073 if (Elem >= VT.getVectorNumElements())
1076 SDValue Base, Disp, Index;
1077 if (!selectBDVAddr12Only(Store->getBasePtr(), ElemV, Base, Disp, Index) ||
1078 Index.getValueType() != VT.changeVectorElementTypeToInteger())
1083 Vec, Base, Disp, Index, CurDAG->getTargetConstant(Elem, DL, MVT::i32),
1086 return CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops);
1089 bool SystemZDAGToDAGISel::canUseBlockOperation(StoreSDNode *Store,
1090 LoadSDNode *Load) const {
1091 // Check that the two memory operands have the same size.
1092 if (Load->getMemoryVT() != Store->getMemoryVT())
1095 // Volatility stops an access from being decomposed.
1096 if (Load->isVolatile() || Store->isVolatile())
1099 // There's no chance of overlap if the load is invariant.
1100 if (Load->isInvariant())
1103 // Otherwise we need to check whether there's an alias.
1104 const Value *V1 = Load->getMemOperand()->getValue();
1105 const Value *V2 = Store->getMemOperand()->getValue();
1110 uint64_t Size = Load->getMemoryVT().getStoreSize();
1111 int64_t End1 = Load->getSrcValueOffset() + Size;
1112 int64_t End2 = Store->getSrcValueOffset() + Size;
1113 if (V1 == V2 && End1 == End2)
1116 return !AA->alias(MemoryLocation(V1, End1, Load->getAAInfo()),
1117 MemoryLocation(V2, End2, Store->getAAInfo()));
1120 bool SystemZDAGToDAGISel::storeLoadCanUseMVC(SDNode *N) const {
1121 auto *Store = cast<StoreSDNode>(N);
1122 auto *Load = cast<LoadSDNode>(Store->getValue());
1124 // Prefer not to use MVC if either address can use ... RELATIVE LONG
1126 uint64_t Size = Load->getMemoryVT().getStoreSize();
1127 if (Size > 1 && Size <= 8) {
1128 // Prefer LHRL, LRL and LGRL.
1129 if (SystemZISD::isPCREL(Load->getBasePtr().getOpcode()))
1131 // Prefer STHRL, STRL and STGRL.
1132 if (SystemZISD::isPCREL(Store->getBasePtr().getOpcode()))
1136 return canUseBlockOperation(Store, Load);
1139 bool SystemZDAGToDAGISel::storeLoadCanUseBlockBinary(SDNode *N,
1141 auto *StoreA = cast<StoreSDNode>(N);
1142 auto *LoadA = cast<LoadSDNode>(StoreA->getValue().getOperand(1 - I));
1143 auto *LoadB = cast<LoadSDNode>(StoreA->getValue().getOperand(I));
1144 return !LoadA->isVolatile() && canUseBlockOperation(StoreA, LoadB);
1147 SDNode *SystemZDAGToDAGISel::Select(SDNode *Node) {
1148 // Dump information about the Node being selected
1149 DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
1151 // If we have a custom node, we already have selected!
1152 if (Node->isMachineOpcode()) {
1153 DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
1154 Node->setNodeId(-1);
1158 unsigned Opcode = Node->getOpcode();
1159 SDNode *ResNode = nullptr;
1162 if (Node->getOperand(1).getOpcode() != ISD::Constant)
1163 ResNode = tryRxSBG(Node, SystemZ::ROSBG);
1167 if (Node->getOperand(1).getOpcode() != ISD::Constant)
1168 ResNode = tryRxSBG(Node, SystemZ::RXSBG);
1171 // If this is a 64-bit operation in which both 32-bit halves are nonzero,
1172 // split the operation into two.
1173 if (!ResNode && Node->getValueType(0) == MVT::i64)
1174 if (auto *Op1 = dyn_cast<ConstantSDNode>(Node->getOperand(1))) {
1175 uint64_t Val = Op1->getZExtValue();
1176 if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val))
1177 Node = splitLargeImmediate(Opcode, Node, Node->getOperand(0),
1178 Val - uint32_t(Val), uint32_t(Val));
1183 if (Node->getOperand(1).getOpcode() != ISD::Constant)
1184 ResNode = tryRxSBG(Node, SystemZ::RNSBG);
1189 case ISD::ZERO_EXTEND:
1191 ResNode = tryRISBGZero(Node);
1195 // If this is a 64-bit constant that is out of the range of LLILF,
1196 // LLIHF and LGFI, split it into two 32-bit pieces.
1197 if (Node->getValueType(0) == MVT::i64) {
1198 uint64_t Val = cast<ConstantSDNode>(Node)->getZExtValue();
1199 if (!SystemZ::isImmLF(Val) && !SystemZ::isImmHF(Val) && !isInt<32>(Val))
1200 Node = splitLargeImmediate(ISD::OR, Node, SDValue(),
1201 Val - uint32_t(Val), uint32_t(Val));
1205 case SystemZISD::SELECT_CCMASK: {
1206 SDValue Op0 = Node->getOperand(0);
1207 SDValue Op1 = Node->getOperand(1);
1208 // Prefer to put any load first, so that it can be matched as a
1209 // conditional load.
1210 if (Op1.getOpcode() == ISD::LOAD && Op0.getOpcode() != ISD::LOAD) {
1211 SDValue CCValid = Node->getOperand(2);
1212 SDValue CCMask = Node->getOperand(3);
1213 uint64_t ConstCCValid =
1214 cast<ConstantSDNode>(CCValid.getNode())->getZExtValue();
1215 uint64_t ConstCCMask =
1216 cast<ConstantSDNode>(CCMask.getNode())->getZExtValue();
1217 // Invert the condition.
1218 CCMask = CurDAG->getConstant(ConstCCValid ^ ConstCCMask, SDLoc(Node),
1219 CCMask.getValueType());
1220 SDValue Op4 = Node->getOperand(4);
1221 Node = CurDAG->UpdateNodeOperands(Node, Op1, Op0, CCValid, CCMask, Op4);
1226 case ISD::INSERT_VECTOR_ELT: {
1227 EVT VT = Node->getValueType(0);
1228 unsigned ElemBitSize = VT.getVectorElementType().getSizeInBits();
1229 if (ElemBitSize == 32)
1230 ResNode = tryGather(Node, SystemZ::VGEF);
1231 else if (ElemBitSize == 64)
1232 ResNode = tryGather(Node, SystemZ::VGEG);
1237 auto *Store = cast<StoreSDNode>(Node);
1238 unsigned ElemBitSize = Store->getValue().getValueType().getSizeInBits();
1239 if (ElemBitSize == 32)
1240 ResNode = tryScatter(Store, SystemZ::VSCEF);
1241 else if (ElemBitSize == 64)
1242 ResNode = tryScatter(Store, SystemZ::VSCEG);
1247 // Select the default instruction
1249 ResNode = SelectCode(Node);
1251 DEBUG(errs() << "=> ";
1252 if (ResNode == nullptr || ResNode == Node)
1255 ResNode->dump(CurDAG);
1261 bool SystemZDAGToDAGISel::
1262 SelectInlineAsmMemoryOperand(const SDValue &Op,
1263 unsigned ConstraintID,
1264 std::vector<SDValue> &OutOps) {
1265 switch(ConstraintID) {
1267 llvm_unreachable("Unexpected asm memory constraint");
1268 case InlineAsm::Constraint_i:
1269 case InlineAsm::Constraint_m:
1270 case InlineAsm::Constraint_Q:
1271 case InlineAsm::Constraint_R:
1272 case InlineAsm::Constraint_S:
1273 case InlineAsm::Constraint_T:
1274 // Accept addresses with short displacements, which are compatible
1275 // with Q, R, S and T. But keep the index operand for future expansion.
1276 SDValue Base, Disp, Index;
1277 if (selectBDXAddr(SystemZAddressingMode::FormBD,
1278 SystemZAddressingMode::Disp12Only,
1279 Op, Base, Disp, Index)) {
1280 OutOps.push_back(Base);
1281 OutOps.push_back(Disp);
1282 OutOps.push_back(Index);