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