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