LLVM 24.0.0git
AVRISelLowering.cpp
Go to the documentation of this file.
1//===-- AVRISelLowering.cpp - AVR DAG Lowering Implementation -------------===//
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// This file defines the interfaces that AVR uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AVRISelLowering.h"
15
16#include "llvm/ADT/ArrayRef.h"
24#include "llvm/IR/Function.h"
26
27#include "AVR.h"
29#include "AVRSubtarget.h"
30#include "AVRTargetMachine.h"
32
33namespace llvm {
34
36 const AVRSubtarget &STI)
37 : TargetLowering(TM, STI), Subtarget(STI) {
38 // Set up the register classes.
39 addRegisterClass(MVT::i8, &AVR::GPR8RegClass);
40 addRegisterClass(MVT::i16, &AVR::DREGSRegClass);
41
42 // Compute derived properties from the register classes.
43 computeRegisterProperties(Subtarget.getRegisterInfo());
44
50
55
60
62
63 for (MVT VT : MVT::integer_valuetypes()) {
64 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
65 setLoadExtAction(N, VT, MVT::i1, Promote);
66 setLoadExtAction(N, VT, MVT::i8, Expand);
67 }
68 }
69
70 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
71
72 for (MVT VT : MVT::integer_valuetypes()) {
77 }
78
79 // sub (x, imm) gets canonicalized to add (x, -imm), so for illegal types
80 // revert into a sub since we don't have an add with immediate instruction.
83
84 // our shift instructions are only able to shift 1 bit at a time, so handle
85 // this in a custom way.
98
103
109
120
122
123 // Add support for postincrement and predecrement load/stores.
132
134
139
140 // Atomic operations which must be lowered to rtlib calls
141 for (MVT VT : MVT::integer_valuetypes()) {
149 }
150
151 // Division/remainder
160
161 // Make division and modulus custom
168
169 // Do not use MUL. The AVR instructions are closer to SMUL_LOHI &co.
172
173 // Expand 16 bit multiplications.
176
177 // Expand multiplications to libcalls when there is
178 // no hardware MUL.
179 if (!Subtarget.supportsMultiplication()) {
182 }
183
184 for (MVT VT : MVT::integer_valuetypes()) {
187 }
188
189 for (MVT VT : MVT::integer_valuetypes()) {
193 }
194
195 for (MVT VT : MVT::integer_valuetypes()) {
197 // TODO: The generated code is pretty poor. Investigate using the
198 // same "shift and subtract with carry" trick that we do for
199 // extending 8-bit to 16-bit. This may require infrastructure
200 // improvements in how we treat 16-bit "registers" to be feasible.
201 }
202
205}
206
208 EVT VT) const {
209 assert(!VT.isVector() && "No AVR SetCC type for vectors!");
210 return MVT::i8;
211}
212
213SDValue AVRTargetLowering::LowerShifts(SDValue Op, SelectionDAG &DAG) const {
214 unsigned Opc8;
215 const SDNode *N = Op.getNode();
216 EVT VT = Op.getValueType();
217 SDLoc dl(N);
219 "Expected power-of-2 shift amount");
220
221 if (VT.getSizeInBits() == 32) {
222 if (!isa<ConstantSDNode>(N->getOperand(1))) {
223 // 32-bit shifts are converted to a loop in IR.
224 // This should be unreachable.
225 report_fatal_error("Expected a constant shift amount!");
226 }
227 SDVTList ResTys = DAG.getVTList(MVT::i16, MVT::i16);
228 SDValue SrcLo =
229 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i16, Op.getOperand(0),
230 DAG.getConstant(0, dl, MVT::i16));
231 SDValue SrcHi =
232 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i16, Op.getOperand(0),
233 DAG.getConstant(1, dl, MVT::i16));
234 uint64_t ShiftAmount = N->getConstantOperandVal(1);
235 if (ShiftAmount == 16) {
236 // Special case these two operations because they appear to be used by the
237 // generic codegen parts to lower 32-bit numbers.
238 // TODO: perhaps we can lower shift amounts bigger than 16 to a 16-bit
239 // shift of a part of the 32-bit value?
240 switch (Op.getOpcode()) {
241 case ISD::SHL: {
242 SDValue Zero = DAG.getConstant(0, dl, MVT::i16);
243 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i32, Zero, SrcLo);
244 }
245 case ISD::SRL: {
246 SDValue Zero = DAG.getConstant(0, dl, MVT::i16);
247 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i32, SrcHi, Zero);
248 }
249 }
250 }
251 SDValue Cnt = DAG.getTargetConstant(ShiftAmount, dl, MVT::i8);
252 unsigned Opc;
253 switch (Op.getOpcode()) {
254 default:
255 llvm_unreachable("Invalid 32-bit shift opcode!");
256 case ISD::SHL:
257 Opc = AVRISD::LSLW;
258 break;
259 case ISD::SRL:
260 Opc = AVRISD::LSRW;
261 break;
262 case ISD::SRA:
263 Opc = AVRISD::ASRW;
264 break;
265 }
266 SDValue Result = DAG.getNode(Opc, dl, ResTys, SrcLo, SrcHi, Cnt);
267 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i32, Result.getValue(0),
268 Result.getValue(1));
269 }
270
271 // Expand non-constant shifts to loops.
272 if (!isa<ConstantSDNode>(N->getOperand(1))) {
273 switch (Op.getOpcode()) {
274 default:
275 llvm_unreachable("Invalid shift opcode!");
276 case ISD::SHL:
277 return DAG.getNode(AVRISD::LSLLOOP, dl, VT, N->getOperand(0),
278 N->getOperand(1));
279 case ISD::SRL:
280 return DAG.getNode(AVRISD::LSRLOOP, dl, VT, N->getOperand(0),
281 N->getOperand(1));
282 case ISD::ROTL: {
283 SDValue Amt = N->getOperand(1);
284 EVT AmtVT = Amt.getValueType();
285 Amt = DAG.getNode(ISD::AND, dl, AmtVT, Amt,
286 DAG.getConstant(VT.getSizeInBits() - 1, dl, AmtVT));
287 return DAG.getNode(AVRISD::ROLLOOP, dl, VT, N->getOperand(0), Amt);
288 }
289 case ISD::ROTR: {
290 SDValue Amt = N->getOperand(1);
291 EVT AmtVT = Amt.getValueType();
292 Amt = DAG.getNode(ISD::AND, dl, AmtVT, Amt,
293 DAG.getConstant(VT.getSizeInBits() - 1, dl, AmtVT));
294 return DAG.getNode(AVRISD::RORLOOP, dl, VT, N->getOperand(0), Amt);
295 }
296 case ISD::SRA:
297 return DAG.getNode(AVRISD::ASRLOOP, dl, VT, N->getOperand(0),
298 N->getOperand(1));
299 }
300 }
301
302 uint64_t ShiftAmount = N->getConstantOperandVal(1);
303 SDValue Victim = N->getOperand(0);
304
305 switch (Op.getOpcode()) {
306 case ISD::SRA:
307 Opc8 = AVRISD::ASR;
308 break;
309 case ISD::ROTL:
310 Opc8 = AVRISD::ROL;
311 ShiftAmount = ShiftAmount % VT.getSizeInBits();
312 break;
313 case ISD::ROTR:
314 Opc8 = AVRISD::ROR;
315 ShiftAmount = ShiftAmount % VT.getSizeInBits();
316 break;
317 case ISD::SRL:
318 Opc8 = AVRISD::LSR;
319 break;
320 case ISD::SHL:
321 Opc8 = AVRISD::LSL;
322 break;
323 default:
324 llvm_unreachable("Invalid shift opcode");
325 }
326
327 // Optimize int8/int16 shifts.
328 if (VT.getSizeInBits() == 8) {
329 if (Op.getOpcode() == ISD::SHL && 4 <= ShiftAmount && ShiftAmount < 7) {
330 // Optimize LSL when 4 <= ShiftAmount <= 6.
331 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim);
332 Victim =
333 DAG.getNode(ISD::AND, dl, VT, Victim, DAG.getConstant(0xf0, dl, VT));
334 ShiftAmount -= 4;
335 } else if (Op.getOpcode() == ISD::SRL && 4 <= ShiftAmount &&
336 ShiftAmount < 7) {
337 // Optimize LSR when 4 <= ShiftAmount <= 6.
338 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim);
339 Victim =
340 DAG.getNode(ISD::AND, dl, VT, Victim, DAG.getConstant(0x0f, dl, VT));
341 ShiftAmount -= 4;
342 } else if (Op.getOpcode() == ISD::SHL && ShiftAmount == 7) {
343 // Optimize LSL when ShiftAmount == 7.
344 Victim = DAG.getNode(AVRISD::LSLBN, dl, VT, Victim,
345 DAG.getConstant(7, dl, VT));
346 ShiftAmount = 0;
347 } else if (Op.getOpcode() == ISD::SRL && ShiftAmount == 7) {
348 // Optimize LSR when ShiftAmount == 7.
349 Victim = DAG.getNode(AVRISD::LSRBN, dl, VT, Victim,
350 DAG.getConstant(7, dl, VT));
351 ShiftAmount = 0;
352 } else if (Op.getOpcode() == ISD::SRA && ShiftAmount == 6) {
353 // Optimize ASR when ShiftAmount == 6.
354 Victim = DAG.getNode(AVRISD::ASRBN, dl, VT, Victim,
355 DAG.getConstant(6, dl, VT));
356 ShiftAmount = 0;
357 } else if (Op.getOpcode() == ISD::SRA && ShiftAmount == 7) {
358 // Optimize ASR when ShiftAmount == 7.
359 Victim = DAG.getNode(AVRISD::ASRBN, dl, VT, Victim,
360 DAG.getConstant(7, dl, VT));
361 ShiftAmount = 0;
362 } else if (Op.getOpcode() == ISD::ROTL && ShiftAmount == 3) {
363 // Optimize left rotation 3 bits to swap then right rotation 1 bit.
364 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim);
365 Victim = DAG.getNode(AVRISD::ROR, dl, VT, Victim);
366 ShiftAmount = 0;
367 } else if (Op.getOpcode() == ISD::ROTR && ShiftAmount == 3) {
368 // Optimize right rotation 3 bits to swap then left rotation 1 bit.
369 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim);
370 Victim = DAG.getNode(AVRISD::ROL, dl, VT, Victim);
371 ShiftAmount = 0;
372 } else if (Op.getOpcode() == ISD::ROTL && ShiftAmount == 7) {
373 // Optimize left rotation 7 bits to right rotation 1 bit.
374 Victim = DAG.getNode(AVRISD::ROR, dl, VT, Victim);
375 ShiftAmount = 0;
376 } else if (Op.getOpcode() == ISD::ROTR && ShiftAmount == 7) {
377 // Optimize right rotation 7 bits to left rotation 1 bit.
378 Victim = DAG.getNode(AVRISD::ROL, dl, VT, Victim);
379 ShiftAmount = 0;
380 } else if ((Op.getOpcode() == ISD::ROTR || Op.getOpcode() == ISD::ROTL) &&
381 ShiftAmount >= 4) {
382 // Optimize left/right rotation with the SWAP instruction.
383 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim);
384 ShiftAmount -= 4;
385 }
386 } else if (VT.getSizeInBits() == 16) {
387 if (Op.getOpcode() == ISD::SRA)
388 // Special optimization for int16 arithmetic right shift.
389 switch (ShiftAmount) {
390 case 15:
391 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim,
392 DAG.getConstant(15, dl, VT));
393 ShiftAmount = 0;
394 break;
395 case 14:
396 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim,
397 DAG.getConstant(14, dl, VT));
398 ShiftAmount = 0;
399 break;
400 case 7:
401 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim,
402 DAG.getConstant(7, dl, VT));
403 ShiftAmount = 0;
404 break;
405 default:
406 break;
407 }
408 if (4 <= ShiftAmount && ShiftAmount < 8)
409 switch (Op.getOpcode()) {
410 case ISD::SHL:
411 Victim = DAG.getNode(AVRISD::LSLWN, dl, VT, Victim,
412 DAG.getConstant(4, dl, VT));
413 ShiftAmount -= 4;
414 break;
415 case ISD::SRL:
416 Victim = DAG.getNode(AVRISD::LSRWN, dl, VT, Victim,
417 DAG.getConstant(4, dl, VT));
418 ShiftAmount -= 4;
419 break;
420 default:
421 break;
422 }
423 else if (8 <= ShiftAmount && ShiftAmount < 12)
424 switch (Op.getOpcode()) {
425 case ISD::SHL:
426 Victim = DAG.getNode(AVRISD::LSLWN, dl, VT, Victim,
427 DAG.getConstant(8, dl, VT));
428 ShiftAmount -= 8;
429 // Only operate on the higher byte for remaining shift bits.
430 Opc8 = AVRISD::LSLHI;
431 break;
432 case ISD::SRL:
433 Victim = DAG.getNode(AVRISD::LSRWN, dl, VT, Victim,
434 DAG.getConstant(8, dl, VT));
435 ShiftAmount -= 8;
436 // Only operate on the lower byte for remaining shift bits.
437 Opc8 = AVRISD::LSRLO;
438 break;
439 case ISD::SRA:
440 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim,
441 DAG.getConstant(8, dl, VT));
442 ShiftAmount -= 8;
443 // Only operate on the lower byte for remaining shift bits.
444 Opc8 = AVRISD::ASRLO;
445 break;
446 default:
447 break;
448 }
449 else if (12 <= ShiftAmount)
450 switch (Op.getOpcode()) {
451 case ISD::SHL:
452 Victim = DAG.getNode(AVRISD::LSLWN, dl, VT, Victim,
453 DAG.getConstant(12, dl, VT));
454 ShiftAmount -= 12;
455 // Only operate on the higher byte for remaining shift bits.
456 Opc8 = AVRISD::LSLHI;
457 break;
458 case ISD::SRL:
459 Victim = DAG.getNode(AVRISD::LSRWN, dl, VT, Victim,
460 DAG.getConstant(12, dl, VT));
461 ShiftAmount -= 12;
462 // Only operate on the lower byte for remaining shift bits.
463 Opc8 = AVRISD::LSRLO;
464 break;
465 case ISD::SRA:
466 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim,
467 DAG.getConstant(8, dl, VT));
468 ShiftAmount -= 8;
469 // Only operate on the lower byte for remaining shift bits.
470 Opc8 = AVRISD::ASRLO;
471 break;
472 default:
473 break;
474 }
475 }
476
477 while (ShiftAmount--) {
478 Victim = DAG.getNode(Opc8, dl, VT, Victim);
479 }
480
481 return Victim;
482}
483
484SDValue AVRTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
485 unsigned Opcode = Op->getOpcode();
486 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
487 "Invalid opcode for Div/Rem lowering");
488 bool IsSigned = (Opcode == ISD::SDIVREM);
489 EVT VT = Op->getValueType(0);
490 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
491
492 RTLIB::Libcall LC;
493 switch (VT.getSimpleVT().SimpleTy) {
494 default:
495 llvm_unreachable("Unexpected request for libcall!");
496 case MVT::i8:
497 LC = IsSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8;
498 break;
499 case MVT::i16:
500 LC = IsSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16;
501 break;
502 case MVT::i32:
503 LC = IsSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32;
504 break;
505 }
506
507 SDValue InChain = DAG.getEntryNode();
508
510 for (SDValue const &Value : Op->op_values()) {
511 TargetLowering::ArgListEntry Entry(
512 Value, Value.getValueType().getTypeForEVT(*DAG.getContext()));
513 Entry.IsSExt = IsSigned;
514 Entry.IsZExt = !IsSigned;
515 Args.push_back(Entry);
516 }
517
518 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
519 if (LCImpl == RTLIB::Unsupported)
520 return SDValue();
521
522 SDValue Callee =
523 DAG.getExternalSymbol(LCImpl, getPointerTy(DAG.getDataLayout()));
524
525 Type *RetTy = (Type *)StructType::get(Ty, Ty);
526
527 SDLoc dl(Op);
528 TargetLowering::CallLoweringInfo CLI(DAG);
529 CLI.setDebugLoc(dl)
530 .setChain(InChain)
531 .setLibCallee(DAG.getLibcalls().getLibcallImplCallingConv(LCImpl), RetTy,
532 Callee, std::move(Args))
533 .setInRegister()
534 .setSExtResult(IsSigned)
535 .setZExtResult(!IsSigned);
536
537 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
538 return CallInfo.first;
539}
540
541SDValue AVRTargetLowering::LowerGlobalAddress(SDValue Op,
542 SelectionDAG &DAG) const {
543 auto DL = DAG.getDataLayout();
544
545 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
546 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
547
548 // Create the TargetGlobalAddress node, folding in the constant offset.
549 SDValue Result =
550 DAG.getTargetGlobalAddress(GV, SDLoc(Op), getPointerTy(DL), Offset);
551 return DAG.getNode(AVRISD::WRAPPER, SDLoc(Op), getPointerTy(DL), Result);
552}
553
554SDValue AVRTargetLowering::LowerBlockAddress(SDValue Op,
555 SelectionDAG &DAG) const {
556 auto DL = DAG.getDataLayout();
557 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
558
559 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(DL));
560
561 return DAG.getNode(AVRISD::WRAPPER, SDLoc(Op), getPointerTy(DL), Result);
562}
563
564/// IntCCToAVRCC - Convert a DAG integer condition code to an AVR CC.
566 switch (CC) {
567 default:
568 llvm_unreachable("Unknown condition code!");
569 case ISD::SETEQ:
570 return AVRCC::COND_EQ;
571 case ISD::SETNE:
572 return AVRCC::COND_NE;
573 case ISD::SETGE:
574 return AVRCC::COND_GE;
575 case ISD::SETLT:
576 return AVRCC::COND_LT;
577 case ISD::SETUGE:
578 return AVRCC::COND_SH;
579 case ISD::SETULT:
580 return AVRCC::COND_LO;
581 }
582}
583
584/// Returns appropriate CP/CPI/CPC nodes code for the given 8/16-bit operands.
585SDValue AVRTargetLowering::getAVRCmp(SDValue LHS, SDValue RHS,
586 SelectionDAG &DAG, SDLoc DL) const {
587 assert((LHS.getSimpleValueType() == RHS.getSimpleValueType()) &&
588 "LHS and RHS have different types");
589 assert(((LHS.getSimpleValueType() == MVT::i16) ||
590 (LHS.getSimpleValueType() == MVT::i8)) &&
591 "invalid comparison type");
592
593 SDValue Cmp;
594
595 if (LHS.getSimpleValueType() == MVT::i16 && isa<ConstantSDNode>(RHS)) {
596 uint64_t Imm = RHS->getAsZExtVal();
597 // Generate a CPI/CPC pair if RHS is a 16-bit constant. Use the zero
598 // register for the constant RHS if its lower or higher byte is zero.
599 SDValue LHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS,
600 DAG.getIntPtrConstant(0, DL));
601 SDValue LHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS,
602 DAG.getIntPtrConstant(1, DL));
603 SDValue RHSlo = (Imm & 0xff) == 0
604 ? DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8)
605 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, RHS,
606 DAG.getIntPtrConstant(0, DL));
607 SDValue RHShi = (Imm & 0xff00) == 0
608 ? DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8)
609 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, RHS,
610 DAG.getIntPtrConstant(1, DL));
611 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHSlo, RHSlo);
612 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHShi, RHShi, Cmp);
613 } else if (RHS.getSimpleValueType() == MVT::i16 && isa<ConstantSDNode>(LHS)) {
614 // Generate a CPI/CPC pair if LHS is a 16-bit constant. Use the zero
615 // register for the constant LHS if its lower or higher byte is zero.
616 uint64_t Imm = LHS->getAsZExtVal();
617 SDValue LHSlo = (Imm & 0xff) == 0
618 ? DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8)
619 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS,
620 DAG.getIntPtrConstant(0, DL));
621 SDValue LHShi = (Imm & 0xff00) == 0
622 ? DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8)
623 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS,
624 DAG.getIntPtrConstant(1, DL));
625 SDValue RHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, RHS,
626 DAG.getIntPtrConstant(0, DL));
627 SDValue RHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, RHS,
628 DAG.getIntPtrConstant(1, DL));
629 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHSlo, RHSlo);
630 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHShi, RHShi, Cmp);
631 } else {
632 // Generate ordinary 16-bit comparison.
633 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHS, RHS);
634 }
635
636 return Cmp;
637}
638
639/// Returns appropriate AVR CMP/CMPC nodes and corresponding condition code for
640/// the given operands.
641SDValue AVRTargetLowering::getAVRCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
642 SDValue &AVRcc, SelectionDAG &DAG,
643 SDLoc DL) const {
644 SDValue Cmp;
645 EVT VT = LHS.getValueType();
646 bool UseTest = false;
647
648 switch (CC) {
649 default:
650 break;
651 case ISD::SETLE: {
652 // Swap operands and reverse the branching condition.
653 std::swap(LHS, RHS);
654 CC = ISD::SETGE;
655 break;
656 }
657 case ISD::SETGT: {
658 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
659 switch (C->getSExtValue()) {
660 case -1: {
661 // When doing lhs > -1 use a tst instruction on the top part of lhs
662 // and use brpl instead of using a chain of cp/cpc.
663 UseTest = true;
664 AVRcc = DAG.getConstant(AVRCC::COND_PL, DL, MVT::i8);
665 break;
666 }
667 case 0: {
668 // Turn lhs > 0 into 0 < lhs since 0 can be materialized with
669 // __zero_reg__ in lhs.
670 RHS = LHS;
671 LHS = DAG.getConstant(0, DL, VT);
672 CC = ISD::SETLT;
673 break;
674 }
675 default: {
676 if (C->getConstantIntValue()->isMaxValue(true)) {
677 // Applying this optimization requires calculating rhs+1, which we
678 // can't do if that overflows. Swap operands and reverse the
679 // branching condition instead.
680 std::swap(LHS, RHS);
681 CC = ISD::SETLT;
682 break;
683 }
684
685 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows
686 // us to fold the constant into the cmp instruction.
687 RHS = DAG.getSignedConstant(C->getSExtValue() + 1, DL, VT);
688 CC = ISD::SETGE;
689 break;
690 }
691 }
692 break;
693 }
694 // Swap operands and reverse the branching condition.
695 std::swap(LHS, RHS);
696 CC = ISD::SETLT;
697 break;
698 }
699 case ISD::SETLT: {
700 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
701 switch (C->getSExtValue()) {
702 case 1: {
703 // Turn lhs < 1 into 0 >= lhs since 0 can be materialized with
704 // __zero_reg__ in lhs.
705 RHS = LHS;
706 LHS = DAG.getConstant(0, DL, VT);
707 CC = ISD::SETGE;
708 break;
709 }
710 case 0: {
711 // When doing lhs < 0 use a tst instruction on the top part of lhs
712 // and use brmi instead of using a chain of cp/cpc.
713 UseTest = true;
714 AVRcc = DAG.getConstant(AVRCC::COND_MI, DL, MVT::i8);
715 break;
716 }
717 }
718 }
719 break;
720 }
721 case ISD::SETULE: {
722 // Swap operands and reverse the branching condition.
723 std::swap(LHS, RHS);
724 CC = ISD::SETUGE;
725 break;
726 }
727 case ISD::SETUGT: {
728 // Turn `lhs > rhs` with constant rhs into `lhs >= rhs + 1`, because this
729 // allows us to fold the constant into the cmp instruction.
730 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
731 if (C->getConstantIntValue()->isMaxValue(false)) {
732 // Applying this optimization requires calculating rhs+1, which we can't
733 // do if that overflows; it can happen during i128->i64 lowering.
734 } else {
735 RHS = DAG.getConstant(C->getZExtValue() + 1, DL, VT);
736 CC = ISD::SETUGE;
737 break;
738 }
739 }
740 // Swap operands and reverse the branching condition.
741 std::swap(LHS, RHS);
742 CC = ISD::SETULT;
743 break;
744 }
745 }
746
747 // Expand 32 and 64 bit comparisons with custom CMP and CMPC nodes instead of
748 // using the default and/or/xor expansion code which is much longer.
749 if (VT == MVT::i32) {
750 SDValue LHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS,
751 DAG.getIntPtrConstant(0, DL));
752 SDValue LHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS,
753 DAG.getIntPtrConstant(1, DL));
754 SDValue RHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS,
755 DAG.getIntPtrConstant(0, DL));
756 SDValue RHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS,
757 DAG.getIntPtrConstant(1, DL));
758
759 if (UseTest) {
760 // When using tst we only care about the highest part.
761 SDValue Top = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHShi,
762 DAG.getIntPtrConstant(1, DL));
763 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, Top);
764 } else {
765 Cmp = getAVRCmp(LHSlo, RHSlo, DAG, DL);
766 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHShi, RHShi, Cmp);
767 }
768 } else if (VT == MVT::i64) {
769 SDValue LHS_0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS,
770 DAG.getIntPtrConstant(0, DL));
771 SDValue LHS_1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS,
772 DAG.getIntPtrConstant(1, DL));
773
774 SDValue LHS0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_0,
775 DAG.getIntPtrConstant(0, DL));
776 SDValue LHS1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_0,
777 DAG.getIntPtrConstant(1, DL));
778 SDValue LHS2 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_1,
779 DAG.getIntPtrConstant(0, DL));
780 SDValue LHS3 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_1,
781 DAG.getIntPtrConstant(1, DL));
782
783 SDValue RHS_0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS,
784 DAG.getIntPtrConstant(0, DL));
785 SDValue RHS_1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS,
786 DAG.getIntPtrConstant(1, DL));
787
788 SDValue RHS0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_0,
789 DAG.getIntPtrConstant(0, DL));
790 SDValue RHS1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_0,
791 DAG.getIntPtrConstant(1, DL));
792 SDValue RHS2 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_1,
793 DAG.getIntPtrConstant(0, DL));
794 SDValue RHS3 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_1,
795 DAG.getIntPtrConstant(1, DL));
796
797 if (UseTest) {
798 // When using tst we only care about the highest part.
799 SDValue Top = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS3,
800 DAG.getIntPtrConstant(1, DL));
801 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, Top);
802 } else {
803 Cmp = getAVRCmp(LHS0, RHS0, DAG, DL);
804 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS1, RHS1, Cmp);
805 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS2, RHS2, Cmp);
806 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS3, RHS3, Cmp);
807 }
808 } else if (VT == MVT::i8 || VT == MVT::i16) {
809 if (UseTest) {
810 // When using tst we only care about the highest part.
811 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue,
812 (VT == MVT::i8)
813 ? LHS
814 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8,
815 LHS, DAG.getIntPtrConstant(1, DL)));
816 } else {
817 Cmp = getAVRCmp(LHS, RHS, DAG, DL);
818 }
819 } else {
820 llvm_unreachable("Invalid comparison size");
821 }
822
823 // When using a test instruction AVRcc is already set.
824 if (!UseTest) {
825 AVRcc = DAG.getConstant(intCCToAVRCC(CC), DL, MVT::i8);
826 }
827
828 return Cmp;
829}
830
831SDValue AVRTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
832 SDValue Chain = Op.getOperand(0);
833 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
834 SDValue LHS = Op.getOperand(2);
835 SDValue RHS = Op.getOperand(3);
836 SDValue Dest = Op.getOperand(4);
837 SDLoc dl(Op);
838
839 SDValue TargetCC;
840 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, dl);
841
842 return DAG.getNode(AVRISD::BRCOND, dl, MVT::Other, Chain, Dest, TargetCC,
843 Cmp);
844}
845
846SDValue AVRTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
847 SDValue LHS = Op.getOperand(0);
848 SDValue RHS = Op.getOperand(1);
849 SDValue TrueV = Op.getOperand(2);
850 SDValue FalseV = Op.getOperand(3);
851 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
852 SDLoc dl(Op);
853
854 SDValue TargetCC;
855 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, dl);
856
857 SDValue Ops[] = {TrueV, FalseV, TargetCC, Cmp};
858
859 return DAG.getNode(AVRISD::SELECT_CC, dl, Op.getValueType(), Ops);
860}
861
862SDValue AVRTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
863 SDValue LHS = Op.getOperand(0);
864 SDValue RHS = Op.getOperand(1);
865 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
866 SDLoc DL(Op);
867
868 SDValue TargetCC;
869 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, DL);
870
871 SDValue TrueV = DAG.getConstant(1, DL, Op.getValueType());
872 SDValue FalseV = DAG.getConstant(0, DL, Op.getValueType());
873 SDValue Ops[] = {TrueV, FalseV, TargetCC, Cmp};
874
875 return DAG.getNode(AVRISD::SELECT_CC, DL, Op.getValueType(), Ops);
876}
877
878SDValue AVRTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
879 const MachineFunction &MF = DAG.getMachineFunction();
880 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
881 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
882 auto DL = DAG.getDataLayout();
883 SDLoc dl(Op);
884
885 // Vastart just stores the address of the VarArgsFrameIndex slot into the
886 // memory location argument.
887 SDValue FI = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(), getPointerTy(DL));
888
889 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
890 MachinePointerInfo(SV));
891}
892
893// Modify the existing ISD::INLINEASM node to add the implicit zero register.
894SDValue AVRTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
895 SDValue ZeroReg = DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8);
896 if (Op.getOperand(Op.getNumOperands() - 1) == ZeroReg ||
897 Op.getOperand(Op.getNumOperands() - 2) == ZeroReg) {
898 // Zero register has already been added. Don't add it again.
899 // If this isn't handled, we get called over and over again.
900 return Op;
901 }
902
903 // Get a list of operands to the new INLINEASM node. This is mostly a copy,
904 // with some edits.
905 // Add the following operands at the end (but before the glue node, if it's
906 // there):
907 // - The flags of the implicit zero register operand.
908 // - The implicit zero register operand itself.
909 SDLoc dl(Op);
911 SDNode *N = Op.getNode();
912 SDValue Glue;
913 for (unsigned I = 0; I < N->getNumOperands(); I++) {
914 SDValue Operand = N->getOperand(I);
915 if (Operand.getValueType() == MVT::Glue) {
916 // The glue operand always needs to be at the end, so we need to treat it
917 // specially.
918 Glue = Operand;
919 } else {
920 Ops.push_back(Operand);
921 }
922 }
923 InlineAsm::Flag Flags(InlineAsm::Kind::RegUse, 1);
924 Ops.push_back(DAG.getTargetConstant(Flags, dl, MVT::i32));
925 Ops.push_back(ZeroReg);
926 if (Glue) {
927 Ops.push_back(Glue);
928 }
929
930 // Replace the current INLINEASM node with a new one that has the zero
931 // register as implicit parameter.
932 SDValue New = DAG.getNode(N->getOpcode(), dl, N->getVTList(), Ops);
933 DAG.ReplaceAllUsesOfValueWith(Op, New);
934 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), New.getValue(1));
935
936 return New;
937}
938
940 switch (Op.getOpcode()) {
941 default:
942 llvm_unreachable("Don't know how to custom lower this!");
943 case ISD::SHL:
944 case ISD::SRA:
945 case ISD::SRL:
946 case ISD::ROTL:
947 case ISD::ROTR:
948 return LowerShifts(Op, DAG);
950 return LowerGlobalAddress(Op, DAG);
952 return LowerBlockAddress(Op, DAG);
953 case ISD::BR_CC:
954 return LowerBR_CC(Op, DAG);
955 case ISD::SELECT_CC:
956 return LowerSELECT_CC(Op, DAG);
957 case ISD::SETCC:
958 return LowerSETCC(Op, DAG);
959 case ISD::VASTART:
960 return LowerVASTART(Op, DAG);
961 case ISD::SDIVREM:
962 case ISD::UDIVREM:
963 return LowerDivRem(Op, DAG);
964 case ISD::INLINEASM:
965 return LowerINLINEASM(Op, DAG);
966 case ISD::FRAMEADDR:
967 return LowerFRAMEADDR(Op, DAG);
968 case ISD::RETURNADDR:
969 return LowerRETURNADDR(Op, DAG);
970 }
971
972 return SDValue();
973}
974
975SDValue AVRTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
976 // The frame pointer (Y = r29:r28) is set up to contain the stack pointer
977 // *after* the frame has been allocated, i.e. Y == SP_entry - StackSize,
978 // which means it points to the lowest address of the frame: it is really a
979 // frame *base* rather than the canonical frame address. The slot holding the
980 // caller's Y therefore sits at a function dependent offset (the frame size)
981 // above it. Walking the frame chain is only possible for the current frame.
982 //
983 // This is also what avr-gcc returns for __builtin_frame_address(0).
984 if (Op.getConstantOperandVal(0) > 0)
985 // Use the legalizer's default expansion, which is to return 0 (what this
986 // function is documented to do).
987 return SDValue();
988
990 // Mark frame address as taken, so that during frame lowering we're forced to
991 // emit frame pointer register (R29R28) we rely on here.
992 MFI.setFrameAddressIsTaken(true);
993
994 // Note that AVRRegisterInfo::getFrameRegister returns R28, which is only
995 // the low half of the frame pointer: use the full 16-bit register pair.
996 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), AVR::R29R28,
997 Op.getValueType());
998}
999
1000SDValue AVRTargetLowering::LowerRETURNADDR(SDValue Op,
1001 SelectionDAG &DAG) const {
1002 // AVR has no link register: the return address is pushed onto the stack by
1003 // the call instruction. The stack pointer always points at the first free
1004 // byte, so the pushed return address ends up right below the local area (the
1005 // incoming stack arguments), which starts at SP_entry + 3.
1006 //
1007 // The return address is pushed most significant byte first, hence it is
1008 // stored big-endian: [SP_entry + 1] is the high byte and [SP_entry + 2] the
1009 // low byte. This is why avr-gcc has to swap the two bytes it reads for
1010 // __builtin_return_address(0).
1011 //
1012 // Walking the frame chain is not possible, because the distance between the
1013 // frame base and the slot holding the caller's return address depends on the
1014 // caller's frame size, which is not known here. This is also what avr-gcc
1015 // does for __builtin_return_address(1), which returns zero.
1016 if (Op.getConstantOperandVal(0) > 0)
1017 // Use the legalizer's default expansion, which is to return 0 (what this
1018 // function is documented to do).
1019 return SDValue();
1020
1021 MachineFunction &MF = DAG.getMachineFunction();
1022 MachineFrameInfo &MFI = MF.getFrameInfo();
1023 // Mark return address as taken, so that during frame lowering we're forced to
1024 // emit frame pointer register (R29R28) we rely on here.
1025 MFI.setReturnAddressIsTaken(true);
1026
1027 SDLoc DL(Op);
1028 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1029
1030 // A call pushes as many bytes as the program counter is wide: three on
1031 // devices with a 22-bit PC (the ones providing EIJMP/EICALL), two elsewhere.
1032 // Only the two low bytes of the return address are returned, so on the former
1033 // they are found one byte higher up.
1034 int PCWidth = Subtarget.hasEIJMPCALL() ? 3 : 2;
1035
1036 // A fixed object at offset N is located at SP_entry + N + 3, so the two low
1037 // bytes of the return address are the fixed object at offset PCWidth - 4.
1038 // Note that a frame index can only be referenced through Y, so taking the
1039 // return address forces the function to have a frame pointer (see
1040 // AVRFrameLowering::hasFPImpl).
1041 int FI = MFI.CreateFixedObject(2, PCWidth - 4, true);
1042 SDValue Addr = DAG.getFrameIndex(FI, PtrVT);
1043
1044 // Load the two bytes separately and put them in the right halves of the
1045 // result, which is cheaper than loading a word and byte swapping it.
1046 SDValue Hi = DAG.getLoad(MVT::i8, DL, DAG.getEntryNode(), Addr,
1048 SDValue Lo =
1049 DAG.getLoad(MVT::i8, DL, DAG.getEntryNode(),
1050 DAG.getObjectPtrOffset(DL, Addr, TypeSize::getFixed(1)),
1052
1053 SDValue Res = DAG.getTargetInsertSubreg(AVR::sub_lo, DL, MVT::i16,
1054 DAG.getUNDEF(MVT::i16), Lo);
1055 return DAG.getTargetInsertSubreg(AVR::sub_hi, DL, MVT::i16, Res, Hi);
1056}
1057
1058/// Replace a node with an illegal result type
1059/// with a new node built out of custom code.
1062 SelectionDAG &DAG) const {
1063 SDLoc DL(N);
1064
1065 switch (N->getOpcode()) {
1066 case ISD::ADD: {
1067 // Convert add (x, imm) into sub (x, -imm).
1068 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1069 SDValue Sub = DAG.getNode(
1070 ISD::SUB, DL, N->getValueType(0), N->getOperand(0),
1071 DAG.getConstant(-C->getAPIntValue(), DL, C->getValueType(0)));
1072 Results.push_back(Sub);
1073 }
1074 break;
1075 }
1076 default: {
1077 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1078
1079 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1080 Results.push_back(Res.getValue(I));
1081
1082 break;
1083 }
1084 }
1085}
1086
1087/// Return true if the addressing mode represented
1088/// by AM is legal for this target, for a load/store of the specified type.
1090 const AddrMode &AM, Type *Ty,
1091 unsigned AS,
1092 Instruction *I) const {
1093 int64_t Offs = AM.BaseOffs;
1094
1095 // Allow absolute addresses.
1096 if (AM.BaseGV && !AM.HasBaseReg && AM.Scale == 0 && Offs == 0) {
1097 return true;
1098 }
1099
1100 // Flash memory instructions only allow zero offsets.
1101 if (isa<PointerType>(Ty) && AS == AVR::ProgramMemory) {
1102 return false;
1103 }
1104
1105 // Allow reg+<6bit> offset.
1106 if (Offs < 0)
1107 Offs = -Offs;
1108 if (AM.BaseGV == nullptr && AM.HasBaseReg && AM.Scale == 0 &&
1109 isUInt<6>(Offs)) {
1110 return true;
1111 }
1112
1113 return false;
1114}
1115
1116/// Returns true by value, base pointer and
1117/// offset pointer and addressing mode by reference if the node's address
1118/// can be legally represented as pre-indexed load / store address.
1120 SDValue &Offset,
1122 SelectionDAG &DAG) const {
1123 EVT VT;
1124 const SDNode *Op;
1125 SDLoc DL(N);
1126
1127 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1128 VT = LD->getMemoryVT();
1129 Op = LD->getBasePtr().getNode();
1130 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1131 return false;
1133 return false;
1134 }
1135 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1136 VT = ST->getMemoryVT();
1137 Op = ST->getBasePtr().getNode();
1139 return false;
1140 }
1141 } else {
1142 return false;
1143 }
1144
1145 if (VT != MVT::i8 && VT != MVT::i16) {
1146 return false;
1147 }
1148
1149 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) {
1150 return false;
1151 }
1152
1153 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1154 int RHSC = RHS->getSExtValue();
1155 if (Op->getOpcode() == ISD::SUB)
1156 RHSC = -RHSC;
1157
1158 if ((VT == MVT::i16 && RHSC != -2) || (VT == MVT::i8 && RHSC != -1)) {
1159 return false;
1160 }
1161
1162 Base = Op->getOperand(0);
1163 Offset = DAG.getSignedConstant(RHSC, DL, MVT::i8);
1164 AM = ISD::PRE_DEC;
1165
1166 return true;
1167 }
1168
1169 return false;
1170}
1171
1172/// Returns true by value, base pointer and
1173/// offset pointer and addressing mode by reference if this node can be
1174/// combined with a load / store to form a post-indexed load / store.
1176 SDValue &Base,
1177 SDValue &Offset,
1179 SelectionDAG &DAG) const {
1180 EVT VT;
1181 SDValue Ptr;
1182 SDLoc DL(N);
1183
1184 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1185 VT = LD->getMemoryVT();
1186 Ptr = LD->getBasePtr();
1187 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1188 return false;
1189 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1190 VT = ST->getMemoryVT();
1191 Ptr = ST->getBasePtr();
1192 // We can not store to program memory.
1194 return false;
1195 // Since the high byte need to be stored first, we can not emit
1196 // i16 post increment store like:
1197 // st X+, r24
1198 // st X+, r25
1199 if (VT == MVT::i16 && !Subtarget.hasLowByteFirst())
1200 return false;
1201 } else {
1202 return false;
1203 }
1204
1205 if (VT != MVT::i8 && VT != MVT::i16) {
1206 return false;
1207 }
1208
1209 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) {
1210 return false;
1211 }
1212
1213 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1214 int RHSC = RHS->getSExtValue();
1215 if (Op->getOpcode() == ISD::SUB)
1216 RHSC = -RHSC;
1217 if ((VT == MVT::i16 && RHSC != 2) || (VT == MVT::i8 && RHSC != 1)) {
1218 return false;
1219 }
1220
1221 // FIXME: We temporarily disable post increment load from program memory,
1222 // due to bug https://github.com/llvm/llvm-project/issues/59914.
1223 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
1225 return false;
1226
1227 Base = Op->getOperand(0);
1228
1229 // Post-indexing updates the base, so it's not a valid transform
1230 // if that's not the same as the load's pointer.
1231 if (Ptr != Base)
1232 return false;
1233
1234 Offset = DAG.getConstant(RHSC, DL, MVT::i8);
1235 AM = ISD::POST_INC;
1236
1237 return true;
1238 }
1239
1240 return false;
1241}
1242
1244 const GlobalAddressSDNode *GA) const {
1245 return true;
1246}
1247
1248//===----------------------------------------------------------------------===//
1249// Formal Arguments Calling Convention Implementation
1250//===----------------------------------------------------------------------===//
1251
1252#define GET_CALLING_CONV_IMPL
1253#include "AVRGenCallingConv.inc"
1254
1255/// Registers for calling conventions, ordered in reverse as required by ABI.
1256/// Both arrays must be of the same length.
1257static const MCPhysReg RegList8AVR[] = {
1258 AVR::R25, AVR::R24, AVR::R23, AVR::R22, AVR::R21, AVR::R20,
1259 AVR::R19, AVR::R18, AVR::R17, AVR::R16, AVR::R15, AVR::R14,
1260 AVR::R13, AVR::R12, AVR::R11, AVR::R10, AVR::R9, AVR::R8};
1261static const MCPhysReg RegList8Tiny[] = {AVR::R25, AVR::R24, AVR::R23,
1262 AVR::R22, AVR::R21, AVR::R20};
1263static const MCPhysReg RegList16AVR[] = {
1264 AVR::R26R25, AVR::R25R24, AVR::R24R23, AVR::R23R22, AVR::R22R21,
1265 AVR::R21R20, AVR::R20R19, AVR::R19R18, AVR::R18R17, AVR::R17R16,
1266 AVR::R16R15, AVR::R15R14, AVR::R14R13, AVR::R13R12, AVR::R12R11,
1267 AVR::R11R10, AVR::R10R9, AVR::R9R8};
1268static const MCPhysReg RegList16Tiny[] = {AVR::R26R25, AVR::R25R24,
1269 AVR::R24R23, AVR::R23R22,
1270 AVR::R22R21, AVR::R21R20};
1271
1272static_assert(std::size(RegList8AVR) == std::size(RegList16AVR),
1273 "8-bit and 16-bit register arrays must be of equal length");
1274static_assert(std::size(RegList8Tiny) == std::size(RegList16Tiny),
1275 "8-bit and 16-bit register arrays must be of equal length");
1276
1277/// Analyze incoming and outgoing function arguments. We need custom C++ code
1278/// to handle special constraints in the ABI.
1279/// In addition, all pieces of a certain argument have to be passed either
1280/// using registers or the stack but never mixing both.
1281template <typename ArgT>
1283 const Function *F, const DataLayout *TD,
1284 const SmallVectorImpl<ArgT> &Args,
1286 CCState &CCInfo, bool Tiny) {
1287 // Choose the proper register list for argument passing according to the ABI.
1288 ArrayRef<MCPhysReg> RegList8;
1289 ArrayRef<MCPhysReg> RegList16;
1290 if (Tiny) {
1291 RegList8 = ArrayRef(RegList8Tiny);
1292 RegList16 = ArrayRef(RegList16Tiny);
1293 } else {
1294 RegList8 = ArrayRef(RegList8AVR);
1295 RegList16 = ArrayRef(RegList16AVR);
1296 }
1297
1298 unsigned NumArgs = Args.size();
1299 // This is the index of the last used register, in RegList*.
1300 // -1 means R26 (R26 is never actually used in CC).
1301 int RegLastIdx = -1;
1302 // Once a value is passed to the stack it will always be used
1303 bool UseStack = false;
1304 for (unsigned i = 0; i != NumArgs;) {
1305 MVT VT = Args[i].VT;
1306 // We have to count the number of bytes for each function argument, that is
1307 // those Args with the same OrigArgIndex. This is important in case the
1308 // function takes an aggregate type.
1309 // Current argument will be between [i..j).
1310 unsigned ArgIndex = Args[i].OrigArgIndex;
1311 unsigned TotalBytes = VT.getStoreSize();
1312 unsigned j = i + 1;
1313 for (; j != NumArgs; ++j) {
1314 if (Args[j].OrigArgIndex != ArgIndex)
1315 break;
1316 TotalBytes += Args[j].VT.getStoreSize();
1317 }
1318 // Round up to even number of bytes.
1319 TotalBytes = alignTo(TotalBytes, 2);
1320 // Skip zero sized arguments
1321 if (TotalBytes == 0)
1322 continue;
1323 // The index of the first register to be used
1324 unsigned RegIdx = RegLastIdx + TotalBytes;
1325 RegLastIdx = RegIdx;
1326 // If there are not enough registers, use the stack
1327 if (RegIdx >= RegList8.size()) {
1328 UseStack = true;
1329 }
1330 for (; i != j; ++i) {
1331 MVT VT = Args[i].VT;
1332
1333 if (UseStack) {
1334 auto evt = EVT(VT).getTypeForEVT(CCInfo.getContext());
1335 unsigned Offset = CCInfo.AllocateStack(TD->getTypeAllocSize(evt),
1336 TD->getABITypeAlign(evt));
1337 CCInfo.addLoc(
1339 } else {
1340 unsigned Reg;
1341 if (VT == MVT::i8) {
1342 Reg = CCInfo.AllocateReg(RegList8[RegIdx]);
1343 } else if (VT == MVT::i16) {
1344 Reg = CCInfo.AllocateReg(RegList16[RegIdx]);
1345 } else {
1347 "calling convention can only manage i8 and i16 types");
1348 }
1349 assert(Reg && "register not available in calling convention");
1350 CCInfo.addLoc(CCValAssign::getReg(i, VT, Reg, VT, CCValAssign::Full));
1351 // Registers inside a particular argument are sorted in increasing order
1352 // (remember the array is reversed).
1353 RegIdx -= VT.getStoreSize();
1354 }
1355 }
1356 }
1357}
1358
1359/// Count the total number of bytes needed to pass or return these arguments.
1360template <typename ArgT>
1361static unsigned
1363 unsigned TotalBytes = 0;
1364
1365 for (const ArgT &Arg : Args) {
1366 TotalBytes += Arg.VT.getStoreSize();
1367 }
1368 return TotalBytes;
1369}
1370
1371/// Analyze incoming and outgoing value of returning from a function.
1372/// The algorithm is similar to analyzeArguments, but there can only be
1373/// one value, possibly an aggregate, and it is limited to 8 bytes.
1374template <typename ArgT>
1376 CCState &CCInfo, bool Tiny) {
1377 unsigned NumArgs = Args.size();
1378 unsigned TotalBytes = getTotalArgumentsSizeInBytes(Args);
1379 // CanLowerReturn() guarantees this assertion.
1380 if (Tiny)
1381 assert(TotalBytes <= 4 &&
1382 "return values greater than 4 bytes cannot be lowered on AVRTiny");
1383 else
1384 assert(TotalBytes <= 8 &&
1385 "return values greater than 8 bytes cannot be lowered on AVR");
1386
1387 // Choose the proper register list for argument passing according to the ABI.
1388 ArrayRef<MCPhysReg> RegList8;
1389 ArrayRef<MCPhysReg> RegList16;
1390 if (Tiny) {
1391 RegList8 = ArrayRef(RegList8Tiny);
1392 RegList16 = ArrayRef(RegList16Tiny);
1393 } else {
1394 RegList8 = ArrayRef(RegList8AVR);
1395 RegList16 = ArrayRef(RegList16AVR);
1396 }
1397
1398 // GCC-ABI says that the size is rounded up to the next even number,
1399 // but actually once it is more than 4 it will always round up to 8.
1400 if (TotalBytes > 4) {
1401 TotalBytes = 8;
1402 } else {
1403 TotalBytes = alignTo(TotalBytes, 2);
1404 }
1405
1406 // The index of the first register to use.
1407 int RegIdx = TotalBytes - 1;
1408 for (unsigned i = 0; i != NumArgs; ++i) {
1409 MVT VT = Args[i].VT;
1410 unsigned Reg;
1411 if (VT == MVT::i8) {
1412 Reg = CCInfo.AllocateReg(RegList8[RegIdx]);
1413 } else if (VT == MVT::i16) {
1414 Reg = CCInfo.AllocateReg(RegList16[RegIdx]);
1415 } else {
1416 llvm_unreachable("calling convention can only manage i8 and i16 types");
1417 }
1418 assert(Reg && "register not available in calling convention");
1419 CCInfo.addLoc(CCValAssign::getReg(i, VT, Reg, VT, CCValAssign::Full));
1420 // Registers sort in increasing order
1421 RegIdx -= VT.getStoreSize();
1422 }
1423}
1424
1425SDValue AVRTargetLowering::LowerFormalArguments(
1426 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1427 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1428 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1429 MachineFunction &MF = DAG.getMachineFunction();
1430 MachineFrameInfo &MFI = MF.getFrameInfo();
1431 auto DL = DAG.getDataLayout();
1432
1433 // Assign locations to all of the incoming arguments.
1435 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1436 *DAG.getContext());
1437
1438 // Variadic functions do not need all the analysis below.
1439 if (isVarArg) {
1440 CCInfo.AnalyzeFormalArguments(Ins, ArgCC_AVR_Vararg);
1441 } else {
1442 analyzeArguments(nullptr, &MF.getFunction(), &DL, Ins, ArgLocs, CCInfo,
1443 Subtarget.hasTinyEncoding());
1444 }
1445
1446 SDValue ArgValue;
1447 for (CCValAssign &VA : ArgLocs) {
1448
1449 // Arguments stored on registers.
1450 if (VA.isRegLoc()) {
1451 EVT RegVT = VA.getLocVT();
1452 const TargetRegisterClass *RC;
1453 if (RegVT == MVT::i8) {
1454 RC = &AVR::GPR8RegClass;
1455 } else if (RegVT == MVT::i16) {
1456 RC = &AVR::DREGSRegClass;
1457 } else {
1458 llvm_unreachable("Unknown argument type!");
1459 }
1460
1461 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
1462 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1463
1464 // :NOTE: Clang should not promote any i8 into i16 but for safety the
1465 // following code will handle zexts or sexts generated by other
1466 // front ends. Otherwise:
1467 // If this is an 8 bit value, it is really passed promoted
1468 // to 16 bits. Insert an assert[sz]ext to capture this, then
1469 // truncate to the right size.
1470 switch (VA.getLocInfo()) {
1471 default:
1472 llvm_unreachable("Unknown loc info!");
1473 case CCValAssign::Full:
1474 break;
1475 case CCValAssign::BCvt:
1476 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1477 break;
1478 case CCValAssign::SExt:
1479 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1480 DAG.getValueType(VA.getValVT()));
1481 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1482 break;
1483 case CCValAssign::ZExt:
1484 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1485 DAG.getValueType(VA.getValVT()));
1486 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1487 break;
1488 }
1489
1490 InVals.push_back(ArgValue);
1491 } else {
1492 // Only arguments passed on the stack should make it here.
1493 assert(VA.isMemLoc());
1494
1495 EVT LocVT = VA.getLocVT();
1496
1497 // Create the frame index object for this incoming parameter.
1498 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
1499 VA.getLocMemOffset(), true);
1500
1501 // Create the SelectionDAG nodes corresponding to a load
1502 // from this parameter.
1503 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DL));
1504 InVals.push_back(DAG.getLoad(LocVT, dl, Chain, FIN,
1506 }
1507 }
1508
1509 // If the function takes variable number of arguments, make a frame index for
1510 // the start of the first vararg value... for expansion of llvm.va_start.
1511 if (isVarArg) {
1512 unsigned StackSize = CCInfo.getStackSize();
1513 AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
1514
1515 AFI->setVarArgsFrameIndex(MFI.CreateFixedObject(2, StackSize, true));
1516 }
1517
1518 return Chain;
1519}
1520
1521//===----------------------------------------------------------------------===//
1522// Call Calling Convention Implementation
1523//===----------------------------------------------------------------------===//
1524
1525SDValue AVRTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1526 SmallVectorImpl<SDValue> &InVals) const {
1527 SelectionDAG &DAG = CLI.DAG;
1528 SDLoc &DL = CLI.DL;
1529 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1530 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1531 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1532 SDValue Chain = CLI.Chain;
1533 SDValue Callee = CLI.Callee;
1534 bool &isTailCall = CLI.IsTailCall;
1535 CallingConv::ID CallConv = CLI.CallConv;
1536 bool isVarArg = CLI.IsVarArg;
1537
1538 MachineFunction &MF = DAG.getMachineFunction();
1539
1540 // AVR does not yet support tail call optimization.
1541 isTailCall = false;
1542
1543 // Analyze operands of the call, assigning locations to each operand.
1545 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1546 *DAG.getContext());
1547
1548 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1549 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1550 // node so that legalize doesn't hack it.
1551 const Function *F = nullptr;
1552 if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1553 const GlobalValue *GV = G->getGlobal();
1554 if (isa<Function>(GV))
1555 F = cast<Function>(GV);
1556 Callee =
1557 DAG.getTargetGlobalAddress(GV, DL, getPointerTy(DAG.getDataLayout()));
1558 } else if (const ExternalSymbolSDNode *ES =
1560 Callee = DAG.getTargetExternalSymbol(ES->getSymbol(),
1561 getPointerTy(DAG.getDataLayout()));
1562 }
1563
1564 // Variadic functions do not need all the analysis below.
1565 if (isVarArg) {
1566 CCInfo.AnalyzeCallOperands(Outs, ArgCC_AVR_Vararg);
1567 } else {
1568 analyzeArguments(&CLI, F, &DAG.getDataLayout(), Outs, ArgLocs, CCInfo,
1569 Subtarget.hasTinyEncoding());
1570 }
1571
1572 // Get a count of how many bytes are to be pushed on the stack.
1573 unsigned NumBytes = CCInfo.getStackSize();
1574
1575 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
1576
1578
1579 // First, walk the register assignments, inserting copies.
1580 unsigned AI, AE;
1581 bool HasStackArgs = false;
1582 for (AI = 0, AE = ArgLocs.size(); AI != AE; ++AI) {
1583 CCValAssign &VA = ArgLocs[AI];
1584 EVT RegVT = VA.getLocVT();
1585 SDValue Arg = OutVals[AI];
1586
1587 // Promote the value if needed. With Clang this should not happen.
1588 switch (VA.getLocInfo()) {
1589 default:
1590 llvm_unreachable("Unknown loc info!");
1591 case CCValAssign::Full:
1592 break;
1593 case CCValAssign::SExt:
1594 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, RegVT, Arg);
1595 break;
1596 case CCValAssign::ZExt:
1597 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, RegVT, Arg);
1598 break;
1599 case CCValAssign::AExt:
1600 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, RegVT, Arg);
1601 break;
1602 case CCValAssign::BCvt:
1603 Arg = DAG.getNode(ISD::BITCAST, DL, RegVT, Arg);
1604 break;
1605 }
1606
1607 // Stop when we encounter a stack argument, we need to process them
1608 // in reverse order in the loop below.
1609 if (VA.isMemLoc()) {
1610 HasStackArgs = true;
1611 break;
1612 }
1613
1614 // Arguments that can be passed on registers must be kept in the RegsToPass
1615 // vector.
1616 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1617 }
1618
1619 // Second, stack arguments have to walked.
1620 // Previously this code created chained stores but those chained stores appear
1621 // to be unchained in the legalization phase. Therefore, do not attempt to
1622 // chain them here. In fact, chaining them here somehow causes the first and
1623 // second store to be reversed which is the exact opposite of the intended
1624 // effect.
1625 if (HasStackArgs) {
1626 SmallVector<SDValue, 8> MemOpChains;
1627 for (; AI != AE; AI++) {
1628 CCValAssign &VA = ArgLocs[AI];
1629 SDValue Arg = OutVals[AI];
1630
1631 assert(VA.isMemLoc());
1632
1633 // SP points to one stack slot further so add one to adjust it.
1634 SDValue PtrOff = DAG.getNode(
1635 ISD::ADD, DL, getPointerTy(DAG.getDataLayout()),
1636 DAG.getRegister(AVR::SP, getPointerTy(DAG.getDataLayout())),
1637 DAG.getIntPtrConstant(VA.getLocMemOffset() + 1, DL));
1638
1639 MemOpChains.push_back(
1640 DAG.getStore(Chain, DL, Arg, PtrOff,
1641 MachinePointerInfo::getStack(MF, VA.getLocMemOffset())));
1642 }
1643
1644 if (!MemOpChains.empty())
1645 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1646 }
1647
1648 // Build a sequence of copy-to-reg nodes chained together with token chain and
1649 // flag operands which copy the outgoing args into registers. The InGlue in
1650 // necessary since all emited instructions must be stuck together.
1651 SDValue InGlue;
1652 for (auto Reg : RegsToPass) {
1653 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, InGlue);
1654 InGlue = Chain.getValue(1);
1655 }
1656
1657 // Returns a chain & a flag for retval copy to use.
1658 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1660 Ops.push_back(Chain);
1661 Ops.push_back(Callee);
1662
1663 // Add argument registers to the end of the list so that they are known live
1664 // into the call.
1665 for (auto Reg : RegsToPass) {
1666 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1667 }
1668
1669 // The zero register (usually R1) must be passed as an implicit register so
1670 // that this register is correctly zeroed in interrupts.
1671 Ops.push_back(DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8));
1672
1673 // Add a register mask operand representing the call-preserved registers.
1674 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1675 const uint32_t *Mask =
1676 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
1677 assert(Mask && "Missing call preserved mask for calling convention");
1678 Ops.push_back(DAG.getRegisterMask(Mask));
1679
1680 if (InGlue.getNode()) {
1681 Ops.push_back(InGlue);
1682 }
1683
1684 Chain = DAG.getNode(AVRISD::CALL, DL, NodeTys, Ops);
1685 InGlue = Chain.getValue(1);
1686
1687 // Create the CALLSEQ_END node.
1688 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, DL);
1689
1690 if (!Ins.empty()) {
1691 InGlue = Chain.getValue(1);
1692 }
1693
1694 // Handle result values, copying them out of physregs into vregs that we
1695 // return.
1696 return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, DL, DAG,
1697 InVals);
1698}
1699
1700/// Lower the result values of a call into the
1701/// appropriate copies out of appropriate physical registers.
1702///
1703SDValue AVRTargetLowering::LowerCallResult(
1704 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
1705 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1706 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1707
1708 // Assign locations to each value returned by this call.
1710 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1711 *DAG.getContext());
1712
1713 // Handle runtime calling convs.
1714 if (CallConv == CallingConv::AVR_BUILTIN) {
1715 CCInfo.AnalyzeCallResult(Ins, RetCC_AVR_BUILTIN);
1716 } else {
1717 analyzeReturnValues(Ins, CCInfo, Subtarget.hasTinyEncoding());
1718 }
1719
1720 // Copy all of the result registers out of their specified physreg.
1721 for (CCValAssign const &RVLoc : RVLocs) {
1722 Chain = DAG.getCopyFromReg(Chain, dl, RVLoc.getLocReg(), RVLoc.getValVT(),
1723 InGlue)
1724 .getValue(1);
1725 InGlue = Chain.getValue(2);
1726 InVals.push_back(Chain.getValue(0));
1727 }
1728
1729 return Chain;
1730}
1731
1732//===----------------------------------------------------------------------===//
1733// Return Value Calling Convention Implementation
1734//===----------------------------------------------------------------------===//
1735
1736bool AVRTargetLowering::CanLowerReturn(
1737 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
1739 const Type *RetTy) const {
1740 if (CallConv == CallingConv::AVR_BUILTIN) {
1742 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1743 return CCInfo.CheckReturn(Outs, RetCC_AVR_BUILTIN);
1744 }
1745
1746 unsigned TotalBytes = getTotalArgumentsSizeInBytes(Outs);
1747 return TotalBytes <= (unsigned)(Subtarget.hasTinyEncoding() ? 4 : 8);
1748}
1749
1750SDValue
1751AVRTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1752 bool isVarArg,
1754 const SmallVectorImpl<SDValue> &OutVals,
1755 const SDLoc &dl, SelectionDAG &DAG) const {
1756 // CCValAssign - represent the assignment of the return value to locations.
1758
1759 // CCState - Info about the registers and stack slot.
1760 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1761 *DAG.getContext());
1762
1763 MachineFunction &MF = DAG.getMachineFunction();
1764
1765 // Analyze return values.
1766 if (CallConv == CallingConv::AVR_BUILTIN) {
1767 CCInfo.AnalyzeReturn(Outs, RetCC_AVR_BUILTIN);
1768 } else {
1769 analyzeReturnValues(Outs, CCInfo, Subtarget.hasTinyEncoding());
1770 }
1771
1772 SDValue Glue;
1773 SmallVector<SDValue, 4> RetOps(1, Chain);
1774 // Copy the result values into the output registers.
1775 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1776 CCValAssign &VA = RVLocs[i];
1777 assert(VA.isRegLoc() && "Can only return in registers!");
1778
1779 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Glue);
1780
1781 // Guarantee that all emitted copies are stuck together with flags.
1782 Glue = Chain.getValue(1);
1783 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1784 }
1785
1786 // Don't emit the ret/reti instruction when the naked attribute is present in
1787 // the function being compiled.
1788 if (MF.getFunction().getAttributes().hasFnAttr(Attribute::Naked)) {
1789 return Chain;
1790 }
1791
1792 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
1793
1794 if (!AFI->isInterruptOrSignalHandler()) {
1795 // The return instruction has an implicit zero register operand: it must
1796 // contain zero on return.
1797 // This is not needed in interrupts however, where the zero register is
1798 // handled specially (only pushed/popped when needed).
1799 RetOps.push_back(DAG.getRegister(Subtarget.getZeroRegister(), MVT::i8));
1800 }
1801
1802 unsigned RetOpc =
1803 AFI->isInterruptOrSignalHandler() ? AVRISD::RETI_GLUE : AVRISD::RET_GLUE;
1804
1805 RetOps[0] = Chain; // Update chain.
1806
1807 if (Glue.getNode()) {
1808 RetOps.push_back(Glue);
1809 }
1810
1811 return DAG.getNode(RetOpc, dl, MVT::Other, RetOps);
1812}
1813
1814//===----------------------------------------------------------------------===//
1815// Custom Inserters
1816//===----------------------------------------------------------------------===//
1817
1818MachineBasicBlock *AVRTargetLowering::insertShift(MachineInstr &MI,
1820 bool Tiny) const {
1821 unsigned Opc;
1822 const TargetRegisterClass *RC;
1823 bool HasRepeatedOperand = false;
1824 MachineFunction *F = BB->getParent();
1825 MachineRegisterInfo &RI = F->getRegInfo();
1826 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1827 DebugLoc dl = MI.getDebugLoc();
1828
1829 switch (MI.getOpcode()) {
1830 default:
1831 llvm_unreachable("Invalid shift opcode!");
1832 case AVR::Lsl8:
1833 Opc = AVR::ADDRdRr; // LSL is an alias of ADD Rd, Rd
1834 RC = &AVR::GPR8RegClass;
1835 HasRepeatedOperand = true;
1836 break;
1837 case AVR::Lsl16:
1838 Opc = AVR::LSLWRd;
1839 RC = &AVR::DREGSRegClass;
1840 break;
1841 case AVR::Asr8:
1842 Opc = AVR::ASRRd;
1843 RC = &AVR::GPR8RegClass;
1844 break;
1845 case AVR::Asr16:
1846 Opc = AVR::ASRWRd;
1847 RC = &AVR::DREGSRegClass;
1848 break;
1849 case AVR::Lsr8:
1850 Opc = AVR::LSRRd;
1851 RC = &AVR::GPR8RegClass;
1852 break;
1853 case AVR::Lsr16:
1854 Opc = AVR::LSRWRd;
1855 RC = &AVR::DREGSRegClass;
1856 break;
1857 case AVR::Rol8:
1858 Opc = Tiny ? AVR::ROLBRdR17 : AVR::ROLBRdR1;
1859 RC = &AVR::GPR8RegClass;
1860 break;
1861 case AVR::Rol16:
1862 Opc = AVR::ROLWRd;
1863 RC = &AVR::DREGSRegClass;
1864 break;
1865 case AVR::Ror8:
1866 Opc = AVR::RORBRd;
1867 RC = &AVR::GPR8RegClass;
1868 break;
1869 case AVR::Ror16:
1870 Opc = AVR::RORWRd;
1871 RC = &AVR::DREGSRegClass;
1872 break;
1873 }
1874
1875 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1876
1878 for (I = BB->getIterator(); I != F->end() && &(*I) != BB; ++I)
1879 ;
1880 if (I != F->end())
1881 ++I;
1882
1883 // Create loop block.
1884 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1885 MachineBasicBlock *CheckBB = F->CreateMachineBasicBlock(LLVM_BB);
1886 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB);
1887
1888 F->insert(I, LoopBB);
1889 F->insert(I, CheckBB);
1890 F->insert(I, RemBB);
1891
1892 // Update machine-CFG edges by transferring all successors of the current
1893 // block to the block containing instructions after shift.
1894 RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
1895 BB->end());
1896 RemBB->transferSuccessorsAndUpdatePHIs(BB);
1897
1898 // Add edges BB => LoopBB => CheckBB => RemBB, CheckBB => LoopBB.
1899 BB->addSuccessor(CheckBB);
1900 LoopBB->addSuccessor(CheckBB);
1901 CheckBB->addSuccessor(LoopBB);
1902 CheckBB->addSuccessor(RemBB);
1903
1904 Register ShiftAmtReg = RI.createVirtualRegister(&AVR::GPR8RegClass);
1905 Register ShiftAmtReg2 = RI.createVirtualRegister(&AVR::GPR8RegClass);
1906 Register ShiftReg = RI.createVirtualRegister(RC);
1907 Register ShiftReg2 = RI.createVirtualRegister(RC);
1908 Register ShiftAmtSrcReg = MI.getOperand(2).getReg();
1909 Register SrcReg = MI.getOperand(1).getReg();
1910 Register DstReg = MI.getOperand(0).getReg();
1911
1912 // BB:
1913 // rjmp CheckBB
1914 BuildMI(BB, dl, TII.get(AVR::RJMPk)).addMBB(CheckBB);
1915
1916 // LoopBB:
1917 // ShiftReg2 = shift ShiftReg
1918 auto ShiftMI = BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2).addReg(ShiftReg);
1919 if (HasRepeatedOperand)
1920 ShiftMI.addReg(ShiftReg);
1921
1922 // CheckBB:
1923 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1924 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
1925 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1926 // ShiftAmt2 = ShiftAmt - 1;
1927 // if (ShiftAmt2 >= 0) goto LoopBB;
1928 BuildMI(CheckBB, dl, TII.get(AVR::PHI), ShiftReg)
1929 .addReg(SrcReg)
1930 .addMBB(BB)
1931 .addReg(ShiftReg2)
1932 .addMBB(LoopBB);
1933 BuildMI(CheckBB, dl, TII.get(AVR::PHI), ShiftAmtReg)
1934 .addReg(ShiftAmtSrcReg)
1935 .addMBB(BB)
1936 .addReg(ShiftAmtReg2)
1937 .addMBB(LoopBB);
1938 BuildMI(CheckBB, dl, TII.get(AVR::PHI), DstReg)
1939 .addReg(SrcReg)
1940 .addMBB(BB)
1941 .addReg(ShiftReg2)
1942 .addMBB(LoopBB);
1943
1944 BuildMI(CheckBB, dl, TII.get(AVR::DECRd), ShiftAmtReg2).addReg(ShiftAmtReg);
1945 BuildMI(CheckBB, dl, TII.get(AVR::BRPLk)).addMBB(LoopBB);
1946
1947 MI.eraseFromParent(); // The pseudo instruction is gone now.
1948 return RemBB;
1949}
1950
1951// Do a multibyte AVR shift. Insert shift instructions and put the output
1952// registers in the Regs array.
1953// Because AVR does not have a normal shift instruction (only a single bit shift
1954// instruction), we have to emulate this behavior with other instructions.
1955// It first tries large steps (moving registers around) and then smaller steps
1956// like single bit shifts.
1957// Large shifts actually reduce the number of shifted registers, so the below
1958// algorithms have to work independently of the number of registers that are
1959// shifted.
1960// For more information and background, see this blogpost:
1961// https://aykevl.nl/2021/02/avr-bitshift
1963 MutableArrayRef<std::pair<Register, int>> Regs,
1964 ISD::NodeType Opc, int64_t ShiftAmt) {
1966 const AVRSubtarget &STI = BB->getParent()->getSubtarget<AVRSubtarget>();
1968 const DebugLoc &dl = MI.getDebugLoc();
1969
1970 const bool ShiftLeft = Opc == ISD::SHL;
1971 const bool ArithmeticShift = Opc == ISD::SRA;
1972
1973 // Zero a register, for use in later operations.
1974 Register ZeroReg = MRI.createVirtualRegister(&AVR::GPR8RegClass);
1975 BuildMI(*BB, MI, dl, TII.get(AVR::COPY), ZeroReg)
1976 .addReg(STI.getZeroRegister());
1977
1978 // Do a shift modulo 6 or 7. This is a bit more complicated than most shifts
1979 // and is hard to compose with the rest, so these are special cased.
1980 // The basic idea is to shift one or two bits in the opposite direction and
1981 // then move registers around to get the correct end result.
1982 if (ShiftLeft && (ShiftAmt % 8) >= 6) {
1983 // Left shift modulo 6 or 7.
1984
1985 // Create a slice of the registers we're going to modify, to ease working
1986 // with them.
1987 size_t ShiftRegsOffset = ShiftAmt / 8;
1988 size_t ShiftRegsSize = Regs.size() - ShiftRegsOffset;
1990 Regs.slice(ShiftRegsOffset, ShiftRegsSize);
1991
1992 // Shift one to the right, keeping the least significant bit as the carry
1993 // bit.
1994 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SRL, 1);
1995
1996 // Rotate the least significant bit from the carry bit into a new register
1997 // (that starts out zero).
1998 Register LowByte = MRI.createVirtualRegister(&AVR::GPR8RegClass);
1999 BuildMI(*BB, MI, dl, TII.get(AVR::RORRd), LowByte).addReg(ZeroReg);
2000
2001 // Shift one more to the right if this is a modulo-6 shift.
2002 if (ShiftAmt % 8 == 6) {
2003 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SRL, 1);
2004 Register NewLowByte = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2005 BuildMI(*BB, MI, dl, TII.get(AVR::RORRd), NewLowByte).addReg(LowByte);
2006 LowByte = NewLowByte;
2007 }
2008
2009 // Move all registers to the left, zeroing the bottom registers as needed.
2010 for (size_t I = 0; I < Regs.size(); I++) {
2011 int ShiftRegsIdx = I + 1;
2012 if (ShiftRegsIdx < (int)ShiftRegs.size()) {
2013 Regs[I] = ShiftRegs[ShiftRegsIdx];
2014 } else if (ShiftRegsIdx == (int)ShiftRegs.size()) {
2015 Regs[I] = std::pair(LowByte, 0);
2016 } else {
2017 Regs[I] = std::pair(ZeroReg, 0);
2018 }
2019 }
2020
2021 return;
2022 }
2023
2024 // Right shift modulo 6 or 7.
2025 if (!ShiftLeft && (ShiftAmt % 8) >= 6) {
2026 // Create a view on the registers we're going to modify, to ease working
2027 // with them.
2028 size_t ShiftRegsSize = Regs.size() - (ShiftAmt / 8);
2030 Regs.slice(0, ShiftRegsSize);
2031
2032 // Shift one to the left.
2033 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SHL, 1);
2034
2035 // Sign or zero extend the most significant register into a new register.
2036 // The HighByte is the byte that still has one (or two) bits from the
2037 // original value. The ExtByte is purely a zero/sign extend byte (all bits
2038 // are either 0 or 1).
2039 Register HighByte = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2040 Register ExtByte = 0;
2041 if (ArithmeticShift) {
2042 // Sign-extend bit that was shifted out last.
2043 BuildMI(*BB, MI, dl, TII.get(AVR::SBCRdRr), HighByte)
2044 .addReg(HighByte, RegState::Undef)
2045 .addReg(HighByte, RegState::Undef);
2046 ExtByte = HighByte;
2047 // The highest bit of the original value is the same as the zero-extend
2048 // byte, so HighByte and ExtByte are the same.
2049 } else {
2050 // Use the zero register for zero extending.
2051 ExtByte = ZeroReg;
2052 // Rotate most significant bit into a new register (that starts out zero).
2053 BuildMI(*BB, MI, dl, TII.get(AVR::ADCRdRr), HighByte)
2054 .addReg(ExtByte)
2055 .addReg(ExtByte);
2056 }
2057
2058 // Shift one more to the left for modulo 6 shifts.
2059 if (ShiftAmt % 8 == 6) {
2060 insertMultibyteShift(MI, BB, ShiftRegs, ISD::SHL, 1);
2061 // Shift the topmost bit into the HighByte.
2062 Register NewExt = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2063 BuildMI(*BB, MI, dl, TII.get(AVR::ADCRdRr), NewExt)
2064 .addReg(HighByte)
2065 .addReg(HighByte);
2066 HighByte = NewExt;
2067 }
2068
2069 // Move all to the right, while sign or zero extending.
2070 for (int I = Regs.size() - 1; I >= 0; I--) {
2071 int ShiftRegsIdx = I - (Regs.size() - ShiftRegs.size()) - 1;
2072 if (ShiftRegsIdx >= 0) {
2073 Regs[I] = ShiftRegs[ShiftRegsIdx];
2074 } else if (ShiftRegsIdx == -1) {
2075 Regs[I] = std::pair(HighByte, 0);
2076 } else {
2077 Regs[I] = std::pair(ExtByte, 0);
2078 }
2079 }
2080
2081 return;
2082 }
2083
2084 // For shift amounts of at least one register, simply rename the registers and
2085 // zero the bottom registers.
2086 while (ShiftLeft && ShiftAmt >= 8) {
2087 // Move all registers one to the left.
2088 for (size_t I = 0; I < Regs.size() - 1; I++) {
2089 Regs[I] = Regs[I + 1];
2090 }
2091
2092 // Zero the least significant register.
2093 Regs[Regs.size() - 1] = std::pair(ZeroReg, 0);
2094
2095 // Continue shifts with the leftover registers.
2096 Regs = Regs.drop_back(1);
2097
2098 ShiftAmt -= 8;
2099 }
2100
2101 // And again, the same for right shifts.
2102 Register ShrExtendReg = 0;
2103 if (!ShiftLeft && ShiftAmt >= 8) {
2104 if (ArithmeticShift) {
2105 // Sign extend the most significant register into ShrExtendReg.
2106 ShrExtendReg = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2107 Register Tmp = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2108 BuildMI(*BB, MI, dl, TII.get(AVR::ADDRdRr), Tmp)
2109 .addReg(Regs[0].first, {}, Regs[0].second)
2110 .addReg(Regs[0].first, {}, Regs[0].second);
2111 BuildMI(*BB, MI, dl, TII.get(AVR::SBCRdRr), ShrExtendReg)
2112 .addReg(Tmp)
2113 .addReg(Tmp);
2114 } else {
2115 ShrExtendReg = ZeroReg;
2116 }
2117 for (; ShiftAmt >= 8; ShiftAmt -= 8) {
2118 // Move all registers one to the right.
2119 for (size_t I = Regs.size() - 1; I != 0; I--) {
2120 Regs[I] = Regs[I - 1];
2121 }
2122
2123 // Zero or sign extend the most significant register.
2124 Regs[0] = std::pair(ShrExtendReg, 0);
2125
2126 // Continue shifts with the leftover registers.
2127 Regs = Regs.drop_front(1);
2128 }
2129 }
2130
2131 // The bigger shifts are already handled above.
2132 assert((ShiftAmt < 8) && "Unexpect shift amount");
2133
2134 // Shift by four bits, using a complicated swap/eor/andi/eor sequence.
2135 // It only works for logical shifts because the bits shifted in are all
2136 // zeroes.
2137 // To shift a single byte right, it produces code like this:
2138 // swap r0
2139 // andi r0, 0x0f
2140 // For a two-byte (16-bit) shift, it adds the following instructions to shift
2141 // the upper byte into the lower byte:
2142 // swap r1
2143 // eor r0, r1
2144 // andi r1, 0x0f
2145 // eor r0, r1
2146 // For bigger shifts, it repeats the above sequence. For example, for a 3-byte
2147 // (24-bit) shift it adds:
2148 // swap r2
2149 // eor r1, r2
2150 // andi r2, 0x0f
2151 // eor r1, r2
2152 if (!ArithmeticShift && ShiftAmt >= 4) {
2153 Register Prev = 0;
2154 for (size_t I = 0; I < Regs.size(); I++) {
2155 size_t Idx = ShiftLeft ? I : Regs.size() - I - 1;
2156 Register SwapReg = MRI.createVirtualRegister(&AVR::LD8RegClass);
2157 BuildMI(*BB, MI, dl, TII.get(AVR::SWAPRd), SwapReg)
2158 .addReg(Regs[Idx].first, {}, Regs[Idx].second);
2159 if (I != 0) {
2160 Register R = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2161 BuildMI(*BB, MI, dl, TII.get(AVR::EORRdRr), R)
2162 .addReg(Prev)
2163 .addReg(SwapReg);
2164 Prev = R;
2165 }
2166 Register AndReg = MRI.createVirtualRegister(&AVR::LD8RegClass);
2167 BuildMI(*BB, MI, dl, TII.get(AVR::ANDIRdK), AndReg)
2168 .addReg(SwapReg)
2169 .addImm(ShiftLeft ? 0xf0 : 0x0f);
2170 if (I != 0) {
2171 Register R = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2172 BuildMI(*BB, MI, dl, TII.get(AVR::EORRdRr), R)
2173 .addReg(Prev)
2174 .addReg(AndReg);
2175 size_t PrevIdx = ShiftLeft ? Idx - 1 : Idx + 1;
2176 Regs[PrevIdx] = std::pair(R, 0);
2177 }
2178 Prev = AndReg;
2179 Regs[Idx] = std::pair(AndReg, 0);
2180 }
2181 ShiftAmt -= 4;
2182 }
2183
2184 // Shift by one. This is the fallback that always works, and the shift
2185 // operation that is used for 1, 2, and 3 bit shifts.
2186 while (ShiftLeft && ShiftAmt) {
2187 // Shift one to the left.
2188 for (ssize_t I = Regs.size() - 1; I >= 0; I--) {
2189 Register Out = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2190 Register In = Regs[I].first;
2191 Register InSubreg = Regs[I].second;
2192 if (I == (ssize_t)Regs.size() - 1) { // first iteration
2193 BuildMI(*BB, MI, dl, TII.get(AVR::ADDRdRr), Out)
2194 .addReg(In, {}, InSubreg)
2195 .addReg(In, {}, InSubreg);
2196 } else {
2197 BuildMI(*BB, MI, dl, TII.get(AVR::ADCRdRr), Out)
2198 .addReg(In, {}, InSubreg)
2199 .addReg(In, {}, InSubreg);
2200 }
2201 Regs[I] = std::pair(Out, 0);
2202 }
2203 ShiftAmt--;
2204 }
2205 while (!ShiftLeft && ShiftAmt) {
2206 // Shift one to the right.
2207 for (size_t I = 0; I < Regs.size(); I++) {
2208 Register Out = MRI.createVirtualRegister(&AVR::GPR8RegClass);
2209 Register In = Regs[I].first;
2210 Register InSubreg = Regs[I].second;
2211 if (I == 0) {
2212 unsigned Opc = ArithmeticShift ? AVR::ASRRd : AVR::LSRRd;
2213 BuildMI(*BB, MI, dl, TII.get(Opc), Out).addReg(In, {}, InSubreg);
2214 } else {
2215 BuildMI(*BB, MI, dl, TII.get(AVR::RORRd), Out).addReg(In, {}, InSubreg);
2216 }
2217 Regs[I] = std::pair(Out, 0);
2218 }
2219 ShiftAmt--;
2220 }
2221
2222 if (ShiftAmt != 0) {
2223 llvm_unreachable("don't know how to shift!"); // sanity check
2224 }
2225}
2226
2227// Do a wide (32-bit) shift.
2228MachineBasicBlock *
2229AVRTargetLowering::insertWideShift(MachineInstr &MI,
2230 MachineBasicBlock *BB) const {
2231 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2232 const DebugLoc &dl = MI.getDebugLoc();
2233
2234 // How much to shift to the right (meaning: a negative number indicates a left
2235 // shift).
2236 int64_t ShiftAmt = MI.getOperand(4).getImm();
2238 switch (MI.getOpcode()) {
2239 case AVR::Lsl32:
2240 Opc = ISD::SHL;
2241 break;
2242 case AVR::Lsr32:
2243 Opc = ISD::SRL;
2244 break;
2245 case AVR::Asr32:
2246 Opc = ISD::SRA;
2247 break;
2248 }
2249
2250 // Read the input registers, with the most significant register at index 0.
2251 std::array<std::pair<Register, int>, 4> Registers = {
2252 std::pair(MI.getOperand(3).getReg(), AVR::sub_hi),
2253 std::pair(MI.getOperand(3).getReg(), AVR::sub_lo),
2254 std::pair(MI.getOperand(2).getReg(), AVR::sub_hi),
2255 std::pair(MI.getOperand(2).getReg(), AVR::sub_lo),
2256 };
2257
2258 // Do the shift. The registers are modified in-place.
2259 insertMultibyteShift(MI, BB, Registers, Opc, ShiftAmt);
2260
2261 // Combine the 8-bit registers into 16-bit register pairs.
2262 // This done either from LSB to MSB or from MSB to LSB, depending on the
2263 // shift. It's an optimization so that the register allocator will use the
2264 // fewest movs possible (which order we use isn't a correctness issue, just an
2265 // optimization issue).
2266 // - lsl prefers starting from the most significant byte (2nd case).
2267 // - lshr prefers starting from the least significant byte (1st case).
2268 // - for ashr it depends on the number of shifted bytes.
2269 // Some shift operations still don't get the most optimal mov sequences even
2270 // with this distinction. TODO: figure out why and try to fix it (but we're
2271 // already equal to or faster than avr-gcc in all cases except ashr 8).
2272 if (Opc != ISD::SHL &&
2273 (Opc != ISD::SRA || (ShiftAmt < 16 || ShiftAmt >= 22))) {
2274 // Use the resulting registers starting with the least significant byte.
2275 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(0).getReg())
2276 .addReg(Registers[3].first, {}, Registers[3].second)
2277 .addImm(AVR::sub_lo)
2278 .addReg(Registers[2].first, {}, Registers[2].second)
2279 .addImm(AVR::sub_hi);
2280 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(1).getReg())
2281 .addReg(Registers[1].first, {}, Registers[1].second)
2282 .addImm(AVR::sub_lo)
2283 .addReg(Registers[0].first, {}, Registers[0].second)
2284 .addImm(AVR::sub_hi);
2285 } else {
2286 // Use the resulting registers starting with the most significant byte.
2287 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(1).getReg())
2288 .addReg(Registers[0].first, {}, Registers[0].second)
2289 .addImm(AVR::sub_hi)
2290 .addReg(Registers[1].first, {}, Registers[1].second)
2291 .addImm(AVR::sub_lo);
2292 BuildMI(*BB, MI, dl, TII.get(AVR::REG_SEQUENCE), MI.getOperand(0).getReg())
2293 .addReg(Registers[2].first, {}, Registers[2].second)
2294 .addImm(AVR::sub_hi)
2295 .addReg(Registers[3].first, {}, Registers[3].second)
2296 .addImm(AVR::sub_lo);
2297 }
2298
2299 // Remove the pseudo instruction.
2300 MI.eraseFromParent();
2301 return BB;
2302}
2303
2305 if (I->getOpcode() == AVR::COPY) {
2306 Register SrcReg = I->getOperand(1).getReg();
2307 return (SrcReg == AVR::R0 || SrcReg == AVR::R1);
2308 }
2309
2310 return false;
2311}
2312
2313// The mul instructions wreak havock on our zero_reg R1. We need to clear it
2314// after the result has been evacuated. This is probably not the best way to do
2315// it, but it works for now.
2316MachineBasicBlock *AVRTargetLowering::insertMul(MachineInstr &MI,
2317 MachineBasicBlock *BB) const {
2318 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2320 ++I; // in any case insert *after* the mul instruction
2321 if (isCopyMulResult(I))
2322 ++I;
2323 if (isCopyMulResult(I))
2324 ++I;
2325 BuildMI(*BB, I, MI.getDebugLoc(), TII.get(AVR::EORRdRr), AVR::R1)
2326 .addReg(AVR::R1)
2327 .addReg(AVR::R1);
2328 return BB;
2329}
2330
2331// Insert a read from the zero register.
2333AVRTargetLowering::insertCopyZero(MachineInstr &MI,
2334 MachineBasicBlock *BB) const {
2335 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2337 BuildMI(*BB, I, MI.getDebugLoc(), TII.get(AVR::COPY))
2338 .add(MI.getOperand(0))
2339 .addReg(Subtarget.getZeroRegister());
2340 MI.eraseFromParent();
2341 return BB;
2342}
2343
2344// Lower atomicrmw operation to disable interrupts, do operation, and restore
2345// interrupts. This works because all AVR microcontrollers are single core.
2346MachineBasicBlock *AVRTargetLowering::insertAtomicArithmeticOp(
2347 MachineInstr &MI, MachineBasicBlock *BB, unsigned Opcode, int Width) const {
2348 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2349 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
2351 DebugLoc dl = MI.getDebugLoc();
2352
2353 // Example instruction sequence, for an atomic 8-bit add:
2354 // ldi r25, 5
2355 // in r0, SREG
2356 // cli
2357 // ld r24, X
2358 // add r25, r24
2359 // st X, r25
2360 // out SREG, r0
2361
2362 const TargetRegisterClass *RC =
2363 (Width == 8) ? &AVR::GPR8RegClass : &AVR::DREGSNOZRegClass;
2364 unsigned LoadOpcode = (Width == 8) ? AVR::LDRdPtr : AVR::LDWRdPtr;
2365 unsigned StoreOpcode = (Width == 8) ? AVR::STPtrRr : AVR::STWPtrRr;
2366
2367 // Disable interrupts.
2368 BuildMI(*BB, I, dl, TII.get(AVR::INRdA), Subtarget.getTmpRegister())
2369 .addImm(Subtarget.getIORegSREG());
2370 BuildMI(*BB, I, dl, TII.get(AVR::BCLRs)).addImm(7);
2371
2372 // Load the original value.
2373 BuildMI(*BB, I, dl, TII.get(LoadOpcode), MI.getOperand(0).getReg())
2374 .add(MI.getOperand(1));
2375
2376 // Do the arithmetic operation.
2377 Register Result = MRI.createVirtualRegister(RC);
2378 BuildMI(*BB, I, dl, TII.get(Opcode), Result)
2379 .addReg(MI.getOperand(0).getReg())
2380 .add(MI.getOperand(2));
2381
2382 // Store the result.
2383 BuildMI(*BB, I, dl, TII.get(StoreOpcode))
2384 .add(MI.getOperand(1))
2385 .addReg(Result);
2386
2387 // Restore interrupts.
2388 BuildMI(*BB, I, dl, TII.get(AVR::OUTARr))
2389 .addImm(Subtarget.getIORegSREG())
2390 .addReg(Subtarget.getTmpRegister());
2391
2392 // Remove the pseudo instruction.
2393 MI.eraseFromParent();
2394 return BB;
2395}
2396
2399 MachineBasicBlock *MBB) const {
2400 int Opc = MI.getOpcode();
2401 const AVRSubtarget &STI = MBB->getParent()->getSubtarget<AVRSubtarget>();
2402
2403 // Pseudo shift instructions with a non constant shift amount are expanded
2404 // into a loop.
2405 switch (Opc) {
2406 case AVR::Lsl8:
2407 case AVR::Lsl16:
2408 case AVR::Lsr8:
2409 case AVR::Lsr16:
2410 case AVR::Rol8:
2411 case AVR::Rol16:
2412 case AVR::Ror8:
2413 case AVR::Ror16:
2414 case AVR::Asr8:
2415 case AVR::Asr16:
2416 return insertShift(MI, MBB, STI.hasTinyEncoding());
2417 case AVR::Lsl32:
2418 case AVR::Lsr32:
2419 case AVR::Asr32:
2420 return insertWideShift(MI, MBB);
2421 case AVR::MULRdRr:
2422 case AVR::MULSRdRr:
2423 return insertMul(MI, MBB);
2424 case AVR::CopyZero:
2425 return insertCopyZero(MI, MBB);
2426 case AVR::AtomicLoadAdd8:
2427 return insertAtomicArithmeticOp(MI, MBB, AVR::ADDRdRr, 8);
2428 case AVR::AtomicLoadAdd16:
2429 return insertAtomicArithmeticOp(MI, MBB, AVR::ADDWRdRr, 16);
2430 case AVR::AtomicLoadSub8:
2431 return insertAtomicArithmeticOp(MI, MBB, AVR::SUBRdRr, 8);
2432 case AVR::AtomicLoadSub16:
2433 return insertAtomicArithmeticOp(MI, MBB, AVR::SUBWRdRr, 16);
2434 case AVR::AtomicLoadAnd8:
2435 return insertAtomicArithmeticOp(MI, MBB, AVR::ANDRdRr, 8);
2436 case AVR::AtomicLoadAnd16:
2437 return insertAtomicArithmeticOp(MI, MBB, AVR::ANDWRdRr, 16);
2438 case AVR::AtomicLoadOr8:
2439 return insertAtomicArithmeticOp(MI, MBB, AVR::ORRdRr, 8);
2440 case AVR::AtomicLoadOr16:
2441 return insertAtomicArithmeticOp(MI, MBB, AVR::ORWRdRr, 16);
2442 case AVR::AtomicLoadXor8:
2443 return insertAtomicArithmeticOp(MI, MBB, AVR::EORRdRr, 8);
2444 case AVR::AtomicLoadXor16:
2445 return insertAtomicArithmeticOp(MI, MBB, AVR::EORWRdRr, 16);
2446 }
2447
2448 assert((Opc == AVR::Select16 || Opc == AVR::Select8) &&
2449 "Unexpected instr type to insert");
2450
2451 const AVRInstrInfo &TII = (const AVRInstrInfo &)*MI.getParent()
2452 ->getParent()
2453 ->getSubtarget()
2454 .getInstrInfo();
2455 DebugLoc dl = MI.getDebugLoc();
2456
2457 // To "insert" a SELECT instruction, we insert the diamond
2458 // control-flow pattern. The incoming instruction knows the
2459 // destination vreg to set, the condition code register to branch
2460 // on, the true/false values to select between, and a branch opcode
2461 // to use.
2462
2463 MachineFunction *MF = MBB->getParent();
2464 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
2465 MachineBasicBlock *FallThrough = MBB->getFallThrough();
2466
2467 // If the current basic block falls through to another basic block,
2468 // we must insert an unconditional branch to the fallthrough destination
2469 // if we are to insert basic blocks at the prior fallthrough point.
2470 if (FallThrough != nullptr) {
2471 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(FallThrough);
2472 }
2473
2474 MachineBasicBlock *trueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
2475 MachineBasicBlock *falseMBB = MF->CreateMachineBasicBlock(LLVM_BB);
2476
2478 for (I = MF->begin(); I != MF->end() && &(*I) != MBB; ++I)
2479 ;
2480 if (I != MF->end())
2481 ++I;
2482 MF->insert(I, trueMBB);
2483 MF->insert(I, falseMBB);
2484
2485 // Set the call frame size on entry to the new basic blocks.
2486 unsigned CallFrameSize = TII.getCallFrameSizeAt(MI);
2487 trueMBB->setCallFrameSize(CallFrameSize);
2488 falseMBB->setCallFrameSize(CallFrameSize);
2489
2490 // Transfer remaining instructions and all successors of the current
2491 // block to the block which will contain the Phi node for the
2492 // select.
2493 trueMBB->splice(trueMBB->begin(), MBB,
2494 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
2496
2497 AVRCC::CondCodes CC = (AVRCC::CondCodes)MI.getOperand(3).getImm();
2498 BuildMI(MBB, dl, TII.getBrCond(CC)).addMBB(trueMBB);
2499 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(falseMBB);
2500 MBB->addSuccessor(falseMBB);
2501 MBB->addSuccessor(trueMBB);
2502
2503 // Unconditionally flow back to the true block
2504 BuildMI(falseMBB, dl, TII.get(AVR::RJMPk)).addMBB(trueMBB);
2505 falseMBB->addSuccessor(trueMBB);
2506
2507 // Set up the Phi node to determine where we came from
2508 BuildMI(*trueMBB, trueMBB->begin(), dl, TII.get(AVR::PHI),
2509 MI.getOperand(0).getReg())
2510 .addReg(MI.getOperand(1).getReg())
2511 .addMBB(MBB)
2512 .addReg(MI.getOperand(2).getReg())
2513 .addMBB(falseMBB);
2514
2515 MI.eraseFromParent(); // The pseudo instruction is gone now.
2516 return trueMBB;
2517}
2518
2519//===----------------------------------------------------------------------===//
2520// Inline Asm Support
2521//===----------------------------------------------------------------------===//
2522
2525 if (Constraint.size() == 1) {
2526 // See http://www.nongnu.org/avr-libc/user-manual/inline_asm.html
2527 switch (Constraint[0]) {
2528 default:
2529 break;
2530 case 'a': // Simple upper registers
2531 case 'b': // Base pointer registers pairs
2532 case 'd': // Upper register
2533 case 'l': // Lower registers
2534 case 'e': // Pointer register pairs
2535 case 'q': // Stack pointer register
2536 case 'r': // Any register
2537 case 'w': // Special upper register pairs
2538 return C_RegisterClass;
2539 case 't': // Temporary register
2540 case 'x':
2541 case 'X': // Pointer register pair X
2542 case 'y':
2543 case 'Y': // Pointer register pair Y
2544 case 'z':
2545 case 'Z': // Pointer register pair Z
2546 return C_Register;
2547 case 'Q': // A memory address based on Y or Z pointer with displacement.
2548 return C_Memory;
2549 case 'G': // Floating point constant
2550 case 'I': // 6-bit positive integer constant
2551 case 'J': // 6-bit negative integer constant
2552 case 'K': // Integer constant (Range: 2)
2553 case 'L': // Integer constant (Range: 0)
2554 case 'M': // 8-bit integer constant
2555 case 'N': // Integer constant (Range: -1)
2556 case 'O': // Integer constant (Range: 8, 16, 24)
2557 case 'P': // Integer constant (Range: 1)
2558 case 'R': // Integer constant (Range: -6 to 5)x
2559 return C_Immediate;
2560 }
2561 }
2562
2563 return TargetLowering::getConstraintType(Constraint);
2564}
2565
2568 // Not sure if this is actually the right thing to do, but we got to do
2569 // *something* [agnat]
2570 switch (ConstraintCode[0]) {
2571 case 'Q':
2573 }
2574 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
2575}
2576
2579 AsmOperandInfo &info, const char *constraint) const {
2581 Value *CallOperandVal = info.CallOperandVal;
2582
2583 // If we don't have a value, we can't do a match,
2584 // but allow it at the lowest weight.
2585 // (this behaviour has been copied from the ARM backend)
2586 if (!CallOperandVal) {
2587 return CW_Default;
2588 }
2589
2590 // Look at the constraint type.
2591 switch (*constraint) {
2592 default:
2594 break;
2595 case 'd':
2596 case 'r':
2597 case 'l':
2598 weight = CW_Register;
2599 break;
2600 case 'a':
2601 case 'b':
2602 case 'e':
2603 case 'q':
2604 case 't':
2605 case 'w':
2606 case 'x':
2607 case 'X':
2608 case 'y':
2609 case 'Y':
2610 case 'z':
2611 case 'Z':
2612 weight = CW_SpecificReg;
2613 break;
2614 case 'G':
2615 if (const ConstantFP *C = dyn_cast<ConstantFP>(CallOperandVal)) {
2616 if (C->isZero()) {
2617 weight = CW_Constant;
2618 }
2619 }
2620 break;
2621 case 'I':
2622 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2623 if (isUInt<6>(C->getZExtValue())) {
2624 weight = CW_Constant;
2625 }
2626 }
2627 break;
2628 case 'J':
2629 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2630 if ((C->getSExtValue() >= -63) && (C->getSExtValue() <= 0)) {
2631 weight = CW_Constant;
2632 }
2633 }
2634 break;
2635 case 'K':
2636 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2637 if (C->getZExtValue() == 2) {
2638 weight = CW_Constant;
2639 }
2640 }
2641 break;
2642 case 'L':
2643 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2644 if (C->getZExtValue() == 0) {
2645 weight = CW_Constant;
2646 }
2647 }
2648 break;
2649 case 'M':
2650 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2651 if (isUInt<8>(C->getZExtValue())) {
2652 weight = CW_Constant;
2653 }
2654 }
2655 break;
2656 case 'N':
2657 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2658 if (C->getSExtValue() == -1) {
2659 weight = CW_Constant;
2660 }
2661 }
2662 break;
2663 case 'O':
2664 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2665 if ((C->getZExtValue() == 8) || (C->getZExtValue() == 16) ||
2666 (C->getZExtValue() == 24)) {
2667 weight = CW_Constant;
2668 }
2669 }
2670 break;
2671 case 'P':
2672 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2673 if (C->getZExtValue() == 1) {
2674 weight = CW_Constant;
2675 }
2676 }
2677 break;
2678 case 'R':
2679 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
2680 if ((C->getSExtValue() >= -6) && (C->getSExtValue() <= 5)) {
2681 weight = CW_Constant;
2682 }
2683 }
2684 break;
2685 case 'Q':
2686 weight = CW_Memory;
2687 break;
2688 }
2689
2690 return weight;
2691}
2692
2693std::pair<unsigned, const TargetRegisterClass *>
2695 StringRef Constraint,
2696 MVT VT) const {
2697 if (Constraint.size() == 1) {
2698 switch (Constraint[0]) {
2699 case 'a': // Simple upper registers r16..r23.
2700 if (VT == MVT::i8)
2701 return std::make_pair(0U, &AVR::LD8loRegClass);
2702 else if (VT == MVT::i16)
2703 return std::make_pair(0U, &AVR::DREGSLD8loRegClass);
2704 break;
2705 case 'b': // Base pointer registers: y, z.
2706 if (VT == MVT::i8 || VT == MVT::i16)
2707 return std::make_pair(0U, &AVR::PTRDISPREGSRegClass);
2708 break;
2709 case 'd': // Upper registers r16..r31.
2710 if (VT == MVT::i8)
2711 return std::make_pair(0U, &AVR::LD8RegClass);
2712 else if (VT == MVT::i16)
2713 return std::make_pair(0U, &AVR::DLDREGSRegClass);
2714 break;
2715 case 'l': // Lower registers r0..r15.
2716 if (VT == MVT::i8)
2717 return std::make_pair(0U, &AVR::GPR8loRegClass);
2718 else if (VT == MVT::i16)
2719 return std::make_pair(0U, &AVR::DREGSloRegClass);
2720 break;
2721 case 'e': // Pointer register pairs: x, y, z.
2722 if (VT == MVT::i8 || VT == MVT::i16)
2723 return std::make_pair(0U, &AVR::PTRREGSRegClass);
2724 break;
2725 case 'q': // Stack pointer register: SPH:SPL.
2726 return std::make_pair(0U, &AVR::GPRSPRegClass);
2727 case 'r': // Any register: r0..r31.
2728 if (VT == MVT::i8)
2729 return std::make_pair(0U, &AVR::GPR8RegClass);
2730 else if (VT == MVT::i16)
2731 return std::make_pair(0U, &AVR::DREGSRegClass);
2732 break;
2733 case 't': // Temporary register: r0.
2734 if (VT == MVT::i8)
2735 return std::make_pair(unsigned(Subtarget.getTmpRegister()),
2736 &AVR::GPR8RegClass);
2737 break;
2738 case 'w': // Special upper register pairs: r24, r26, r28, r30.
2739 if (VT == MVT::i8 || VT == MVT::i16)
2740 return std::make_pair(0U, &AVR::IWREGSRegClass);
2741 break;
2742 case 'x': // Pointer register pair X: r27:r26.
2743 case 'X':
2744 if (VT == MVT::i8 || VT == MVT::i16)
2745 return std::make_pair(unsigned(AVR::R27R26), &AVR::PTRREGSRegClass);
2746 break;
2747 case 'y': // Pointer register pair Y: r29:r28.
2748 case 'Y':
2749 if (VT == MVT::i8 || VT == MVT::i16)
2750 return std::make_pair(unsigned(AVR::R29R28), &AVR::PTRREGSRegClass);
2751 break;
2752 case 'z': // Pointer register pair Z: r31:r30.
2753 case 'Z':
2754 if (VT == MVT::i8 || VT == MVT::i16)
2755 return std::make_pair(unsigned(AVR::R31R30), &AVR::PTRREGSRegClass);
2756 break;
2757 default:
2758 break;
2759 }
2760 }
2761
2763 Subtarget.getRegisterInfo(), Constraint, VT);
2764}
2765
2767 StringRef Constraint,
2768 std::vector<SDValue> &Ops,
2769 SelectionDAG &DAG) const {
2770 SDValue Result;
2771 SDLoc DL(Op);
2772 EVT Ty = Op.getValueType();
2773
2774 // Currently only support length 1 constraints.
2775 if (Constraint.size() != 1) {
2776 return;
2777 }
2778
2779 char ConstraintLetter = Constraint[0];
2780 switch (ConstraintLetter) {
2781 default:
2782 break;
2783 // Deal with integers first:
2784 case 'I':
2785 case 'J':
2786 case 'K':
2787 case 'L':
2788 case 'M':
2789 case 'N':
2790 case 'O':
2791 case 'P':
2792 case 'R': {
2794 if (!C) {
2795 return;
2796 }
2797
2798 int64_t CVal64 = C->getSExtValue();
2799 uint64_t CUVal64 = C->getZExtValue();
2800 switch (ConstraintLetter) {
2801 case 'I': // 0..63
2802 if (!isUInt<6>(CUVal64))
2803 return;
2804 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2805 break;
2806 case 'J': // -63..0
2807 if (CVal64 < -63 || CVal64 > 0)
2808 return;
2809 Result = DAG.getTargetConstant(CVal64, DL, Ty);
2810 break;
2811 case 'K': // 2
2812 if (CUVal64 != 2)
2813 return;
2814 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2815 break;
2816 case 'L': // 0
2817 if (CUVal64 != 0)
2818 return;
2819 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2820 break;
2821 case 'M': // 0..255
2822 if (!isUInt<8>(CUVal64))
2823 return;
2824 // i8 type may be printed as a negative number,
2825 // e.g. 254 would be printed as -2,
2826 // so we force it to i16 at least.
2827 if (Ty.getSimpleVT() == MVT::i8) {
2828 Ty = MVT::i16;
2829 }
2830 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2831 break;
2832 case 'N': // -1
2833 if (CVal64 != -1)
2834 return;
2835 Result = DAG.getTargetConstant(CVal64, DL, Ty);
2836 break;
2837 case 'O': // 8, 16, 24
2838 if (CUVal64 != 8 && CUVal64 != 16 && CUVal64 != 24)
2839 return;
2840 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2841 break;
2842 case 'P': // 1
2843 if (CUVal64 != 1)
2844 return;
2845 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
2846 break;
2847 case 'R': // -6..5
2848 if (CVal64 < -6 || CVal64 > 5)
2849 return;
2850 Result = DAG.getTargetConstant(CVal64, DL, Ty);
2851 break;
2852 }
2853
2854 break;
2855 }
2856 case 'G':
2858 if (!FC || !FC->isZero())
2859 return;
2860 // Soften float to i8 0
2861 Result = DAG.getTargetConstant(0, DL, MVT::i8);
2862 break;
2863 }
2864
2865 if (Result.getNode()) {
2866 Ops.push_back(Result);
2867 return;
2868 }
2869
2870 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
2871}
2872
2874 const MachineFunction &MF) const {
2875 Register Reg;
2876
2877 if (VT == LLT::scalar(8)) {
2879 .Case("r0", AVR::R0)
2880 .Case("r1", AVR::R1)
2881 .Default(0);
2882 } else {
2884 .Case("r0", AVR::R1R0)
2885 .Case("sp", AVR::SP)
2886 .Default(0);
2887 }
2888
2889 if (Reg)
2890 return Reg;
2891
2893 Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
2894}
2895
2896} // end of namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
AMDGPU Reserve WWM Registers
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
lazy value info
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
Value * RHS
Value * LHS
Utilities related to the AVR instruction set.
A specific AVR target MCU.
Register getZeroRegister() const
const AVRInstrInfo * getInstrInfo() const override
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
Replace a node with an illegal result type with a new node built out of custom code.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
bool getPreIndexedAddressParts(SDNode *N, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const override
Returns true by value, base pointer and offset pointer and addressing mode by reference if the node's...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
ConstraintType getConstraintType(StringRef Constraint) const override
Given a constraint, return the type of constraint it is for this target.
const AVRSubtarget & Subtarget
InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const override
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const override
Examine constraint string and operand type and determine a weight value.
bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override
Return true if folding a constant offset with the given GlobalAddress is legal.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
AVRTargetLowering(const AVRTargetMachine &TM, const AVRSubtarget &STI)
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
Return the ValueType of the result of SETCC operations.
bool getPostIndexedAddressParts(SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const override
Returns true by value, base pointer and offset pointer and addressing mode by reference if this node ...
A generic AVR implementation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
LLVM Basic Block Representation.
Definition BasicBlock.h:62
CCState - This class holds information needed while lowering arguments and return values.
MCRegister AllocateReg(MCPhysReg Reg)
AllocateReg - Attempt to allocate one register.
LLVMContext & getContext() const
int64_t AllocateStack(unsigned Size, Align Alignment)
AllocateStack - Allocate a chunk of stack space with the specified size and alignment.
void addLoc(const CCValAssign &V)
static CCValAssign getReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP, bool IsCustom=false)
static CCValAssign getMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP, bool IsCustom=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
A debug info location.
Definition DebugLoc.h:126
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This class is used to represent ISD::LOAD nodes.
Machine Value Type.
static auto integer_valuetypes()
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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.
void setFrameAddressIsTaken(bool T)
void setReturnAddressIsTaken(bool s)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
BasicBlockListType::iterator iterator
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
MutableArrayRef< T > slice(size_t N, size_t M) const
Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:372
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDValue getValue(unsigned R) const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
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.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
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)
MachineFunction & getMachineFunction() const
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...
This class is used to represent ISD::STORE nodes.
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)
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:467
TargetInstrInfo - Interface to description of machine instruction set.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
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...
void setIndexedLoadAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed load does or does not work with the specified type and indicate w...
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.
void setIndexedStoreAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed store does or does not work with the specified type and indicate ...
void setSupportsUnalignedAtomics(bool UnalignedSupported)
Sets whether unaligned atomic operations are supported.
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...
void setMinimumJumpTableEntries(unsigned Val)
Indicate the minimum number of blocks to generate jump tables.
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....
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
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
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.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
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.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
CondCodes
AVR specific condition codes.
@ COND_SH
Unsigned same or higher.
@ COND_GE
Greater than or equal.
@ COND_MI
Minus.
@ COND_LO
Unsigned lower.
@ COND_LT
Less than.
@ COND_PL
Plus.
@ COND_EQ
Equal.
@ COND_NE
Not equal.
bool isProgramMemoryAccess(MemSDNode const *N)
Definition AVR.h:75
@ ProgramMemory
Definition AVR.h:45
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.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AVR_BUILTIN
Used for special AVR rtlib functions which have an "optimized" convention to preserve registers.
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ 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
@ 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...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:254
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ BR_CC
BR_CC - Conditional branch.
@ BR_JT
BR_JT - Jumptable branch.
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ 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,...
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:898
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:110
@ 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,...
@ 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
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
static void analyzeReturnValues(const SmallVectorImpl< ArgT > &Args, CCState &CCInfo, bool Tiny)
Analyze incoming and outgoing value of returning from a function.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
static const MCPhysReg RegList16Tiny[]
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
static const MCPhysReg RegList8Tiny[]
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
static void analyzeArguments(TargetLowering::CallLoweringInfo *CLI, const Function *F, const DataLayout *TD, const SmallVectorImpl< ArgT > &Args, SmallVectorImpl< CCValAssign > &ArgLocs, CCState &CCInfo, bool Tiny)
Analyze incoming and outgoing function arguments.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
static const MCPhysReg RegList16AVR[]
@ Sub
Subtraction of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
static unsigned getTotalArgumentsSizeInBytes(const SmallVectorImpl< ArgT > &Args)
Count the total number of bytes needed to pass or return these arguments.
DWARFExpression::Operation Op
static AVRCC::CondCodes intCCToAVRCC(ISD::CondCode CC)
IntCCToAVRCC - Convert a DAG integer condition code to an AVR CC.
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static bool isCopyMulResult(MachineBasicBlock::iterator const &I)
static void insertMultibyteShift(MachineInstr &MI, MachineBasicBlock *BB, MutableArrayRef< std::pair< Register, int > > Regs, ISD::NodeType Opc, int64_t ShiftAmt)
static const MCPhysReg RegList8AVR[]
Registers for calling conventions, ordered in reverse as required by ABI.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
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 an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This contains information for each constraint that we are lowering.
This structure contains all information that is necessary for lowering calls.