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" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/StringSwitch.h" 19 #include "llvm/CodeGen/CallingConvLower.h" 20 #include "llvm/CodeGen/MachineFrameInfo.h" 21 #include "llvm/CodeGen/MachineInstrBuilder.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/CodeGen/SelectionDAG.h" 24 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/Support/ErrorHandling.h" 27 28 #include "AVR.h" 29 #include "AVRMachineFunctionInfo.h" 30 #include "AVRSubtarget.h" 31 #include "AVRTargetMachine.h" 32 #include "MCTargetDesc/AVRMCTargetDesc.h" 33 34 namespace llvm { 35 36 AVRTargetLowering::AVRTargetLowering(const AVRTargetMachine &TM, 37 const AVRSubtarget &STI) 38 : TargetLowering(TM), Subtarget(STI) { 39 // Set up the register classes. 40 addRegisterClass(MVT::i8, &AVR::GPR8RegClass); 41 addRegisterClass(MVT::i16, &AVR::DREGSRegClass); 42 43 // Compute derived properties from the register classes. 44 computeRegisterProperties(Subtarget.getRegisterInfo()); 45 46 setBooleanContents(ZeroOrOneBooleanContent); 47 setBooleanVectorContents(ZeroOrOneBooleanContent); 48 setSchedulingPreference(Sched::RegPressure); 49 setStackPointerRegisterToSaveRestore(AVR::SP); 50 setSupportsUnalignedAtomics(true); 51 52 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom); 53 setOperationAction(ISD::BlockAddress, MVT::i16, Custom); 54 55 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 56 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 57 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand); 58 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand); 59 60 for (MVT VT : MVT::integer_valuetypes()) { 61 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) { 62 setLoadExtAction(N, VT, MVT::i1, Promote); 63 setLoadExtAction(N, VT, MVT::i8, Expand); 64 } 65 } 66 67 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 68 69 for (MVT VT : MVT::integer_valuetypes()) { 70 setOperationAction(ISD::ADDC, VT, Legal); 71 setOperationAction(ISD::SUBC, VT, Legal); 72 setOperationAction(ISD::ADDE, VT, Legal); 73 setOperationAction(ISD::SUBE, VT, Legal); 74 } 75 76 // sub (x, imm) gets canonicalized to add (x, -imm), so for illegal types 77 // revert into a sub since we don't have an add with immediate instruction. 78 setOperationAction(ISD::ADD, MVT::i32, Custom); 79 setOperationAction(ISD::ADD, MVT::i64, Custom); 80 81 // our shift instructions are only able to shift 1 bit at a time, so handle 82 // this in a custom way. 83 setOperationAction(ISD::SRA, MVT::i8, Custom); 84 setOperationAction(ISD::SHL, MVT::i8, Custom); 85 setOperationAction(ISD::SRL, MVT::i8, Custom); 86 setOperationAction(ISD::SRA, MVT::i16, Custom); 87 setOperationAction(ISD::SHL, MVT::i16, Custom); 88 setOperationAction(ISD::SRL, MVT::i16, Custom); 89 setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand); 90 setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand); 91 setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand); 92 93 setOperationAction(ISD::ROTL, MVT::i8, Custom); 94 setOperationAction(ISD::ROTL, MVT::i16, Expand); 95 setOperationAction(ISD::ROTR, MVT::i8, Custom); 96 setOperationAction(ISD::ROTR, MVT::i16, Expand); 97 98 setOperationAction(ISD::BR_CC, MVT::i8, Custom); 99 setOperationAction(ISD::BR_CC, MVT::i16, Custom); 100 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 101 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 102 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 103 104 setOperationAction(ISD::SELECT_CC, MVT::i8, Custom); 105 setOperationAction(ISD::SELECT_CC, MVT::i16, Custom); 106 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 107 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 108 setOperationAction(ISD::SETCC, MVT::i8, Custom); 109 setOperationAction(ISD::SETCC, MVT::i16, Custom); 110 setOperationAction(ISD::SETCC, MVT::i32, Custom); 111 setOperationAction(ISD::SETCC, MVT::i64, Custom); 112 setOperationAction(ISD::SELECT, MVT::i8, Expand); 113 setOperationAction(ISD::SELECT, MVT::i16, Expand); 114 115 setOperationAction(ISD::BSWAP, MVT::i16, Expand); 116 117 // Add support for postincrement and predecrement load/stores. 118 setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal); 119 setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal); 120 setIndexedLoadAction(ISD::PRE_DEC, MVT::i8, Legal); 121 setIndexedLoadAction(ISD::PRE_DEC, MVT::i16, Legal); 122 setIndexedStoreAction(ISD::POST_INC, MVT::i8, Legal); 123 setIndexedStoreAction(ISD::POST_INC, MVT::i16, Legal); 124 setIndexedStoreAction(ISD::PRE_DEC, MVT::i8, Legal); 125 setIndexedStoreAction(ISD::PRE_DEC, MVT::i16, Legal); 126 127 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 128 129 setOperationAction(ISD::VASTART, MVT::Other, Custom); 130 setOperationAction(ISD::VAEND, MVT::Other, Expand); 131 setOperationAction(ISD::VAARG, MVT::Other, Expand); 132 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 133 134 // Atomic operations which must be lowered to rtlib calls 135 for (MVT VT : MVT::integer_valuetypes()) { 136 setOperationAction(ISD::ATOMIC_SWAP, VT, Expand); 137 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Expand); 138 setOperationAction(ISD::ATOMIC_LOAD_NAND, VT, Expand); 139 setOperationAction(ISD::ATOMIC_LOAD_MAX, VT, Expand); 140 setOperationAction(ISD::ATOMIC_LOAD_MIN, VT, Expand); 141 setOperationAction(ISD::ATOMIC_LOAD_UMAX, VT, Expand); 142 setOperationAction(ISD::ATOMIC_LOAD_UMIN, VT, Expand); 143 } 144 145 // Division/remainder 146 setOperationAction(ISD::UDIV, MVT::i8, Expand); 147 setOperationAction(ISD::UDIV, MVT::i16, Expand); 148 setOperationAction(ISD::UREM, MVT::i8, Expand); 149 setOperationAction(ISD::UREM, MVT::i16, Expand); 150 setOperationAction(ISD::SDIV, MVT::i8, Expand); 151 setOperationAction(ISD::SDIV, MVT::i16, Expand); 152 setOperationAction(ISD::SREM, MVT::i8, Expand); 153 setOperationAction(ISD::SREM, MVT::i16, Expand); 154 155 // Make division and modulus custom 156 setOperationAction(ISD::UDIVREM, MVT::i8, Custom); 157 setOperationAction(ISD::UDIVREM, MVT::i16, Custom); 158 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 159 setOperationAction(ISD::SDIVREM, MVT::i8, Custom); 160 setOperationAction(ISD::SDIVREM, MVT::i16, Custom); 161 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 162 163 // Do not use MUL. The AVR instructions are closer to SMUL_LOHI &co. 164 setOperationAction(ISD::MUL, MVT::i8, Expand); 165 setOperationAction(ISD::MUL, MVT::i16, Expand); 166 167 // Expand 16 bit multiplications. 168 setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand); 169 setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand); 170 171 // Expand multiplications to libcalls when there is 172 // no hardware MUL. 173 if (!Subtarget.supportsMultiplication()) { 174 setOperationAction(ISD::SMUL_LOHI, MVT::i8, Expand); 175 setOperationAction(ISD::UMUL_LOHI, MVT::i8, Expand); 176 } 177 178 for (MVT VT : MVT::integer_valuetypes()) { 179 setOperationAction(ISD::MULHS, VT, Expand); 180 setOperationAction(ISD::MULHU, VT, Expand); 181 } 182 183 for (MVT VT : MVT::integer_valuetypes()) { 184 setOperationAction(ISD::CTPOP, VT, Expand); 185 setOperationAction(ISD::CTLZ, VT, Expand); 186 setOperationAction(ISD::CTTZ, VT, Expand); 187 } 188 189 for (MVT VT : MVT::integer_valuetypes()) { 190 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 191 // TODO: The generated code is pretty poor. Investigate using the 192 // same "shift and subtract with carry" trick that we do for 193 // extending 8-bit to 16-bit. This may require infrastructure 194 // improvements in how we treat 16-bit "registers" to be feasible. 195 } 196 197 // Division rtlib functions (not supported), use divmod functions instead 198 setLibcallName(RTLIB::SDIV_I8, nullptr); 199 setLibcallName(RTLIB::SDIV_I16, nullptr); 200 setLibcallName(RTLIB::SDIV_I32, nullptr); 201 setLibcallName(RTLIB::UDIV_I8, nullptr); 202 setLibcallName(RTLIB::UDIV_I16, nullptr); 203 setLibcallName(RTLIB::UDIV_I32, nullptr); 204 205 // Modulus rtlib functions (not supported), use divmod functions instead 206 setLibcallName(RTLIB::SREM_I8, nullptr); 207 setLibcallName(RTLIB::SREM_I16, nullptr); 208 setLibcallName(RTLIB::SREM_I32, nullptr); 209 setLibcallName(RTLIB::UREM_I8, nullptr); 210 setLibcallName(RTLIB::UREM_I16, nullptr); 211 setLibcallName(RTLIB::UREM_I32, nullptr); 212 213 // Division and modulus rtlib functions 214 setLibcallName(RTLIB::SDIVREM_I8, "__divmodqi4"); 215 setLibcallName(RTLIB::SDIVREM_I16, "__divmodhi4"); 216 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 217 setLibcallName(RTLIB::UDIVREM_I8, "__udivmodqi4"); 218 setLibcallName(RTLIB::UDIVREM_I16, "__udivmodhi4"); 219 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 220 221 // Several of the runtime library functions use a special calling conv 222 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::AVR_BUILTIN); 223 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::AVR_BUILTIN); 224 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::AVR_BUILTIN); 225 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::AVR_BUILTIN); 226 227 // Trigonometric rtlib functions 228 setLibcallName(RTLIB::SIN_F32, "sin"); 229 setLibcallName(RTLIB::COS_F32, "cos"); 230 231 setMinFunctionAlignment(Align(2)); 232 setMinimumJumpTableEntries(UINT_MAX); 233 } 234 235 const char *AVRTargetLowering::getTargetNodeName(unsigned Opcode) const { 236 #define NODE(name) \ 237 case AVRISD::name: \ 238 return #name 239 240 switch (Opcode) { 241 default: 242 return nullptr; 243 NODE(RET_FLAG); 244 NODE(RETI_FLAG); 245 NODE(CALL); 246 NODE(WRAPPER); 247 NODE(LSL); 248 NODE(LSR); 249 NODE(ROL); 250 NODE(ROR); 251 NODE(ASR); 252 NODE(LSLLOOP); 253 NODE(LSRLOOP); 254 NODE(ROLLOOP); 255 NODE(RORLOOP); 256 NODE(ASRLOOP); 257 NODE(BRCOND); 258 NODE(CMP); 259 NODE(CMPC); 260 NODE(TST); 261 NODE(SELECT_CC); 262 #undef NODE 263 } 264 } 265 266 EVT AVRTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 267 EVT VT) const { 268 assert(!VT.isVector() && "No AVR SetCC type for vectors!"); 269 return MVT::i8; 270 } 271 272 SDValue AVRTargetLowering::LowerShifts(SDValue Op, SelectionDAG &DAG) const { 273 //: TODO: this function has to be completely rewritten to produce optimal 274 // code, for now it's producing very long but correct code. 275 unsigned Opc8; 276 const SDNode *N = Op.getNode(); 277 EVT VT = Op.getValueType(); 278 SDLoc dl(N); 279 assert(isPowerOf2_32(VT.getSizeInBits()) && 280 "Expected power-of-2 shift amount"); 281 282 // Expand non-constant shifts to loops. 283 if (!isa<ConstantSDNode>(N->getOperand(1))) { 284 switch (Op.getOpcode()) { 285 default: 286 llvm_unreachable("Invalid shift opcode!"); 287 case ISD::SHL: 288 return DAG.getNode(AVRISD::LSLLOOP, dl, VT, N->getOperand(0), 289 N->getOperand(1)); 290 case ISD::SRL: 291 return DAG.getNode(AVRISD::LSRLOOP, dl, VT, N->getOperand(0), 292 N->getOperand(1)); 293 case ISD::ROTL: { 294 SDValue Amt = N->getOperand(1); 295 EVT AmtVT = Amt.getValueType(); 296 Amt = DAG.getNode(ISD::AND, dl, AmtVT, Amt, 297 DAG.getConstant(VT.getSizeInBits() - 1, dl, AmtVT)); 298 return DAG.getNode(AVRISD::ROLLOOP, dl, VT, N->getOperand(0), Amt); 299 } 300 case ISD::ROTR: { 301 SDValue Amt = N->getOperand(1); 302 EVT AmtVT = Amt.getValueType(); 303 Amt = DAG.getNode(ISD::AND, dl, AmtVT, Amt, 304 DAG.getConstant(VT.getSizeInBits() - 1, dl, AmtVT)); 305 return DAG.getNode(AVRISD::RORLOOP, dl, VT, N->getOperand(0), Amt); 306 } 307 case ISD::SRA: 308 return DAG.getNode(AVRISD::ASRLOOP, dl, VT, N->getOperand(0), 309 N->getOperand(1)); 310 } 311 } 312 313 uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 314 SDValue Victim = N->getOperand(0); 315 316 switch (Op.getOpcode()) { 317 case ISD::SRA: 318 Opc8 = AVRISD::ASR; 319 break; 320 case ISD::ROTL: 321 Opc8 = AVRISD::ROL; 322 ShiftAmount = ShiftAmount % VT.getSizeInBits(); 323 break; 324 case ISD::ROTR: 325 Opc8 = AVRISD::ROR; 326 ShiftAmount = ShiftAmount % VT.getSizeInBits(); 327 break; 328 case ISD::SRL: 329 Opc8 = AVRISD::LSR; 330 break; 331 case ISD::SHL: 332 Opc8 = AVRISD::LSL; 333 break; 334 default: 335 llvm_unreachable("Invalid shift opcode"); 336 } 337 338 // Optimize int8/int16 shifts. 339 if (VT.getSizeInBits() == 8) { 340 if (Op.getOpcode() == ISD::SHL && 4 <= ShiftAmount && ShiftAmount < 7) { 341 // Optimize LSL when 4 <= ShiftAmount <= 6. 342 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim); 343 Victim = 344 DAG.getNode(ISD::AND, dl, VT, Victim, DAG.getConstant(0xf0, dl, VT)); 345 ShiftAmount -= 4; 346 } else if (Op.getOpcode() == ISD::SRL && 4 <= ShiftAmount && 347 ShiftAmount < 7) { 348 // Optimize LSR when 4 <= ShiftAmount <= 6. 349 Victim = DAG.getNode(AVRISD::SWAP, dl, VT, Victim); 350 Victim = 351 DAG.getNode(ISD::AND, dl, VT, Victim, DAG.getConstant(0x0f, dl, VT)); 352 ShiftAmount -= 4; 353 } else if (Op.getOpcode() == ISD::SHL && ShiftAmount == 7) { 354 // Optimize LSL when ShiftAmount == 7. 355 Victim = DAG.getNode(AVRISD::LSLBN, dl, VT, Victim, 356 DAG.getConstant(7, dl, VT)); 357 ShiftAmount = 0; 358 } else if (Op.getOpcode() == ISD::SRL && ShiftAmount == 7) { 359 // Optimize LSR when ShiftAmount == 7. 360 Victim = DAG.getNode(AVRISD::LSRBN, dl, VT, Victim, 361 DAG.getConstant(7, dl, VT)); 362 ShiftAmount = 0; 363 } else if (Op.getOpcode() == ISD::SRA && ShiftAmount == 6) { 364 // Optimize ASR when ShiftAmount == 6. 365 Victim = DAG.getNode(AVRISD::ASRBN, dl, VT, Victim, 366 DAG.getConstant(6, dl, VT)); 367 ShiftAmount = 0; 368 } else if (Op.getOpcode() == ISD::SRA && ShiftAmount == 7) { 369 // Optimize ASR when ShiftAmount == 7. 370 Victim = DAG.getNode(AVRISD::ASRBN, dl, VT, Victim, 371 DAG.getConstant(7, dl, VT)); 372 ShiftAmount = 0; 373 } 374 } else if (VT.getSizeInBits() == 16) { 375 if (4 <= ShiftAmount && ShiftAmount < 8) 376 switch (Op.getOpcode()) { 377 case ISD::SHL: 378 Victim = DAG.getNode(AVRISD::LSLWN, dl, VT, Victim, 379 DAG.getConstant(4, dl, VT)); 380 ShiftAmount -= 4; 381 break; 382 case ISD::SRL: 383 Victim = DAG.getNode(AVRISD::LSRWN, dl, VT, Victim, 384 DAG.getConstant(4, dl, VT)); 385 ShiftAmount -= 4; 386 break; 387 default: 388 break; 389 } 390 else if (8 <= ShiftAmount && ShiftAmount < 12) 391 switch (Op.getOpcode()) { 392 case ISD::SHL: 393 Victim = DAG.getNode(AVRISD::LSLWN, dl, VT, Victim, 394 DAG.getConstant(8, dl, VT)); 395 ShiftAmount -= 8; 396 // Only operate on the higher byte for remaining shift bits. 397 Opc8 = AVRISD::LSLHI; 398 break; 399 case ISD::SRL: 400 Victim = DAG.getNode(AVRISD::LSRWN, dl, VT, Victim, 401 DAG.getConstant(8, dl, VT)); 402 ShiftAmount -= 8; 403 // Only operate on the lower byte for remaining shift bits. 404 Opc8 = AVRISD::LSRLO; 405 break; 406 case ISD::SRA: 407 Victim = DAG.getNode(AVRISD::ASRWN, dl, VT, Victim, 408 DAG.getConstant(8, dl, VT)); 409 ShiftAmount -= 8; 410 // Only operate on the lower byte for remaining shift bits. 411 Opc8 = AVRISD::ASRLO; 412 break; 413 default: 414 break; 415 } 416 else if (12 <= ShiftAmount) 417 switch (Op.getOpcode()) { 418 case ISD::SHL: 419 Victim = DAG.getNode(AVRISD::LSLWN, dl, VT, Victim, 420 DAG.getConstant(12, dl, VT)); 421 ShiftAmount -= 12; 422 // Only operate on the higher byte for remaining shift bits. 423 Opc8 = AVRISD::LSLHI; 424 break; 425 case ISD::SRL: 426 Victim = DAG.getNode(AVRISD::LSRWN, dl, VT, Victim, 427 DAG.getConstant(12, dl, VT)); 428 ShiftAmount -= 12; 429 // Only operate on the lower byte for remaining shift bits. 430 Opc8 = AVRISD::LSRLO; 431 break; 432 case ISD::SRA: 433 Victim = DAG.getNode(AVRISD::ASRWN, 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::ASRLO; 438 break; 439 default: 440 break; 441 } 442 } 443 444 while (ShiftAmount--) { 445 Victim = DAG.getNode(Opc8, dl, VT, Victim); 446 } 447 448 return Victim; 449 } 450 451 SDValue AVRTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 452 unsigned Opcode = Op->getOpcode(); 453 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 454 "Invalid opcode for Div/Rem lowering"); 455 bool IsSigned = (Opcode == ISD::SDIVREM); 456 EVT VT = Op->getValueType(0); 457 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 458 459 RTLIB::Libcall LC; 460 switch (VT.getSimpleVT().SimpleTy) { 461 default: 462 llvm_unreachable("Unexpected request for libcall!"); 463 case MVT::i8: 464 LC = IsSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; 465 break; 466 case MVT::i16: 467 LC = IsSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; 468 break; 469 case MVT::i32: 470 LC = IsSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; 471 break; 472 } 473 474 SDValue InChain = DAG.getEntryNode(); 475 476 TargetLowering::ArgListTy Args; 477 TargetLowering::ArgListEntry Entry; 478 for (SDValue const &Value : Op->op_values()) { 479 Entry.Node = Value; 480 Entry.Ty = Value.getValueType().getTypeForEVT(*DAG.getContext()); 481 Entry.IsSExt = IsSigned; 482 Entry.IsZExt = !IsSigned; 483 Args.push_back(Entry); 484 } 485 486 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 487 getPointerTy(DAG.getDataLayout())); 488 489 Type *RetTy = (Type *)StructType::get(Ty, Ty); 490 491 SDLoc dl(Op); 492 TargetLowering::CallLoweringInfo CLI(DAG); 493 CLI.setDebugLoc(dl) 494 .setChain(InChain) 495 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 496 .setInRegister() 497 .setSExtResult(IsSigned) 498 .setZExtResult(!IsSigned); 499 500 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 501 return CallInfo.first; 502 } 503 504 SDValue AVRTargetLowering::LowerGlobalAddress(SDValue Op, 505 SelectionDAG &DAG) const { 506 auto DL = DAG.getDataLayout(); 507 508 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 509 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 510 511 // Create the TargetGlobalAddress node, folding in the constant offset. 512 SDValue Result = 513 DAG.getTargetGlobalAddress(GV, SDLoc(Op), getPointerTy(DL), Offset); 514 return DAG.getNode(AVRISD::WRAPPER, SDLoc(Op), getPointerTy(DL), Result); 515 } 516 517 SDValue AVRTargetLowering::LowerBlockAddress(SDValue Op, 518 SelectionDAG &DAG) const { 519 auto DL = DAG.getDataLayout(); 520 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 521 522 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(DL)); 523 524 return DAG.getNode(AVRISD::WRAPPER, SDLoc(Op), getPointerTy(DL), Result); 525 } 526 527 /// IntCCToAVRCC - Convert a DAG integer condition code to an AVR CC. 528 static AVRCC::CondCodes intCCToAVRCC(ISD::CondCode CC) { 529 switch (CC) { 530 default: 531 llvm_unreachable("Unknown condition code!"); 532 case ISD::SETEQ: 533 return AVRCC::COND_EQ; 534 case ISD::SETNE: 535 return AVRCC::COND_NE; 536 case ISD::SETGE: 537 return AVRCC::COND_GE; 538 case ISD::SETLT: 539 return AVRCC::COND_LT; 540 case ISD::SETUGE: 541 return AVRCC::COND_SH; 542 case ISD::SETULT: 543 return AVRCC::COND_LO; 544 } 545 } 546 547 /// Returns appropriate CP/CPI/CPC nodes code for the given 8/16-bit operands. 548 SDValue AVRTargetLowering::getAVRCmp(SDValue LHS, SDValue RHS, 549 SelectionDAG &DAG, SDLoc DL) const { 550 assert((LHS.getSimpleValueType() == RHS.getSimpleValueType()) && 551 "LHS and RHS have different types"); 552 assert(((LHS.getSimpleValueType() == MVT::i16) || 553 (LHS.getSimpleValueType() == MVT::i8)) && 554 "invalid comparison type"); 555 556 SDValue Cmp; 557 558 if (LHS.getSimpleValueType() == MVT::i16 && isa<ConstantSDNode>(RHS)) { 559 // Generate a CPI/CPC pair if RHS is a 16-bit constant. 560 SDValue LHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS, 561 DAG.getIntPtrConstant(0, DL)); 562 SDValue LHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS, 563 DAG.getIntPtrConstant(1, DL)); 564 SDValue RHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, RHS, 565 DAG.getIntPtrConstant(0, DL)); 566 SDValue RHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, RHS, 567 DAG.getIntPtrConstant(1, DL)); 568 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHSlo, RHSlo); 569 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHShi, RHShi, Cmp); 570 } else { 571 // Generate ordinary 16-bit comparison. 572 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHS, RHS); 573 } 574 575 return Cmp; 576 } 577 578 /// Returns appropriate AVR CMP/CMPC nodes and corresponding condition code for 579 /// the given operands. 580 SDValue AVRTargetLowering::getAVRCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 581 SDValue &AVRcc, SelectionDAG &DAG, 582 SDLoc DL) const { 583 SDValue Cmp; 584 EVT VT = LHS.getValueType(); 585 bool UseTest = false; 586 587 switch (CC) { 588 default: 589 break; 590 case ISD::SETLE: { 591 // Swap operands and reverse the branching condition. 592 std::swap(LHS, RHS); 593 CC = ISD::SETGE; 594 break; 595 } 596 case ISD::SETGT: { 597 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 598 switch (C->getSExtValue()) { 599 case -1: { 600 // When doing lhs > -1 use a tst instruction on the top part of lhs 601 // and use brpl instead of using a chain of cp/cpc. 602 UseTest = true; 603 AVRcc = DAG.getConstant(AVRCC::COND_PL, DL, MVT::i8); 604 break; 605 } 606 case 0: { 607 // Turn lhs > 0 into 0 < lhs since 0 can be materialized with 608 // __zero_reg__ in lhs. 609 RHS = LHS; 610 LHS = DAG.getConstant(0, DL, VT); 611 CC = ISD::SETLT; 612 break; 613 } 614 default: { 615 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows 616 // us to fold the constant into the cmp instruction. 617 RHS = DAG.getConstant(C->getSExtValue() + 1, DL, VT); 618 CC = ISD::SETGE; 619 break; 620 } 621 } 622 break; 623 } 624 // Swap operands and reverse the branching condition. 625 std::swap(LHS, RHS); 626 CC = ISD::SETLT; 627 break; 628 } 629 case ISD::SETLT: { 630 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 631 switch (C->getSExtValue()) { 632 case 1: { 633 // Turn lhs < 1 into 0 >= lhs since 0 can be materialized with 634 // __zero_reg__ in lhs. 635 RHS = LHS; 636 LHS = DAG.getConstant(0, DL, VT); 637 CC = ISD::SETGE; 638 break; 639 } 640 case 0: { 641 // When doing lhs < 0 use a tst instruction on the top part of lhs 642 // and use brmi instead of using a chain of cp/cpc. 643 UseTest = true; 644 AVRcc = DAG.getConstant(AVRCC::COND_MI, DL, MVT::i8); 645 break; 646 } 647 } 648 } 649 break; 650 } 651 case ISD::SETULE: { 652 // Swap operands and reverse the branching condition. 653 std::swap(LHS, RHS); 654 CC = ISD::SETUGE; 655 break; 656 } 657 case ISD::SETUGT: { 658 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to 659 // fold the constant into the cmp instruction. 660 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 661 RHS = DAG.getConstant(C->getSExtValue() + 1, DL, VT); 662 CC = ISD::SETUGE; 663 break; 664 } 665 // Swap operands and reverse the branching condition. 666 std::swap(LHS, RHS); 667 CC = ISD::SETULT; 668 break; 669 } 670 } 671 672 // Expand 32 and 64 bit comparisons with custom CMP and CMPC nodes instead of 673 // using the default and/or/xor expansion code which is much longer. 674 if (VT == MVT::i32) { 675 SDValue LHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS, 676 DAG.getIntPtrConstant(0, DL)); 677 SDValue LHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS, 678 DAG.getIntPtrConstant(1, DL)); 679 SDValue RHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS, 680 DAG.getIntPtrConstant(0, DL)); 681 SDValue RHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS, 682 DAG.getIntPtrConstant(1, DL)); 683 684 if (UseTest) { 685 // When using tst we only care about the highest part. 686 SDValue Top = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHShi, 687 DAG.getIntPtrConstant(1, DL)); 688 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, Top); 689 } else { 690 Cmp = getAVRCmp(LHSlo, RHSlo, DAG, DL); 691 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHShi, RHShi, Cmp); 692 } 693 } else if (VT == MVT::i64) { 694 SDValue LHS_0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS, 695 DAG.getIntPtrConstant(0, DL)); 696 SDValue LHS_1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS, 697 DAG.getIntPtrConstant(1, DL)); 698 699 SDValue LHS0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_0, 700 DAG.getIntPtrConstant(0, DL)); 701 SDValue LHS1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_0, 702 DAG.getIntPtrConstant(1, DL)); 703 SDValue LHS2 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_1, 704 DAG.getIntPtrConstant(0, DL)); 705 SDValue LHS3 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_1, 706 DAG.getIntPtrConstant(1, DL)); 707 708 SDValue RHS_0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS, 709 DAG.getIntPtrConstant(0, DL)); 710 SDValue RHS_1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS, 711 DAG.getIntPtrConstant(1, DL)); 712 713 SDValue RHS0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_0, 714 DAG.getIntPtrConstant(0, DL)); 715 SDValue RHS1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_0, 716 DAG.getIntPtrConstant(1, DL)); 717 SDValue RHS2 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_1, 718 DAG.getIntPtrConstant(0, DL)); 719 SDValue RHS3 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_1, 720 DAG.getIntPtrConstant(1, DL)); 721 722 if (UseTest) { 723 // When using tst we only care about the highest part. 724 SDValue Top = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS3, 725 DAG.getIntPtrConstant(1, DL)); 726 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, Top); 727 } else { 728 Cmp = getAVRCmp(LHS0, RHS0, DAG, DL); 729 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS1, RHS1, Cmp); 730 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS2, RHS2, Cmp); 731 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS3, RHS3, Cmp); 732 } 733 } else if (VT == MVT::i8 || VT == MVT::i16) { 734 if (UseTest) { 735 // When using tst we only care about the highest part. 736 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, 737 (VT == MVT::i8) 738 ? LHS 739 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, 740 LHS, DAG.getIntPtrConstant(1, DL))); 741 } else { 742 Cmp = getAVRCmp(LHS, RHS, DAG, DL); 743 } 744 } else { 745 llvm_unreachable("Invalid comparison size"); 746 } 747 748 // When using a test instruction AVRcc is already set. 749 if (!UseTest) { 750 AVRcc = DAG.getConstant(intCCToAVRCC(CC), DL, MVT::i8); 751 } 752 753 return Cmp; 754 } 755 756 SDValue AVRTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 757 SDValue Chain = Op.getOperand(0); 758 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 759 SDValue LHS = Op.getOperand(2); 760 SDValue RHS = Op.getOperand(3); 761 SDValue Dest = Op.getOperand(4); 762 SDLoc dl(Op); 763 764 SDValue TargetCC; 765 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, dl); 766 767 return DAG.getNode(AVRISD::BRCOND, dl, MVT::Other, Chain, Dest, TargetCC, 768 Cmp); 769 } 770 771 SDValue AVRTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 772 SDValue LHS = Op.getOperand(0); 773 SDValue RHS = Op.getOperand(1); 774 SDValue TrueV = Op.getOperand(2); 775 SDValue FalseV = Op.getOperand(3); 776 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 777 SDLoc dl(Op); 778 779 SDValue TargetCC; 780 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, dl); 781 782 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 783 SDValue Ops[] = {TrueV, FalseV, TargetCC, Cmp}; 784 785 return DAG.getNode(AVRISD::SELECT_CC, dl, VTs, Ops); 786 } 787 788 SDValue AVRTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 789 SDValue LHS = Op.getOperand(0); 790 SDValue RHS = Op.getOperand(1); 791 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 792 SDLoc DL(Op); 793 794 SDValue TargetCC; 795 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, DL); 796 797 SDValue TrueV = DAG.getConstant(1, DL, Op.getValueType()); 798 SDValue FalseV = DAG.getConstant(0, DL, Op.getValueType()); 799 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 800 SDValue Ops[] = {TrueV, FalseV, TargetCC, Cmp}; 801 802 return DAG.getNode(AVRISD::SELECT_CC, DL, VTs, Ops); 803 } 804 805 SDValue AVRTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 806 const MachineFunction &MF = DAG.getMachineFunction(); 807 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>(); 808 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 809 auto DL = DAG.getDataLayout(); 810 SDLoc dl(Op); 811 812 // Vastart just stores the address of the VarArgsFrameIndex slot into the 813 // memory location argument. 814 SDValue FI = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(), getPointerTy(DL)); 815 816 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1), 817 MachinePointerInfo(SV)); 818 } 819 820 SDValue AVRTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 821 switch (Op.getOpcode()) { 822 default: 823 llvm_unreachable("Don't know how to custom lower this!"); 824 case ISD::SHL: 825 case ISD::SRA: 826 case ISD::SRL: 827 case ISD::ROTL: 828 case ISD::ROTR: 829 return LowerShifts(Op, DAG); 830 case ISD::GlobalAddress: 831 return LowerGlobalAddress(Op, DAG); 832 case ISD::BlockAddress: 833 return LowerBlockAddress(Op, DAG); 834 case ISD::BR_CC: 835 return LowerBR_CC(Op, DAG); 836 case ISD::SELECT_CC: 837 return LowerSELECT_CC(Op, DAG); 838 case ISD::SETCC: 839 return LowerSETCC(Op, DAG); 840 case ISD::VASTART: 841 return LowerVASTART(Op, DAG); 842 case ISD::SDIVREM: 843 case ISD::UDIVREM: 844 return LowerDivRem(Op, DAG); 845 } 846 847 return SDValue(); 848 } 849 850 /// Replace a node with an illegal result type 851 /// with a new node built out of custom code. 852 void AVRTargetLowering::ReplaceNodeResults(SDNode *N, 853 SmallVectorImpl<SDValue> &Results, 854 SelectionDAG &DAG) const { 855 SDLoc DL(N); 856 857 switch (N->getOpcode()) { 858 case ISD::ADD: { 859 // Convert add (x, imm) into sub (x, -imm). 860 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 861 SDValue Sub = DAG.getNode( 862 ISD::SUB, DL, N->getValueType(0), N->getOperand(0), 863 DAG.getConstant(-C->getAPIntValue(), DL, C->getValueType(0))); 864 Results.push_back(Sub); 865 } 866 break; 867 } 868 default: { 869 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 870 871 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I) 872 Results.push_back(Res.getValue(I)); 873 874 break; 875 } 876 } 877 } 878 879 /// Return true if the addressing mode represented 880 /// by AM is legal for this target, for a load/store of the specified type. 881 bool AVRTargetLowering::isLegalAddressingMode(const DataLayout &DL, 882 const AddrMode &AM, Type *Ty, 883 unsigned AS, 884 Instruction *I) const { 885 int64_t Offs = AM.BaseOffs; 886 887 // Allow absolute addresses. 888 if (AM.BaseGV && !AM.HasBaseReg && AM.Scale == 0 && Offs == 0) { 889 return true; 890 } 891 892 // Flash memory instructions only allow zero offsets. 893 if (isa<PointerType>(Ty) && AS == AVR::ProgramMemory) { 894 return false; 895 } 896 897 // Allow reg+<6bit> offset. 898 if (Offs < 0) 899 Offs = -Offs; 900 if (AM.BaseGV == nullptr && AM.HasBaseReg && AM.Scale == 0 && 901 isUInt<6>(Offs)) { 902 return true; 903 } 904 905 return false; 906 } 907 908 /// Returns true by value, base pointer and 909 /// offset pointer and addressing mode by reference if the node's address 910 /// can be legally represented as pre-indexed load / store address. 911 bool AVRTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 912 SDValue &Offset, 913 ISD::MemIndexedMode &AM, 914 SelectionDAG &DAG) const { 915 EVT VT; 916 const SDNode *Op; 917 SDLoc DL(N); 918 919 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 920 VT = LD->getMemoryVT(); 921 Op = LD->getBasePtr().getNode(); 922 if (LD->getExtensionType() != ISD::NON_EXTLOAD) 923 return false; 924 if (AVR::isProgramMemoryAccess(LD)) { 925 return false; 926 } 927 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 928 VT = ST->getMemoryVT(); 929 Op = ST->getBasePtr().getNode(); 930 if (AVR::isProgramMemoryAccess(ST)) { 931 return false; 932 } 933 } else { 934 return false; 935 } 936 937 if (VT != MVT::i8 && VT != MVT::i16) { 938 return false; 939 } 940 941 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) { 942 return false; 943 } 944 945 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 946 int RHSC = RHS->getSExtValue(); 947 if (Op->getOpcode() == ISD::SUB) 948 RHSC = -RHSC; 949 950 if ((VT == MVT::i16 && RHSC != -2) || (VT == MVT::i8 && RHSC != -1)) { 951 return false; 952 } 953 954 Base = Op->getOperand(0); 955 Offset = DAG.getConstant(RHSC, DL, MVT::i8); 956 AM = ISD::PRE_DEC; 957 958 return true; 959 } 960 961 return false; 962 } 963 964 /// Returns true by value, base pointer and 965 /// offset pointer and addressing mode by reference if this node can be 966 /// combined with a load / store to form a post-indexed load / store. 967 bool AVRTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 968 SDValue &Base, 969 SDValue &Offset, 970 ISD::MemIndexedMode &AM, 971 SelectionDAG &DAG) const { 972 EVT VT; 973 SDLoc DL(N); 974 975 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 976 VT = LD->getMemoryVT(); 977 if (LD->getExtensionType() != ISD::NON_EXTLOAD) 978 return false; 979 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 980 VT = ST->getMemoryVT(); 981 if (AVR::isProgramMemoryAccess(ST)) { 982 return false; 983 } 984 } else { 985 return false; 986 } 987 988 if (VT != MVT::i8 && VT != MVT::i16) { 989 return false; 990 } 991 992 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) { 993 return false; 994 } 995 996 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 997 int RHSC = RHS->getSExtValue(); 998 if (Op->getOpcode() == ISD::SUB) 999 RHSC = -RHSC; 1000 if ((VT == MVT::i16 && RHSC != 2) || (VT == MVT::i8 && RHSC != 1)) { 1001 return false; 1002 } 1003 1004 Base = Op->getOperand(0); 1005 Offset = DAG.getConstant(RHSC, DL, MVT::i8); 1006 AM = ISD::POST_INC; 1007 1008 return true; 1009 } 1010 1011 return false; 1012 } 1013 1014 bool AVRTargetLowering::isOffsetFoldingLegal( 1015 const GlobalAddressSDNode *GA) const { 1016 return true; 1017 } 1018 1019 //===----------------------------------------------------------------------===// 1020 // Formal Arguments Calling Convention Implementation 1021 //===----------------------------------------------------------------------===// 1022 1023 #include "AVRGenCallingConv.inc" 1024 1025 /// Registers for calling conventions, ordered in reverse as required by ABI. 1026 /// Both arrays must be of the same length. 1027 static const MCPhysReg RegList8AVR[] = { 1028 AVR::R25, AVR::R24, AVR::R23, AVR::R22, AVR::R21, AVR::R20, 1029 AVR::R19, AVR::R18, AVR::R17, AVR::R16, AVR::R15, AVR::R14, 1030 AVR::R13, AVR::R12, AVR::R11, AVR::R10, AVR::R9, AVR::R8}; 1031 static const MCPhysReg RegList8Tiny[] = {AVR::R25, AVR::R24, AVR::R23, 1032 AVR::R22, AVR::R21, AVR::R20}; 1033 static const MCPhysReg RegList16AVR[] = { 1034 AVR::R26R25, AVR::R25R24, AVR::R24R23, AVR::R23R22, AVR::R22R21, 1035 AVR::R21R20, AVR::R20R19, AVR::R19R18, AVR::R18R17, AVR::R17R16, 1036 AVR::R16R15, AVR::R15R14, AVR::R14R13, AVR::R13R12, AVR::R12R11, 1037 AVR::R11R10, AVR::R10R9, AVR::R9R8}; 1038 static const MCPhysReg RegList16Tiny[] = {AVR::R26R25, AVR::R25R24, 1039 AVR::R24R23, AVR::R23R22, 1040 AVR::R22R21, AVR::R21R20}; 1041 1042 static_assert(array_lengthof(RegList8AVR) == array_lengthof(RegList16AVR), 1043 "8-bit and 16-bit register arrays must be of equal length"); 1044 static_assert(array_lengthof(RegList8Tiny) == array_lengthof(RegList16Tiny), 1045 "8-bit and 16-bit register arrays must be of equal length"); 1046 1047 /// Analyze incoming and outgoing function arguments. We need custom C++ code 1048 /// to handle special constraints in the ABI. 1049 /// In addition, all pieces of a certain argument have to be passed either 1050 /// using registers or the stack but never mixing both. 1051 template <typename ArgT> 1052 static void analyzeArguments(TargetLowering::CallLoweringInfo *CLI, 1053 const Function *F, const DataLayout *TD, 1054 const SmallVectorImpl<ArgT> &Args, 1055 SmallVectorImpl<CCValAssign> &ArgLocs, 1056 CCState &CCInfo, bool Tiny) { 1057 // Choose the proper register list for argument passing according to the ABI. 1058 ArrayRef<MCPhysReg> RegList8; 1059 ArrayRef<MCPhysReg> RegList16; 1060 if (Tiny) { 1061 RegList8 = makeArrayRef(RegList8Tiny, array_lengthof(RegList8Tiny)); 1062 RegList16 = makeArrayRef(RegList16Tiny, array_lengthof(RegList16Tiny)); 1063 } else { 1064 RegList8 = makeArrayRef(RegList8AVR, array_lengthof(RegList8AVR)); 1065 RegList16 = makeArrayRef(RegList16AVR, array_lengthof(RegList16AVR)); 1066 } 1067 1068 unsigned NumArgs = Args.size(); 1069 // This is the index of the last used register, in RegList*. 1070 // -1 means R26 (R26 is never actually used in CC). 1071 int RegLastIdx = -1; 1072 // Once a value is passed to the stack it will always be used 1073 bool UseStack = false; 1074 for (unsigned i = 0; i != NumArgs;) { 1075 MVT VT = Args[i].VT; 1076 // We have to count the number of bytes for each function argument, that is 1077 // those Args with the same OrigArgIndex. This is important in case the 1078 // function takes an aggregate type. 1079 // Current argument will be between [i..j). 1080 unsigned ArgIndex = Args[i].OrigArgIndex; 1081 unsigned TotalBytes = VT.getStoreSize(); 1082 unsigned j = i + 1; 1083 for (; j != NumArgs; ++j) { 1084 if (Args[j].OrigArgIndex != ArgIndex) 1085 break; 1086 TotalBytes += Args[j].VT.getStoreSize(); 1087 } 1088 // Round up to even number of bytes. 1089 TotalBytes = alignTo(TotalBytes, 2); 1090 // Skip zero sized arguments 1091 if (TotalBytes == 0) 1092 continue; 1093 // The index of the first register to be used 1094 unsigned RegIdx = RegLastIdx + TotalBytes; 1095 RegLastIdx = RegIdx; 1096 // If there are not enough registers, use the stack 1097 if (RegIdx >= RegList8.size()) { 1098 UseStack = true; 1099 } 1100 for (; i != j; ++i) { 1101 MVT VT = Args[i].VT; 1102 1103 if (UseStack) { 1104 auto evt = EVT(VT).getTypeForEVT(CCInfo.getContext()); 1105 unsigned Offset = CCInfo.AllocateStack(TD->getTypeAllocSize(evt), 1106 TD->getABITypeAlign(evt)); 1107 CCInfo.addLoc( 1108 CCValAssign::getMem(i, VT, Offset, VT, CCValAssign::Full)); 1109 } else { 1110 unsigned Reg; 1111 if (VT == MVT::i8) { 1112 Reg = CCInfo.AllocateReg(RegList8[RegIdx]); 1113 } else if (VT == MVT::i16) { 1114 Reg = CCInfo.AllocateReg(RegList16[RegIdx]); 1115 } else { 1116 llvm_unreachable( 1117 "calling convention can only manage i8 and i16 types"); 1118 } 1119 assert(Reg && "register not available in calling convention"); 1120 CCInfo.addLoc(CCValAssign::getReg(i, VT, Reg, VT, CCValAssign::Full)); 1121 // Registers inside a particular argument are sorted in increasing order 1122 // (remember the array is reversed). 1123 RegIdx -= VT.getStoreSize(); 1124 } 1125 } 1126 } 1127 } 1128 1129 /// Count the total number of bytes needed to pass or return these arguments. 1130 template <typename ArgT> 1131 static unsigned 1132 getTotalArgumentsSizeInBytes(const SmallVectorImpl<ArgT> &Args) { 1133 unsigned TotalBytes = 0; 1134 1135 for (const ArgT &Arg : Args) { 1136 TotalBytes += Arg.VT.getStoreSize(); 1137 } 1138 return TotalBytes; 1139 } 1140 1141 /// Analyze incoming and outgoing value of returning from a function. 1142 /// The algorithm is similar to analyzeArguments, but there can only be 1143 /// one value, possibly an aggregate, and it is limited to 8 bytes. 1144 template <typename ArgT> 1145 static void analyzeReturnValues(const SmallVectorImpl<ArgT> &Args, 1146 CCState &CCInfo, bool Tiny) { 1147 unsigned NumArgs = Args.size(); 1148 unsigned TotalBytes = getTotalArgumentsSizeInBytes(Args); 1149 // CanLowerReturn() guarantees this assertion. 1150 assert(TotalBytes <= 8 && 1151 "return values greater than 8 bytes cannot be lowered"); 1152 1153 // Choose the proper register list for argument passing according to the ABI. 1154 ArrayRef<MCPhysReg> RegList8; 1155 ArrayRef<MCPhysReg> RegList16; 1156 if (Tiny) { 1157 RegList8 = makeArrayRef(RegList8Tiny, array_lengthof(RegList8Tiny)); 1158 RegList16 = makeArrayRef(RegList16Tiny, array_lengthof(RegList16Tiny)); 1159 } else { 1160 RegList8 = makeArrayRef(RegList8AVR, array_lengthof(RegList8AVR)); 1161 RegList16 = makeArrayRef(RegList16AVR, array_lengthof(RegList16AVR)); 1162 } 1163 1164 // GCC-ABI says that the size is rounded up to the next even number, 1165 // but actually once it is more than 4 it will always round up to 8. 1166 if (TotalBytes > 4) { 1167 TotalBytes = 8; 1168 } else { 1169 TotalBytes = alignTo(TotalBytes, 2); 1170 } 1171 1172 // The index of the first register to use. 1173 int RegIdx = TotalBytes - 1; 1174 for (unsigned i = 0; i != NumArgs; ++i) { 1175 MVT VT = Args[i].VT; 1176 unsigned Reg; 1177 if (VT == MVT::i8) { 1178 Reg = CCInfo.AllocateReg(RegList8[RegIdx]); 1179 } else if (VT == MVT::i16) { 1180 Reg = CCInfo.AllocateReg(RegList16[RegIdx]); 1181 } else { 1182 llvm_unreachable("calling convention can only manage i8 and i16 types"); 1183 } 1184 assert(Reg && "register not available in calling convention"); 1185 CCInfo.addLoc(CCValAssign::getReg(i, VT, Reg, VT, CCValAssign::Full)); 1186 // Registers sort in increasing order 1187 RegIdx -= VT.getStoreSize(); 1188 } 1189 } 1190 1191 SDValue AVRTargetLowering::LowerFormalArguments( 1192 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1193 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1194 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1195 MachineFunction &MF = DAG.getMachineFunction(); 1196 MachineFrameInfo &MFI = MF.getFrameInfo(); 1197 auto DL = DAG.getDataLayout(); 1198 1199 // Assign locations to all of the incoming arguments. 1200 SmallVector<CCValAssign, 16> ArgLocs; 1201 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1202 *DAG.getContext()); 1203 1204 // Variadic functions do not need all the analysis below. 1205 if (isVarArg) { 1206 CCInfo.AnalyzeFormalArguments(Ins, ArgCC_AVR_Vararg); 1207 } else { 1208 analyzeArguments(nullptr, &MF.getFunction(), &DL, Ins, ArgLocs, CCInfo, 1209 Subtarget.hasTinyEncoding()); 1210 } 1211 1212 SDValue ArgValue; 1213 for (CCValAssign &VA : ArgLocs) { 1214 1215 // Arguments stored on registers. 1216 if (VA.isRegLoc()) { 1217 EVT RegVT = VA.getLocVT(); 1218 const TargetRegisterClass *RC; 1219 if (RegVT == MVT::i8) { 1220 RC = &AVR::GPR8RegClass; 1221 } else if (RegVT == MVT::i16) { 1222 RC = &AVR::DREGSRegClass; 1223 } else { 1224 llvm_unreachable("Unknown argument type!"); 1225 } 1226 1227 Register Reg = MF.addLiveIn(VA.getLocReg(), RC); 1228 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 1229 1230 // :NOTE: Clang should not promote any i8 into i16 but for safety the 1231 // following code will handle zexts or sexts generated by other 1232 // front ends. Otherwise: 1233 // If this is an 8 bit value, it is really passed promoted 1234 // to 16 bits. Insert an assert[sz]ext to capture this, then 1235 // truncate to the right size. 1236 switch (VA.getLocInfo()) { 1237 default: 1238 llvm_unreachable("Unknown loc info!"); 1239 case CCValAssign::Full: 1240 break; 1241 case CCValAssign::BCvt: 1242 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 1243 break; 1244 case CCValAssign::SExt: 1245 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 1246 DAG.getValueType(VA.getValVT())); 1247 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1248 break; 1249 case CCValAssign::ZExt: 1250 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 1251 DAG.getValueType(VA.getValVT())); 1252 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1253 break; 1254 } 1255 1256 InVals.push_back(ArgValue); 1257 } else { 1258 // Only arguments passed on the stack should make it here. 1259 assert(VA.isMemLoc()); 1260 1261 EVT LocVT = VA.getLocVT(); 1262 1263 // Create the frame index object for this incoming parameter. 1264 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, 1265 VA.getLocMemOffset(), true); 1266 1267 // Create the SelectionDAG nodes corresponding to a load 1268 // from this parameter. 1269 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DL)); 1270 InVals.push_back(DAG.getLoad(LocVT, dl, Chain, FIN, 1271 MachinePointerInfo::getFixedStack(MF, FI))); 1272 } 1273 } 1274 1275 // If the function takes variable number of arguments, make a frame index for 1276 // the start of the first vararg value... for expansion of llvm.va_start. 1277 if (isVarArg) { 1278 unsigned StackSize = CCInfo.getNextStackOffset(); 1279 AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>(); 1280 1281 AFI->setVarArgsFrameIndex(MFI.CreateFixedObject(2, StackSize, true)); 1282 } 1283 1284 return Chain; 1285 } 1286 1287 //===----------------------------------------------------------------------===// 1288 // Call Calling Convention Implementation 1289 //===----------------------------------------------------------------------===// 1290 1291 SDValue AVRTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1292 SmallVectorImpl<SDValue> &InVals) const { 1293 SelectionDAG &DAG = CLI.DAG; 1294 SDLoc &DL = CLI.DL; 1295 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1296 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1297 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1298 SDValue Chain = CLI.Chain; 1299 SDValue Callee = CLI.Callee; 1300 bool &isTailCall = CLI.IsTailCall; 1301 CallingConv::ID CallConv = CLI.CallConv; 1302 bool isVarArg = CLI.IsVarArg; 1303 1304 MachineFunction &MF = DAG.getMachineFunction(); 1305 1306 // AVR does not yet support tail call optimization. 1307 isTailCall = false; 1308 1309 // Analyze operands of the call, assigning locations to each operand. 1310 SmallVector<CCValAssign, 16> ArgLocs; 1311 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1312 *DAG.getContext()); 1313 1314 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1315 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1316 // node so that legalize doesn't hack it. 1317 const Function *F = nullptr; 1318 if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1319 const GlobalValue *GV = G->getGlobal(); 1320 if (isa<Function>(GV)) 1321 F = cast<Function>(GV); 1322 Callee = 1323 DAG.getTargetGlobalAddress(GV, DL, getPointerTy(DAG.getDataLayout())); 1324 } else if (const ExternalSymbolSDNode *ES = 1325 dyn_cast<ExternalSymbolSDNode>(Callee)) { 1326 Callee = DAG.getTargetExternalSymbol(ES->getSymbol(), 1327 getPointerTy(DAG.getDataLayout())); 1328 } 1329 1330 // Variadic functions do not need all the analysis below. 1331 if (isVarArg) { 1332 CCInfo.AnalyzeCallOperands(Outs, ArgCC_AVR_Vararg); 1333 } else { 1334 analyzeArguments(&CLI, F, &DAG.getDataLayout(), Outs, ArgLocs, CCInfo, 1335 Subtarget.hasTinyEncoding()); 1336 } 1337 1338 // Get a count of how many bytes are to be pushed on the stack. 1339 unsigned NumBytes = CCInfo.getNextStackOffset(); 1340 1341 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 1342 1343 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 1344 1345 // First, walk the register assignments, inserting copies. 1346 unsigned AI, AE; 1347 bool HasStackArgs = false; 1348 for (AI = 0, AE = ArgLocs.size(); AI != AE; ++AI) { 1349 CCValAssign &VA = ArgLocs[AI]; 1350 EVT RegVT = VA.getLocVT(); 1351 SDValue Arg = OutVals[AI]; 1352 1353 // Promote the value if needed. With Clang this should not happen. 1354 switch (VA.getLocInfo()) { 1355 default: 1356 llvm_unreachable("Unknown loc info!"); 1357 case CCValAssign::Full: 1358 break; 1359 case CCValAssign::SExt: 1360 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, RegVT, Arg); 1361 break; 1362 case CCValAssign::ZExt: 1363 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, RegVT, Arg); 1364 break; 1365 case CCValAssign::AExt: 1366 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, RegVT, Arg); 1367 break; 1368 case CCValAssign::BCvt: 1369 Arg = DAG.getNode(ISD::BITCAST, DL, RegVT, Arg); 1370 break; 1371 } 1372 1373 // Stop when we encounter a stack argument, we need to process them 1374 // in reverse order in the loop below. 1375 if (VA.isMemLoc()) { 1376 HasStackArgs = true; 1377 break; 1378 } 1379 1380 // Arguments that can be passed on registers must be kept in the RegsToPass 1381 // vector. 1382 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1383 } 1384 1385 // Second, stack arguments have to walked. 1386 // Previously this code created chained stores but those chained stores appear 1387 // to be unchained in the legalization phase. Therefore, do not attempt to 1388 // chain them here. In fact, chaining them here somehow causes the first and 1389 // second store to be reversed which is the exact opposite of the intended 1390 // effect. 1391 if (HasStackArgs) { 1392 SmallVector<SDValue, 8> MemOpChains; 1393 for (; AI != AE; AI++) { 1394 CCValAssign &VA = ArgLocs[AI]; 1395 SDValue Arg = OutVals[AI]; 1396 1397 assert(VA.isMemLoc()); 1398 1399 // SP points to one stack slot further so add one to adjust it. 1400 SDValue PtrOff = DAG.getNode( 1401 ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), 1402 DAG.getRegister(AVR::SP, getPointerTy(DAG.getDataLayout())), 1403 DAG.getIntPtrConstant(VA.getLocMemOffset() + 1, DL)); 1404 1405 MemOpChains.push_back( 1406 DAG.getStore(Chain, DL, Arg, PtrOff, 1407 MachinePointerInfo::getStack(MF, VA.getLocMemOffset()))); 1408 } 1409 1410 if (!MemOpChains.empty()) 1411 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 1412 } 1413 1414 // Build a sequence of copy-to-reg nodes chained together with token chain and 1415 // flag operands which copy the outgoing args into registers. The InFlag in 1416 // necessary since all emited instructions must be stuck together. 1417 SDValue InFlag; 1418 for (auto Reg : RegsToPass) { 1419 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, InFlag); 1420 InFlag = Chain.getValue(1); 1421 } 1422 1423 // Returns a chain & a flag for retval copy to use. 1424 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1425 SmallVector<SDValue, 8> Ops; 1426 Ops.push_back(Chain); 1427 Ops.push_back(Callee); 1428 1429 // Add argument registers to the end of the list so that they are known live 1430 // into the call. 1431 for (auto Reg : RegsToPass) { 1432 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 1433 } 1434 1435 // Add a register mask operand representing the call-preserved registers. 1436 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 1437 const uint32_t *Mask = 1438 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 1439 assert(Mask && "Missing call preserved mask for calling convention"); 1440 Ops.push_back(DAG.getRegisterMask(Mask)); 1441 1442 if (InFlag.getNode()) { 1443 Ops.push_back(InFlag); 1444 } 1445 1446 Chain = DAG.getNode(AVRISD::CALL, DL, NodeTys, Ops); 1447 InFlag = Chain.getValue(1); 1448 1449 // Create the CALLSEQ_END node. 1450 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 1451 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 1452 1453 if (!Ins.empty()) { 1454 InFlag = Chain.getValue(1); 1455 } 1456 1457 // Handle result values, copying them out of physregs into vregs that we 1458 // return. 1459 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, DL, DAG, 1460 InVals); 1461 } 1462 1463 /// Lower the result values of a call into the 1464 /// appropriate copies out of appropriate physical registers. 1465 /// 1466 SDValue AVRTargetLowering::LowerCallResult( 1467 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1468 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1469 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1470 1471 // Assign locations to each value returned by this call. 1472 SmallVector<CCValAssign, 16> RVLocs; 1473 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1474 *DAG.getContext()); 1475 1476 // Handle runtime calling convs. 1477 if (CallConv == CallingConv::AVR_BUILTIN) { 1478 CCInfo.AnalyzeCallResult(Ins, RetCC_AVR_BUILTIN); 1479 } else { 1480 analyzeReturnValues(Ins, CCInfo, Subtarget.hasTinyEncoding()); 1481 } 1482 1483 // Copy all of the result registers out of their specified physreg. 1484 for (CCValAssign const &RVLoc : RVLocs) { 1485 Chain = DAG.getCopyFromReg(Chain, dl, RVLoc.getLocReg(), RVLoc.getValVT(), 1486 InFlag) 1487 .getValue(1); 1488 InFlag = Chain.getValue(2); 1489 InVals.push_back(Chain.getValue(0)); 1490 } 1491 1492 return Chain; 1493 } 1494 1495 //===----------------------------------------------------------------------===// 1496 // Return Value Calling Convention Implementation 1497 //===----------------------------------------------------------------------===// 1498 1499 bool AVRTargetLowering::CanLowerReturn( 1500 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 1501 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 1502 if (CallConv == CallingConv::AVR_BUILTIN) { 1503 SmallVector<CCValAssign, 16> RVLocs; 1504 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 1505 return CCInfo.CheckReturn(Outs, RetCC_AVR_BUILTIN); 1506 } 1507 1508 unsigned TotalBytes = getTotalArgumentsSizeInBytes(Outs); 1509 return TotalBytes <= 8; 1510 } 1511 1512 SDValue 1513 AVRTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1514 bool isVarArg, 1515 const SmallVectorImpl<ISD::OutputArg> &Outs, 1516 const SmallVectorImpl<SDValue> &OutVals, 1517 const SDLoc &dl, SelectionDAG &DAG) const { 1518 // CCValAssign - represent the assignment of the return value to locations. 1519 SmallVector<CCValAssign, 16> RVLocs; 1520 1521 // CCState - Info about the registers and stack slot. 1522 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1523 *DAG.getContext()); 1524 1525 MachineFunction &MF = DAG.getMachineFunction(); 1526 1527 // Analyze return values. 1528 if (CallConv == CallingConv::AVR_BUILTIN) { 1529 CCInfo.AnalyzeReturn(Outs, RetCC_AVR_BUILTIN); 1530 } else { 1531 analyzeReturnValues(Outs, CCInfo, Subtarget.hasTinyEncoding()); 1532 } 1533 1534 SDValue Flag; 1535 SmallVector<SDValue, 4> RetOps(1, Chain); 1536 // Copy the result values into the output registers. 1537 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 1538 CCValAssign &VA = RVLocs[i]; 1539 assert(VA.isRegLoc() && "Can only return in registers!"); 1540 1541 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag); 1542 1543 // Guarantee that all emitted copies are stuck together with flags. 1544 Flag = Chain.getValue(1); 1545 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1546 } 1547 1548 // Don't emit the ret/reti instruction when the naked attribute is present in 1549 // the function being compiled. 1550 if (MF.getFunction().getAttributes().hasFnAttr(Attribute::Naked)) { 1551 return Chain; 1552 } 1553 1554 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>(); 1555 1556 unsigned RetOpc = 1557 AFI->isInterruptOrSignalHandler() ? AVRISD::RETI_FLAG : AVRISD::RET_FLAG; 1558 1559 RetOps[0] = Chain; // Update chain. 1560 1561 if (Flag.getNode()) { 1562 RetOps.push_back(Flag); 1563 } 1564 1565 return DAG.getNode(RetOpc, dl, MVT::Other, RetOps); 1566 } 1567 1568 //===----------------------------------------------------------------------===// 1569 // Custom Inserters 1570 //===----------------------------------------------------------------------===// 1571 1572 MachineBasicBlock *AVRTargetLowering::insertShift(MachineInstr &MI, 1573 MachineBasicBlock *BB) const { 1574 unsigned Opc; 1575 const TargetRegisterClass *RC; 1576 bool HasRepeatedOperand = false; 1577 MachineFunction *F = BB->getParent(); 1578 MachineRegisterInfo &RI = F->getRegInfo(); 1579 const TargetInstrInfo &TII = *Subtarget.getInstrInfo(); 1580 DebugLoc dl = MI.getDebugLoc(); 1581 1582 switch (MI.getOpcode()) { 1583 default: 1584 llvm_unreachable("Invalid shift opcode!"); 1585 case AVR::Lsl8: 1586 Opc = AVR::ADDRdRr; // LSL is an alias of ADD Rd, Rd 1587 RC = &AVR::GPR8RegClass; 1588 HasRepeatedOperand = true; 1589 break; 1590 case AVR::Lsl16: 1591 Opc = AVR::LSLWRd; 1592 RC = &AVR::DREGSRegClass; 1593 break; 1594 case AVR::Asr8: 1595 Opc = AVR::ASRRd; 1596 RC = &AVR::GPR8RegClass; 1597 break; 1598 case AVR::Asr16: 1599 Opc = AVR::ASRWRd; 1600 RC = &AVR::DREGSRegClass; 1601 break; 1602 case AVR::Lsr8: 1603 Opc = AVR::LSRRd; 1604 RC = &AVR::GPR8RegClass; 1605 break; 1606 case AVR::Lsr16: 1607 Opc = AVR::LSRWRd; 1608 RC = &AVR::DREGSRegClass; 1609 break; 1610 case AVR::Rol8: 1611 Opc = AVR::ROLBRd; 1612 RC = &AVR::GPR8RegClass; 1613 break; 1614 case AVR::Rol16: 1615 Opc = AVR::ROLWRd; 1616 RC = &AVR::DREGSRegClass; 1617 break; 1618 case AVR::Ror8: 1619 Opc = AVR::RORBRd; 1620 RC = &AVR::GPR8RegClass; 1621 break; 1622 case AVR::Ror16: 1623 Opc = AVR::RORWRd; 1624 RC = &AVR::DREGSRegClass; 1625 break; 1626 } 1627 1628 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1629 1630 MachineFunction::iterator I; 1631 for (I = BB->getIterator(); I != F->end() && &(*I) != BB; ++I) 1632 ; 1633 if (I != F->end()) 1634 ++I; 1635 1636 // Create loop block. 1637 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB); 1638 MachineBasicBlock *CheckBB = F->CreateMachineBasicBlock(LLVM_BB); 1639 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB); 1640 1641 F->insert(I, LoopBB); 1642 F->insert(I, CheckBB); 1643 F->insert(I, RemBB); 1644 1645 // Update machine-CFG edges by transferring all successors of the current 1646 // block to the block containing instructions after shift. 1647 RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)), 1648 BB->end()); 1649 RemBB->transferSuccessorsAndUpdatePHIs(BB); 1650 1651 // Add edges BB => LoopBB => CheckBB => RemBB, CheckBB => LoopBB. 1652 BB->addSuccessor(CheckBB); 1653 LoopBB->addSuccessor(CheckBB); 1654 CheckBB->addSuccessor(LoopBB); 1655 CheckBB->addSuccessor(RemBB); 1656 1657 Register ShiftAmtReg = RI.createVirtualRegister(&AVR::GPR8RegClass); 1658 Register ShiftAmtReg2 = RI.createVirtualRegister(&AVR::GPR8RegClass); 1659 Register ShiftReg = RI.createVirtualRegister(RC); 1660 Register ShiftReg2 = RI.createVirtualRegister(RC); 1661 Register ShiftAmtSrcReg = MI.getOperand(2).getReg(); 1662 Register SrcReg = MI.getOperand(1).getReg(); 1663 Register DstReg = MI.getOperand(0).getReg(); 1664 1665 // BB: 1666 // rjmp CheckBB 1667 BuildMI(BB, dl, TII.get(AVR::RJMPk)).addMBB(CheckBB); 1668 1669 // LoopBB: 1670 // ShiftReg2 = shift ShiftReg 1671 auto ShiftMI = BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2).addReg(ShiftReg); 1672 if (HasRepeatedOperand) 1673 ShiftMI.addReg(ShiftReg); 1674 1675 // CheckBB: 1676 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB] 1677 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB] 1678 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB] 1679 // ShiftAmt2 = ShiftAmt - 1; 1680 // if (ShiftAmt2 >= 0) goto LoopBB; 1681 BuildMI(CheckBB, dl, TII.get(AVR::PHI), ShiftReg) 1682 .addReg(SrcReg) 1683 .addMBB(BB) 1684 .addReg(ShiftReg2) 1685 .addMBB(LoopBB); 1686 BuildMI(CheckBB, dl, TII.get(AVR::PHI), ShiftAmtReg) 1687 .addReg(ShiftAmtSrcReg) 1688 .addMBB(BB) 1689 .addReg(ShiftAmtReg2) 1690 .addMBB(LoopBB); 1691 BuildMI(CheckBB, dl, TII.get(AVR::PHI), DstReg) 1692 .addReg(SrcReg) 1693 .addMBB(BB) 1694 .addReg(ShiftReg2) 1695 .addMBB(LoopBB); 1696 1697 BuildMI(CheckBB, dl, TII.get(AVR::DECRd), ShiftAmtReg2).addReg(ShiftAmtReg); 1698 BuildMI(CheckBB, dl, TII.get(AVR::BRPLk)).addMBB(LoopBB); 1699 1700 MI.eraseFromParent(); // The pseudo instruction is gone now. 1701 return RemBB; 1702 } 1703 1704 static bool isCopyMulResult(MachineBasicBlock::iterator const &I) { 1705 if (I->getOpcode() == AVR::COPY) { 1706 Register SrcReg = I->getOperand(1).getReg(); 1707 return (SrcReg == AVR::R0 || SrcReg == AVR::R1); 1708 } 1709 1710 return false; 1711 } 1712 1713 // The mul instructions wreak havock on our zero_reg R1. We need to clear it 1714 // after the result has been evacuated. This is probably not the best way to do 1715 // it, but it works for now. 1716 MachineBasicBlock *AVRTargetLowering::insertMul(MachineInstr &MI, 1717 MachineBasicBlock *BB) const { 1718 const TargetInstrInfo &TII = *Subtarget.getInstrInfo(); 1719 MachineBasicBlock::iterator I(MI); 1720 ++I; // in any case insert *after* the mul instruction 1721 if (isCopyMulResult(I)) 1722 ++I; 1723 if (isCopyMulResult(I)) 1724 ++I; 1725 BuildMI(*BB, I, MI.getDebugLoc(), TII.get(AVR::EORRdRr), AVR::R1) 1726 .addReg(AVR::R1) 1727 .addReg(AVR::R1); 1728 return BB; 1729 } 1730 1731 // Insert a read from R1, which almost always contains the value 0. 1732 MachineBasicBlock * 1733 AVRTargetLowering::insertCopyR1(MachineInstr &MI, MachineBasicBlock *BB) const { 1734 const TargetInstrInfo &TII = *Subtarget.getInstrInfo(); 1735 MachineBasicBlock::iterator I(MI); 1736 BuildMI(*BB, I, MI.getDebugLoc(), TII.get(AVR::COPY)) 1737 .add(MI.getOperand(0)) 1738 .addReg(AVR::R1); 1739 MI.eraseFromParent(); 1740 return BB; 1741 } 1742 1743 // Lower atomicrmw operation to disable interrupts, do operation, and restore 1744 // interrupts. This works because all AVR microcontrollers are single core. 1745 MachineBasicBlock *AVRTargetLowering::insertAtomicArithmeticOp( 1746 MachineInstr &MI, MachineBasicBlock *BB, unsigned Opcode, int Width) const { 1747 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 1748 const TargetInstrInfo &TII = *Subtarget.getInstrInfo(); 1749 MachineBasicBlock::iterator I(MI); 1750 const Register SCRATCH_REGISTER = AVR::R0; 1751 DebugLoc dl = MI.getDebugLoc(); 1752 1753 // Example instruction sequence, for an atomic 8-bit add: 1754 // ldi r25, 5 1755 // in r0, SREG 1756 // cli 1757 // ld r24, X 1758 // add r25, r24 1759 // st X, r25 1760 // out SREG, r0 1761 1762 const TargetRegisterClass *RC = 1763 (Width == 8) ? &AVR::GPR8RegClass : &AVR::DREGSRegClass; 1764 unsigned LoadOpcode = (Width == 8) ? AVR::LDRdPtr : AVR::LDWRdPtr; 1765 unsigned StoreOpcode = (Width == 8) ? AVR::STPtrRr : AVR::STWPtrRr; 1766 1767 // Disable interrupts. 1768 BuildMI(*BB, I, dl, TII.get(AVR::INRdA), SCRATCH_REGISTER) 1769 .addImm(Subtarget.getIORegSREG()); 1770 BuildMI(*BB, I, dl, TII.get(AVR::BCLRs)).addImm(7); 1771 1772 // Load the original value. 1773 BuildMI(*BB, I, dl, TII.get(LoadOpcode), MI.getOperand(0).getReg()) 1774 .add(MI.getOperand(1)); 1775 1776 // Do the arithmetic operation. 1777 Register Result = MRI.createVirtualRegister(RC); 1778 BuildMI(*BB, I, dl, TII.get(Opcode), Result) 1779 .addReg(MI.getOperand(0).getReg()) 1780 .add(MI.getOperand(2)); 1781 1782 // Store the result. 1783 BuildMI(*BB, I, dl, TII.get(StoreOpcode)) 1784 .add(MI.getOperand(1)) 1785 .addReg(Result); 1786 1787 // Restore interrupts. 1788 BuildMI(*BB, I, dl, TII.get(AVR::OUTARr)) 1789 .addImm(Subtarget.getIORegSREG()) 1790 .addReg(SCRATCH_REGISTER); 1791 1792 // Remove the pseudo instruction. 1793 MI.eraseFromParent(); 1794 return BB; 1795 } 1796 1797 MachineBasicBlock * 1798 AVRTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 1799 MachineBasicBlock *MBB) const { 1800 int Opc = MI.getOpcode(); 1801 1802 // Pseudo shift instructions with a non constant shift amount are expanded 1803 // into a loop. 1804 switch (Opc) { 1805 case AVR::Lsl8: 1806 case AVR::Lsl16: 1807 case AVR::Lsr8: 1808 case AVR::Lsr16: 1809 case AVR::Rol8: 1810 case AVR::Rol16: 1811 case AVR::Ror8: 1812 case AVR::Ror16: 1813 case AVR::Asr8: 1814 case AVR::Asr16: 1815 return insertShift(MI, MBB); 1816 case AVR::MULRdRr: 1817 case AVR::MULSRdRr: 1818 return insertMul(MI, MBB); 1819 case AVR::CopyR1: 1820 return insertCopyR1(MI, MBB); 1821 case AVR::AtomicLoadAdd8: 1822 return insertAtomicArithmeticOp(MI, MBB, AVR::ADDRdRr, 8); 1823 case AVR::AtomicLoadAdd16: 1824 return insertAtomicArithmeticOp(MI, MBB, AVR::ADDWRdRr, 16); 1825 case AVR::AtomicLoadSub8: 1826 return insertAtomicArithmeticOp(MI, MBB, AVR::SUBRdRr, 8); 1827 case AVR::AtomicLoadSub16: 1828 return insertAtomicArithmeticOp(MI, MBB, AVR::SUBWRdRr, 16); 1829 case AVR::AtomicLoadAnd8: 1830 return insertAtomicArithmeticOp(MI, MBB, AVR::ANDRdRr, 8); 1831 case AVR::AtomicLoadAnd16: 1832 return insertAtomicArithmeticOp(MI, MBB, AVR::ANDWRdRr, 16); 1833 case AVR::AtomicLoadOr8: 1834 return insertAtomicArithmeticOp(MI, MBB, AVR::ORRdRr, 8); 1835 case AVR::AtomicLoadOr16: 1836 return insertAtomicArithmeticOp(MI, MBB, AVR::ORWRdRr, 16); 1837 case AVR::AtomicLoadXor8: 1838 return insertAtomicArithmeticOp(MI, MBB, AVR::EORRdRr, 8); 1839 case AVR::AtomicLoadXor16: 1840 return insertAtomicArithmeticOp(MI, MBB, AVR::EORWRdRr, 16); 1841 } 1842 1843 assert((Opc == AVR::Select16 || Opc == AVR::Select8) && 1844 "Unexpected instr type to insert"); 1845 1846 const AVRInstrInfo &TII = (const AVRInstrInfo &)*MI.getParent() 1847 ->getParent() 1848 ->getSubtarget() 1849 .getInstrInfo(); 1850 DebugLoc dl = MI.getDebugLoc(); 1851 1852 // To "insert" a SELECT instruction, we insert the diamond 1853 // control-flow pattern. The incoming instruction knows the 1854 // destination vreg to set, the condition code register to branch 1855 // on, the true/false values to select between, and a branch opcode 1856 // to use. 1857 1858 MachineFunction *MF = MBB->getParent(); 1859 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 1860 MachineBasicBlock *FallThrough = MBB->getFallThrough(); 1861 1862 // If the current basic block falls through to another basic block, 1863 // we must insert an unconditional branch to the fallthrough destination 1864 // if we are to insert basic blocks at the prior fallthrough point. 1865 if (FallThrough != nullptr) { 1866 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(FallThrough); 1867 } 1868 1869 MachineBasicBlock *trueMBB = MF->CreateMachineBasicBlock(LLVM_BB); 1870 MachineBasicBlock *falseMBB = MF->CreateMachineBasicBlock(LLVM_BB); 1871 1872 MachineFunction::iterator I; 1873 for (I = MF->begin(); I != MF->end() && &(*I) != MBB; ++I) 1874 ; 1875 if (I != MF->end()) 1876 ++I; 1877 MF->insert(I, trueMBB); 1878 MF->insert(I, falseMBB); 1879 1880 // Transfer remaining instructions and all successors of the current 1881 // block to the block which will contain the Phi node for the 1882 // select. 1883 trueMBB->splice(trueMBB->begin(), MBB, 1884 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 1885 trueMBB->transferSuccessorsAndUpdatePHIs(MBB); 1886 1887 AVRCC::CondCodes CC = (AVRCC::CondCodes)MI.getOperand(3).getImm(); 1888 BuildMI(MBB, dl, TII.getBrCond(CC)).addMBB(trueMBB); 1889 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(falseMBB); 1890 MBB->addSuccessor(falseMBB); 1891 MBB->addSuccessor(trueMBB); 1892 1893 // Unconditionally flow back to the true block 1894 BuildMI(falseMBB, dl, TII.get(AVR::RJMPk)).addMBB(trueMBB); 1895 falseMBB->addSuccessor(trueMBB); 1896 1897 // Set up the Phi node to determine where we came from 1898 BuildMI(*trueMBB, trueMBB->begin(), dl, TII.get(AVR::PHI), 1899 MI.getOperand(0).getReg()) 1900 .addReg(MI.getOperand(1).getReg()) 1901 .addMBB(MBB) 1902 .addReg(MI.getOperand(2).getReg()) 1903 .addMBB(falseMBB); 1904 1905 MI.eraseFromParent(); // The pseudo instruction is gone now. 1906 return trueMBB; 1907 } 1908 1909 //===----------------------------------------------------------------------===// 1910 // Inline Asm Support 1911 //===----------------------------------------------------------------------===// 1912 1913 AVRTargetLowering::ConstraintType 1914 AVRTargetLowering::getConstraintType(StringRef Constraint) const { 1915 if (Constraint.size() == 1) { 1916 // See http://www.nongnu.org/avr-libc/user-manual/inline_asm.html 1917 switch (Constraint[0]) { 1918 default: 1919 break; 1920 case 'a': // Simple upper registers 1921 case 'b': // Base pointer registers pairs 1922 case 'd': // Upper register 1923 case 'l': // Lower registers 1924 case 'e': // Pointer register pairs 1925 case 'q': // Stack pointer register 1926 case 'r': // Any register 1927 case 'w': // Special upper register pairs 1928 return C_RegisterClass; 1929 case 't': // Temporary register 1930 case 'x': 1931 case 'X': // Pointer register pair X 1932 case 'y': 1933 case 'Y': // Pointer register pair Y 1934 case 'z': 1935 case 'Z': // Pointer register pair Z 1936 return C_Register; 1937 case 'Q': // A memory address based on Y or Z pointer with displacement. 1938 return C_Memory; 1939 case 'G': // Floating point constant 1940 case 'I': // 6-bit positive integer constant 1941 case 'J': // 6-bit negative integer constant 1942 case 'K': // Integer constant (Range: 2) 1943 case 'L': // Integer constant (Range: 0) 1944 case 'M': // 8-bit integer constant 1945 case 'N': // Integer constant (Range: -1) 1946 case 'O': // Integer constant (Range: 8, 16, 24) 1947 case 'P': // Integer constant (Range: 1) 1948 case 'R': // Integer constant (Range: -6 to 5)x 1949 return C_Immediate; 1950 } 1951 } 1952 1953 return TargetLowering::getConstraintType(Constraint); 1954 } 1955 1956 unsigned 1957 AVRTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 1958 // Not sure if this is actually the right thing to do, but we got to do 1959 // *something* [agnat] 1960 switch (ConstraintCode[0]) { 1961 case 'Q': 1962 return InlineAsm::Constraint_Q; 1963 } 1964 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 1965 } 1966 1967 AVRTargetLowering::ConstraintWeight 1968 AVRTargetLowering::getSingleConstraintMatchWeight( 1969 AsmOperandInfo &info, const char *constraint) const { 1970 ConstraintWeight weight = CW_Invalid; 1971 Value *CallOperandVal = info.CallOperandVal; 1972 1973 // If we don't have a value, we can't do a match, 1974 // but allow it at the lowest weight. 1975 // (this behaviour has been copied from the ARM backend) 1976 if (!CallOperandVal) { 1977 return CW_Default; 1978 } 1979 1980 // Look at the constraint type. 1981 switch (*constraint) { 1982 default: 1983 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 1984 break; 1985 case 'd': 1986 case 'r': 1987 case 'l': 1988 weight = CW_Register; 1989 break; 1990 case 'a': 1991 case 'b': 1992 case 'e': 1993 case 'q': 1994 case 't': 1995 case 'w': 1996 case 'x': 1997 case 'X': 1998 case 'y': 1999 case 'Y': 2000 case 'z': 2001 case 'Z': 2002 weight = CW_SpecificReg; 2003 break; 2004 case 'G': 2005 if (const ConstantFP *C = dyn_cast<ConstantFP>(CallOperandVal)) { 2006 if (C->isZero()) { 2007 weight = CW_Constant; 2008 } 2009 } 2010 break; 2011 case 'I': 2012 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 2013 if (isUInt<6>(C->getZExtValue())) { 2014 weight = CW_Constant; 2015 } 2016 } 2017 break; 2018 case 'J': 2019 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 2020 if ((C->getSExtValue() >= -63) && (C->getSExtValue() <= 0)) { 2021 weight = CW_Constant; 2022 } 2023 } 2024 break; 2025 case 'K': 2026 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 2027 if (C->getZExtValue() == 2) { 2028 weight = CW_Constant; 2029 } 2030 } 2031 break; 2032 case 'L': 2033 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 2034 if (C->getZExtValue() == 0) { 2035 weight = CW_Constant; 2036 } 2037 } 2038 break; 2039 case 'M': 2040 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 2041 if (isUInt<8>(C->getZExtValue())) { 2042 weight = CW_Constant; 2043 } 2044 } 2045 break; 2046 case 'N': 2047 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 2048 if (C->getSExtValue() == -1) { 2049 weight = CW_Constant; 2050 } 2051 } 2052 break; 2053 case 'O': 2054 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 2055 if ((C->getZExtValue() == 8) || (C->getZExtValue() == 16) || 2056 (C->getZExtValue() == 24)) { 2057 weight = CW_Constant; 2058 } 2059 } 2060 break; 2061 case 'P': 2062 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 2063 if (C->getZExtValue() == 1) { 2064 weight = CW_Constant; 2065 } 2066 } 2067 break; 2068 case 'R': 2069 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 2070 if ((C->getSExtValue() >= -6) && (C->getSExtValue() <= 5)) { 2071 weight = CW_Constant; 2072 } 2073 } 2074 break; 2075 case 'Q': 2076 weight = CW_Memory; 2077 break; 2078 } 2079 2080 return weight; 2081 } 2082 2083 std::pair<unsigned, const TargetRegisterClass *> 2084 AVRTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 2085 StringRef Constraint, 2086 MVT VT) const { 2087 if (Constraint.size() == 1) { 2088 switch (Constraint[0]) { 2089 case 'a': // Simple upper registers r16..r23. 2090 if (VT == MVT::i8) 2091 return std::make_pair(0U, &AVR::LD8loRegClass); 2092 else if (VT == MVT::i16) 2093 return std::make_pair(0U, &AVR::DREGSLD8loRegClass); 2094 break; 2095 case 'b': // Base pointer registers: y, z. 2096 if (VT == MVT::i8 || VT == MVT::i16) 2097 return std::make_pair(0U, &AVR::PTRDISPREGSRegClass); 2098 break; 2099 case 'd': // Upper registers r16..r31. 2100 if (VT == MVT::i8) 2101 return std::make_pair(0U, &AVR::LD8RegClass); 2102 else if (VT == MVT::i16) 2103 return std::make_pair(0U, &AVR::DLDREGSRegClass); 2104 break; 2105 case 'l': // Lower registers r0..r15. 2106 if (VT == MVT::i8) 2107 return std::make_pair(0U, &AVR::GPR8loRegClass); 2108 else if (VT == MVT::i16) 2109 return std::make_pair(0U, &AVR::DREGSloRegClass); 2110 break; 2111 case 'e': // Pointer register pairs: x, y, z. 2112 if (VT == MVT::i8 || VT == MVT::i16) 2113 return std::make_pair(0U, &AVR::PTRREGSRegClass); 2114 break; 2115 case 'q': // Stack pointer register: SPH:SPL. 2116 return std::make_pair(0U, &AVR::GPRSPRegClass); 2117 case 'r': // Any register: r0..r31. 2118 if (VT == MVT::i8) 2119 return std::make_pair(0U, &AVR::GPR8RegClass); 2120 else if (VT == MVT::i16) 2121 return std::make_pair(0U, &AVR::DREGSRegClass); 2122 break; 2123 case 't': // Temporary register: r0. 2124 if (VT == MVT::i8) 2125 return std::make_pair(unsigned(AVR::R0), &AVR::GPR8RegClass); 2126 break; 2127 case 'w': // Special upper register pairs: r24, r26, r28, r30. 2128 if (VT == MVT::i8 || VT == MVT::i16) 2129 return std::make_pair(0U, &AVR::IWREGSRegClass); 2130 break; 2131 case 'x': // Pointer register pair X: r27:r26. 2132 case 'X': 2133 if (VT == MVT::i8 || VT == MVT::i16) 2134 return std::make_pair(unsigned(AVR::R27R26), &AVR::PTRREGSRegClass); 2135 break; 2136 case 'y': // Pointer register pair Y: r29:r28. 2137 case 'Y': 2138 if (VT == MVT::i8 || VT == MVT::i16) 2139 return std::make_pair(unsigned(AVR::R29R28), &AVR::PTRREGSRegClass); 2140 break; 2141 case 'z': // Pointer register pair Z: r31:r30. 2142 case 'Z': 2143 if (VT == MVT::i8 || VT == MVT::i16) 2144 return std::make_pair(unsigned(AVR::R31R30), &AVR::PTRREGSRegClass); 2145 break; 2146 default: 2147 break; 2148 } 2149 } 2150 2151 return TargetLowering::getRegForInlineAsmConstraint( 2152 Subtarget.getRegisterInfo(), Constraint, VT); 2153 } 2154 2155 void AVRTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 2156 std::string &Constraint, 2157 std::vector<SDValue> &Ops, 2158 SelectionDAG &DAG) const { 2159 SDValue Result; 2160 SDLoc DL(Op); 2161 EVT Ty = Op.getValueType(); 2162 2163 // Currently only support length 1 constraints. 2164 if (Constraint.length() != 1) { 2165 return; 2166 } 2167 2168 char ConstraintLetter = Constraint[0]; 2169 switch (ConstraintLetter) { 2170 default: 2171 break; 2172 // Deal with integers first: 2173 case 'I': 2174 case 'J': 2175 case 'K': 2176 case 'L': 2177 case 'M': 2178 case 'N': 2179 case 'O': 2180 case 'P': 2181 case 'R': { 2182 const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 2183 if (!C) { 2184 return; 2185 } 2186 2187 int64_t CVal64 = C->getSExtValue(); 2188 uint64_t CUVal64 = C->getZExtValue(); 2189 switch (ConstraintLetter) { 2190 case 'I': // 0..63 2191 if (!isUInt<6>(CUVal64)) 2192 return; 2193 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 2194 break; 2195 case 'J': // -63..0 2196 if (CVal64 < -63 || CVal64 > 0) 2197 return; 2198 Result = DAG.getTargetConstant(CVal64, DL, Ty); 2199 break; 2200 case 'K': // 2 2201 if (CUVal64 != 2) 2202 return; 2203 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 2204 break; 2205 case 'L': // 0 2206 if (CUVal64 != 0) 2207 return; 2208 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 2209 break; 2210 case 'M': // 0..255 2211 if (!isUInt<8>(CUVal64)) 2212 return; 2213 // i8 type may be printed as a negative number, 2214 // e.g. 254 would be printed as -2, 2215 // so we force it to i16 at least. 2216 if (Ty.getSimpleVT() == MVT::i8) { 2217 Ty = MVT::i16; 2218 } 2219 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 2220 break; 2221 case 'N': // -1 2222 if (CVal64 != -1) 2223 return; 2224 Result = DAG.getTargetConstant(CVal64, DL, Ty); 2225 break; 2226 case 'O': // 8, 16, 24 2227 if (CUVal64 != 8 && CUVal64 != 16 && CUVal64 != 24) 2228 return; 2229 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 2230 break; 2231 case 'P': // 1 2232 if (CUVal64 != 1) 2233 return; 2234 Result = DAG.getTargetConstant(CUVal64, DL, Ty); 2235 break; 2236 case 'R': // -6..5 2237 if (CVal64 < -6 || CVal64 > 5) 2238 return; 2239 Result = DAG.getTargetConstant(CVal64, DL, Ty); 2240 break; 2241 } 2242 2243 break; 2244 } 2245 case 'G': 2246 const ConstantFPSDNode *FC = dyn_cast<ConstantFPSDNode>(Op); 2247 if (!FC || !FC->isZero()) 2248 return; 2249 // Soften float to i8 0 2250 Result = DAG.getTargetConstant(0, DL, MVT::i8); 2251 break; 2252 } 2253 2254 if (Result.getNode()) { 2255 Ops.push_back(Result); 2256 return; 2257 } 2258 2259 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 2260 } 2261 2262 Register AVRTargetLowering::getRegisterByName(const char *RegName, LLT VT, 2263 const MachineFunction &MF) const { 2264 Register Reg; 2265 2266 if (VT == LLT::scalar(8)) { 2267 Reg = StringSwitch<unsigned>(RegName) 2268 .Case("r0", AVR::R0) 2269 .Case("r1", AVR::R1) 2270 .Default(0); 2271 } else { 2272 Reg = StringSwitch<unsigned>(RegName) 2273 .Case("r0", AVR::R1R0) 2274 .Case("sp", AVR::SP) 2275 .Default(0); 2276 } 2277 2278 if (Reg) 2279 return Reg; 2280 2281 report_fatal_error( 2282 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 2283 } 2284 2285 } // end of namespace llvm 2286