LLVM 24.0.0git
M68kISelLowering.cpp
Go to the documentation of this file.
1//===-- M68kISelLowering.cpp - M68k DAG Lowering Impl -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines the interfaces that M68k uses to lower LLVM code into a
11/// selection DAG.
12///
13//===----------------------------------------------------------------------===//
14
15#include "M68kISelLowering.h"
16#include "M68kCallingConv.h"
17#include "M68kMachineFunction.h"
19#include "M68kSubtarget.h"
20#include "M68kTargetMachine.h"
23
24#include "llvm/ADT/Statistic.h"
33#include "llvm/IR/CallingConv.h"
37#include "llvm/Support/Debug.h"
41
42using namespace llvm;
43
44#define DEBUG_TYPE "M68k-isel"
45
46STATISTIC(NumTailCalls, "Number of tail calls");
47
49 const M68kSubtarget &STI)
50 : TargetLowering(TM, STI), Subtarget(STI), TM(TM) {
51
52 MVT PtrVT = MVT::i32;
53
54 // This is based on M68k SetCC (scc) setting the destination byte to all 1s.
55 // See also getSetCCResultType().
57
58 auto *RegInfo = Subtarget.getRegisterInfo();
59 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
60
61 // Set up the register classes.
62 addRegisterClass(MVT::i8, &M68k::DR8RegClass);
63 addRegisterClass(MVT::i16, &M68k::XR16RegClass);
64 addRegisterClass(MVT::i32, &M68k::XR32RegClass);
65
66 for (auto VT : MVT::integer_valuetypes()) {
70 }
71
72 // We don't accept any truncstore of integer registers.
73 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
74 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
75 setTruncStoreAction(MVT::i64, MVT::i8, Expand);
76 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
77 setTruncStoreAction(MVT::i32, MVT::i8, Expand);
78 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
79
80 // M68k can't natively div/rem 8-bit values, but we define our own patterns
81 // that handle the integer promotion, so it's marked as legal here.
86
87 if (Subtarget.atLeastM68020()) {
91 } else {
95 }
97
101
104 setOperationAction(OP, MVT::i8, Promote);
105 setOperationAction(OP, MVT::i16, Legal);
106 setOperationAction(OP, MVT::i32, LibCall);
107 }
108
109 for (auto OP : {ISD::UMUL_LOHI, ISD::SMUL_LOHI}) {
110 setOperationAction(OP, MVT::i8, Expand);
111 setOperationAction(OP, MVT::i16, Expand);
112 }
113
114 for (auto OP : {ISD::SMULO, ISD::UMULO}) {
115 setOperationAction(OP, MVT::i8, Custom);
116 setOperationAction(OP, MVT::i16, Custom);
117 setOperationAction(OP, MVT::i32, Custom);
118 }
119
121 setOperationAction(OP, MVT::i32, Custom);
122
123 for (auto VT : {MVT::i8, MVT::i16, MVT::i32}) {
126 }
127
128 // SADDO and friends are legal with this setup, i hope
129 for (auto VT : {MVT::i8, MVT::i16, MVT::i32}) {
134 }
135
138
139 for (auto VT : {MVT::i8, MVT::i16, MVT::i32}) {
145 }
146
150
151 for (auto VT : {MVT::i8, MVT::i16, MVT::i32}) {
155 }
156
163
168
171
173
175
176 // We lower the `atomic-compare-and-swap` to `__sync_val_compare_and_swap`
177 // for subtarget < M68020
179 setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i8, MVT::i16, MVT::i32},
180 Subtarget.atLeastM68020() ? Legal : LibCall);
181
183
184 // M68k does not have native read-modify-write support, so expand all of them
185 // to `__sync_fetch_*` for target < M68020, otherwise expand to CmpxChg.
186 // See `shouldExpandAtomicRMWInIR` below.
188 {
200 },
201 {MVT::i8, MVT::i16, MVT::i32}, LibCall);
202
204}
205
212
215 const Constant *) const {
216 return M68k::D0;
217}
218
221 const Constant *) const {
222 return M68k::D1;
223}
224
227 return StringSwitch<InlineAsm::ConstraintCode>(ConstraintCode)
229 // We borrow ConstraintCode::Um for 'U'.
232}
233
235 LLVMContext &Context, EVT VT) const {
236 // M68k SETcc producess either 0x00 or 0xFF
237 return MVT::i8;
238}
239
241 EVT Ty) const {
242 if (Ty.isSimple()) {
243 return Ty.getSimpleVT();
244 }
245 return MVT::getIntegerVT(DL.getPointerSizeInBits(0));
246}
247
248#define GET_CALLING_CONV_IMPL
249#include "M68kGenCallingConv.inc"
250
252
253static StructReturnType
255 if (Outs.empty())
256 return NotStructReturn;
257
258 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
259 if (!Flags.isSRet())
260 return NotStructReturn;
261 if (Flags.isInReg())
262 return RegStructReturn;
263 return StackStructReturn;
264}
265
266/// Determines whether a function uses struct return semantics.
267static StructReturnType
269 if (Ins.empty())
270 return NotStructReturn;
271
272 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
273 if (!Flags.isSRet())
274 return NotStructReturn;
275 if (Flags.isInReg())
276 return RegStructReturn;
277 return StackStructReturn;
278}
279
280/// Make a copy of an aggregate at address specified by "Src" to address
281/// "Dst" with size and alignment information specified by the specific
282/// parameter attribute. The copy will be passed as a byval function parameter.
284 SDValue Chain, ISD::ArgFlagsTy Flags,
285 SelectionDAG &DAG, const SDLoc &DL) {
286 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), DL, MVT::i32);
287 Align Alignment = Flags.getNonZeroByValAlign();
288
289 return DAG.getMemcpy(Chain, DL, Dst, Src, SizeNode, Alignment, Alignment,
290 /*isVolatile=*/false, /*AlwaysInline=*/true,
291 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(),
293}
294
295/// Return true if the calling convention is one that we can guarantee TCO for.
296static bool canGuaranteeTCO(CallingConv::ID CC) { return false; }
297
298/// Return true if we might ever do TCO for calls with this calling convention.
300 switch (CC) {
301 // C calling conventions:
302 case CallingConv::C:
303 return true;
304 default:
305 return canGuaranteeTCO(CC);
306 }
307}
308
309/// Return true if the function is being made into a tailcall target by
310/// changing its ABI.
311static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
312 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
313}
314
315/// Return true if the given stack call argument is already available in the
316/// same position (relatively) of the caller's incoming argument stack.
317static bool MatchingStackOffset(SDValue Arg, unsigned Offset,
320 const M68kInstrInfo *TII,
321 const CCValAssign &VA) {
322 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
323
324 for (;;) {
325 // Look through nodes that don't alter the bits of the incoming value.
326 unsigned Op = Arg.getOpcode();
328 Arg = Arg.getOperand(0);
329 continue;
330 }
331 if (Op == ISD::TRUNCATE) {
332 const SDValue &TruncInput = Arg.getOperand(0);
333 if (TruncInput.getOpcode() == ISD::AssertZext &&
334 cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
335 Arg.getValueType()) {
336 Arg = TruncInput.getOperand(0);
337 continue;
338 }
339 }
340 break;
341 }
342
343 int FI = INT_MAX;
344 if (Arg.getOpcode() == ISD::CopyFromReg) {
345 Register VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
347 return false;
348 MachineInstr *Def = MRI->getVRegDef(VR);
349 if (!Def)
350 return false;
351 if (!Flags.isByVal()) {
352 if (!TII->isLoadFromStackSlot(*Def, FI))
353 return false;
354 } else {
355 unsigned Opcode = Def->getOpcode();
356 if ((Opcode == M68k::LEA32p || Opcode == M68k::LEA32f) &&
357 Def->getOperand(1).isFI()) {
358 FI = Def->getOperand(1).getIndex();
359 Bytes = Flags.getByValSize();
360 } else
361 return false;
362 }
363 } else if (auto *Ld = dyn_cast<LoadSDNode>(Arg)) {
364 if (Flags.isByVal())
365 // ByVal argument is passed in as a pointer but it's now being
366 // dereferenced. e.g.
367 // define @foo(%struct.X* %A) {
368 // tail call @bar(%struct.X* byval %A)
369 // }
370 return false;
371 SDValue Ptr = Ld->getBasePtr();
373 if (!FINode)
374 return false;
375 FI = FINode->getIndex();
376 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
378 FI = FINode->getIndex();
379 Bytes = Flags.getByValSize();
380 } else
381 return false;
382
383 assert(FI != INT_MAX);
384 if (!MFI.isFixedObjectIndex(FI))
385 return false;
386
387 if (Offset != MFI.getObjectOffset(FI))
388 return false;
389
390 if (VA.getLocVT().getSizeInBits() > Arg.getValueType().getSizeInBits()) {
391 // If the argument location is wider than the argument type, check that any
392 // extension flags match.
393 if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
394 Flags.isSExt() != MFI.isObjectSExt(FI)) {
395 return false;
396 }
397 }
398
399 return Bytes == MFI.getObjectSize(FI);
400}
401
403M68kTargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
405 M68kMachineFunctionInfo *FuncInfo = MF.getInfo<M68kMachineFunctionInfo>();
406 int ReturnAddrIndex = FuncInfo->getRAIndex();
407
408 if (ReturnAddrIndex == 0) {
409 // Set up a frame object for the return address.
410 unsigned SlotSize = Subtarget.getSlotSize();
411 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(
412 SlotSize, -(int64_t)SlotSize, false);
413 FuncInfo->setRAIndex(ReturnAddrIndex);
414 }
415
416 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
417}
418
419SDValue M68kTargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
420 SDValue &OutRetAddr,
421 SDValue Chain,
422 bool IsTailCall, int FPDiff,
423 const SDLoc &DL) const {
424 EVT VT = getPointerTy(DAG.getDataLayout());
425 OutRetAddr = getReturnAddressFrameIndex(DAG);
426
427 // Load the "old" Return address.
428 OutRetAddr = DAG.getLoad(VT, DL, Chain, OutRetAddr, MachinePointerInfo());
429 return SDValue(OutRetAddr.getNode(), 1);
430}
431
432SDValue M68kTargetLowering::EmitTailCallStoreRetAddr(
433 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue RetFI,
434 EVT PtrVT, unsigned SlotSize, int FPDiff, const SDLoc &DL) const {
435 if (!FPDiff)
436 return Chain;
437
438 // Calculate the new stack slot for the return address.
439 int NewFO = MF.getFrameInfo().CreateFixedObject(
440 SlotSize, (int64_t)FPDiff - SlotSize, false);
441
442 SDValue NewFI = DAG.getFrameIndex(NewFO, PtrVT);
443 // Store the return address to the appropriate stack slot.
444 Chain = DAG.getStore(
445 Chain, DL, RetFI, NewFI,
447 return Chain;
448}
449
451M68kTargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
453 const SDLoc &DL, SelectionDAG &DAG,
454 const CCValAssign &VA,
455 MachineFrameInfo &MFI,
456 unsigned ArgIdx) const {
457 // Create the nodes corresponding to a load from this parameter slot.
458 ISD::ArgFlagsTy Flags = Ins[ArgIdx].Flags;
459 EVT ValVT;
460
461 // If value is passed by pointer we have address passed instead of the value
462 // itself.
464 ValVT = VA.getLocVT();
465 else
466 ValVT = VA.getValVT();
467
468 // Because we are dealing with BE architecture we need to offset loading of
469 // partial types
470 int Offset = VA.getLocMemOffset();
471 if (VA.getValVT() == MVT::i8) {
472 Offset += 3;
473 } else if (VA.getValVT() == MVT::i16) {
474 Offset += 2;
475 }
476
477 // TODO Interrupt handlers
478 // Calculate SP offset of interrupt parameter, re-arrange the slot normally
479 // taken by a return address.
480
481 // FIXME For now, all byval parameter objects are marked mutable. This can
482 // be changed with more analysis. In case of tail call optimization mark all
483 // arguments mutable. Since they could be overwritten by lowering of arguments
484 // in case of a tail call.
485 bool AlwaysUseMutable = shouldGuaranteeTCO(
486 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
487 bool IsImmutable = !AlwaysUseMutable && !Flags.isByVal();
488
489 if (Flags.isByVal()) {
490 unsigned Bytes = Flags.getByValSize();
491 if (Bytes == 0)
492 Bytes = 1; // Don't create zero-sized stack objects.
493 int FI = MFI.CreateFixedObject(Bytes, Offset, IsImmutable);
494 // TODO Interrupt handlers
495 // Adjust SP offset of interrupt parameter.
496 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
497 } else {
498 int FI =
499 MFI.CreateFixedObject(ValVT.getSizeInBits() / 8, Offset, IsImmutable);
500
501 // Set SExt or ZExt flag.
502 if (VA.getLocInfo() == CCValAssign::ZExt) {
503 MFI.setObjectZExt(FI, true);
504 } else if (VA.getLocInfo() == CCValAssign::SExt) {
505 MFI.setObjectSExt(FI, true);
506 }
507
508 // TODO Interrupt handlers
509 // Adjust SP offset of interrupt parameter.
510
511 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
512 SDValue Val = DAG.getLoad(
513 ValVT, DL, Chain, FIN,
515 return VA.isExtInLoc() ? DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val)
516 : Val;
517 }
518}
519
520SDValue M68kTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
521 SDValue Arg, const SDLoc &DL,
522 SelectionDAG &DAG,
523 const CCValAssign &VA,
524 ISD::ArgFlagsTy Flags) const {
525 unsigned LocMemOffset = VA.getLocMemOffset();
526 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, DL);
527 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()),
528 StackPtr, PtrOff);
529 if (Flags.isByVal())
530 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, DL);
531
532 return DAG.getStore(
533 Chain, DL, Arg, PtrOff,
535}
536
537//===----------------------------------------------------------------------===//
538// Call
539//===----------------------------------------------------------------------===//
540
541SDValue M68kTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
542 SmallVectorImpl<SDValue> &InVals) const {
543 SelectionDAG &DAG = CLI.DAG;
544 SDLoc &DL = CLI.DL;
545 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
546 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
547 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
548 SDValue Chain = CLI.Chain;
549 SDValue Callee = CLI.Callee;
550 CallingConv::ID CallConv = CLI.CallConv;
551 bool &IsTailCall = CLI.IsTailCall;
552 bool IsVarArg = CLI.IsVarArg;
553
556 bool IsSibcall = false;
557 M68kMachineFunctionInfo *MFI = MF.getInfo<M68kMachineFunctionInfo>();
558 // const M68kRegisterInfo *TRI = Subtarget.getRegisterInfo();
559
560 if (CallConv == CallingConv::M68k_INTR)
561 report_fatal_error("M68k interrupts may not be called directly");
562
563 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
564 if (Attr.getValueAsBool())
565 IsTailCall = false;
566
567 // FIXME Add tailcalls support
568
569 bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
570 if (IsMustTail) {
571 // Force this to be a tail call. The verifier rules are enough to ensure
572 // that we can lower this successfully without moving the return address
573 // around.
574 IsTailCall = true;
575 } else if (IsTailCall) {
576 // Check if it's really possible to do a tail call.
577 IsTailCall = IsEligibleForTailCallOptimization(
578 Callee, CallConv, IsVarArg, SR != NotStructReturn,
579 MF.getFunction().hasStructRetAttr(), CLI.RetTy, Outs, OutVals, Ins,
580 DAG);
581
582 // Sibcalls are automatically detected tailcalls which do not require
583 // ABI changes.
584 if (!MF.getTarget().Options.GuaranteedTailCallOpt && IsTailCall)
585 IsSibcall = true;
586
587 if (IsTailCall)
588 ++NumTailCalls;
589 }
590
591 assert(!(IsVarArg && canGuaranteeTCO(CallConv)) &&
592 "Var args not supported with calling convention fastcc");
593
594 // Analyze operands of the call, assigning locations to each operand.
596 SmallVector<Type *, 4> ArgTypes;
597 for (const auto &Arg : CLI.getArgs())
598 ArgTypes.emplace_back(Arg.Ty);
599 M68kCCState CCInfo(ArgTypes, CallConv, IsVarArg, MF, ArgLocs,
600 *DAG.getContext());
601 CCInfo.AnalyzeCallOperands(Outs, CC_M68k);
602
603 // Get a count of how many bytes are to be pushed on the stack.
604 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
605 if (IsSibcall) {
606 // This is a sibcall. The memory operands are available in caller's
607 // own caller's stack.
608 NumBytes = 0;
609 } else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
610 canGuaranteeTCO(CallConv)) {
611 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
612 }
613
614 int FPDiff = 0;
615 if (IsTailCall && !IsSibcall && !IsMustTail) {
616 // Lower arguments at fp - stackoffset + fpdiff.
617 unsigned NumBytesCallerPushed = MFI->getBytesToPopOnReturn();
618
619 FPDiff = NumBytesCallerPushed - NumBytes;
620
621 // Set the delta of movement of the returnaddr stackslot.
622 // But only set if delta is greater than previous delta.
623 if (FPDiff < MFI->getTCReturnAddrDelta())
624 MFI->setTCReturnAddrDelta(FPDiff);
625 }
626
627 unsigned NumBytesToPush = NumBytes;
628 unsigned NumBytesToPop = NumBytes;
629
630 // If we have an inalloca argument, all stack space has already been allocated
631 // for us and be right at the top of the stack. We don't support multiple
632 // arguments passed in memory when using inalloca.
633 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
634 NumBytesToPush = 0;
635 if (!ArgLocs.back().isMemLoc())
636 report_fatal_error("cannot use inalloca attribute on a register "
637 "parameter");
638 if (ArgLocs.back().getLocMemOffset() != 0)
639 report_fatal_error("any parameter with the inalloca attribute must be "
640 "the only memory argument");
641 }
642
643 if (!IsSibcall)
644 Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
645 NumBytes - NumBytesToPush, DL);
646
647 SDValue RetFI;
648 // Load return address for tail calls.
649 if (IsTailCall && FPDiff)
650 Chain = EmitTailCallLoadRetAddr(DAG, RetFI, Chain, IsTailCall, FPDiff, DL);
651
653 SmallVector<SDValue, 8> MemOpChains;
654 SDValue StackPtr;
655
656 // Walk the register/memloc assignments, inserting copies/loads. In the case
657 // of tail call optimization arguments are handle later.
658 const M68kRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
659 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
660 ISD::ArgFlagsTy Flags = Outs[i].Flags;
661
662 // Skip inalloca arguments, they have already been written.
663 if (Flags.isInAlloca())
664 continue;
665
666 CCValAssign &VA = ArgLocs[i];
667 EVT RegVT = VA.getLocVT();
668 SDValue Arg = OutVals[i];
669 bool IsByVal = Flags.isByVal();
670
671 // Promote the value if needed.
672 switch (VA.getLocInfo()) {
673 default:
674 llvm_unreachable("Unknown loc info!");
676 break;
678 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, RegVT, Arg);
679 break;
681 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, RegVT, Arg);
682 break;
684 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, RegVT, Arg);
685 break;
687 Arg = DAG.getBitcast(RegVT, Arg);
688 break;
690 // Store the argument.
691 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
692 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
693 Chain = DAG.getStore(
694 Chain, DL, Arg, SpillSlot,
696 Arg = SpillSlot;
697 break;
698 }
699 }
700
701 if (VA.isRegLoc()) {
702 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
703 } else if (!IsSibcall && (!IsTailCall || IsByVal)) {
704 assert(VA.isMemLoc());
705 if (!StackPtr.getNode()) {
706 StackPtr = DAG.getCopyFromReg(Chain, DL, RegInfo->getStackRegister(),
708 }
709 MemOpChains.push_back(
710 LowerMemOpCallTo(Chain, StackPtr, Arg, DL, DAG, VA, Flags));
711 }
712 }
713
714 if (!MemOpChains.empty())
715 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
716
717 // FIXME Make sure PIC style GOT works as expected
718 // The only time GOT is really needed is for Medium-PIC static data
719 // otherwise we are happy with pc-rel or static references
720
721 if (IsVarArg && IsMustTail) {
722 const auto &Forwards = MFI->getForwardedMustTailRegParms();
723 for (const auto &F : Forwards) {
724 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
725 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
726 }
727 }
728
729 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
730 // don't need this because the eligibility check rejects calls that require
731 // shuffling arguments passed in memory.
732 if (!IsSibcall && IsTailCall) {
733 // Force all the incoming stack arguments to be loaded from the stack
734 // before any new outgoing arguments are stored to the stack, because the
735 // outgoing stack slots may alias the incoming argument stack slots, and
736 // the alias isn't otherwise explicit. This is slightly more conservative
737 // than necessary, because it means that each store effectively depends
738 // on every argument instead of just those arguments it would clobber.
739 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
740
741 SmallVector<SDValue, 8> MemOpChains2;
742 SDValue FIN;
743 int FI = 0;
744 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
745 CCValAssign &VA = ArgLocs[i];
746 if (VA.isRegLoc())
747 continue;
748 assert(VA.isMemLoc());
749 SDValue Arg = OutVals[i];
750 ISD::ArgFlagsTy Flags = Outs[i].Flags;
751 // Skip inalloca arguments. They don't require any work.
752 if (Flags.isInAlloca())
753 continue;
754 // Create frame index.
755 int32_t Offset = VA.getLocMemOffset() + FPDiff;
756 uint32_t OpSize = (VA.getLocVT().getSizeInBits() + 7) / 8;
757 FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
758 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
759
760 if (Flags.isByVal()) {
761 // Copy relative to framepointer.
762 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), DL);
763 if (!StackPtr.getNode()) {
764 StackPtr = DAG.getCopyFromReg(Chain, DL, RegInfo->getStackRegister(),
766 }
768 StackPtr, Source);
769
770 MemOpChains2.push_back(
771 CreateCopyOfByValArgument(Source, FIN, ArgChain, Flags, DAG, DL));
772 } else {
773 // Store relative to framepointer.
774 MemOpChains2.push_back(DAG.getStore(
775 ArgChain, DL, Arg, FIN,
777 }
778 }
779
780 if (!MemOpChains2.empty())
781 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains2);
782
783 // Store the return address to the appropriate stack slot.
784 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetFI,
786 Subtarget.getSlotSize(), FPDiff, DL);
787 }
788
789 // Build a sequence of copy-to-reg nodes chained together with token chain
790 // and flag operands which copy the outgoing args into registers.
791 SDValue InGlue;
792 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
793 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
794 RegsToPass[i].second, InGlue);
795 InGlue = Chain.getValue(1);
796 }
797
798 if (Callee->getOpcode() == ISD::GlobalAddress) {
799 // If the callee is a GlobalAddress node (quite common, every direct call
800 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
801 // it.
802 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
803
804 // We should use extra load for direct calls to dllimported functions in
805 // non-JIT mode.
806 const GlobalValue *GV = G->getGlobal();
807 if (!GV->hasDLLImportStorageClass()) {
808 unsigned char OpFlags = Subtarget.classifyGlobalFunctionReference(GV);
809
811 GV, DL, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
812
813 if (OpFlags == M68kII::MO_GOTPCREL) {
814
815 // Add a wrapper.
816 Callee = DAG.getNode(M68kISD::WrapperPC, DL,
817 getPointerTy(DAG.getDataLayout()), Callee);
818
819 // Add extra indirection
820 Callee = DAG.getLoad(
821 getPointerTy(DAG.getDataLayout()), DL, DAG.getEntryNode(), Callee,
823 }
824 }
825 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
827 unsigned char OpFlags =
828 Subtarget.classifyGlobalFunctionReference(nullptr, *Mod);
829
831 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
832 }
833
835
836 if (!IsSibcall && IsTailCall) {
837 Chain = DAG.getCALLSEQ_END(Chain, NumBytesToPop, 0, InGlue, DL);
838 InGlue = Chain.getValue(1);
839 }
840
841 Ops.push_back(Chain);
842 Ops.push_back(Callee);
843
844 if (IsTailCall)
845 Ops.push_back(DAG.getConstant(FPDiff, DL, MVT::i32));
846
847 // Add argument registers to the end of the list so that they are known live
848 // into the call.
849 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
850 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
851 RegsToPass[i].second.getValueType()));
852
853 // Add a register mask operand representing the call-preserved registers.
854 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
855 assert(Mask && "Missing call preserved mask for calling convention");
856
857 Ops.push_back(DAG.getRegisterMask(Mask));
858
859 if (InGlue.getNode())
860 Ops.push_back(InGlue);
861
862 if (IsTailCall) {
864 return DAG.getNode(M68kISD::TC_RETURN, DL, MVT::Other, Ops);
865 }
866
867 // Returns a chain & a flag for retval copy to use.
868 Chain = DAG.getNode(M68kISD::CALL, DL, {MVT::Other, MVT::Glue}, Ops);
869 InGlue = Chain.getValue(1);
870
871 // Create the CALLSEQ_END node.
872 unsigned NumBytesForCalleeToPop;
873 if (M68k::isCalleePop(CallConv, IsVarArg,
875 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
876 } else if (!canGuaranteeTCO(CallConv) && SR == StackStructReturn) {
877 // If this is a call to a struct-return function, the callee
878 // pops the hidden struct pointer, so we have to push it back.
879 NumBytesForCalleeToPop = 4;
880 } else {
881 NumBytesForCalleeToPop = 0; // Callee pops nothing.
882 }
883
884 if (CLI.DoesNotReturn && !getTargetMachine().Options.TrapUnreachable) {
885 // No need to reset the stack after the call if the call doesn't return. To
886 // make the MI verify, we'll pretend the callee does it for us.
887 NumBytesForCalleeToPop = NumBytes;
888 }
889
890 // Returns a flag for retval copy to use.
891 if (!IsSibcall) {
892 Chain = DAG.getCALLSEQ_END(Chain, NumBytesToPop, NumBytesForCalleeToPop,
893 InGlue, DL);
894 InGlue = Chain.getValue(1);
895 }
896
897 // Handle result values, copying them out of physregs into vregs that we
898 // return.
899 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
900 InVals);
901}
902
903SDValue M68kTargetLowering::LowerCallResult(
904 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
905 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
906 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
907
908 // Assign locations to each value returned by this call.
910 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
911 *DAG.getContext());
912 CCInfo.AnalyzeCallResult(Ins, RetCC_M68k);
913
914 // Copy all of the result registers out of their specified physreg.
915 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
916 CCValAssign &VA = RVLocs[i];
917 EVT CopyVT = VA.getLocVT();
918
919 /// ??? is this correct?
920 Chain = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), CopyVT, InGlue)
921 .getValue(1);
922 SDValue Val = Chain.getValue(0);
923
924 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
925 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
926
927 InGlue = Chain.getValue(2);
928 InVals.push_back(Val);
929 }
930
931 return Chain;
932}
933
934//===----------------------------------------------------------------------===//
935// Formal Arguments Calling Convention Implementation
936//===----------------------------------------------------------------------===//
937
938SDValue M68kTargetLowering::LowerFormalArguments(
939 SDValue Chain, CallingConv::ID CCID, bool IsVarArg,
940 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
941 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
943 M68kMachineFunctionInfo *MMFI = MF.getInfo<M68kMachineFunctionInfo>();
944 // const TargetFrameLowering &TFL = *Subtarget.getFrameLowering();
945
946 MachineFrameInfo &MFI = MF.getFrameInfo();
947
948 // Assign locations to all of the incoming arguments.
950 SmallVector<Type *, 4> ArgTypes;
951 for (const Argument &Arg : MF.getFunction().args())
952 ArgTypes.emplace_back(Arg.getType());
953 M68kCCState CCInfo(ArgTypes, CCID, IsVarArg, MF, ArgLocs, *DAG.getContext());
954
955 CCInfo.AnalyzeFormalArguments(Ins, CC_M68k);
956
957 unsigned LastVal = ~0U;
958 SDValue ArgValue;
959 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
960 CCValAssign &VA = ArgLocs[i];
961 assert(VA.getValNo() != LastVal && "Same value in different locations");
962 (void)LastVal;
963
964 LastVal = VA.getValNo();
965
966 if (VA.isRegLoc()) {
967 EVT RegVT = VA.getLocVT();
968 const TargetRegisterClass *RC;
969 if (RegVT == MVT::i32)
970 RC = &M68k::XR32RegClass;
971 else
972 llvm_unreachable("Unknown argument type!");
973
974 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
975 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
976
977 // If this is an 8 or 16-bit value, it is really passed promoted to 32
978 // bits. Insert an assert[sz]ext to capture this, then truncate to the
979 // right size.
980 if (VA.getLocInfo() == CCValAssign::SExt) {
981 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
982 DAG.getValueType(VA.getValVT()));
983 } else if (VA.getLocInfo() == CCValAssign::ZExt) {
984 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
985 DAG.getValueType(VA.getValVT()));
986 } else if (VA.getLocInfo() == CCValAssign::BCvt) {
987 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
988 }
989
990 if (VA.isExtInLoc()) {
991 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
992 }
993 } else {
994 assert(VA.isMemLoc());
995 ArgValue = LowerMemArgument(Chain, CCID, Ins, DL, DAG, VA, MFI, i);
996 }
997
998 // If value is passed via pointer - do a load.
999 // TODO Make sure this handling on indirect arguments is correct
1001 ArgValue =
1002 DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
1003
1004 InVals.push_back(ArgValue);
1005 }
1006
1007 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1008 // Swift calling convention does not require we copy the sret argument
1009 // into %D0 for the return. We don't set SRetReturnReg for Swift.
1010 if (CCID == CallingConv::Swift)
1011 continue;
1012
1013 // ABI require that for returning structs by value we copy the sret argument
1014 // into %D0 for the return. Save the argument into a virtual register so
1015 // that we can access it from the return points.
1016 if (Ins[i].Flags.isSRet()) {
1017 unsigned Reg = MMFI->getSRetReturnReg();
1018 if (!Reg) {
1019 MVT PtrTy = getPointerTy(DAG.getDataLayout());
1021 MMFI->setSRetReturnReg(Reg);
1022 }
1023 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
1024 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
1025 break;
1026 }
1027 }
1028
1029 unsigned StackSize = CCInfo.getStackSize();
1030 // Align stack specially for tail calls.
1032 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1033
1034 // If the function takes variable number of arguments, make a frame index for
1035 // the start of the first vararg value... for expansion of llvm.va_start. We
1036 // can skip this if there are no va_start calls.
1037 if (MFI.hasVAStart()) {
1038 MMFI->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
1039 }
1040
1041 if (IsVarArg && MFI.hasMustTailInVarArgFunc()) {
1042 // We forward some GPRs and some vector types.
1043 SmallVector<MVT, 2> RegParmTypes;
1044 MVT IntVT = MVT::i32;
1045 RegParmTypes.push_back(IntVT);
1046
1047 // Compute the set of forwarded registers. The rest are scratch.
1048 // ??? what is this for?
1049 SmallVectorImpl<ForwardedRegister> &Forwards =
1051 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_M68k);
1052
1053 // Copy all forwards from physical to virtual registers.
1054 for (ForwardedRegister &F : Forwards) {
1055 // FIXME Can we use a less constrained schedule?
1056 SDValue RegVal = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
1058 Chain = DAG.getCopyToReg(Chain, DL, F.VReg, RegVal);
1059 }
1060 }
1061
1062 // Some CCs need callee pop.
1063 if (M68k::isCalleePop(CCID, IsVarArg,
1065 MMFI->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1066 } else {
1067 MMFI->setBytesToPopOnReturn(0); // Callee pops nothing.
1068 // If this is an sret function, the return should pop the hidden pointer.
1070 MMFI->setBytesToPopOnReturn(4);
1071 }
1072
1073 MMFI->setArgumentStackSize(StackSize);
1074
1075 return Chain;
1076}
1077
1078//===----------------------------------------------------------------------===//
1079// Return Value Calling Convention Implementation
1080//===----------------------------------------------------------------------===//
1081
1082bool M68kTargetLowering::CanLowerReturn(
1083 CallingConv::ID CCID, MachineFunction &MF, bool IsVarArg,
1085 const Type *RetTy) const {
1087 CCState CCInfo(CCID, IsVarArg, MF, RVLocs, Context);
1088 return CCInfo.CheckReturn(Outs, RetCC_M68k);
1089}
1090
1091SDValue
1092M68kTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CCID,
1093 bool IsVarArg,
1095 const SmallVectorImpl<SDValue> &OutVals,
1096 const SDLoc &DL, SelectionDAG &DAG) const {
1098 M68kMachineFunctionInfo *MFI = MF.getInfo<M68kMachineFunctionInfo>();
1099
1101 CCState CCInfo(CCID, IsVarArg, MF, RVLocs, *DAG.getContext());
1102 CCInfo.AnalyzeReturn(Outs, RetCC_M68k);
1103
1104 SDValue Glue;
1106 // Operand #0 = Chain (updated below)
1107 RetOps.push_back(Chain);
1108 // Operand #1 = Bytes To Pop
1109 RetOps.push_back(
1110 DAG.getTargetConstant(MFI->getBytesToPopOnReturn(), DL, MVT::i32));
1111
1112 // Copy the result values into the output registers.
1113 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1114 CCValAssign &VA = RVLocs[i];
1115 assert(VA.isRegLoc() && "Can only return in registers!");
1116 SDValue ValToCopy = OutVals[i];
1117 EVT ValVT = ValToCopy.getValueType();
1118
1119 // Promote values to the appropriate types.
1120 if (VA.getLocInfo() == CCValAssign::SExt)
1121 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), ValToCopy);
1122 else if (VA.getLocInfo() == CCValAssign::ZExt)
1123 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), ValToCopy);
1124 else if (VA.getLocInfo() == CCValAssign::AExt) {
1125 if (ValVT.isVectorOf(MVT::i1))
1126 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), ValToCopy);
1127 else
1128 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), ValToCopy);
1129 } else if (VA.getLocInfo() == CCValAssign::BCvt)
1130 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
1131
1132 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), ValToCopy, Glue);
1133 Glue = Chain.getValue(1);
1134 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1135 }
1136
1137 // Swift calling convention does not require we copy the sret argument
1138 // into %d0 for the return, and SRetReturnReg is not set for Swift.
1139
1140 // ABI require that for returning structs by value we copy the sret argument
1141 // into %D0 for the return. Save the argument into a virtual register so that
1142 // we can access it from the return points.
1143 //
1144 // Checking Function.hasStructRetAttr() here is insufficient because the IR
1145 // may not have an explicit sret argument. If MFI.CanLowerReturn is
1146 // false, then an sret argument may be implicitly inserted in the SelDAG. In
1147 // either case MFI->setSRetReturnReg() will have been called.
1148 if (unsigned SRetReg = MFI->getSRetReturnReg()) {
1149 // ??? Can i just move this to the top and escape this explanation?
1150 // When we have both sret and another return value, we should use the
1151 // original Chain stored in RetOps[0], instead of the current Chain updated
1152 // in the above loop. If we only have sret, RetOps[0] equals to Chain.
1153
1154 // For the case of sret and another return value, we have
1155 // Chain_0 at the function entry
1156 // Chain_1 = getCopyToReg(Chain_0) in the above loop
1157 // If we use Chain_1 in getCopyFromReg, we will have
1158 // Val = getCopyFromReg(Chain_1)
1159 // Chain_2 = getCopyToReg(Chain_1, Val) from below
1160
1161 // getCopyToReg(Chain_0) will be glued together with
1162 // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
1163 // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
1164 // Data dependency from Unit B to Unit A due to usage of Val in
1165 // getCopyToReg(Chain_1, Val)
1166 // Chain dependency from Unit A to Unit B
1167
1168 // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
1169 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
1171
1172 // ??? How will this work if CC does not use registers for args passing?
1173 // ??? What if I return multiple structs?
1174 unsigned RetValReg = M68k::D0;
1175 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Glue);
1176 Glue = Chain.getValue(1);
1177
1178 RetOps.push_back(
1179 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
1180 }
1181
1182 RetOps[0] = Chain; // Update chain.
1183
1184 // Add the glue if we have it.
1185 if (Glue.getNode())
1186 RetOps.push_back(Glue);
1187
1188 return DAG.getNode(M68kISD::RET, DL, MVT::Other, RetOps);
1189}
1190
1191//===----------------------------------------------------------------------===//
1192// Fast Calling Convention (tail call) implementation
1193//===----------------------------------------------------------------------===//
1194
1195// Like std call, callee cleans arguments, convention except that ECX is
1196// reserved for storing the tail called function address. Only 2 registers are
1197// free for argument passing (inreg). Tail call optimization is performed
1198// provided:
1199// * tailcallopt is enabled
1200// * caller/callee are fastcc
1201// On M68k_64 architecture with GOT-style position independent code only
1202// local (within module) calls are supported at the moment. To keep the stack
1203// aligned according to platform abi the function GetAlignedArgumentStackSize
1204// ensures that argument delta is always multiples of stack alignment. (Dynamic
1205// linkers need this - darwin's dyld for example) If a tail called function
1206// callee has more arguments than the caller the caller needs to make sure that
1207// there is room to move the RETADDR to. This is achieved by reserving an area
1208// the size of the argument delta right after the original RETADDR, but before
1209// the saved framepointer or the spilled registers e.g. caller(arg1, arg2)
1210// calls callee(arg1, arg2,arg3,arg4) stack layout:
1211// arg1
1212// arg2
1213// RETADDR
1214// [ new RETADDR
1215// move area ]
1216// (possible EBP)
1217// ESI
1218// EDI
1219// local1 ..
1220
1221/// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
1222/// requirement.
1223unsigned
1224M68kTargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1225 SelectionDAG &DAG) const {
1226 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
1227 unsigned StackAlignment = TFI.getStackAlignment();
1228 uint64_t AlignMask = StackAlignment - 1;
1229 int64_t Offset = StackSize;
1230 unsigned SlotSize = Subtarget.getSlotSize();
1231 if ((Offset & AlignMask) <= (StackAlignment - SlotSize)) {
1232 // Number smaller than 12 so just add the difference.
1233 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1234 } else {
1235 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1236 Offset =
1237 ((~AlignMask) & Offset) + StackAlignment + (StackAlignment - SlotSize);
1238 }
1239 return Offset;
1240}
1241
1242/// Check whether the call is eligible for tail call optimization. Targets
1243/// that want to do tail call optimization should implement this function.
1244bool M68kTargetLowering::IsEligibleForTailCallOptimization(
1245 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
1246 bool IsCalleeStructRet, bool IsCallerStructRet, Type *RetTy,
1248 const SmallVectorImpl<SDValue> &OutVals,
1249 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
1250 if (!mayTailCallThisCC(CalleeCC))
1251 return false;
1252
1253 // If -tailcallopt is specified, make fastcc functions tail-callable.
1255 const auto &CallerF = MF.getFunction();
1256
1257 CallingConv::ID CallerCC = CallerF.getCallingConv();
1258 bool CCMatch = CallerCC == CalleeCC;
1259
1261 if (canGuaranteeTCO(CalleeCC) && CCMatch)
1262 return true;
1263 return false;
1264 }
1265
1266 // Look for obvious safe cases to perform tail call optimization that do not
1267 // require ABI changes. This is what gcc calls sibcall.
1268
1269 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
1270 // emit a special epilogue.
1271 const M68kRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1272 if (RegInfo->hasStackRealignment(MF))
1273 return false;
1274
1275 // Also avoid sibcall optimization if either caller or callee uses struct
1276 // return semantics.
1277 if (IsCalleeStructRet || IsCallerStructRet)
1278 return false;
1279
1280 // Do not sibcall optimize vararg calls unless all arguments are passed via
1281 // registers.
1282 LLVMContext &C = *DAG.getContext();
1283 if (IsVarArg && !Outs.empty()) {
1284
1286 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, C);
1287
1288 CCInfo.AnalyzeCallOperands(Outs, CC_M68k);
1289 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
1290 if (!ArgLocs[i].isRegLoc())
1291 return false;
1292 }
1293
1294 // Check that the call results are passed in the same way.
1295 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, RetCC_M68k,
1296 RetCC_M68k))
1297 return false;
1298
1299 // The callee has to preserve all registers the caller needs to preserve.
1300 const M68kRegisterInfo *TRI = Subtarget.getRegisterInfo();
1301 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1302 if (!CCMatch) {
1303 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
1304 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
1305 return false;
1306 }
1307
1308 unsigned StackArgsSize = 0;
1309
1310 // If the callee takes no arguments then go on to check the results of the
1311 // call.
1312 if (!Outs.empty()) {
1313 // Check if stack adjustment is needed. For now, do not do this if any
1314 // argument is passed on the stack.
1316 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, C);
1317
1318 CCInfo.AnalyzeCallOperands(Outs, CC_M68k);
1319 StackArgsSize = CCInfo.getStackSize();
1320
1321 if (StackArgsSize) {
1322 // Check if the arguments are already laid out in the right way as
1323 // the caller's fixed stack objects.
1324 MachineFrameInfo &MFI = MF.getFrameInfo();
1325 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1326 const M68kInstrInfo *TII = Subtarget.getInstrInfo();
1327 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1328 CCValAssign &VA = ArgLocs[i];
1329 SDValue Arg = OutVals[i];
1330 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1332 return false;
1333 if (!VA.isRegLoc()) {
1334 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, MFI, MRI,
1335 TII, VA))
1336 return false;
1337 }
1338 }
1339 }
1340
1341 bool PositionIndependent = isPositionIndependent();
1342 // If the tailcall address may be in a register, then make sure it's
1343 // possible to register allocate for it. The call address can
1344 // only target %A0 or %A1 since the tail call must be scheduled after
1345 // callee-saved registers are restored. These happen to be the same
1346 // registers used to pass 'inreg' arguments so watch out for those.
1347 if ((!isa<GlobalAddressSDNode>(Callee) &&
1348 !isa<ExternalSymbolSDNode>(Callee)) ||
1349 PositionIndependent) {
1350 unsigned NumInRegs = 0;
1351 // In PIC we need an extra register to formulate the address computation
1352 // for the callee.
1353 unsigned MaxInRegs = PositionIndependent ? 1 : 2;
1354
1355 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1356 CCValAssign &VA = ArgLocs[i];
1357 if (!VA.isRegLoc())
1358 continue;
1359 Register Reg = VA.getLocReg();
1360 switch (Reg) {
1361 default:
1362 break;
1363 case M68k::A0:
1364 case M68k::A1:
1365 if (++NumInRegs == MaxInRegs)
1366 return false;
1367 break;
1368 }
1369 }
1370 }
1371
1372 const MachineRegisterInfo &MRI = MF.getRegInfo();
1373 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
1374 return false;
1375 }
1376
1377 bool CalleeWillPop = M68k::isCalleePop(
1378 CalleeCC, IsVarArg, MF.getTarget().Options.GuaranteedTailCallOpt);
1379
1380 if (unsigned BytesToPop =
1381 MF.getInfo<M68kMachineFunctionInfo>()->getBytesToPopOnReturn()) {
1382 // If we have bytes to pop, the callee must pop them.
1383 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
1384 if (!CalleePopMatches)
1385 return false;
1386 } else if (CalleeWillPop && StackArgsSize > 0) {
1387 // If we don't have bytes to pop, make sure the callee doesn't pop any.
1388 return false;
1389 }
1390
1391 return true;
1392}
1393
1394//===----------------------------------------------------------------------===//
1395// Custom Lower
1396//===----------------------------------------------------------------------===//
1397
1399 SelectionDAG &DAG) const {
1400 switch (Op.getOpcode()) {
1401 default:
1402 llvm_unreachable("Should not custom lower this!");
1403 case ISD::SADDO:
1404 case ISD::UADDO:
1405 case ISD::SSUBO:
1406 case ISD::USUBO:
1407 case ISD::SMULO:
1408 case ISD::UMULO:
1409 return LowerXALUO(Op, DAG);
1410 case ISD::SETCC:
1411 return LowerSETCC(Op, DAG);
1412 case ISD::SETCCCARRY:
1413 return LowerSETCCCARRY(Op, DAG);
1414 case ISD::SELECT:
1415 return LowerSELECT(Op, DAG);
1416 case ISD::BRCOND:
1417 return LowerBRCOND(Op, DAG);
1418 case ISD::UADDO_CARRY:
1419 case ISD::USUBO_CARRY:
1420 return LowerUADDO_USUBO_CARRY(Op, DAG);
1421 case ISD::ConstantPool:
1422 return LowerConstantPool(Op, DAG);
1423 case ISD::GlobalAddress:
1424 return LowerGlobalAddress(Op, DAG);
1426 return LowerExternalSymbol(Op, DAG);
1427 case ISD::BlockAddress:
1428 return LowerBlockAddress(Op, DAG);
1429 case ISD::JumpTable:
1430 return LowerJumpTable(Op, DAG);
1431 case ISD::VASTART:
1432 return LowerVASTART(Op, DAG);
1434 return LowerDYNAMIC_STACKALLOC(Op, DAG);
1435 case ISD::SHL_PARTS:
1436 return LowerShiftLeftParts(Op, DAG);
1437 case ISD::SRA_PARTS:
1438 return LowerShiftRightParts(Op, DAG, true);
1439 case ISD::SRL_PARTS:
1440 return LowerShiftRightParts(Op, DAG, false);
1441 case ISD::ATOMIC_FENCE:
1442 return LowerATOMICFENCE(Op, DAG);
1444 return LowerGlobalTLSAddress(Op, DAG);
1445 }
1446}
1447
1448SDValue M68kTargetLowering::LowerExternalSymbolCall(SelectionDAG &DAG,
1449 SDLoc Loc,
1450 llvm::StringRef SymbolName,
1451 ArgListTy &&ArgList) const {
1452 PointerType *PtrTy = PointerType::get(*DAG.getContext(), 0);
1453 CallLoweringInfo CLI(DAG);
1454 CLI.setDebugLoc(Loc)
1455 .setChain(DAG.getEntryNode())
1457 DAG.getExternalSymbol(SymbolName.data(),
1459 std::move(ArgList));
1460 return LowerCallTo(CLI).first;
1461}
1462
1463SDValue M68kTargetLowering::getTLSGetAddr(GlobalAddressSDNode *GA,
1464 SelectionDAG &DAG,
1465 unsigned TargetFlags) const {
1466 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1468 GA->getGlobal(), GA, GA->getValueType(0), GA->getOffset(), TargetFlags);
1469 SDValue Arg = DAG.getNode(ISD::ADD, SDLoc(GA), MVT::i32, GOT, TGA);
1470
1471 PointerType *PtrTy = PointerType::get(*DAG.getContext(), 0);
1472
1473 ArgListTy Args;
1474 Args.emplace_back(Arg, PtrTy);
1475 return LowerExternalSymbolCall(DAG, SDLoc(GA), "__tls_get_addr",
1476 std::move(Args));
1477}
1478
1479SDValue M68kTargetLowering::getM68kReadTp(SDLoc Loc, SelectionDAG &DAG) const {
1480 return LowerExternalSymbolCall(DAG, Loc, "__m68k_read_tp", ArgListTy());
1481}
1482
1483SDValue M68kTargetLowering::LowerTLSGeneralDynamic(GlobalAddressSDNode *GA,
1484 SelectionDAG &DAG) const {
1485 return getTLSGetAddr(GA, DAG, M68kII::MO_TLSGD);
1486}
1487
1488SDValue M68kTargetLowering::LowerTLSLocalDynamic(GlobalAddressSDNode *GA,
1489 SelectionDAG &DAG) const {
1490 SDValue Addr = getTLSGetAddr(GA, DAG, M68kII::MO_TLSLDM);
1491 SDValue TGA =
1492 DAG.getTargetGlobalAddress(GA->getGlobal(), GA, GA->getValueType(0),
1494 return DAG.getNode(ISD::ADD, SDLoc(GA), MVT::i32, TGA, Addr);
1495}
1496
1497SDValue M68kTargetLowering::LowerTLSInitialExec(GlobalAddressSDNode *GA,
1498 SelectionDAG &DAG) const {
1499 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1500 SDValue Tp = getM68kReadTp(SDLoc(GA), DAG);
1501 SDValue TGA =
1502 DAG.getTargetGlobalAddress(GA->getGlobal(), GA, GA->getValueType(0),
1504 SDValue Addr = DAG.getNode(ISD::ADD, SDLoc(GA), MVT::i32, TGA, GOT);
1505 SDValue Offset =
1506 DAG.getLoad(MVT::i32, SDLoc(GA), DAG.getEntryNode(), Addr,
1508
1509 return DAG.getNode(ISD::ADD, SDLoc(GA), MVT::i32, Offset, Tp);
1510}
1511
1512SDValue M68kTargetLowering::LowerTLSLocalExec(GlobalAddressSDNode *GA,
1513 SelectionDAG &DAG) const {
1514 SDValue Tp = getM68kReadTp(SDLoc(GA), DAG);
1515 SDValue TGA =
1516 DAG.getTargetGlobalAddress(GA->getGlobal(), GA, GA->getValueType(0),
1518 return DAG.getNode(ISD::ADD, SDLoc(GA), MVT::i32, TGA, Tp);
1519}
1520
1521SDValue M68kTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1522 SelectionDAG &DAG) const {
1523 assert(Subtarget.isTargetELF());
1524
1525 auto *GA = cast<GlobalAddressSDNode>(Op);
1526 TLSModel::Model AccessModel = DAG.getTarget().getTLSModel(GA->getGlobal());
1527
1528 switch (AccessModel) {
1530 return LowerTLSGeneralDynamic(GA, DAG);
1532 return LowerTLSLocalDynamic(GA, DAG);
1534 return LowerTLSInitialExec(GA, DAG);
1536 return LowerTLSLocalExec(GA, DAG);
1537 }
1538
1539 llvm_unreachable("Unexpected TLS access model type");
1540}
1541
1542bool M68kTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
1543 SDValue C) const {
1544 // Shifts and add instructions in M68000 and M68010 support
1545 // up to 32 bits, but mul only has 16-bit variant. So it's almost
1546 // certainly beneficial to lower 8/16/32-bit mul to their
1547 // add / shifts counterparts. But for 64-bits mul, it might be
1548 // safer to just leave it to compiler runtime implementations.
1549 return VT.bitsLE(MVT::i32) || Subtarget.atLeastM68020();
1550}
1551
1553 SelectionDAG &DAG) {
1554 return DAG.getNode(M68kISD::SETCC, dl, MVT::i8,
1555 DAG.getConstant(Cond, dl, MVT::i8), CCR);
1556}
1557
1558static bool isOverflowArithmetic(unsigned Opcode) {
1559 switch (Opcode) {
1560 case ISD::UADDO:
1561 case ISD::SADDO:
1562 case ISD::USUBO:
1563 case ISD::SSUBO:
1564 case ISD::UMULO:
1565 case ISD::SMULO:
1566 return true;
1567 default:
1568 return false;
1569 }
1570}
1571
1573 SDValue &Result, SDValue &CCR,
1574 M68k::CondCode &CC) {
1575 SDNode *N = Op.getNode();
1576 EVT VT = N->getValueType(0);
1577 SDValue LHS = N->getOperand(0);
1578 SDValue RHS = N->getOperand(1);
1579 SDLoc DL(Op);
1580
1581 unsigned TruncOp = 0;
1582 auto PromoteMULO = [&](unsigned ExtOp) {
1583 // We don't have 8-bit multiplications, so promote i8 version of U/SMULO
1584 // to i16.
1585 // Ideally this should be done by legalizer but sadly there is no promotion
1586 // rule for U/SMULO at this moment.
1587 if (VT == MVT::i8) {
1588 LHS = DAG.getNode(ExtOp, DL, MVT::i16, LHS);
1589 RHS = DAG.getNode(ExtOp, DL, MVT::i16, RHS);
1590 VT = MVT::i16;
1591 TruncOp = ISD::TRUNCATE;
1592 }
1593 };
1594
1595 bool NoOverflow = false;
1596 unsigned BaseOp = 0;
1597 switch (Op.getOpcode()) {
1598 default:
1599 llvm_unreachable("Unknown ovf instruction!");
1600 case ISD::SADDO:
1601 BaseOp = M68kISD::ADD;
1602 CC = M68k::COND_VS;
1603 break;
1604 case ISD::UADDO:
1605 BaseOp = M68kISD::ADD;
1606 CC = M68k::COND_CS;
1607 break;
1608 case ISD::SSUBO:
1609 BaseOp = M68kISD::SUB;
1610 CC = M68k::COND_VS;
1611 break;
1612 case ISD::USUBO:
1613 BaseOp = M68kISD::SUB;
1614 CC = M68k::COND_CS;
1615 break;
1616 case ISD::UMULO:
1617 PromoteMULO(ISD::ZERO_EXTEND);
1618 NoOverflow = VT != MVT::i32;
1619 BaseOp = NoOverflow ? (unsigned)ISD::MUL : (unsigned)M68kISD::UMUL;
1620 CC = M68k::COND_VS;
1621 break;
1622 case ISD::SMULO:
1623 PromoteMULO(ISD::SIGN_EXTEND);
1624 NoOverflow = VT != MVT::i32;
1625 BaseOp = NoOverflow ? (unsigned)ISD::MUL : (unsigned)M68kISD::SMUL;
1626 CC = M68k::COND_VS;
1627 break;
1628 }
1629
1630 SDVTList VTs;
1631 if (NoOverflow)
1632 VTs = DAG.getVTList(VT);
1633 else
1634 // Also sets CCR.
1635 VTs = DAG.getVTList(VT, MVT::i8);
1636
1637 SDValue Arith = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
1638 Result = Arith.getValue(0);
1639 if (TruncOp)
1640 // Right now the only place to truncate is from i16 to i8.
1641 Result = DAG.getNode(TruncOp, DL, MVT::i8, Arith);
1642
1643 if (NoOverflow)
1644 CCR = DAG.getConstant(0, DL, N->getValueType(1));
1645 else
1646 CCR = Arith.getValue(1);
1647}
1648
1649SDValue M68kTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
1650 SDNode *N = Op.getNode();
1651 SDLoc DL(Op);
1652
1653 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
1654 // a "setcc" instruction that checks the overflow flag.
1655 SDValue Result, CCR;
1657 lowerOverflowArithmetic(Op, DAG, Result, CCR, CC);
1658
1659 SDValue Overflow;
1660 if (isa<ConstantSDNode>(CCR)) {
1661 // It's likely a result of operations that will not overflow
1662 // hence no setcc is needed.
1663 Overflow = CCR;
1664 } else {
1665 // Generate a M68kISD::SETCC.
1666 Overflow = DAG.getNode(M68kISD::SETCC, DL, N->getValueType(1),
1667 DAG.getConstant(CC, DL, MVT::i8), CCR);
1668 }
1669
1670 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Overflow);
1671}
1672
1673/// Create a BTST (Bit Test) node - Test bit \p BitNo in \p Src and set
1674/// condition according to equal/not-equal condition code \p CC.
1676 const SDLoc &DL, SelectionDAG &DAG) {
1677 // If Src is i8, promote it to i32 with any_extend. There is no i8 BTST
1678 // instruction. Since the shift amount is in-range-or-undefined, we know
1679 // that doing a bittest on the i32 value is ok.
1680 if (Src.getValueType() == MVT::i8 || Src.getValueType() == MVT::i16)
1681 Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
1682
1683 // If the operand types disagree, extend the shift amount to match. Since
1684 // BTST ignores high bits (like shifts) we can use anyextend.
1685 if (Src.getValueType() != BitNo.getValueType())
1686 BitNo = DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(), BitNo);
1687
1688 SDValue BTST = DAG.getNode(M68kISD::BTST, DL, MVT::i8, Src, BitNo);
1689
1690 // NOTE BTST sets CCR.Z flag if bit is 0, same as AND with bitmask
1692 return DAG.getNode(M68kISD::SETCC, DL, MVT::i8,
1693 DAG.getConstant(Cond, DL, MVT::i8), BTST);
1694}
1695
1696/// Result of 'and' is compared against zero. Change to a BTST node if possible.
1698 SelectionDAG &DAG) {
1699 SDValue Op0 = And.getOperand(0);
1700 SDValue Op1 = And.getOperand(1);
1701 if (Op0.getOpcode() == ISD::TRUNCATE)
1702 Op0 = Op0.getOperand(0);
1703 if (Op1.getOpcode() == ISD::TRUNCATE)
1704 Op1 = Op1.getOperand(0);
1705
1706 SDValue LHS, RHS;
1707 if (Op1.getOpcode() == ISD::SHL)
1708 std::swap(Op0, Op1);
1709 if (Op0.getOpcode() == ISD::SHL) {
1710 if (isOneConstant(Op0.getOperand(0))) {
1711 // If we looked past a truncate, check that it's only truncating away
1712 // known zeros.
1713 unsigned BitWidth = Op0.getValueSizeInBits();
1714 unsigned AndBitWidth = And.getValueSizeInBits();
1715 if (BitWidth > AndBitWidth) {
1716 auto Known = DAG.computeKnownBits(Op0);
1717 if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
1718 return SDValue();
1719 }
1720 LHS = Op1;
1721 RHS = Op0.getOperand(1);
1722 }
1723 } else if (auto *AndRHS = dyn_cast<ConstantSDNode>(Op1)) {
1724 uint64_t AndRHSVal = AndRHS->getZExtValue();
1725 SDValue AndLHS = Op0;
1726
1727 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
1728 LHS = AndLHS.getOperand(0);
1729 RHS = AndLHS.getOperand(1);
1730 }
1731
1732 // Use BTST if the immediate can't be encoded in a TEST instruction.
1733 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
1734 LHS = AndLHS;
1735 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), DL, LHS.getValueType());
1736 }
1737 }
1738
1739 if (LHS.getNode())
1740 return getBitTestCondition(LHS, RHS, CC, DL, DAG);
1741
1742 return SDValue();
1743}
1744
1746 switch (SetCCOpcode) {
1747 default:
1748 llvm_unreachable("Invalid integer condition!");
1749 case ISD::SETEQ:
1750 return M68k::COND_EQ;
1751 case ISD::SETGT:
1752 return M68k::COND_GT;
1753 case ISD::SETGE:
1754 return M68k::COND_GE;
1755 case ISD::SETLT:
1756 return M68k::COND_LT;
1757 case ISD::SETLE:
1758 return M68k::COND_LE;
1759 case ISD::SETNE:
1760 return M68k::COND_NE;
1761 case ISD::SETULT:
1762 return M68k::COND_CS;
1763 case ISD::SETUGE:
1764 return M68k::COND_CC;
1765 case ISD::SETUGT:
1766 return M68k::COND_HI;
1767 case ISD::SETULE:
1768 return M68k::COND_LS;
1769 }
1770}
1771
1772/// Do a one-to-one translation of a ISD::CondCode to the M68k-specific
1773/// condition code, returning the condition code and the LHS/RHS of the
1774/// comparison to make.
1776 const SDLoc &DL, bool IsFP, SDValue &LHS,
1777 SDValue &RHS, SelectionDAG &DAG) {
1778 if (!IsFP) {
1780 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
1781 // X > -1 -> X == 0, jump !sign.
1782 RHS = DAG.getConstant(0, DL, RHS.getValueType());
1783 return M68k::COND_PL;
1784 }
1785 if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
1786 // X < 0 -> X == 0, jump on sign.
1787 return M68k::COND_MI;
1788 }
1789 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1790 // X < 1 -> X <= 0
1791 RHS = DAG.getConstant(0, DL, RHS.getValueType());
1792 return M68k::COND_LE;
1793 }
1794 }
1795
1796 return TranslateIntegerM68kCC(SetCCOpcode);
1797 }
1798
1799 // First determine if it is required or is profitable to flip the operands.
1800
1801 // If LHS is a foldable load, but RHS is not, flip the condition.
1802 if (ISD::isNON_EXTLoad(LHS.getNode()) && !ISD::isNON_EXTLoad(RHS.getNode())) {
1803 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
1804 std::swap(LHS, RHS);
1805 }
1806
1807 switch (SetCCOpcode) {
1808 default:
1809 break;
1810 case ISD::SETOLT:
1811 case ISD::SETOLE:
1812 case ISD::SETUGT:
1813 case ISD::SETUGE:
1814 std::swap(LHS, RHS);
1815 break;
1816 }
1817
1818 // On a floating point condition, the flags are set as follows:
1819 // ZF PF CF op
1820 // 0 | 0 | 0 | X > Y
1821 // 0 | 0 | 1 | X < Y
1822 // 1 | 0 | 0 | X == Y
1823 // 1 | 1 | 1 | unordered
1824 switch (SetCCOpcode) {
1825 default:
1826 llvm_unreachable("Condcode should be pre-legalized away");
1827 case ISD::SETUEQ:
1828 case ISD::SETEQ:
1829 return M68k::COND_EQ;
1830 case ISD::SETOLT: // flipped
1831 case ISD::SETOGT:
1832 case ISD::SETGT:
1833 return M68k::COND_HI;
1834 case ISD::SETOLE: // flipped
1835 case ISD::SETOGE:
1836 case ISD::SETGE:
1837 return M68k::COND_CC;
1838 case ISD::SETUGT: // flipped
1839 case ISD::SETULT:
1840 case ISD::SETLT:
1841 return M68k::COND_CS;
1842 case ISD::SETUGE: // flipped
1843 case ISD::SETULE:
1844 case ISD::SETLE:
1845 return M68k::COND_LS;
1846 case ISD::SETONE:
1847 case ISD::SETNE:
1848 return M68k::COND_NE;
1849 case ISD::SETOEQ:
1850 case ISD::SETUNE:
1851 return M68k::COND_INVALID;
1852 }
1853}
1854
1855// Convert (truncate (srl X, N) to i1) to (bt X, N)
1857 const SDLoc &DL, SelectionDAG &DAG) {
1858
1859 assert(Op.getOpcode() == ISD::TRUNCATE && Op.getValueType() == MVT::i1 &&
1860 "Expected TRUNCATE to i1 node");
1861
1862 if (Op.getOperand(0).getOpcode() != ISD::SRL)
1863 return SDValue();
1864
1865 SDValue ShiftRight = Op.getOperand(0);
1866 return getBitTestCondition(ShiftRight.getOperand(0), ShiftRight.getOperand(1),
1867 CC, DL, DAG);
1868}
1869
1870/// \brief return true if \c Op has a use that doesn't just read flags.
1872 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
1873 ++UI) {
1874 SDNode *User = UI->getUser();
1875 unsigned UOpNo = UI->getOperandNo();
1876 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
1877 // Look past truncate.
1878 UOpNo = User->use_begin()->getOperandNo();
1879 User = User->use_begin()->getUser();
1880 }
1881
1882 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
1883 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
1884 return true;
1885 }
1886 return false;
1887}
1888
1889SDValue M68kTargetLowering::EmitTest(SDValue Op, unsigned M68kCC,
1890 const SDLoc &DL, SelectionDAG &DAG) const {
1891
1892 // CF and OF aren't always set the way we want. Determine which
1893 // of these we need.
1894 bool NeedCF = false;
1895 bool NeedOF = false;
1896 switch (M68kCC) {
1897 default:
1898 break;
1899 case M68k::COND_HI:
1900 case M68k::COND_CC:
1901 case M68k::COND_CS:
1902 case M68k::COND_LS:
1903 NeedCF = true;
1904 break;
1905 case M68k::COND_GT:
1906 case M68k::COND_GE:
1907 case M68k::COND_LT:
1908 case M68k::COND_LE:
1909 case M68k::COND_VS:
1910 case M68k::COND_VC: {
1911 // Check if we really need to set the
1912 // Overflow flag. If NoSignedWrap is present
1913 // that is not actually needed.
1914 switch (Op->getOpcode()) {
1915 case ISD::ADD:
1916 case ISD::SUB:
1917 case ISD::MUL:
1918 case ISD::SHL: {
1919 if (Op.getNode()->getFlags().hasNoSignedWrap())
1920 break;
1921 [[fallthrough]];
1922 }
1923 default:
1924 NeedOF = true;
1925 break;
1926 }
1927 break;
1928 }
1929 }
1930 // See if we can use the CCR value from the operand instead of
1931 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
1932 // we prove that the arithmetic won't overflow, we can't use OF or CF.
1933 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
1934 // Emit a CMP with 0, which is the TEST pattern.
1935 return DAG.getNode(M68kISD::CMP, DL, MVT::i8,
1936 DAG.getConstant(0, DL, Op.getValueType()), Op);
1937 }
1938 unsigned Opcode = 0;
1939 unsigned NumOperands = 0;
1940
1941 // Truncate operations may prevent the merge of the SETCC instruction
1942 // and the arithmetic instruction before it. Attempt to truncate the operands
1943 // of the arithmetic instruction and use a reduced bit-width instruction.
1944 bool NeedTruncation = false;
1945 SDValue ArithOp = Op;
1946 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
1947 SDValue Arith = Op->getOperand(0);
1948 // Both the trunc and the arithmetic op need to have one user each.
1949 if (Arith->hasOneUse())
1950 switch (Arith.getOpcode()) {
1951 default:
1952 break;
1953 case ISD::ADD:
1954 case ISD::SUB:
1955 case ISD::AND:
1956 case ISD::OR:
1957 case ISD::XOR: {
1958 NeedTruncation = true;
1959 ArithOp = Arith;
1960 }
1961 }
1962 }
1963
1964 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
1965 // which may be the result of a CAST. We use the variable 'Op', which is the
1966 // non-casted variable when we check for possible users.
1967 switch (ArithOp.getOpcode()) {
1968 case ISD::ADD:
1969 Opcode = M68kISD::ADD;
1970 NumOperands = 2;
1971 break;
1972 case ISD::SHL:
1973 case ISD::SRL:
1974 // If we have a constant logical shift that's only used in a comparison
1975 // against zero turn it into an equivalent AND. This allows turning it into
1976 // a TEST instruction later.
1977 if ((M68kCC == M68k::COND_EQ || M68kCC == M68k::COND_NE) &&
1978 Op->hasOneUse() && isa<ConstantSDNode>(Op->getOperand(1)) &&
1979 !hasNonFlagsUse(Op)) {
1980 EVT VT = Op.getValueType();
1981 unsigned BitWidth = VT.getSizeInBits();
1982 unsigned ShAmt = Op->getConstantOperandVal(1);
1983 if (ShAmt >= BitWidth) // Avoid undefined shifts.
1984 break;
1985 APInt Mask = ArithOp.getOpcode() == ISD::SRL
1987 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
1988 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
1989 break;
1990 Op = DAG.getNode(ISD::AND, DL, VT, Op->getOperand(0),
1991 DAG.getConstant(Mask, DL, VT));
1992 }
1993 break;
1994
1995 case ISD::AND:
1996 // If the primary 'and' result isn't used, don't bother using
1997 // M68kISD::AND, because a TEST instruction will be better.
1998 if (!hasNonFlagsUse(Op)) {
1999 SDValue Op0 = ArithOp->getOperand(0);
2000 SDValue Op1 = ArithOp->getOperand(1);
2001 EVT VT = ArithOp.getValueType();
2002 bool IsAndn = isBitwiseNot(Op0) || isBitwiseNot(Op1);
2003 bool IsLegalAndnType = VT == MVT::i32 || VT == MVT::i64;
2004
2005 // But if we can combine this into an ANDN operation, then create an AND
2006 // now and allow it to be pattern matched into an ANDN.
2007 if (/*!Subtarget.hasBMI() ||*/ !IsAndn || !IsLegalAndnType)
2008 break;
2009 }
2010 [[fallthrough]];
2011 case ISD::SUB:
2012 case ISD::OR:
2013 case ISD::XOR:
2014 // Due to the ISEL shortcoming noted above, be conservative if this op is
2015 // likely to be selected as part of a load-modify-store instruction.
2016 for (const auto *U : Op.getNode()->users())
2017 if (U->getOpcode() == ISD::STORE)
2018 goto default_case;
2019
2020 // Otherwise use a regular CCR-setting instruction.
2021 switch (ArithOp.getOpcode()) {
2022 default:
2023 llvm_unreachable("unexpected operator!");
2024 case ISD::SUB:
2025 Opcode = M68kISD::SUB;
2026 break;
2027 case ISD::XOR:
2028 Opcode = M68kISD::XOR;
2029 break;
2030 case ISD::AND:
2031 Opcode = M68kISD::AND;
2032 break;
2033 case ISD::OR:
2034 Opcode = M68kISD::OR;
2035 break;
2036 }
2037
2038 NumOperands = 2;
2039 break;
2040 case M68kISD::ADD:
2041 case M68kISD::SUB:
2042 case M68kISD::OR:
2043 case M68kISD::XOR:
2044 case M68kISD::AND:
2045 return SDValue(Op.getNode(), 1);
2046 default:
2047 default_case:
2048 break;
2049 }
2050
2051 // If we found that truncation is beneficial, perform the truncation and
2052 // update 'Op'.
2053 if (NeedTruncation) {
2054 EVT VT = Op.getValueType();
2055 SDValue WideVal = Op->getOperand(0);
2056 EVT WideVT = WideVal.getValueType();
2057 unsigned ConvertedOp = 0;
2058 // Use a target machine opcode to prevent further DAGCombine
2059 // optimizations that may separate the arithmetic operations
2060 // from the setcc node.
2061 switch (WideVal.getOpcode()) {
2062 default:
2063 break;
2064 case ISD::ADD:
2065 ConvertedOp = M68kISD::ADD;
2066 break;
2067 case ISD::SUB:
2068 ConvertedOp = M68kISD::SUB;
2069 break;
2070 case ISD::AND:
2071 ConvertedOp = M68kISD::AND;
2072 break;
2073 case ISD::OR:
2074 ConvertedOp = M68kISD::OR;
2075 break;
2076 case ISD::XOR:
2077 ConvertedOp = M68kISD::XOR;
2078 break;
2079 }
2080
2081 if (ConvertedOp) {
2082 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2083 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
2084 SDValue V0 = DAG.getNode(ISD::TRUNCATE, DL, VT, WideVal.getOperand(0));
2085 SDValue V1 = DAG.getNode(ISD::TRUNCATE, DL, VT, WideVal.getOperand(1));
2086 Op = DAG.getNode(ConvertedOp, DL, VT, V0, V1);
2087 }
2088 }
2089 }
2090
2091 if (Opcode == 0) {
2092 // Emit a CMP with 0, which is the TEST pattern.
2093 return DAG.getNode(M68kISD::CMP, DL, MVT::i8,
2094 DAG.getConstant(0, DL, Op.getValueType()), Op);
2095 }
2096 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i8);
2097 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
2098
2099 SDValue New = DAG.getNode(Opcode, DL, VTs, Ops);
2100 DAG.ReplaceAllUsesWith(Op, New);
2101 return SDValue(New.getNode(), 1);
2102}
2103
2104SDValue M68kTargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned M68kCC,
2105 const SDLoc &DL, SelectionDAG &DAG) const {
2106 if (isNullConstant(Op1))
2107 return EmitTest(Op0, M68kCC, DL, DAG);
2108
2109 assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
2110 "Unexpected comparison operation for MVT::i1 operands");
2111
2112 return DAG.getNode(M68kISD::CMP, DL, MVT::i8, Op1, Op0);
2113}
2114
2115/// Result of 'and' or 'trunc to i1' is compared against zero.
2116/// Change to a BTST node if possible.
2117SDValue M68kTargetLowering::LowerToBTST(SDValue Op, ISD::CondCode CC,
2118 const SDLoc &DL,
2119 SelectionDAG &DAG) const {
2120 if (Op.getOpcode() == ISD::AND)
2121 return LowerAndToBTST(Op, CC, DL, DAG);
2122 if (Op.getOpcode() == ISD::TRUNCATE && Op.getValueType() == MVT::i1)
2123 return LowerTruncateToBTST(Op, CC, DL, DAG);
2124 return SDValue();
2125}
2126
2127SDValue M68kTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2128 MVT VT = Op.getSimpleValueType();
2129 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
2130
2131 SDValue Op0 = Op.getOperand(0);
2132 SDValue Op1 = Op.getOperand(1);
2133 SDLoc DL(Op);
2134 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2135
2136 // Optimize to BTST if possible.
2137 // Lower (X & (1 << N)) == 0 to BTST(X, N).
2138 // Lower ((X >>u N) & 1) != 0 to BTST(X, N).
2139 // Lower ((X >>s N) & 1) != 0 to BTST(X, N).
2140 // Lower (trunc (X >> N) to i1) to BTST(X, N).
2141 if (Op0.hasOneUse() && isNullConstant(Op1) &&
2142 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2143 if (SDValue NewSetCC = LowerToBTST(Op0, CC, DL, DAG)) {
2144 if (VT == MVT::i1)
2145 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, NewSetCC);
2146 return NewSetCC;
2147 }
2148 }
2149
2150 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
2151 // these.
2152 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
2153 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2154
2155 // If the input is a setcc, then reuse the input setcc or use a new one with
2156 // the inverted condition.
2157 if (Op0.getOpcode() == M68kISD::SETCC) {
2159 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
2160 if (!Invert)
2161 return Op0;
2162
2163 CCode = M68k::GetOppositeBranchCondition(CCode);
2164 SDValue SetCC =
2165 DAG.getNode(M68kISD::SETCC, DL, MVT::i8,
2166 DAG.getConstant(CCode, DL, MVT::i8), Op0.getOperand(1));
2167 if (VT == MVT::i1)
2168 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
2169 return SetCC;
2170 }
2171 }
2172 if (Op0.getValueType() == MVT::i1 && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2173 if (isOneConstant(Op1)) {
2175 return DAG.getSetCC(DL, VT, Op0, DAG.getConstant(0, DL, MVT::i1), NewCC);
2176 }
2177 if (!isNullConstant(Op1)) {
2178 SDValue Xor = DAG.getNode(ISD::XOR, DL, MVT::i1, Op0, Op1);
2179 return DAG.getSetCC(DL, VT, Xor, DAG.getConstant(0, DL, MVT::i1), CC);
2180 }
2181 }
2182
2183 bool IsFP = Op1.getSimpleValueType().isFloatingPoint();
2184 M68k::CondCode M68kCC = TranslateM68kCC(CC, DL, IsFP, Op0, Op1, DAG);
2185 if (M68kCC == M68k::COND_INVALID)
2186 return SDValue();
2187
2188 SDValue CCR = EmitCmp(Op0, Op1, M68kCC, DL, DAG);
2189 return DAG.getNode(M68kISD::SETCC, DL, MVT::i8,
2190 DAG.getConstant(M68kCC, DL, MVT::i8), CCR);
2191}
2192
2193SDValue M68kTargetLowering::LowerSETCCCARRY(SDValue Op,
2194 SelectionDAG &DAG) const {
2195 SDValue LHS = Op.getOperand(0);
2196 SDValue RHS = Op.getOperand(1);
2197 SDValue Carry = Op.getOperand(2);
2198 SDValue Cond = Op.getOperand(3);
2199 SDLoc DL(Op);
2200
2201 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
2203
2204 EVT CarryVT = Carry.getValueType();
2205 APInt NegOne = APInt::getAllOnes(CarryVT.getScalarSizeInBits());
2206 Carry = DAG.getNode(M68kISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i8), Carry,
2207 DAG.getConstant(NegOne, DL, CarryVT));
2208
2209 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i8);
2210 SDValue Cmp =
2211 DAG.getNode(M68kISD::SUBX, DL, VTs, LHS, RHS, Carry.getValue(1));
2212
2213 return DAG.getNode(M68kISD::SETCC, DL, MVT::i8,
2214 DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
2215}
2216
2217/// Return true if opcode is a M68k logical comparison.
2219 unsigned Opc = Op.getNode()->getOpcode();
2220 if (Opc == M68kISD::CMP)
2221 return true;
2222 if (Op.getResNo() == 1 &&
2223 (Opc == M68kISD::ADD || Opc == M68kISD::SUB || Opc == M68kISD::ADDX ||
2224 Opc == M68kISD::SUBX || Opc == M68kISD::SMUL || Opc == M68kISD::UMUL ||
2225 Opc == M68kISD::OR || Opc == M68kISD::XOR || Opc == M68kISD::AND))
2226 return true;
2227
2228 if (Op.getResNo() == 2 && Opc == M68kISD::UMUL)
2229 return true;
2230
2231 return false;
2232}
2233
2235 if (V.getOpcode() != ISD::TRUNCATE)
2236 return false;
2237
2238 SDValue VOp0 = V.getOperand(0);
2239 unsigned InBits = VOp0.getValueSizeInBits();
2240 unsigned Bits = V.getValueSizeInBits();
2241 return DAG.MaskedValueIsZero(VOp0,
2242 APInt::getHighBitsSet(InBits, InBits - Bits));
2243}
2244
2245SDValue M68kTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2246 bool addTest = true;
2247 SDValue Cond = Op.getOperand(0);
2248 SDValue Op1 = Op.getOperand(1);
2249 SDValue Op2 = Op.getOperand(2);
2250 SDLoc DL(Op);
2251 SDValue CC;
2252
2253 if (Cond.getOpcode() == ISD::SETCC) {
2254 if (SDValue NewCond = LowerSETCC(Cond, DAG))
2255 Cond = NewCond;
2256 }
2257
2258 // If condition flag is set by a M68kISD::CMP, then use it as the condition
2259 // setting operand in place of the M68kISD::SETCC.
2260 unsigned CondOpcode = Cond.getOpcode();
2261 if (CondOpcode == M68kISD::SETCC) {
2262 CC = Cond.getOperand(0);
2263
2264 SDValue Cmp = Cond.getOperand(1);
2265 unsigned Opc = Cmp.getOpcode();
2266
2267 bool IllegalFPCMov = false;
2268
2269 if ((isM68kLogicalCmp(Cmp) && !IllegalFPCMov) || Opc == M68kISD::BTST) {
2270 Cond = Cmp;
2271 addTest = false;
2272 }
2273 } else if (isOverflowArithmetic(CondOpcode)) {
2274 // Result is unused here.
2275 SDValue Result;
2276 M68k::CondCode CCode;
2277 lowerOverflowArithmetic(Cond, DAG, Result, Cond, CCode);
2278 CC = DAG.getConstant(CCode, DL, MVT::i8);
2279 addTest = false;
2280 }
2281
2282 if (addTest) {
2283 // Look past the truncate if the high bits are known zero.
2285 Cond = Cond.getOperand(0);
2286
2287 // We know the result of AND is compared against zero. Try to match
2288 // it to BT.
2289 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
2290 if (SDValue NewSetCC = LowerToBTST(Cond, ISD::SETNE, DL, DAG)) {
2291 CC = NewSetCC.getOperand(0);
2292 Cond = NewSetCC.getOperand(1);
2293 addTest = false;
2294 }
2295 }
2296 }
2297
2298 if (addTest) {
2299 CC = DAG.getConstant(M68k::COND_NE, DL, MVT::i8);
2300 Cond = EmitTest(Cond, M68k::COND_NE, DL, DAG);
2301 }
2302
2303 // M68k doesn't have an i8 cmov. If both operands are the result of a
2304 // truncate widen the cmov and push the truncate through. This avoids
2305 // introducing a new branch during isel and doesn't add any extensions.
2306 if (Op.getValueType() == MVT::i8 && Op1.getOpcode() == ISD::TRUNCATE &&
2307 Op2.getOpcode() == ISD::TRUNCATE) {
2308 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
2309 if (T1.getValueType() == T2.getValueType() &&
2310 // Block CopyFromReg so partial register stalls are avoided.
2311 T1.getOpcode() != ISD::CopyFromReg &&
2312 T2.getOpcode() != ISD::CopyFromReg) {
2313 SDValue Cmov =
2314 DAG.getNode(M68kISD::CMOV, DL, T1.getValueType(), T2, T1, CC, Cond);
2315 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
2316 }
2317 }
2318
2319 // Simple optimization when Cond is a constant to avoid generating
2320 // M68kISD::CMOV if possible.
2321 // TODO: Generalize this to use SelectionDAG::computeKnownBits.
2322 if (auto *Const = dyn_cast<ConstantSDNode>(Cond.getNode())) {
2323 const APInt &C = Const->getAPIntValue();
2324 if (C.countr_zero() >= 5)
2325 return Op2;
2326 else if (C.countr_one() >= 5)
2327 return Op1;
2328 }
2329
2330 // M68kISD::CMOV means set the result (which is operand 1) to the RHS if
2331 // condition is true.
2332 SDValue Ops[] = {Op2, Op1, CC, Cond};
2333 return DAG.getNode(M68kISD::CMOV, DL, Op.getValueType(), Ops);
2334}
2335
2336/// Return true if node is an ISD::AND or ISD::OR of two M68k::SETcc nodes
2337/// each of which has no other use apart from the AND / OR.
2338static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
2339 Opc = Op.getOpcode();
2340 if (Opc != ISD::OR && Opc != ISD::AND)
2341 return false;
2342 return (M68k::IsSETCC(Op.getOperand(0).getOpcode()) &&
2343 Op.getOperand(0).hasOneUse() &&
2344 M68k::IsSETCC(Op.getOperand(1).getOpcode()) &&
2345 Op.getOperand(1).hasOneUse());
2346}
2347
2348/// Return true if node is an ISD::XOR of a M68kISD::SETCC and 1 and that the
2349/// SETCC node has a single use.
2351 if (Op.getOpcode() != ISD::XOR)
2352 return false;
2353 if (isOneConstant(Op.getOperand(1)))
2354 return Op.getOperand(0).getOpcode() == M68kISD::SETCC &&
2355 Op.getOperand(0).hasOneUse();
2356 return false;
2357}
2358
2359SDValue M68kTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2360 bool AddTest = true;
2361 SDValue Chain = Op.getOperand(0);
2362 SDValue Cond = Op.getOperand(1);
2363 SDValue Dest = Op.getOperand(2);
2364 SDLoc DL(Op);
2365 SDValue CC;
2366 bool Inverted = false;
2367
2368 if (Cond.getOpcode() == ISD::SETCC) {
2369 // Check for setcc([su]{add,sub}o == 0).
2370 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
2371 isNullConstant(Cond.getOperand(1)) &&
2372 Cond.getOperand(0).getResNo() == 1 &&
2373 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
2374 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
2375 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
2376 Cond.getOperand(0).getOpcode() == ISD::USUBO)) {
2377 Inverted = true;
2378 Cond = Cond.getOperand(0);
2379 } else {
2380 if (SDValue NewCond = LowerSETCC(Cond, DAG))
2381 Cond = NewCond;
2382 }
2383 }
2384
2385 // If condition flag is set by a M68kISD::CMP, then use it as the condition
2386 // setting operand in place of the M68kISD::SETCC.
2387 unsigned CondOpcode = Cond.getOpcode();
2388 if (CondOpcode == M68kISD::SETCC) {
2389 CC = Cond.getOperand(0);
2390
2391 SDValue Cmp = Cond.getOperand(1);
2392 unsigned Opc = Cmp.getOpcode();
2393
2394 if (isM68kLogicalCmp(Cmp) || Opc == M68kISD::BTST) {
2395 Cond = Cmp;
2396 AddTest = false;
2397 } else {
2398 switch (CC->getAsZExtVal()) {
2399 default:
2400 break;
2401 case M68k::COND_VS:
2402 case M68k::COND_CS:
2403 // These can only come from an arithmetic instruction with overflow,
2404 // e.g. SADDO, UADDO.
2405 Cond = Cond.getNode()->getOperand(1);
2406 AddTest = false;
2407 break;
2408 }
2409 }
2410 }
2411 CondOpcode = Cond.getOpcode();
2412 if (isOverflowArithmetic(CondOpcode)) {
2413 SDValue Result;
2414 M68k::CondCode CCode;
2415 lowerOverflowArithmetic(Cond, DAG, Result, Cond, CCode);
2416
2417 if (Inverted)
2418 CCode = M68k::GetOppositeBranchCondition(CCode);
2419 CC = DAG.getConstant(CCode, DL, MVT::i8);
2420
2421 AddTest = false;
2422 } else {
2423 unsigned CondOpc;
2424 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
2425 SDValue Cmp = Cond.getOperand(0).getOperand(1);
2426 if (CondOpc == ISD::OR) {
2427 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
2428 // two branches instead of an explicit OR instruction with a
2429 // separate test.
2430 if (Cmp == Cond.getOperand(1).getOperand(1) && isM68kLogicalCmp(Cmp)) {
2431 CC = Cond.getOperand(0).getOperand(0);
2432 Chain = DAG.getNode(M68kISD::BRCOND, DL, Op.getValueType(), Chain,
2433 Dest, CC, Cmp);
2434 CC = Cond.getOperand(1).getOperand(0);
2435 Cond = Cmp;
2436 AddTest = false;
2437 }
2438 } else { // ISD::AND
2439 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
2440 // two branches instead of an explicit AND instruction with a
2441 // separate test. However, we only do this if this block doesn't
2442 // have a fall-through edge, because this requires an explicit
2443 // jmp when the condition is false.
2444 if (Cmp == Cond.getOperand(1).getOperand(1) && isM68kLogicalCmp(Cmp) &&
2445 Op.getNode()->hasOneUse()) {
2446 M68k::CondCode CCode =
2447 (M68k::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
2448 CCode = M68k::GetOppositeBranchCondition(CCode);
2449 CC = DAG.getConstant(CCode, DL, MVT::i8);
2450 SDNode *User = *Op.getNode()->user_begin();
2451 // Look for an unconditional branch following this conditional branch.
2452 // We need this because we need to reverse the successors in order
2453 // to implement FCMP_OEQ.
2454 if (User->getOpcode() == ISD::BR) {
2455 SDValue FalseBB = User->getOperand(1);
2456 SDNode *NewBR =
2457 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
2458 assert(NewBR == User);
2459 (void)NewBR;
2460 Dest = FalseBB;
2461
2462 Chain = DAG.getNode(M68kISD::BRCOND, DL, Op.getValueType(), Chain,
2463 Dest, CC, Cmp);
2464 M68k::CondCode CCode =
2465 (M68k::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
2466 CCode = M68k::GetOppositeBranchCondition(CCode);
2467 CC = DAG.getConstant(CCode, DL, MVT::i8);
2468 Cond = Cmp;
2469 AddTest = false;
2470 }
2471 }
2472 }
2473 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
2474 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
2475 // It should be transformed during dag combiner except when the condition
2476 // is set by a arithmetics with overflow node.
2477 M68k::CondCode CCode =
2478 (M68k::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
2479 CCode = M68k::GetOppositeBranchCondition(CCode);
2480 CC = DAG.getConstant(CCode, DL, MVT::i8);
2481 Cond = Cond.getOperand(0).getOperand(1);
2482 AddTest = false;
2483 }
2484 }
2485
2486 if (AddTest) {
2487 // Look pass the truncate if the high bits are known zero.
2489 Cond = Cond.getOperand(0);
2490
2491 // We know the result is compared against zero. Try to match it to BT.
2492 if (Cond.hasOneUse()) {
2493 if (SDValue NewSetCC = LowerToBTST(Cond, ISD::SETNE, DL, DAG)) {
2494 CC = NewSetCC.getOperand(0);
2495 Cond = NewSetCC.getOperand(1);
2496 AddTest = false;
2497 }
2498 }
2499 }
2500
2501 if (AddTest) {
2502 M68k::CondCode MxCond = Inverted ? M68k::COND_EQ : M68k::COND_NE;
2503 CC = DAG.getConstant(MxCond, DL, MVT::i8);
2504 Cond = EmitTest(Cond, MxCond, DL, DAG);
2505 }
2506 return DAG.getNode(M68kISD::BRCOND, DL, Op.getValueType(), Chain, Dest, CC,
2507 Cond);
2508}
2509
2510SDValue M68kTargetLowering::LowerUADDO_USUBO_CARRY(SDValue Op,
2511 SelectionDAG &DAG) const {
2512 SDNode *N = Op.getNode();
2513 MVT VT = N->getSimpleValueType(0);
2514 SDLoc DL(N);
2515
2516 // Set the X flag from the carry-in. ADD sets X and C; ADDX/SUBX read X.
2517 SDValue Carry = Op.getOperand(2);
2518 EVT CarryVT = Carry.getValueType();
2519 SDValue Flags = DAG.getNode(M68kISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i8),
2520 Carry, DAG.getAllOnesConstant(DL, CarryVT))
2521 .getValue(1);
2522
2523 bool IsAdd = Op.getOpcode() == ISD::UADDO_CARRY;
2524 SDValue Sum = DAG.getNode(IsAdd ? M68kISD::ADDX : M68kISD::SUBX, DL,
2525 DAG.getVTList(VT, MVT::i8), Op.getOperand(0),
2526 Op.getOperand(1), Flags);
2527
2528 SDValue SetCC = getSETCC(M68k::COND_CS, Sum.getValue(1), DL, DAG);
2529
2530 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
2531}
2532
2533// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2534// their target countpart wrapped in the M68kISD::Wrapper node. Suppose N is
2535// one of the above mentioned nodes. It has to be wrapped because otherwise
2536// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2537// be used to form addressing mode. These wrapped nodes will be selected
2538// into MOV32ri.
2539SDValue M68kTargetLowering::LowerConstantPool(SDValue Op,
2540 SelectionDAG &DAG) const {
2541 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2542
2543 // In PIC mode (unless we're in PCRel PIC mode) we add an offset to the
2544 // global base reg.
2545 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
2546
2547 unsigned WrapperKind = M68kISD::Wrapper;
2548 if (M68kII::isPCRelGlobalReference(OpFlag)) {
2549 WrapperKind = M68kISD::WrapperPC;
2550 }
2551
2552 MVT PtrVT = getPointerTy(DAG.getDataLayout());
2553 SDValue Result = DAG.getTargetConstantPool(
2554 CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
2555
2556 SDLoc DL(CP);
2557 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
2558
2559 // With PIC, the address is actually $g + Offset.
2561 Result = DAG.getNode(ISD::ADD, DL, PtrVT,
2562 DAG.getNode(M68kISD::GLOBAL_BASE_REG, SDLoc(), PtrVT),
2563 Result);
2564 }
2565
2566 return Result;
2567}
2568
2569SDValue M68kTargetLowering::LowerExternalSymbol(SDValue Op,
2570 SelectionDAG &DAG) const {
2571 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
2572
2573 // In PIC mode (unless we're in PCRel PIC mode) we add an offset to the
2574 // global base reg.
2576 unsigned char OpFlag = Subtarget.classifyExternalReference(*Mod);
2577
2578 unsigned WrapperKind = M68kISD::Wrapper;
2579 if (M68kII::isPCRelGlobalReference(OpFlag)) {
2580 WrapperKind = M68kISD::WrapperPC;
2581 }
2582
2583 auto PtrVT = getPointerTy(DAG.getDataLayout());
2584 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
2585
2586 SDLoc DL(Op);
2587 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
2588
2589 // With PIC, the address is actually $g + Offset.
2591 Result = DAG.getNode(ISD::ADD, DL, PtrVT,
2592 DAG.getNode(M68kISD::GLOBAL_BASE_REG, SDLoc(), PtrVT),
2593 Result);
2594 }
2595
2596 // For symbols that require a load from a stub to get the address, emit the
2597 // load.
2598 if (M68kII::isGlobalStubReference(OpFlag)) {
2599 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2601 }
2602
2603 return Result;
2604}
2605
2606SDValue M68kTargetLowering::LowerBlockAddress(SDValue Op,
2607 SelectionDAG &DAG) const {
2608 unsigned char OpFlags = Subtarget.classifyBlockAddressReference();
2609 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2610 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
2611 SDLoc DL(Op);
2612 auto PtrVT = getPointerTy(DAG.getDataLayout());
2613
2614 // Create the TargetBlockAddressAddress node.
2615 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
2616
2617 if (M68kII::isPCRelBlockReference(OpFlags)) {
2618 Result = DAG.getNode(M68kISD::WrapperPC, DL, PtrVT, Result);
2619 } else {
2620 Result = DAG.getNode(M68kISD::Wrapper, DL, PtrVT, Result);
2621 }
2622
2623 // With PIC, the address is actually $g + Offset.
2624 if (M68kII::isGlobalRelativeToPICBase(OpFlags)) {
2625 Result =
2626 DAG.getNode(ISD::ADD, DL, PtrVT,
2627 DAG.getNode(M68kISD::GLOBAL_BASE_REG, DL, PtrVT), Result);
2628 }
2629
2630 return Result;
2631}
2632
2633SDValue M68kTargetLowering::LowerGlobalAddress(const GlobalValue *GV,
2634 const SDLoc &DL, int64_t Offset,
2635 SelectionDAG &DAG) const {
2636 unsigned char OpFlags = Subtarget.classifyGlobalReference(GV);
2637 auto PtrVT = getPointerTy(DAG.getDataLayout());
2638
2639 // Create the TargetGlobalAddress node, folding in the constant
2640 // offset if it is legal.
2641 SDValue Result;
2642 if (M68kII::isDirectGlobalReference(OpFlags)) {
2643 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Offset);
2644 Offset = 0;
2645 } else {
2646 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2647 }
2648
2649 if (M68kII::isPCRelGlobalReference(OpFlags))
2650 Result = DAG.getNode(M68kISD::WrapperPC, DL, PtrVT, Result);
2651 else
2652 Result = DAG.getNode(M68kISD::Wrapper, DL, PtrVT, Result);
2653
2654 // With PIC, the address is actually $g + Offset.
2655 if (M68kII::isGlobalRelativeToPICBase(OpFlags)) {
2656 Result =
2657 DAG.getNode(ISD::ADD, DL, PtrVT,
2658 DAG.getNode(M68kISD::GLOBAL_BASE_REG, DL, PtrVT), Result);
2659 }
2660
2661 // For globals that require a load from a stub to get the address, emit the
2662 // load.
2663 if (M68kII::isGlobalStubReference(OpFlags)) {
2664 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2666 }
2667
2668 // If there was a non-zero offset that we didn't fold, create an explicit
2669 // addition for it.
2670 if (Offset != 0) {
2671 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2672 DAG.getConstant(Offset, DL, PtrVT));
2673 }
2674
2675 return Result;
2676}
2677
2678SDValue M68kTargetLowering::LowerGlobalAddress(SDValue Op,
2679 SelectionDAG &DAG) const {
2680 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2681 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
2682 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
2683}
2684
2685//===----------------------------------------------------------------------===//
2686// Custom Lower Jump Table
2687//===----------------------------------------------------------------------===//
2688
2689SDValue M68kTargetLowering::LowerJumpTable(SDValue Op,
2690 SelectionDAG &DAG) const {
2691 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2692
2693 // In PIC mode (unless we're in PCRel PIC mode) we add an offset to the
2694 // global base reg.
2695 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
2696
2697 unsigned WrapperKind = M68kISD::Wrapper;
2698 if (M68kII::isPCRelGlobalReference(OpFlag)) {
2699 WrapperKind = M68kISD::WrapperPC;
2700 }
2701
2702 auto PtrVT = getPointerTy(DAG.getDataLayout());
2703 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
2704 SDLoc DL(JT);
2705 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
2706
2707 // With PIC, the address is actually $g + Offset.
2709 Result = DAG.getNode(ISD::ADD, DL, PtrVT,
2710 DAG.getNode(M68kISD::GLOBAL_BASE_REG, SDLoc(), PtrVT),
2711 Result);
2712 }
2713
2714 return Result;
2715}
2716
2718 return Subtarget.getJumpTableEncoding();
2719}
2720
2722 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
2723 unsigned uid, MCContext &Ctx) const {
2724 return MCSymbolRefExpr::create(MBB->getSymbol(), M68k::S_GOTOFF, Ctx);
2725}
2726
2728 SelectionDAG &DAG) const {
2730 return DAG.getNode(M68kISD::GLOBAL_BASE_REG, SDLoc(),
2732
2733 // MachineJumpTableInfo::EK_LabelDifference32 entry
2734 return Table;
2735}
2736
2737// NOTE This only used for MachineJumpTableInfo::EK_LabelDifference32 entries
2739 const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const {
2740 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
2741}
2742
2745 if (Constraint.size() > 0) {
2746 switch (Constraint[0]) {
2747 case 'a':
2748 case 'd':
2749 return C_RegisterClass;
2750 case 'I':
2751 case 'J':
2752 case 'K':
2753 case 'L':
2754 case 'M':
2755 case 'N':
2756 case 'O':
2757 case 'P':
2758 return C_Immediate;
2759 case 'C':
2760 if (Constraint.size() == 2)
2761 switch (Constraint[1]) {
2762 case '0':
2763 case 'i':
2764 case 'j':
2765 return C_Immediate;
2766 default:
2767 break;
2768 }
2769 break;
2770 case 'Q':
2771 case 'U':
2772 return C_Memory;
2773 default:
2774 break;
2775 }
2776 }
2777
2778 return TargetLowering::getConstraintType(Constraint);
2779}
2780
2782 StringRef Constraint,
2783 std::vector<SDValue> &Ops,
2784 SelectionDAG &DAG) const {
2785 SDValue Result;
2786
2787 if (Constraint.size() == 1) {
2788 // Constant constraints
2789 switch (Constraint[0]) {
2790 case 'I':
2791 case 'J':
2792 case 'K':
2793 case 'L':
2794 case 'M':
2795 case 'N':
2796 case 'O':
2797 case 'P': {
2798 auto *C = dyn_cast<ConstantSDNode>(Op);
2799 if (!C)
2800 return;
2801
2802 int64_t Val = C->getSExtValue();
2803 switch (Constraint[0]) {
2804 case 'I': // constant integer in the range [1,8]
2805 if (Val > 0 && Val <= 8)
2806 break;
2807 return;
2808 case 'J': // constant signed 16-bit integer
2809 if (isInt<16>(Val))
2810 break;
2811 return;
2812 case 'K': // constant that is NOT in the range of [-0x80, 0x80)
2813 if (Val < -0x80 || Val >= 0x80)
2814 break;
2815 return;
2816 case 'L': // constant integer in the range [-8,-1]
2817 if (Val < 0 && Val >= -8)
2818 break;
2819 return;
2820 case 'M': // constant that is NOT in the range of [-0x100, 0x100]
2821 if (Val < -0x100 || Val >= 0x100)
2822 break;
2823 return;
2824 case 'N': // constant integer in the range [24,31]
2825 if (Val >= 24 && Val <= 31)
2826 break;
2827 return;
2828 case 'O': // constant integer 16
2829 if (Val == 16)
2830 break;
2831 return;
2832 case 'P': // constant integer in the range [8,15]
2833 if (Val >= 8 && Val <= 15)
2834 break;
2835 return;
2836 default:
2837 llvm_unreachable("Unhandled constant constraint");
2838 }
2839
2840 Result = DAG.getSignedTargetConstant(Val, SDLoc(Op), Op.getValueType());
2841 break;
2842 }
2843 default:
2844 break;
2845 }
2846 }
2847
2848 if (Constraint.size() == 2) {
2849 switch (Constraint[0]) {
2850 case 'C':
2851 // Constant constraints start with 'C'
2852 switch (Constraint[1]) {
2853 case '0':
2854 case 'i':
2855 case 'j': {
2856 auto *C = dyn_cast<ConstantSDNode>(Op);
2857 if (!C)
2858 break;
2859
2860 int64_t Val = C->getSExtValue();
2861 switch (Constraint[1]) {
2862 case '0': // constant integer 0
2863 if (!Val)
2864 break;
2865 return;
2866 case 'i': // constant integer
2867 break;
2868 case 'j': // integer constant that doesn't fit in 16 bits
2869 if (!isInt<16>(C->getSExtValue()))
2870 break;
2871 return;
2872 default:
2873 llvm_unreachable("Unhandled constant constraint");
2874 }
2875
2876 Result = DAG.getSignedTargetConstant(Val, SDLoc(Op), Op.getValueType());
2877 break;
2878 }
2879 default:
2880 break;
2881 }
2882 break;
2883 default:
2884 break;
2885 }
2886 }
2887
2888 if (Result.getNode()) {
2889 Ops.push_back(Result);
2890 return;
2891 }
2892
2894}
2895
2896std::pair<unsigned, const TargetRegisterClass *>
2898 StringRef Constraint,
2899 MVT VT) const {
2900 if (Constraint.size() == 1) {
2901 switch (Constraint[0]) {
2902 case 'r':
2903 case 'd':
2904 switch (VT.SimpleTy) {
2905 case MVT::i8:
2906 return std::make_pair(0U, &M68k::DR8RegClass);
2907 case MVT::i16:
2908 return std::make_pair(0U, &M68k::DR16RegClass);
2909 case MVT::i32:
2910 return std::make_pair(0U, &M68k::DR32RegClass);
2911 default:
2912 break;
2913 }
2914 break;
2915 case 'a':
2916 switch (VT.SimpleTy) {
2917 case MVT::i16:
2918 return std::make_pair(0U, &M68k::AR16RegClass);
2919 case MVT::i32:
2920 return std::make_pair(0U, &M68k::AR32RegClass);
2921 default:
2922 break;
2923 }
2924 break;
2925 default:
2926 break;
2927 }
2928 }
2929
2930 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2931}
2932
2933/// Determines whether the callee is required to pop its own arguments.
2934/// Callee pop is necessary to support tail calls.
2935bool M68k::isCalleePop(CallingConv::ID CC, bool IsVarArg, bool GuaranteeTCO) {
2936 return CC == CallingConv::M68k_RTD && !IsVarArg;
2937}
2938
2939// Return true if it is OK for this CMOV pseudo-opcode to be cascaded
2940// together with other CMOV pseudo-opcodes into a single basic-block with
2941// conditional jump around it.
2943 switch (MI.getOpcode()) {
2944 case M68k::CMOV8d:
2945 case M68k::CMOV16d:
2946 case M68k::CMOV32r:
2947 return true;
2948
2949 default:
2950 return false;
2951 }
2952}
2953
2954// The CCR operand of SelectItr might be missing a kill marker
2955// because there were multiple uses of CCR, and ISel didn't know
2956// which to mark. Figure out whether SelectItr should have had a
2957// kill marker, and set it if it should. Returns the correct kill
2958// marker value.
2961 const TargetRegisterInfo *TRI) {
2962 // Scan forward through BB for a use/def of CCR.
2963 MachineBasicBlock::iterator miI(std::next(SelectItr));
2964 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
2965 const MachineInstr &mi = *miI;
2966 if (mi.readsRegister(M68k::CCR, /*TRI=*/nullptr))
2967 return false;
2968 if (mi.definesRegister(M68k::CCR, /*TRI=*/nullptr))
2969 break; // Should have kill-flag - update below.
2970 }
2971
2972 // If we hit the end of the block, check whether CCR is live into a
2973 // successor.
2974 if (miI == BB->end())
2975 for (const auto *SBB : BB->successors())
2976 if (SBB->isLiveIn(M68k::CCR))
2977 return false;
2978
2979 // We found a def, or hit the end of the basic block and CCR wasn't live
2980 // out. SelectMI should have a kill flag on CCR.
2981 SelectItr->addRegisterKilled(M68k::CCR, TRI);
2982 return true;
2983}
2984
2986M68kTargetLowering::EmitLoweredSelect(MachineInstr &MI,
2987 MachineBasicBlock *MBB) const {
2988 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
2989 DebugLoc DL = MI.getDebugLoc();
2990
2991 // To "insert" a SELECT_CC instruction, we actually have to insert the
2992 // diamond control-flow pattern. The incoming instruction knows the
2993 // destination vreg to set, the condition code register to branch on, the
2994 // true/false values to select between, and a branch opcode to use.
2995 const BasicBlock *BB = MBB->getBasicBlock();
2997
2998 // ThisMBB:
2999 // ...
3000 // TrueVal = ...
3001 // cmp ccX, r1, r2
3002 // bcc Copy1MBB
3003 // fallthrough --> Copy0MBB
3004 MachineBasicBlock *ThisMBB = MBB;
3006
3007 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
3008 // as described above, by inserting a MBB, and then making a PHI at the join
3009 // point to select the true and false operands of the CMOV in the PHI.
3010 //
3011 // The code also handles two different cases of multiple CMOV opcodes
3012 // in a row.
3013 //
3014 // Case 1:
3015 // In this case, there are multiple CMOVs in a row, all which are based on
3016 // the same condition setting (or the exact opposite condition setting).
3017 // In this case we can lower all the CMOVs using a single inserted MBB, and
3018 // then make a number of PHIs at the join point to model the CMOVs. The only
3019 // trickiness here, is that in a case like:
3020 //
3021 // t2 = CMOV cond1 t1, f1
3022 // t3 = CMOV cond1 t2, f2
3023 //
3024 // when rewriting this into PHIs, we have to perform some renaming on the
3025 // temps since you cannot have a PHI operand refer to a PHI result earlier
3026 // in the same block. The "simple" but wrong lowering would be:
3027 //
3028 // t2 = PHI t1(BB1), f1(BB2)
3029 // t3 = PHI t2(BB1), f2(BB2)
3030 //
3031 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
3032 // renaming is to note that on the path through BB1, t2 is really just a
3033 // copy of t1, and do that renaming, properly generating:
3034 //
3035 // t2 = PHI t1(BB1), f1(BB2)
3036 // t3 = PHI t1(BB1), f2(BB2)
3037 //
3038 // Case 2, we lower cascaded CMOVs such as
3039 //
3040 // (CMOV (CMOV F, T, cc1), T, cc2)
3041 //
3042 // to two successives branches.
3043 MachineInstr *CascadedCMOV = nullptr;
3044 MachineInstr *LastCMOV = &MI;
3045 M68k::CondCode CC = M68k::CondCode(MI.getOperand(3).getImm());
3048 std::next(MachineBasicBlock::iterator(MI));
3049
3050 // Check for case 1, where there are multiple CMOVs with the same condition
3051 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
3052 // number of jumps the most.
3053
3054 if (isCMOVPseudo(MI)) {
3055 // See if we have a string of CMOVS with the same condition.
3056 while (NextMIIt != MBB->end() && isCMOVPseudo(*NextMIIt) &&
3057 (NextMIIt->getOperand(3).getImm() == CC ||
3058 NextMIIt->getOperand(3).getImm() == OppCC)) {
3059 LastCMOV = &*NextMIIt;
3060 ++NextMIIt;
3061 }
3062 }
3063
3064 // This checks for case 2, but only do this if we didn't already find
3065 // case 1, as indicated by LastCMOV == MI.
3066 if (LastCMOV == &MI && NextMIIt != MBB->end() &&
3067 NextMIIt->getOpcode() == MI.getOpcode() &&
3068 NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
3069 NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
3070 NextMIIt->getOperand(1).isKill()) {
3071 CascadedCMOV = &*NextMIIt;
3072 }
3073
3074 MachineBasicBlock *Jcc1MBB = nullptr;
3075
3076 // If we have a cascaded CMOV, we lower it to two successive branches to
3077 // the same block. CCR is used by both, so mark it as live in the second.
3078 if (CascadedCMOV) {
3079 Jcc1MBB = F->CreateMachineBasicBlock(BB);
3080 F->insert(It, Jcc1MBB);
3081 Jcc1MBB->addLiveIn(M68k::CCR);
3082 }
3083
3084 MachineBasicBlock *Copy0MBB = F->CreateMachineBasicBlock(BB);
3085 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(BB);
3086 F->insert(It, Copy0MBB);
3087 F->insert(It, SinkMBB);
3088
3089 // Set the call frame size on entry to the new basic blocks.
3090 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
3091 Copy0MBB->setCallFrameSize(CallFrameSize);
3092 SinkMBB->setCallFrameSize(CallFrameSize);
3093
3094 // If the CCR register isn't dead in the terminator, then claim that it's
3095 // live into the sink and copy blocks.
3096 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3097
3098 MachineInstr *LastCCRSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
3099 if (!LastCCRSUser->killsRegister(M68k::CCR, /*TRI=*/nullptr) &&
3100 !checkAndUpdateCCRKill(LastCCRSUser, MBB, TRI)) {
3101 Copy0MBB->addLiveIn(M68k::CCR);
3102 SinkMBB->addLiveIn(M68k::CCR);
3103 }
3104
3105 // Transfer the remainder of MBB and its successor edges to SinkMBB.
3106 SinkMBB->splice(SinkMBB->begin(), MBB,
3107 std::next(MachineBasicBlock::iterator(LastCMOV)), MBB->end());
3109
3110 // Add the true and fallthrough blocks as its successors.
3111 if (CascadedCMOV) {
3112 // The fallthrough block may be Jcc1MBB, if we have a cascaded CMOV.
3113 MBB->addSuccessor(Jcc1MBB);
3114
3115 // In that case, Jcc1MBB will itself fallthrough the Copy0MBB, and
3116 // jump to the SinkMBB.
3117 Jcc1MBB->addSuccessor(Copy0MBB);
3118 Jcc1MBB->addSuccessor(SinkMBB);
3119 } else {
3120 MBB->addSuccessor(Copy0MBB);
3121 }
3122
3123 // The true block target of the first (or only) branch is always SinkMBB.
3124 MBB->addSuccessor(SinkMBB);
3125
3126 // Create the conditional branch instruction.
3128 BuildMI(MBB, DL, TII->get(Opc)).addMBB(SinkMBB);
3129
3130 if (CascadedCMOV) {
3131 unsigned Opc2 = M68k::GetCondBranchFromCond(
3132 (M68k::CondCode)CascadedCMOV->getOperand(3).getImm());
3133 BuildMI(Jcc1MBB, DL, TII->get(Opc2)).addMBB(SinkMBB);
3134 }
3135
3136 // Copy0MBB:
3137 // %FalseValue = ...
3138 // # fallthrough to SinkMBB
3139 Copy0MBB->addSuccessor(SinkMBB);
3140
3141 // SinkMBB:
3142 // %Result = phi [ %FalseValue, Copy0MBB ], [ %TrueValue, ThisMBB ]
3143 // ...
3146 std::next(MachineBasicBlock::iterator(LastCMOV));
3147 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
3148 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
3149 MachineInstrBuilder MIB;
3150
3151 // As we are creating the PHIs, we have to be careful if there is more than
3152 // one. Later CMOVs may reference the results of earlier CMOVs, but later
3153 // PHIs have to reference the individual true/false inputs from earlier PHIs.
3154 // That also means that PHI construction must work forward from earlier to
3155 // later, and that the code must maintain a mapping from earlier PHI's
3156 // destination registers, and the registers that went into the PHI.
3157
3158 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
3159 Register DestReg = MIIt->getOperand(0).getReg();
3160 Register Op1Reg = MIIt->getOperand(1).getReg();
3161 Register Op2Reg = MIIt->getOperand(2).getReg();
3162
3163 // If this CMOV we are generating is the opposite condition from
3164 // the jump we generated, then we have to swap the operands for the
3165 // PHI that is going to be generated.
3166 if (MIIt->getOperand(3).getImm() == OppCC)
3167 std::swap(Op1Reg, Op2Reg);
3168
3169 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
3170 Op1Reg = RegRewriteTable[Op1Reg].first;
3171
3172 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
3173 Op2Reg = RegRewriteTable[Op2Reg].second;
3174
3175 MIB =
3176 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(M68k::PHI), DestReg)
3177 .addReg(Op1Reg)
3178 .addMBB(Copy0MBB)
3179 .addReg(Op2Reg)
3180 .addMBB(ThisMBB);
3181
3182 // Add this PHI to the rewrite table.
3183 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
3184 }
3185
3186 // If we have a cascaded CMOV, the second Jcc provides the same incoming
3187 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
3188 if (CascadedCMOV) {
3189 MIB.addReg(MI.getOperand(2).getReg()).addMBB(Jcc1MBB);
3190 // Copy the PHI result to the register defined by the second CMOV.
3191 BuildMI(*SinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
3192 DL, TII->get(TargetOpcode::COPY),
3193 CascadedCMOV->getOperand(0).getReg())
3194 .addReg(MI.getOperand(0).getReg());
3195 CascadedCMOV->eraseFromParent();
3196 }
3197
3198 // Now remove the CMOV(s).
3199 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd;)
3200 (MIIt++)->eraseFromParent();
3201
3202 return SinkMBB;
3203}
3204
3206M68kTargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
3207 MachineBasicBlock *BB) const {
3208 llvm_unreachable("Cannot lower Segmented Stack Alloca with stack-split on");
3209}
3210
3213 MachineBasicBlock *BB) const {
3214 switch (MI.getOpcode()) {
3215 default:
3216 llvm_unreachable("Unexpected instr type to insert");
3217 case M68k::CMOV8d:
3218 case M68k::CMOV16d:
3219 case M68k::CMOV32r:
3220 return EmitLoweredSelect(MI, BB);
3221 case M68k::SALLOCA:
3222 return EmitLoweredSegAlloca(MI, BB);
3223 }
3224}
3225
3226SDValue M68kTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3228 auto PtrVT = getPointerTy(MF.getDataLayout());
3230
3231 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3232 SDLoc DL(Op);
3233
3234 // vastart just stores the address of the VarArgsFrameIndex slot into the
3235 // memory location argument.
3236 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3237 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3238 MachinePointerInfo(SV));
3239}
3240
3241SDValue M68kTargetLowering::LowerATOMICFENCE(SDValue Op,
3242 SelectionDAG &DAG) const {
3243 // Lower to a memory barrier created from inline asm.
3244 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3245 LLVMContext &Ctx = *DAG.getContext();
3246
3247 const unsigned Flags = InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore |
3249 const SDValue AsmOperands[4] = {
3250 Op.getOperand(0), // Input chain
3252 "", TLI.getProgramPointerTy(
3253 DAG.getDataLayout())), // Empty inline asm string
3254 DAG.getMDNode(MDNode::get(Ctx, {})), // (empty) srcloc
3255 DAG.getTargetConstant(Flags, SDLoc(Op),
3256 TLI.getPointerTy(DAG.getDataLayout())), // Flags
3257 };
3258
3259 return DAG.getNode(ISD::INLINEASM, SDLoc(Op),
3260 DAG.getVTList(MVT::Other, MVT::Glue), AsmOperands);
3261}
3262
3263// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
3264// Calls to _alloca are needed to probe the stack when allocating more than 4k
3265// bytes in one go. Touching the stack at 4K increments is necessary to ensure
3266// that the guard pages used by the OS virtual memory manager are allocated in
3267// correct sequence.
3268SDValue M68kTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3269 SelectionDAG &DAG) const {
3271 bool SplitStack = MF.shouldSplitStack();
3272
3273 SDLoc DL(Op);
3274
3275 // Get the inputs.
3276 SDNode *Node = Op.getNode();
3277 SDValue Chain = Op.getOperand(0);
3278 SDValue Size = Op.getOperand(1);
3279 unsigned Align = Op.getConstantOperandVal(2);
3280 EVT VT = Node->getValueType(0);
3281
3282 // Chain the dynamic stack allocation so that it doesn't modify the stack
3283 // pointer when other instructions are using the stack.
3284 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3285
3286 SDValue Result;
3287 if (SplitStack) {
3288 auto &MRI = MF.getRegInfo();
3289 auto SPTy = getPointerTy(DAG.getDataLayout());
3290 auto *ARClass = getRegClassFor(SPTy);
3291 Register Vreg = MRI.createVirtualRegister(ARClass);
3292 Chain = DAG.getCopyToReg(Chain, DL, Vreg, Size);
3293 Result = DAG.getNode(M68kISD::SEG_ALLOCA, DL, SPTy, Chain,
3294 DAG.getRegister(Vreg, SPTy));
3295 } else {
3296 auto &TLI = DAG.getTargetLoweringInfo();
3298 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
3299 " not tell us which reg is the stack pointer!");
3300
3301 SDValue SP = DAG.getCopyFromReg(Chain, DL, SPReg, VT);
3302 Chain = SP.getValue(1);
3303 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3304 unsigned StackAlign = TFI.getStackAlignment();
3305 Result = DAG.getNode(ISD::SUB, DL, VT, SP, Size); // Value
3306 if (Align > StackAlign)
3307 Result = DAG.getNode(ISD::AND, DL, VT, Result,
3308 DAG.getSignedConstant(-(uint64_t)Align, DL, VT));
3309 Chain = DAG.getCopyToReg(Chain, DL, SPReg, Result); // Output chain
3310 }
3311
3312 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), DL);
3313
3314 SDValue Ops[2] = {Result, Chain};
3315 return DAG.getMergeValues(Ops, DL);
3316}
3317
3318SDValue M68kTargetLowering::LowerShiftLeftParts(SDValue Op,
3319 SelectionDAG &DAG) const {
3320 SDLoc DL(Op);
3321 SDValue Lo = Op.getOperand(0);
3322 SDValue Hi = Op.getOperand(1);
3323 SDValue Shamt = Op.getOperand(2);
3324 EVT VT = Lo.getValueType();
3325
3326 // if Shamt - register size < 0: // Shamt < register size
3327 // Lo = Lo << Shamt
3328 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (register size - 1 ^ Shamt))
3329 // else:
3330 // Lo = 0
3331 // Hi = Lo << (Shamt - register size)
3332
3333 SDValue Zero = DAG.getConstant(0, DL, VT);
3334 SDValue One = DAG.getConstant(1, DL, VT);
3335 SDValue MinusRegisterSize = DAG.getSignedConstant(-32, DL, VT);
3336 SDValue RegisterSizeMinus1 = DAG.getConstant(32 - 1, DL, VT);
3337 SDValue ShamtMinusRegisterSize =
3338 DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusRegisterSize);
3339 SDValue RegisterSizeMinus1Shamt =
3340 DAG.getNode(ISD::XOR, DL, VT, RegisterSizeMinus1, Shamt);
3341
3342 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3343 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3344 SDValue ShiftRightLo =
3345 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, RegisterSizeMinus1Shamt);
3346 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3347 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3348 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusRegisterSize);
3349
3350 SDValue CC =
3351 DAG.getSetCC(DL, MVT::i8, ShamtMinusRegisterSize, Zero, ISD::SETLT);
3352
3353 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3354 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3355
3356 return DAG.getMergeValues({Lo, Hi}, DL);
3357}
3358
3359SDValue M68kTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3360 bool IsSRA) const {
3361 SDLoc DL(Op);
3362 SDValue Lo = Op.getOperand(0);
3363 SDValue Hi = Op.getOperand(1);
3364 SDValue Shamt = Op.getOperand(2);
3365 EVT VT = Lo.getValueType();
3366
3367 // SRA expansion:
3368 // if Shamt - register size < 0: // Shamt < register size
3369 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (register size - 1 ^ Shamt))
3370 // Hi = Hi >>s Shamt
3371 // else:
3372 // Lo = Hi >>s (Shamt - register size);
3373 // Hi = Hi >>s (register size - 1)
3374 //
3375 // SRL expansion:
3376 // if Shamt - register size < 0: // Shamt < register size
3377 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (register size - 1 ^ Shamt))
3378 // Hi = Hi >>u Shamt
3379 // else:
3380 // Lo = Hi >>u (Shamt - register size);
3381 // Hi = 0;
3382
3383 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3384
3385 SDValue Zero = DAG.getConstant(0, DL, VT);
3386 SDValue One = DAG.getConstant(1, DL, VT);
3387 SDValue MinusRegisterSize = DAG.getSignedConstant(-32, DL, VT);
3388 SDValue RegisterSizeMinus1 = DAG.getConstant(32 - 1, DL, VT);
3389 SDValue ShamtMinusRegisterSize =
3390 DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusRegisterSize);
3391 SDValue RegisterSizeMinus1Shamt =
3392 DAG.getNode(ISD::XOR, DL, VT, RegisterSizeMinus1, Shamt);
3393
3394 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3395 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3396 SDValue ShiftLeftHi =
3397 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, RegisterSizeMinus1Shamt);
3398 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3399 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3400 SDValue LoFalse =
3401 DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusRegisterSize);
3402 SDValue HiFalse =
3403 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, RegisterSizeMinus1) : Zero;
3404
3405 SDValue CC =
3406 DAG.getSetCC(DL, MVT::i8, ShamtMinusRegisterSize, Zero, ISD::SETLT);
3407
3408 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3409 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3410
3411 return DAG.getMergeValues({Lo, Hi}, DL);
3412}
3413
3414//===----------------------------------------------------------------------===//
3415// DAG Combine
3416//===----------------------------------------------------------------------===//
3417
3418// When legalizing carry, we create carries via add X, -1
3419// If that comes from an actual carry, via setcc, we use the
3420// carry directly. If \p NeedX is set, the user reads the X flag rather than C,
3421// so only use flags from nodes that set X to the same value as C.
3422static SDValue combineCarryThroughADD(SDValue CCR, bool NeedX) {
3423 if (CCR.getOpcode() == M68kISD::ADD) {
3424 if (isAllOnesConstant(CCR.getOperand(1))) {
3425 SDValue Carry = CCR.getOperand(0);
3426 while (Carry.getOpcode() == ISD::TRUNCATE ||
3427 Carry.getOpcode() == ISD::ZERO_EXTEND ||
3428 Carry.getOpcode() == ISD::SIGN_EXTEND ||
3429 Carry.getOpcode() == ISD::ANY_EXTEND ||
3430 (Carry.getOpcode() == ISD::AND &&
3431 isOneConstant(Carry.getOperand(1))))
3432 Carry = Carry.getOperand(0);
3433 if (Carry.getOpcode() == M68kISD::SETCC) {
3434 if (Carry.getConstantOperandVal(0) == M68k::COND_CS) {
3435 SDValue Flags = Carry.getOperand(1);
3436 if (NeedX && Flags.getOpcode() != M68kISD::ADD &&
3437 Flags.getOpcode() != M68kISD::SUB &&
3438 Flags.getOpcode() != M68kISD::ADDX &&
3439 Flags.getOpcode() != M68kISD::SUBX)
3440 return SDValue();
3441 return Flags;
3442 }
3443 }
3444 }
3445 }
3446
3447 return SDValue();
3448}
3449
3450/// Optimize a CCR definition used according to the condition code \p CC into
3451/// a simpler CCR value, potentially returning a new \p CC and replacing uses
3452/// of chain values.
3454 SelectionDAG &DAG,
3455 const M68kSubtarget &Subtarget) {
3456 if (CC == M68k::COND_CS)
3457 if (SDValue Flags = combineCarryThroughADD(CCR, /*NeedX=*/false))
3458 return Flags;
3459
3460 return SDValue();
3461}
3462
3463// Optimize RES = M68kISD::SETCC CONDCODE, CCR_INPUT
3465 const M68kSubtarget &Subtarget) {
3466 SDLoc DL(N);
3467 M68k::CondCode CC = M68k::CondCode(N->getConstantOperandVal(0));
3468 SDValue CCR = N->getOperand(1);
3469
3470 // Try to simplify the CCR and condition code operands.
3471 if (SDValue Flags = combineSetCCCCR(CCR, CC, DAG, Subtarget))
3472 return getSETCC(CC, Flags, DL, DAG);
3473
3474 return SDValue();
3475}
3477 const M68kSubtarget &Subtarget) {
3478 SDLoc DL(N);
3479 M68k::CondCode CC = M68k::CondCode(N->getConstantOperandVal(2));
3480 SDValue CCR = N->getOperand(3);
3481
3482 // Try to simplify the CCR and condition code operands.
3483 // Make sure to not keep references to operands, as combineSetCCCCR can
3484 // RAUW them under us.
3485 if (SDValue Flags = combineSetCCCCR(CCR, CC, DAG, Subtarget)) {
3486 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
3487 return DAG.getNode(M68kISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
3488 N->getOperand(1), Cond, Flags);
3489 }
3490
3491 return SDValue();
3492}
3493
3495 if (SDValue Flags =
3496 combineCarryThroughADD(N->getOperand(2), /*NeedX=*/true)) {
3497 MVT VT = N->getSimpleValueType(0);
3498 SDVTList VTs = DAG.getVTList(VT, MVT::i8);
3499 return DAG.getNode(M68kISD::SUBX, SDLoc(N), VTs, N->getOperand(0),
3500 N->getOperand(1), Flags);
3501 }
3502
3503 return SDValue();
3504}
3505
3506// Optimize RES, CCR = M68kISD::ADDX LHS, RHS, CCR
3509 if (SDValue Flags =
3510 combineCarryThroughADD(N->getOperand(2), /*NeedX=*/true)) {
3511 MVT VT = N->getSimpleValueType(0);
3512 SDVTList VTs = DAG.getVTList(VT, MVT::i8);
3513 return DAG.getNode(M68kISD::ADDX, SDLoc(N), VTs, N->getOperand(0),
3514 N->getOperand(1), Flags);
3515 }
3516
3517 return SDValue();
3518}
3519
3520SDValue M68kTargetLowering::PerformDAGCombine(SDNode *N,
3521 DAGCombinerInfo &DCI) const {
3522 SelectionDAG &DAG = DCI.DAG;
3523 switch (N->getOpcode()) {
3524 case M68kISD::SUBX:
3525 return combineSUBX(N, DAG);
3526 case M68kISD::ADDX:
3527 return combineADDX(N, DAG, DCI);
3528 case M68kISD::SETCC:
3529 return combineM68kSetCC(N, DAG, Subtarget);
3530 case M68kISD::BRCOND:
3531 return combineM68kBrCond(N, DAG, Subtarget);
3532 }
3533
3534 return SDValue();
3535}
3536
3538 bool IsVarArg) const {
3539 if (Return)
3540 return RetCC_M68k_C;
3541 else
3542 return CC_M68k_C;
3543}
static SDValue getSETCC(AArch64CC::CondCode CC, SDValue NZCV, const SDLoc &DL, SelectionDAG &DAG)
Helper function to create 'CSET', which is equivalent to 'CSINC <Wd>, WZR, WZR, invert(<cond>)'.
static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls)
Return true if the calling convention is one that we can guarantee TCO for.
static bool mayTailCallThisCC(CallingConv::ID CC)
Return true if we might ever do TCO for calls with this calling convention.
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
const HexagonInstrInfo * TII
static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, ISD::ArgFlagsTy Flags, SelectionDAG &DAG, const SDLoc &dl)
CreateCopyOfByValArgument - Make a copy of an aggregate at address specified by "Src" to address "Dst...
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
This file contains the custom routines for the M68k Calling Convention that aren't done by tablegen.
static SDValue LowerTruncateToBTST(SDValue Op, ISD::CondCode CC, const SDLoc &DL, SelectionDAG &DAG)
static SDValue combineADDX(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI)
static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc)
Return true if node is an ISD::AND or ISD::OR of two M68k::SETcc nodes each of which has no other use...
static bool hasNonFlagsUse(SDValue Op)
return true if Op has a use that doesn't just read flags.
static StructReturnType callIsStructReturn(const SmallVectorImpl< ISD::OutputArg > &Outs)
static bool isXor1OfSetCC(SDValue Op)
Return true if node is an ISD::XOR of a M68kISD::SETCC and 1 and that the SETCC node has a single use...
static SDValue LowerAndToBTST(SDValue And, ISD::CondCode CC, const SDLoc &DL, SelectionDAG &DAG)
Result of 'and' is compared against zero. Change to a BTST node if possible.
static SDValue combineM68kBrCond(SDNode *N, SelectionDAG &DAG, const M68kSubtarget &Subtarget)
static M68k::CondCode TranslateIntegerM68kCC(ISD::CondCode SetCCOpcode)
static StructReturnType argsAreStructReturn(const SmallVectorImpl< ISD::InputArg > &Ins)
Determines whether a function uses struct return semantics.
static M68k::CondCode TranslateM68kCC(ISD::CondCode SetCCOpcode, const SDLoc &DL, bool IsFP, SDValue &LHS, SDValue &RHS, SelectionDAG &DAG)
Do a one-to-one translation of a ISD::CondCode to the M68k-specific condition code,...
static bool isCMOVPseudo(MachineInstr &MI)
static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt)
Return true if the function is being made into a tailcall target by changing its ABI.
static bool isM68kLogicalCmp(SDValue Op)
Return true if opcode is a M68k logical comparison.
static SDValue combineM68kSetCC(SDNode *N, SelectionDAG &DAG, const M68kSubtarget &Subtarget)
static void lowerOverflowArithmetic(SDValue Op, SelectionDAG &DAG, SDValue &Result, SDValue &CCR, M68k::CondCode &CC)
static SDValue combineSetCCCCR(SDValue CCR, M68k::CondCode &CC, SelectionDAG &DAG, const M68kSubtarget &Subtarget)
Optimize a CCR definition used according to the condition code CC into a simpler CCR value,...
static bool isOverflowArithmetic(unsigned Opcode)
static bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, const M68kInstrInfo *TII, const CCValAssign &VA)
Return true if the given stack call argument is already available in the same position (relatively) o...
static SDValue getBitTestCondition(SDValue Src, SDValue BitNo, ISD::CondCode CC, const SDLoc &DL, SelectionDAG &DAG)
Create a BTST (Bit Test) node - Test bit BitNo in Src and set condition according to equal/not-equal ...
StructReturnType
@ NotStructReturn
@ RegStructReturn
@ StackStructReturn
static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG)
static bool checkAndUpdateCCRKill(MachineBasicBlock::iterator SelectItr, MachineBasicBlock *BB, const TargetRegisterInfo *TRI)
static SDValue combineSUBX(SDNode *N, SelectionDAG &DAG)
static SDValue combineCarryThroughADD(SDValue CCR, bool NeedX)
This file defines the interfaces that M68k uses to lower LLVM code into a selection DAG.
This file contains the declarations of the M68k MCAsmInfo properties.
This file declares the M68k specific subclass of MachineFunctionInfo.
This file declares the M68k specific subclass of TargetSubtargetInfo.
This file declares the M68k specific subclass of TargetMachine.
This file contains declarations for M68k ELF object file lowering.
#define F(x, y, z)
Definition MD5.cpp:54
#define G(x, y, z)
Definition MD5.cpp:55
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T1
static constexpr MCPhysReg SPReg
SmallVector< MachineOperand, 4 > Cond
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
#define OP(OPC)
Definition Instruction.h:46
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
Value * RHS
Value * LHS
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
an instruction that atomically reads a memory location, combines it with another value,...
static LLVM_ABI bool resultsCompatible(CallingConv::ID CalleeCC, CallingConv::ID CallerCC, MachineFunction &MF, LLVMContext &C, const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn CalleeFn, CCAssignFn CallerFn)
Returns true if the results of the two calling conventions are compatible.
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
bool isExtInLoc() const
int64_t getLocMemOffset() const
unsigned getValNo() const
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
const Constant * getConstVal() const
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
iterator_range< arg_iterator > args()
Definition Function.h:877
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
bool hasStructRetAttr() const
Determine if the function returns a structure through first or second pointer argument.
Definition Function.h:673
const GlobalValue * getGlobal() const
bool hasDLLImportStorageClass() const
Module * getParent()
Get the module that this global value is contained inside of...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
SmallVectorImpl< ForwardedRegister > & getForwardedMustTailRegParms()
void setBytesToPopOnReturn(unsigned bytes)
void setArgumentStackSize(unsigned size)
const uint32_t * getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const override
unsigned getStackRegister() const
const M68kRegisterInfo * getRegisterInfo() const override
ConstraintType getConstraintType(StringRef ConstraintStr) const override
Given a constraint, return the type of constraint it is for this target.
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const override
EVT is not used in-tree, but is used by out-of-tree target.
const MCExpr * LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, unsigned uid, MCContext &Ctx) const override
SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const override
Returns relocation base for the given PIC jumptable.
const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const override
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
CCAssignFn * getCCAssignFn(CallingConv::ID CC, bool Return, bool IsVarArg) const
M68kTargetLowering(const M68kTargetMachine &TM, const M68kSubtarget &STI)
InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const override
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
Provide custom lowering hooks for some operations.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
Return the value type to use for ISD::SETCC.
Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
unsigned getJumpTableEncoding() const override
Return the entry encoding for a jump table in the current function.
Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
Machine Value Type.
SimpleValueType SimpleTy
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
static MVT getIntegerVT(unsigned BitWidth)
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setObjectZExt(int ObjectIdx, bool IsZExt)
void setObjectSExt(int ObjectIdx, bool IsSExt)
void setHasTailCall(bool V=true)
bool isObjectZExt(int ObjectIdx) const
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool isObjectSExt(int ObjectIdx) const
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
bool killsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr kills the specified register.
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
int64_t getImm() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Class to represent pointers.
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static constexpr bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:66
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
bool hasOneUse() const
Return true if there is exactly one use of this node.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain)
Compute a TokenFactor to force all the incoming stack arguments to be loaded from the stack.
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
SDValue getGLOBAL_OFFSET_TABLE(EVT VT)
Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
const TargetMachine & getTargetMachine() const
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
MVT getProgramPointerTy(const DataLayout &DL) const
Return the type for code pointers, which is determined by the program address space specified through...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
std::vector< ArgListEntry > ArgListTy
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< SDValue > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
bool isPositionIndependent() const
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
TargetOptions Options
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
LLVM Value Representation.
Definition Value.h:75
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
use_iterator use_begin()
Definition Value.h:366
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ M68k_INTR
Used for M68k interrupt routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:845
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:805
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:879
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:870
@ BR
Control flow instructions. These all have token chains.
@ SETCCCARRY
Like SetCC, ops #0 and #1 are the LHS and RHS operands to compare, but op #2 is a boolean indicating ...
Definition ISDOpcodes.h:853
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BR_JT
BR_JT - Jumptable branch.
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:822
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:714
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:787
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:876
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:837
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:757
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ ExternalSymbol
Definition ISDOpcodes.h:95
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:882
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:859
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
static bool isPCRelBlockReference(unsigned char Flag)
Return True if the Block is referenced using PC.
static bool isGlobalRelativeToPICBase(unsigned char TargetFlag)
Return true if the specified global value reference is relative to a 32-bit PIC base (M68kISD::GLOBAL...
static bool isGlobalStubReference(unsigned char TargetFlag)
Return true if the specified TargetFlag operand is a reference to a stub for a global,...
static bool isPCRelGlobalReference(unsigned char Flag)
Return True if the specified GlobalValue requires PC addressing mode.
@ MO_TLSLDM
On a symbol operand, this indicates that the immediate is the offset to the slot in GOT which stores ...
@ MO_TLSLE
On a symbol operand, this indicates that the immediate is the offset to the variable within in the th...
@ MO_TLSGD
On a symbol operand, this indicates that the immediate is the offset to the slot in GOT which stores ...
@ MO_GOTPCREL
On a symbol operand this indicates that the immediate is offset to the GOT entry for the symbol name ...
@ MO_TLSIE
On a symbol operand, this indicates that the immediate is the offset to the variable within the threa...
@ MO_TLSLD
On a symbol operand, this indicates that the immediate is the offset to variable within the thread lo...
static bool isDirectGlobalReference(unsigned char Flag)
Return True if the specified GlobalValue is a direct reference for a symbol.
static bool IsSETCC(unsigned SETCC)
static unsigned GetCondBranchFromCond(M68k::CondCode CC)
bool isCalleePop(CallingConv::ID CallingConv, bool IsVarArg, bool GuaranteeTCO)
Determines whether the callee is required to pop its own arguments.
static M68k::CondCode GetOppositeBranchCondition(M68k::CondCode CC)
constexpr MCPhysReg SP
@ User
could "use" a pointer
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition MathExtras.h:345
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ Xor
Bitwise or logical XOR of integers.
DWARFExpression::Operation Op
constexpr unsigned BitWidth
ExceptionHandling
Definition CodeGen.h:54
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
bool isVectorOf(EVT EltVT) const
Return true if this is a vector with matching element type.
Definition ValueTypes.h:181
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:331
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
SmallVector< ISD::OutputArg, 32 > Outs
Type * RetTy
Same as OrigRetTy, or partially legalized for soft float libcalls.
CallLoweringInfo & setChain(SDValue InChain)