blob: 0b95d3819399c11b660d841d13e686ef4fe1448f [file] [log] [blame]
Dylan McKay7549b0a2016-11-02 06:47:40 +00001//===-- AVRISelLowering.cpp - AVR DAG Lowering Implementation -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that AVR uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#include "AVRISelLowering.h"
16
Dylan McKay8fa6d8d2017-01-07 23:39:47 +000017#include "llvm/ADT/StringSwitch.h"
Dylan McKay7549b0a2016-11-02 06:47:40 +000018#include "llvm/CodeGen/CallingConvLower.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineInstrBuilder.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/SelectionDAG.h"
23#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
24#include "llvm/IR/Function.h"
25#include "llvm/Support/ErrorHandling.h"
26
27#include "AVR.h"
28#include "AVRMachineFunctionInfo.h"
29#include "AVRTargetMachine.h"
30#include "MCTargetDesc/AVRMCTargetDesc.h"
31
32namespace llvm {
33
34AVRTargetLowering::AVRTargetLowering(AVRTargetMachine &tm)
35 : TargetLowering(tm) {
36 // Set up the register classes.
37 addRegisterClass(MVT::i8, &AVR::GPR8RegClass);
38 addRegisterClass(MVT::i16, &AVR::DREGSRegClass);
39
40 // Compute derived properties from the register classes.
41 computeRegisterProperties(tm.getSubtargetImpl()->getRegisterInfo());
42
43 setBooleanContents(ZeroOrOneBooleanContent);
44 setBooleanVectorContents(ZeroOrOneBooleanContent);
45 setSchedulingPreference(Sched::RegPressure);
46 setStackPointerRegisterToSaveRestore(AVR::SP);
47
48 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
49 setOperationAction(ISD::BlockAddress, MVT::i16, Custom);
50
Dylan McKayccd819a2017-02-05 21:35:45 +000051 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
52 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Dylan McKay7549b0a2016-11-02 06:47:40 +000053 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
54 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
55
56 for (MVT VT : MVT::integer_valuetypes()) {
57 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
58 setLoadExtAction(N, VT, MVT::i1, Promote);
59 setLoadExtAction(N, VT, MVT::i8, Expand);
60 }
61 }
62
63 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
64
65 // sub (x, imm) gets canonicalized to add (x, -imm), so for illegal types
66 // revert into a sub since we don't have an add with immediate instruction.
67 setOperationAction(ISD::ADD, MVT::i32, Custom);
68 setOperationAction(ISD::ADD, MVT::i64, Custom);
69
70 // our shift instructions are only able to shift 1 bit at a time, so handle
71 // this in a custom way.
72 setOperationAction(ISD::SRA, MVT::i8, Custom);
73 setOperationAction(ISD::SHL, MVT::i8, Custom);
74 setOperationAction(ISD::SRL, MVT::i8, Custom);
75 setOperationAction(ISD::SRA, MVT::i16, Custom);
76 setOperationAction(ISD::SHL, MVT::i16, Custom);
77 setOperationAction(ISD::SRL, MVT::i16, Custom);
78 setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand);
79 setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand);
80 setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand);
81
82 setOperationAction(ISD::BR_CC, MVT::i8, Custom);
83 setOperationAction(ISD::BR_CC, MVT::i16, Custom);
84 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
85 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
86 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
87
88 setOperationAction(ISD::SELECT_CC, MVT::i8, Custom);
89 setOperationAction(ISD::SELECT_CC, MVT::i16, Custom);
Dylan McKay99b756e2016-12-07 12:34:47 +000090 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
91 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
Dylan McKay7549b0a2016-11-02 06:47:40 +000092 setOperationAction(ISD::SETCC, MVT::i8, Custom);
93 setOperationAction(ISD::SETCC, MVT::i16, Custom);
94 setOperationAction(ISD::SETCC, MVT::i32, Custom);
95 setOperationAction(ISD::SETCC, MVT::i64, Custom);
96 setOperationAction(ISD::SELECT, MVT::i8, Expand);
97 setOperationAction(ISD::SELECT, MVT::i16, Expand);
98
99 setOperationAction(ISD::BSWAP, MVT::i16, Expand);
100
101 // Add support for postincrement and predecrement load/stores.
102 setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
103 setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
104 setIndexedLoadAction(ISD::PRE_DEC, MVT::i8, Legal);
105 setIndexedLoadAction(ISD::PRE_DEC, MVT::i16, Legal);
106 setIndexedStoreAction(ISD::POST_INC, MVT::i8, Legal);
107 setIndexedStoreAction(ISD::POST_INC, MVT::i16, Legal);
108 setIndexedStoreAction(ISD::PRE_DEC, MVT::i8, Legal);
109 setIndexedStoreAction(ISD::PRE_DEC, MVT::i16, Legal);
110
111 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
112
113 setOperationAction(ISD::VASTART, MVT::Other, Custom);
114 setOperationAction(ISD::VAEND, MVT::Other, Expand);
115 setOperationAction(ISD::VAARG, MVT::Other, Expand);
116 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
117
118 // Atomic operations which must be lowered to rtlib calls
119 for (MVT VT : MVT::integer_valuetypes()) {
120 setOperationAction(ISD::ATOMIC_SWAP, VT, Expand);
121 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Expand);
122 setOperationAction(ISD::ATOMIC_LOAD_NAND, VT, Expand);
123 setOperationAction(ISD::ATOMIC_LOAD_MAX, VT, Expand);
124 setOperationAction(ISD::ATOMIC_LOAD_MIN, VT, Expand);
125 setOperationAction(ISD::ATOMIC_LOAD_UMAX, VT, Expand);
126 setOperationAction(ISD::ATOMIC_LOAD_UMIN, VT, Expand);
127 }
128
129 // Division/remainder
130 setOperationAction(ISD::UDIV, MVT::i8, Expand);
131 setOperationAction(ISD::UDIV, MVT::i16, Expand);
132 setOperationAction(ISD::UREM, MVT::i8, Expand);
133 setOperationAction(ISD::UREM, MVT::i16, Expand);
134 setOperationAction(ISD::SDIV, MVT::i8, Expand);
135 setOperationAction(ISD::SDIV, MVT::i16, Expand);
136 setOperationAction(ISD::SREM, MVT::i8, Expand);
137 setOperationAction(ISD::SREM, MVT::i16, Expand);
138
139 // Make division and modulus custom
140 for (MVT VT : MVT::integer_valuetypes()) {
141 setOperationAction(ISD::UDIVREM, VT, Custom);
142 setOperationAction(ISD::SDIVREM, VT, Custom);
143 }
144
145 // Do not use MUL. The AVR instructions are closer to SMUL_LOHI &co.
146 setOperationAction(ISD::MUL, MVT::i8, Expand);
147 setOperationAction(ISD::MUL, MVT::i16, Expand);
148
149 // Expand 16 bit multiplications.
150 setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand);
151 setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand);
152
153 for (MVT VT : MVT::integer_valuetypes()) {
154 setOperationAction(ISD::MULHS, VT, Expand);
155 setOperationAction(ISD::MULHU, VT, Expand);
156 }
157
158 for (MVT VT : MVT::integer_valuetypes()) {
159 setOperationAction(ISD::CTPOP, VT, Expand);
160 setOperationAction(ISD::CTLZ, VT, Expand);
161 setOperationAction(ISD::CTTZ, VT, Expand);
162 }
163
164 for (MVT VT : MVT::integer_valuetypes()) {
165 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
166 // TODO: The generated code is pretty poor. Investigate using the
167 // same "shift and subtract with carry" trick that we do for
168 // extending 8-bit to 16-bit. This may require infrastructure
169 // improvements in how we treat 16-bit "registers" to be feasible.
170 }
171
172 // Division rtlib functions (not supported)
173 setLibcallName(RTLIB::SDIV_I8, nullptr);
174 setLibcallName(RTLIB::SDIV_I16, nullptr);
175 setLibcallName(RTLIB::SDIV_I32, nullptr);
176 setLibcallName(RTLIB::SDIV_I64, nullptr);
177 setLibcallName(RTLIB::SDIV_I128, nullptr);
178 setLibcallName(RTLIB::UDIV_I8, nullptr);
179 setLibcallName(RTLIB::UDIV_I16, nullptr);
180 setLibcallName(RTLIB::UDIV_I32, nullptr);
181 setLibcallName(RTLIB::UDIV_I64, nullptr);
182 setLibcallName(RTLIB::UDIV_I128, nullptr);
183
184 // Modulus rtlib functions (not supported)
185 setLibcallName(RTLIB::SREM_I8, nullptr);
186 setLibcallName(RTLIB::SREM_I16, nullptr);
187 setLibcallName(RTLIB::SREM_I32, nullptr);
188 setLibcallName(RTLIB::SREM_I64, nullptr);
189 setLibcallName(RTLIB::SREM_I128, nullptr);
190 setLibcallName(RTLIB::UREM_I8, nullptr);
191 setLibcallName(RTLIB::UREM_I16, nullptr);
192 setLibcallName(RTLIB::UREM_I32, nullptr);
193 setLibcallName(RTLIB::UREM_I64, nullptr);
194 setLibcallName(RTLIB::UREM_I128, nullptr);
195
196 // Division and modulus rtlib functions
197 setLibcallName(RTLIB::SDIVREM_I8, "__divmodqi4");
198 setLibcallName(RTLIB::SDIVREM_I16, "__divmodhi4");
199 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
200 setLibcallName(RTLIB::SDIVREM_I64, "__divmoddi4");
201 setLibcallName(RTLIB::SDIVREM_I128, "__divmodti4");
202 setLibcallName(RTLIB::UDIVREM_I8, "__udivmodqi4");
203 setLibcallName(RTLIB::UDIVREM_I16, "__udivmodhi4");
204 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
205 setLibcallName(RTLIB::UDIVREM_I64, "__udivmoddi4");
206 setLibcallName(RTLIB::UDIVREM_I128, "__udivmodti4");
207
208 // Several of the runtime library functions use a special calling conv
209 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::AVR_BUILTIN);
210 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::AVR_BUILTIN);
211 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::AVR_BUILTIN);
212 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::AVR_BUILTIN);
213
214 // Trigonometric rtlib functions
215 setLibcallName(RTLIB::SIN_F32, "sin");
216 setLibcallName(RTLIB::COS_F32, "cos");
217
218 setMinFunctionAlignment(1);
219 setMinimumJumpTableEntries(INT_MAX);
220}
221
222const char *AVRTargetLowering::getTargetNodeName(unsigned Opcode) const {
223#define NODE(name) \
224 case AVRISD::name: \
225 return #name
226
227 switch (Opcode) {
228 default:
229 return nullptr;
230 NODE(RET_FLAG);
231 NODE(RETI_FLAG);
232 NODE(CALL);
233 NODE(WRAPPER);
234 NODE(LSL);
235 NODE(LSR);
236 NODE(ROL);
237 NODE(ROR);
238 NODE(ASR);
239 NODE(LSLLOOP);
240 NODE(LSRLOOP);
241 NODE(ASRLOOP);
242 NODE(BRCOND);
243 NODE(CMP);
244 NODE(CMPC);
245 NODE(TST);
246 NODE(SELECT_CC);
247#undef NODE
248 }
249}
250
251EVT AVRTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
252 EVT VT) const {
253 assert(!VT.isVector() && "No AVR SetCC type for vectors!");
254 return MVT::i8;
255}
256
257SDValue AVRTargetLowering::LowerShifts(SDValue Op, SelectionDAG &DAG) const {
258 //:TODO: this function has to be completely rewritten to produce optimal
259 // code, for now it's producing very long but correct code.
260 unsigned Opc8;
261 const SDNode *N = Op.getNode();
262 EVT VT = Op.getValueType();
263 SDLoc dl(N);
264
265 // Expand non-constant shifts to loops.
266 if (!isa<ConstantSDNode>(N->getOperand(1))) {
267 switch (Op.getOpcode()) {
268 default:
269 llvm_unreachable("Invalid shift opcode!");
270 case ISD::SHL:
271 return DAG.getNode(AVRISD::LSLLOOP, dl, VT, N->getOperand(0),
272 N->getOperand(1));
273 case ISD::SRL:
274 return DAG.getNode(AVRISD::LSRLOOP, dl, VT, N->getOperand(0),
275 N->getOperand(1));
276 case ISD::SRA:
277 return DAG.getNode(AVRISD::ASRLOOP, dl, VT, N->getOperand(0),
278 N->getOperand(1));
279 }
280 }
281
282 uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
283 SDValue Victim = N->getOperand(0);
284
285 switch (Op.getOpcode()) {
286 case ISD::SRA:
287 Opc8 = AVRISD::ASR;
288 break;
289 case ISD::ROTL:
290 Opc8 = AVRISD::ROL;
291 break;
292 case ISD::ROTR:
293 Opc8 = AVRISD::ROR;
294 break;
295 case ISD::SRL:
296 Opc8 = AVRISD::LSR;
297 break;
298 case ISD::SHL:
299 Opc8 = AVRISD::LSL;
300 break;
301 default:
302 llvm_unreachable("Invalid shift opcode");
303 }
304
305 while (ShiftAmount--) {
306 Victim = DAG.getNode(Opc8, dl, VT, Victim);
307 }
308
309 return Victim;
310}
311
312SDValue AVRTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
313 unsigned Opcode = Op->getOpcode();
314 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
315 "Invalid opcode for Div/Rem lowering");
Meador Inge5d3c5992017-03-24 01:57:29 +0000316 bool IsSigned = (Opcode == ISD::SDIVREM);
Dylan McKay7549b0a2016-11-02 06:47:40 +0000317 EVT VT = Op->getValueType(0);
318 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
319
320 RTLIB::Libcall LC;
321 switch (VT.getSimpleVT().SimpleTy) {
322 default:
323 llvm_unreachable("Unexpected request for libcall!");
324 case MVT::i8:
Meador Inge5d3c5992017-03-24 01:57:29 +0000325 LC = IsSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8;
Dylan McKay7549b0a2016-11-02 06:47:40 +0000326 break;
327 case MVT::i16:
Meador Inge5d3c5992017-03-24 01:57:29 +0000328 LC = IsSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16;
Dylan McKay7549b0a2016-11-02 06:47:40 +0000329 break;
330 case MVT::i32:
Meador Inge5d3c5992017-03-24 01:57:29 +0000331 LC = IsSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32;
Dylan McKay7549b0a2016-11-02 06:47:40 +0000332 break;
333 case MVT::i64:
Meador Inge5d3c5992017-03-24 01:57:29 +0000334 LC = IsSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64;
Dylan McKay7549b0a2016-11-02 06:47:40 +0000335 break;
336 }
337
338 SDValue InChain = DAG.getEntryNode();
339
340 TargetLowering::ArgListTy Args;
341 TargetLowering::ArgListEntry Entry;
342 for (SDValue const &Value : Op->op_values()) {
343 Entry.Node = Value;
344 Entry.Ty = Value.getValueType().getTypeForEVT(*DAG.getContext());
Meador Inge5d3c5992017-03-24 01:57:29 +0000345 Entry.IsSExt = IsSigned;
346 Entry.IsZExt = !IsSigned;
Dylan McKay7549b0a2016-11-02 06:47:40 +0000347 Args.push_back(Entry);
348 }
349
350 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
351 getPointerTy(DAG.getDataLayout()));
352
353 Type *RetTy = (Type *)StructType::get(Ty, Ty, nullptr);
354
355 SDLoc dl(Op);
356 TargetLowering::CallLoweringInfo CLI(DAG);
357 CLI.setDebugLoc(dl)
358 .setChain(InChain)
Nirav Daveac6081c2017-03-18 00:44:07 +0000359 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
Dylan McKay7549b0a2016-11-02 06:47:40 +0000360 .setInRegister()
Meador Inge5d3c5992017-03-24 01:57:29 +0000361 .setSExtResult(IsSigned)
362 .setZExtResult(!IsSigned);
Dylan McKay7549b0a2016-11-02 06:47:40 +0000363
364 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
365 return CallInfo.first;
366}
367
368SDValue AVRTargetLowering::LowerGlobalAddress(SDValue Op,
369 SelectionDAG &DAG) const {
370 auto DL = DAG.getDataLayout();
371
372 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
373 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
374
375 // Create the TargetGlobalAddress node, folding in the constant offset.
376 SDValue Result =
377 DAG.getTargetGlobalAddress(GV, SDLoc(Op), getPointerTy(DL), Offset);
378 return DAG.getNode(AVRISD::WRAPPER, SDLoc(Op), getPointerTy(DL), Result);
379}
380
381SDValue AVRTargetLowering::LowerBlockAddress(SDValue Op,
382 SelectionDAG &DAG) const {
383 auto DL = DAG.getDataLayout();
384 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
385
386 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(DL));
387
388 return DAG.getNode(AVRISD::WRAPPER, SDLoc(Op), getPointerTy(DL), Result);
389}
390
391/// IntCCToAVRCC - Convert a DAG integer condition code to an AVR CC.
392static AVRCC::CondCodes intCCToAVRCC(ISD::CondCode CC) {
393 switch (CC) {
394 default:
395 llvm_unreachable("Unknown condition code!");
396 case ISD::SETEQ:
397 return AVRCC::COND_EQ;
398 case ISD::SETNE:
399 return AVRCC::COND_NE;
400 case ISD::SETGE:
401 return AVRCC::COND_GE;
402 case ISD::SETLT:
403 return AVRCC::COND_LT;
404 case ISD::SETUGE:
405 return AVRCC::COND_SH;
406 case ISD::SETULT:
407 return AVRCC::COND_LO;
408 }
409}
410
411/// Returns appropriate AVR CMP/CMPC nodes and corresponding condition code for
412/// the given operands.
413SDValue AVRTargetLowering::getAVRCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
414 SDValue &AVRcc, SelectionDAG &DAG,
415 SDLoc DL) const {
416 SDValue Cmp;
417 EVT VT = LHS.getValueType();
418 bool UseTest = false;
419
420 switch (CC) {
421 default:
422 break;
423 case ISD::SETLE: {
424 // Swap operands and reverse the branching condition.
425 std::swap(LHS, RHS);
426 CC = ISD::SETGE;
427 break;
428 }
429 case ISD::SETGT: {
430 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
431 switch (C->getSExtValue()) {
432 case -1: {
433 // When doing lhs > -1 use a tst instruction on the top part of lhs
434 // and use brpl instead of using a chain of cp/cpc.
435 UseTest = true;
436 AVRcc = DAG.getConstant(AVRCC::COND_PL, DL, MVT::i8);
437 break;
438 }
439 case 0: {
440 // Turn lhs > 0 into 0 < lhs since 0 can be materialized with
441 // __zero_reg__ in lhs.
442 RHS = LHS;
443 LHS = DAG.getConstant(0, DL, VT);
444 CC = ISD::SETLT;
445 break;
446 }
447 default: {
448 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows
449 // us to fold the constant into the cmp instruction.
450 RHS = DAG.getConstant(C->getSExtValue() + 1, DL, VT);
451 CC = ISD::SETGE;
452 break;
453 }
454 }
455 break;
456 }
457 // Swap operands and reverse the branching condition.
458 std::swap(LHS, RHS);
459 CC = ISD::SETLT;
460 break;
461 }
462 case ISD::SETLT: {
463 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
464 switch (C->getSExtValue()) {
465 case 1: {
466 // Turn lhs < 1 into 0 >= lhs since 0 can be materialized with
467 // __zero_reg__ in lhs.
468 RHS = LHS;
469 LHS = DAG.getConstant(0, DL, VT);
470 CC = ISD::SETGE;
471 break;
472 }
473 case 0: {
474 // When doing lhs < 0 use a tst instruction on the top part of lhs
475 // and use brmi instead of using a chain of cp/cpc.
476 UseTest = true;
477 AVRcc = DAG.getConstant(AVRCC::COND_MI, DL, MVT::i8);
478 break;
479 }
480 }
481 }
482 break;
483 }
484 case ISD::SETULE: {
485 // Swap operands and reverse the branching condition.
486 std::swap(LHS, RHS);
487 CC = ISD::SETUGE;
488 break;
489 }
490 case ISD::SETUGT: {
491 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
492 // fold the constant into the cmp instruction.
493 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
494 RHS = DAG.getConstant(C->getSExtValue() + 1, DL, VT);
495 CC = ISD::SETUGE;
496 break;
497 }
498 // Swap operands and reverse the branching condition.
499 std::swap(LHS, RHS);
500 CC = ISD::SETULT;
501 break;
502 }
503 }
504
505 // Expand 32 and 64 bit comparisons with custom CMP and CMPC nodes instead of
506 // using the default and/or/xor expansion code which is much longer.
507 if (VT == MVT::i32) {
508 SDValue LHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS,
509 DAG.getIntPtrConstant(0, DL));
510 SDValue LHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS,
511 DAG.getIntPtrConstant(1, DL));
512 SDValue RHSlo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS,
513 DAG.getIntPtrConstant(0, DL));
514 SDValue RHShi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS,
515 DAG.getIntPtrConstant(1, DL));
516
517 if (UseTest) {
518 // When using tst we only care about the highest part.
519 SDValue Top = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHShi,
520 DAG.getIntPtrConstant(1, DL));
521 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, Top);
522 } else {
523 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHSlo, RHSlo);
524 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHShi, RHShi, Cmp);
525 }
526 } else if (VT == MVT::i64) {
527 SDValue LHS_0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS,
528 DAG.getIntPtrConstant(0, DL));
529 SDValue LHS_1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS,
530 DAG.getIntPtrConstant(1, DL));
531
532 SDValue LHS0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_0,
533 DAG.getIntPtrConstant(0, DL));
534 SDValue LHS1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_0,
535 DAG.getIntPtrConstant(1, DL));
536 SDValue LHS2 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_1,
537 DAG.getIntPtrConstant(0, DL));
538 SDValue LHS3 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, LHS_1,
539 DAG.getIntPtrConstant(1, DL));
540
541 SDValue RHS_0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS,
542 DAG.getIntPtrConstant(0, DL));
543 SDValue RHS_1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS,
544 DAG.getIntPtrConstant(1, DL));
545
546 SDValue RHS0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_0,
547 DAG.getIntPtrConstant(0, DL));
548 SDValue RHS1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_0,
549 DAG.getIntPtrConstant(1, DL));
550 SDValue RHS2 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_1,
551 DAG.getIntPtrConstant(0, DL));
552 SDValue RHS3 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i16, RHS_1,
553 DAG.getIntPtrConstant(1, DL));
554
555 if (UseTest) {
556 // When using tst we only care about the highest part.
557 SDValue Top = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8, LHS3,
558 DAG.getIntPtrConstant(1, DL));
559 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue, Top);
560 } else {
561 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHS0, RHS0);
562 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS1, RHS1, Cmp);
563 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS2, RHS2, Cmp);
564 Cmp = DAG.getNode(AVRISD::CMPC, DL, MVT::Glue, LHS3, RHS3, Cmp);
565 }
566 } else if (VT == MVT::i8 || VT == MVT::i16) {
567 if (UseTest) {
568 // When using tst we only care about the highest part.
569 Cmp = DAG.getNode(AVRISD::TST, DL, MVT::Glue,
570 (VT == MVT::i8)
571 ? LHS
572 : DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i8,
573 LHS, DAG.getIntPtrConstant(1, DL)));
574 } else {
575 Cmp = DAG.getNode(AVRISD::CMP, DL, MVT::Glue, LHS, RHS);
576 }
577 } else {
578 llvm_unreachable("Invalid comparison size");
579 }
580
581 // When using a test instruction AVRcc is already set.
582 if (!UseTest) {
583 AVRcc = DAG.getConstant(intCCToAVRCC(CC), DL, MVT::i8);
584 }
585
586 return Cmp;
587}
588
589SDValue AVRTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
590 SDValue Chain = Op.getOperand(0);
591 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
592 SDValue LHS = Op.getOperand(2);
593 SDValue RHS = Op.getOperand(3);
594 SDValue Dest = Op.getOperand(4);
595 SDLoc dl(Op);
596
597 SDValue TargetCC;
598 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, dl);
599
600 return DAG.getNode(AVRISD::BRCOND, dl, MVT::Other, Chain, Dest, TargetCC,
601 Cmp);
602}
603
604SDValue AVRTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
605 SDValue LHS = Op.getOperand(0);
606 SDValue RHS = Op.getOperand(1);
607 SDValue TrueV = Op.getOperand(2);
608 SDValue FalseV = Op.getOperand(3);
609 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
610 SDLoc dl(Op);
611
612 SDValue TargetCC;
613 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, dl);
614
615 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
616 SDValue Ops[] = {TrueV, FalseV, TargetCC, Cmp};
617
618 return DAG.getNode(AVRISD::SELECT_CC, dl, VTs, Ops);
619}
620
621SDValue AVRTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
622 SDValue LHS = Op.getOperand(0);
623 SDValue RHS = Op.getOperand(1);
624 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
625 SDLoc DL(Op);
626
627 SDValue TargetCC;
628 SDValue Cmp = getAVRCmp(LHS, RHS, CC, TargetCC, DAG, DL);
629
630 SDValue TrueV = DAG.getConstant(1, DL, Op.getValueType());
631 SDValue FalseV = DAG.getConstant(0, DL, Op.getValueType());
632 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
633 SDValue Ops[] = {TrueV, FalseV, TargetCC, Cmp};
634
635 return DAG.getNode(AVRISD::SELECT_CC, DL, VTs, Ops);
636}
637
638SDValue AVRTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
639 const MachineFunction &MF = DAG.getMachineFunction();
640 const AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
641 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
642 auto DL = DAG.getDataLayout();
643 SDLoc dl(Op);
644
645 // Vastart just stores the address of the VarArgsFrameIndex slot into the
646 // memory location argument.
647 SDValue FI = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(), getPointerTy(DL));
648
649 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
650 MachinePointerInfo(SV), 0);
651}
652
653SDValue AVRTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
654 switch (Op.getOpcode()) {
655 default:
656 llvm_unreachable("Don't know how to custom lower this!");
657 case ISD::SHL:
658 case ISD::SRA:
659 case ISD::SRL:
660 case ISD::ROTL:
661 case ISD::ROTR:
662 return LowerShifts(Op, DAG);
663 case ISD::GlobalAddress:
664 return LowerGlobalAddress(Op, DAG);
665 case ISD::BlockAddress:
666 return LowerBlockAddress(Op, DAG);
667 case ISD::BR_CC:
668 return LowerBR_CC(Op, DAG);
669 case ISD::SELECT_CC:
670 return LowerSELECT_CC(Op, DAG);
671 case ISD::SETCC:
672 return LowerSETCC(Op, DAG);
673 case ISD::VASTART:
674 return LowerVASTART(Op, DAG);
675 case ISD::SDIVREM:
676 case ISD::UDIVREM:
677 return LowerDivRem(Op, DAG);
678 }
679
680 return SDValue();
681}
682
683/// Replace a node with an illegal result type
684/// with a new node built out of custom code.
685void AVRTargetLowering::ReplaceNodeResults(SDNode *N,
686 SmallVectorImpl<SDValue> &Results,
687 SelectionDAG &DAG) const {
688 SDLoc DL(N);
689
690 switch (N->getOpcode()) {
691 case ISD::ADD: {
692 // Convert add (x, imm) into sub (x, -imm).
693 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
694 SDValue Sub = DAG.getNode(
695 ISD::SUB, DL, N->getValueType(0), N->getOperand(0),
696 DAG.getConstant(-C->getAPIntValue(), DL, C->getValueType(0)));
697 Results.push_back(Sub);
698 }
699 break;
700 }
701 default: {
702 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
703
704 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
705 Results.push_back(Res.getValue(I));
706
707 break;
708 }
709 }
710}
711
712/// Return true if the addressing mode represented
713/// by AM is legal for this target, for a load/store of the specified type.
714bool AVRTargetLowering::isLegalAddressingMode(const DataLayout &DL,
715 const AddrMode &AM, Type *Ty,
716 unsigned AS) const {
717 int64_t Offs = AM.BaseOffs;
718
719 // Allow absolute addresses.
720 if (AM.BaseGV && !AM.HasBaseReg && AM.Scale == 0 && Offs == 0) {
721 return true;
722 }
723
724 // Flash memory instructions only allow zero offsets.
725 if (isa<PointerType>(Ty) && AS == AVR::ProgramMemory) {
726 return false;
727 }
728
729 // Allow reg+<6bit> offset.
730 if (Offs < 0)
731 Offs = -Offs;
732 if (AM.BaseGV == 0 && AM.HasBaseReg && AM.Scale == 0 && isUInt<6>(Offs)) {
733 return true;
734 }
735
736 return false;
737}
738
739/// Returns true by value, base pointer and
740/// offset pointer and addressing mode by reference if the node's address
741/// can be legally represented as pre-indexed load / store address.
742bool AVRTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
743 SDValue &Offset,
744 ISD::MemIndexedMode &AM,
745 SelectionDAG &DAG) const {
746 EVT VT;
747 const SDNode *Op;
748 SDLoc DL(N);
749
750 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
751 VT = LD->getMemoryVT();
752 Op = LD->getBasePtr().getNode();
753 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
754 return false;
755 if (AVR::isProgramMemoryAccess(LD)) {
756 return false;
757 }
758 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
759 VT = ST->getMemoryVT();
760 Op = ST->getBasePtr().getNode();
761 if (AVR::isProgramMemoryAccess(ST)) {
762 return false;
763 }
764 } else {
765 return false;
766 }
767
768 if (VT != MVT::i8 && VT != MVT::i16) {
769 return false;
770 }
771
772 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) {
773 return false;
774 }
775
776 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
777 int RHSC = RHS->getSExtValue();
778 if (Op->getOpcode() == ISD::SUB)
779 RHSC = -RHSC;
780
781 if ((VT == MVT::i16 && RHSC != -2) || (VT == MVT::i8 && RHSC != -1)) {
782 return false;
783 }
784
785 Base = Op->getOperand(0);
786 Offset = DAG.getConstant(RHSC, DL, MVT::i8);
787 AM = ISD::PRE_DEC;
788
789 return true;
790 }
791
792 return false;
793}
794
795/// Returns true by value, base pointer and
796/// offset pointer and addressing mode by reference if this node can be
797/// combined with a load / store to form a post-indexed load / store.
798bool AVRTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
799 SDValue &Base,
800 SDValue &Offset,
801 ISD::MemIndexedMode &AM,
802 SelectionDAG &DAG) const {
803 EVT VT;
804 SDLoc DL(N);
805
806 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
807 VT = LD->getMemoryVT();
808 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
809 return false;
810 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
811 VT = ST->getMemoryVT();
812 if (AVR::isProgramMemoryAccess(ST)) {
813 return false;
814 }
815 } else {
816 return false;
817 }
818
819 if (VT != MVT::i8 && VT != MVT::i16) {
820 return false;
821 }
822
823 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) {
824 return false;
825 }
826
827 if (const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
828 int RHSC = RHS->getSExtValue();
829 if (Op->getOpcode() == ISD::SUB)
830 RHSC = -RHSC;
831 if ((VT == MVT::i16 && RHSC != 2) || (VT == MVT::i8 && RHSC != 1)) {
832 return false;
833 }
834
835 Base = Op->getOperand(0);
836 Offset = DAG.getConstant(RHSC, DL, MVT::i8);
837 AM = ISD::POST_INC;
838
839 return true;
840 }
841
842 return false;
843}
844
845bool AVRTargetLowering::isOffsetFoldingLegal(
846 const GlobalAddressSDNode *GA) const {
847 return true;
848}
849
850//===----------------------------------------------------------------------===//
851// Formal Arguments Calling Convention Implementation
852//===----------------------------------------------------------------------===//
853
854#include "AVRGenCallingConv.inc"
855
856/// For each argument in a function store the number of pieces it is composed
857/// of.
858static void parseFunctionArgs(const Function *F, const DataLayout *TD,
859 SmallVectorImpl<unsigned> &Out) {
860 for (Argument const &Arg : F->args()) {
861 unsigned Bytes = (TD->getTypeSizeInBits(Arg.getType()) + 7) / 8;
862 Out.push_back((Bytes + 1) / 2);
863 }
864}
865
866/// For external symbols there is no function prototype information so we
867/// have to rely directly on argument sizes.
868static void parseExternFuncCallArgs(const SmallVectorImpl<ISD::OutputArg> &In,
869 SmallVectorImpl<unsigned> &Out) {
870 for (unsigned i = 0, e = In.size(); i != e;) {
871 unsigned Size = 0;
872 unsigned Offset = 0;
873 while ((i != e) && (In[i].PartOffset == Offset)) {
874 Offset += In[i].VT.getStoreSize();
875 ++i;
876 ++Size;
877 }
878 Out.push_back(Size);
879 }
880}
881
882static StringRef getFunctionName(TargetLowering::CallLoweringInfo &CLI) {
883 SDValue Callee = CLI.Callee;
884
885 if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee)) {
886 return G->getSymbol();
887 }
888
889 if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
890 return G->getGlobal()->getName();
891 }
892
893 llvm_unreachable("don't know how to get the name for this callee");
894}
895
896/// Analyze incoming and outgoing function arguments. We need custom C++ code
897/// to handle special constraints in the ABI like reversing the order of the
898/// pieces of splitted arguments. In addition, all pieces of a certain argument
899/// have to be passed either using registers or the stack but never mixing both.
900static void analyzeStandardArguments(TargetLowering::CallLoweringInfo *CLI,
901 const Function *F, const DataLayout *TD,
902 const SmallVectorImpl<ISD::OutputArg> *Outs,
903 const SmallVectorImpl<ISD::InputArg> *Ins,
904 CallingConv::ID CallConv,
905 SmallVectorImpl<CCValAssign> &ArgLocs,
906 CCState &CCInfo, bool IsCall, bool IsVarArg) {
907 static const MCPhysReg RegList8[] = {AVR::R24, AVR::R22, AVR::R20,
908 AVR::R18, AVR::R16, AVR::R14,
909 AVR::R12, AVR::R10, AVR::R8};
910 static const MCPhysReg RegList16[] = {AVR::R25R24, AVR::R23R22, AVR::R21R20,
911 AVR::R19R18, AVR::R17R16, AVR::R15R14,
912 AVR::R13R12, AVR::R11R10, AVR::R9R8};
913 if (IsVarArg) {
914 // Variadic functions do not need all the analisys below.
915 if (IsCall) {
916 CCInfo.AnalyzeCallOperands(*Outs, ArgCC_AVR_Vararg);
917 } else {
918 CCInfo.AnalyzeFormalArguments(*Ins, ArgCC_AVR_Vararg);
919 }
920 return;
921 }
922
923 // Fill in the Args array which will contain original argument sizes.
924 SmallVector<unsigned, 8> Args;
925 if (IsCall) {
926 parseExternFuncCallArgs(*Outs, Args);
927 } else {
928 assert(F != nullptr && "function should not be null");
929 parseFunctionArgs(F, TD, Args);
930 }
931
932 unsigned RegsLeft = array_lengthof(RegList8), ValNo = 0;
933 // Variadic functions always use the stack.
934 bool UsesStack = false;
935 for (unsigned i = 0, pos = 0, e = Args.size(); i != e; ++i) {
936 unsigned Size = Args[i];
Dylan McKay7a3eb292017-02-05 09:53:45 +0000937
938 // If we have a zero-sized argument, don't attempt to lower it.
939 // AVR-GCC does not support zero-sized arguments and so we need not
940 // worry about ABI compatibility.
941 if (Size == 0) continue;
942
Dylan McKay7549b0a2016-11-02 06:47:40 +0000943 MVT LocVT = (IsCall) ? (*Outs)[pos].VT : (*Ins)[pos].VT;
944
945 // If we have plenty of regs to pass the whole argument do it.
946 if (!UsesStack && (Size <= RegsLeft)) {
947 const MCPhysReg *RegList = (LocVT == MVT::i16) ? RegList16 : RegList8;
948
949 for (unsigned j = 0; j != Size; ++j) {
950 unsigned Reg = CCInfo.AllocateReg(
951 ArrayRef<MCPhysReg>(RegList, array_lengthof(RegList8)));
952 CCInfo.addLoc(
953 CCValAssign::getReg(ValNo++, LocVT, Reg, LocVT, CCValAssign::Full));
954 --RegsLeft;
955 }
956
957 // Reverse the order of the pieces to agree with the "big endian" format
958 // required in the calling convention ABI.
959 std::reverse(ArgLocs.begin() + pos, ArgLocs.begin() + pos + Size);
960 } else {
961 // Pass the rest of arguments using the stack.
962 UsesStack = true;
963 for (unsigned j = 0; j != Size; ++j) {
964 unsigned Offset = CCInfo.AllocateStack(
965 TD->getTypeAllocSize(EVT(LocVT).getTypeForEVT(CCInfo.getContext())),
966 TD->getABITypeAlignment(
967 EVT(LocVT).getTypeForEVT(CCInfo.getContext())));
968 CCInfo.addLoc(CCValAssign::getMem(ValNo++, LocVT, Offset, LocVT,
969 CCValAssign::Full));
970 }
971 }
972 pos += Size;
973 }
974}
975
976static void analyzeBuiltinArguments(TargetLowering::CallLoweringInfo &CLI,
977 const Function *F, const DataLayout *TD,
978 const SmallVectorImpl<ISD::OutputArg> *Outs,
979 const SmallVectorImpl<ISD::InputArg> *Ins,
980 CallingConv::ID CallConv,
981 SmallVectorImpl<CCValAssign> &ArgLocs,
982 CCState &CCInfo, bool IsCall, bool IsVarArg) {
983 StringRef FuncName = getFunctionName(CLI);
984
985 if (FuncName.startswith("__udivmod") || FuncName.startswith("__divmod")) {
986 CCInfo.AnalyzeCallOperands(*Outs, ArgCC_AVR_BUILTIN_DIV);
987 } else {
988 analyzeStandardArguments(&CLI, F, TD, Outs, Ins,
989 CallConv, ArgLocs, CCInfo,
990 IsCall, IsVarArg);
991 }
992}
993
994static void analyzeArguments(TargetLowering::CallLoweringInfo *CLI,
995 const Function *F, const DataLayout *TD,
996 const SmallVectorImpl<ISD::OutputArg> *Outs,
997 const SmallVectorImpl<ISD::InputArg> *Ins,
998 CallingConv::ID CallConv,
999 SmallVectorImpl<CCValAssign> &ArgLocs,
1000 CCState &CCInfo, bool IsCall, bool IsVarArg) {
1001 switch (CallConv) {
1002 case CallingConv::AVR_BUILTIN: {
1003 analyzeBuiltinArguments(*CLI, F, TD, Outs, Ins,
1004 CallConv, ArgLocs, CCInfo,
1005 IsCall, IsVarArg);
1006 return;
1007 }
1008 default: {
1009 analyzeStandardArguments(CLI, F, TD, Outs, Ins,
1010 CallConv, ArgLocs, CCInfo,
1011 IsCall, IsVarArg);
1012 return;
1013 }
1014 }
1015}
1016
1017SDValue AVRTargetLowering::LowerFormalArguments(
1018 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1019 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, SelectionDAG &DAG,
1020 SmallVectorImpl<SDValue> &InVals) const {
1021 MachineFunction &MF = DAG.getMachineFunction();
1022 MachineFrameInfo &MFI = MF.getFrameInfo();
1023 auto DL = DAG.getDataLayout();
1024
1025 // Assign locations to all of the incoming arguments.
1026 SmallVector<CCValAssign, 16> ArgLocs;
1027 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1028 *DAG.getContext());
1029
1030 analyzeArguments(nullptr, MF.getFunction(), &DL, 0, &Ins, CallConv, ArgLocs, CCInfo,
1031 false, isVarArg);
1032
1033 SDValue ArgValue;
1034 for (CCValAssign &VA : ArgLocs) {
1035
1036 // Arguments stored on registers.
1037 if (VA.isRegLoc()) {
1038 EVT RegVT = VA.getLocVT();
1039 const TargetRegisterClass *RC;
1040 if (RegVT == MVT::i8) {
1041 RC = &AVR::GPR8RegClass;
1042 } else if (RegVT == MVT::i16) {
1043 RC = &AVR::DREGSRegClass;
1044 } else {
1045 llvm_unreachable("Unknown argument type!");
1046 }
1047
1048 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1049 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1050
1051 // :NOTE: Clang should not promote any i8 into i16 but for safety the
1052 // following code will handle zexts or sexts generated by other
1053 // front ends. Otherwise:
1054 // If this is an 8 bit value, it is really passed promoted
1055 // to 16 bits. Insert an assert[sz]ext to capture this, then
1056 // truncate to the right size.
1057 switch (VA.getLocInfo()) {
1058 default:
1059 llvm_unreachable("Unknown loc info!");
1060 case CCValAssign::Full:
1061 break;
1062 case CCValAssign::BCvt:
1063 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1064 break;
1065 case CCValAssign::SExt:
1066 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1067 DAG.getValueType(VA.getValVT()));
1068 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1069 break;
1070 case CCValAssign::ZExt:
1071 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1072 DAG.getValueType(VA.getValVT()));
1073 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1074 break;
1075 }
1076
1077 InVals.push_back(ArgValue);
1078 } else {
1079 // Sanity check.
1080 assert(VA.isMemLoc());
1081
1082 EVT LocVT = VA.getLocVT();
1083
1084 // Create the frame index object for this incoming parameter.
1085 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
1086 VA.getLocMemOffset(), true);
1087
1088 // Create the SelectionDAG nodes corresponding to a load
1089 // from this parameter.
1090 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DL));
1091 InVals.push_back(DAG.getLoad(LocVT, dl, Chain, FIN,
1092 MachinePointerInfo::getFixedStack(MF, FI),
1093 0));
1094 }
1095 }
1096
1097 // If the function takes variable number of arguments, make a frame index for
1098 // the start of the first vararg value... for expansion of llvm.va_start.
1099 if (isVarArg) {
1100 unsigned StackSize = CCInfo.getNextStackOffset();
1101 AVRMachineFunctionInfo *AFI = MF.getInfo<AVRMachineFunctionInfo>();
1102
1103 AFI->setVarArgsFrameIndex(MFI.CreateFixedObject(2, StackSize, true));
1104 }
1105
1106 return Chain;
1107}
1108
1109//===----------------------------------------------------------------------===//
1110// Call Calling Convention Implementation
1111//===----------------------------------------------------------------------===//
1112
1113SDValue AVRTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1114 SmallVectorImpl<SDValue> &InVals) const {
1115 SelectionDAG &DAG = CLI.DAG;
1116 SDLoc &DL = CLI.DL;
1117 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1118 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1119 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1120 SDValue Chain = CLI.Chain;
1121 SDValue Callee = CLI.Callee;
1122 bool &isTailCall = CLI.IsTailCall;
1123 CallingConv::ID CallConv = CLI.CallConv;
1124 bool isVarArg = CLI.IsVarArg;
1125
1126 MachineFunction &MF = DAG.getMachineFunction();
1127
1128 // AVR does not yet support tail call optimization.
1129 isTailCall = false;
1130
1131 // Analyze operands of the call, assigning locations to each operand.
1132 SmallVector<CCValAssign, 16> ArgLocs;
1133 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1134 *DAG.getContext());
1135
1136 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1137 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1138 // node so that legalize doesn't hack it.
1139 const Function *F = nullptr;
1140 if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1141 const GlobalValue *GV = G->getGlobal();
1142
1143 F = cast<Function>(GV);
1144 Callee =
1145 DAG.getTargetGlobalAddress(GV, DL, getPointerTy(DAG.getDataLayout()));
1146 } else if (const ExternalSymbolSDNode *ES =
1147 dyn_cast<ExternalSymbolSDNode>(Callee)) {
1148 Callee = DAG.getTargetExternalSymbol(ES->getSymbol(),
1149 getPointerTy(DAG.getDataLayout()));
1150 }
1151
1152 analyzeArguments(&CLI, F, &DAG.getDataLayout(), &Outs, 0, CallConv, ArgLocs, CCInfo,
1153 true, isVarArg);
1154
1155 // Get a count of how many bytes are to be pushed on the stack.
1156 unsigned NumBytes = CCInfo.getNextStackOffset();
1157
1158 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
1159 DL);
1160
1161 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1162
1163 // First, walk the register assignments, inserting copies.
1164 unsigned AI, AE;
1165 bool HasStackArgs = false;
1166 for (AI = 0, AE = ArgLocs.size(); AI != AE; ++AI) {
1167 CCValAssign &VA = ArgLocs[AI];
1168 EVT RegVT = VA.getLocVT();
1169 SDValue Arg = OutVals[AI];
1170
1171 // Promote the value if needed. With Clang this should not happen.
1172 switch (VA.getLocInfo()) {
1173 default:
1174 llvm_unreachable("Unknown loc info!");
1175 case CCValAssign::Full:
1176 break;
1177 case CCValAssign::SExt:
1178 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, RegVT, Arg);
1179 break;
1180 case CCValAssign::ZExt:
1181 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, RegVT, Arg);
1182 break;
1183 case CCValAssign::AExt:
1184 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, RegVT, Arg);
1185 break;
1186 case CCValAssign::BCvt:
1187 Arg = DAG.getNode(ISD::BITCAST, DL, RegVT, Arg);
1188 break;
1189 }
1190
1191 // Stop when we encounter a stack argument, we need to process them
1192 // in reverse order in the loop below.
1193 if (VA.isMemLoc()) {
1194 HasStackArgs = true;
1195 break;
1196 }
1197
1198 // Arguments that can be passed on registers must be kept in the RegsToPass
1199 // vector.
1200 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1201 }
1202
1203 // Second, stack arguments have to walked in reverse order by inserting
1204 // chained stores, this ensures their order is not changed by the scheduler
1205 // and that the push instruction sequence generated is correct, otherwise they
1206 // can be freely intermixed.
1207 if (HasStackArgs) {
1208 for (AE = AI, AI = ArgLocs.size(); AI != AE; --AI) {
1209 unsigned Loc = AI - 1;
1210 CCValAssign &VA = ArgLocs[Loc];
1211 SDValue Arg = OutVals[Loc];
1212
1213 assert(VA.isMemLoc());
1214
1215 // SP points to one stack slot further so add one to adjust it.
1216 SDValue PtrOff = DAG.getNode(
1217 ISD::ADD, DL, getPointerTy(DAG.getDataLayout()),
1218 DAG.getRegister(AVR::SP, getPointerTy(DAG.getDataLayout())),
1219 DAG.getIntPtrConstant(VA.getLocMemOffset() + 1, DL));
1220
1221 Chain =
1222 DAG.getStore(Chain, DL, Arg, PtrOff,
1223 MachinePointerInfo::getStack(MF, VA.getLocMemOffset()),
1224 0);
1225 }
1226 }
1227
1228 // Build a sequence of copy-to-reg nodes chained together with token chain and
1229 // flag operands which copy the outgoing args into registers. The InFlag in
1230 // necessary since all emited instructions must be stuck together.
1231 SDValue InFlag;
1232 for (auto Reg : RegsToPass) {
1233 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, InFlag);
1234 InFlag = Chain.getValue(1);
1235 }
1236
1237 // Returns a chain & a flag for retval copy to use.
1238 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1239 SmallVector<SDValue, 8> Ops;
1240 Ops.push_back(Chain);
1241 Ops.push_back(Callee);
1242
1243 // Add argument registers to the end of the list so that they are known live
1244 // into the call.
1245 for (auto Reg : RegsToPass) {
1246 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
1247 }
1248
1249 // Add a register mask operand representing the call-preserved registers.
1250 const AVRTargetMachine &TM = (const AVRTargetMachine &)getTargetMachine();
1251 const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
1252 const uint32_t *Mask =
1253 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
1254 assert(Mask && "Missing call preserved mask for calling convention");
1255 Ops.push_back(DAG.getRegisterMask(Mask));
1256
1257 if (InFlag.getNode()) {
1258 Ops.push_back(InFlag);
1259 }
1260
1261 Chain = DAG.getNode(AVRISD::CALL, DL, NodeTys, Ops);
1262 InFlag = Chain.getValue(1);
1263
1264 // Create the CALLSEQ_END node.
1265 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
1266 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
1267
1268 if (!Ins.empty()) {
1269 InFlag = Chain.getValue(1);
1270 }
1271
1272 // Handle result values, copying them out of physregs into vregs that we
1273 // return.
1274 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, DL, DAG,
1275 InVals);
1276}
1277
1278/// Lower the result values of a call into the
1279/// appropriate copies out of appropriate physical registers.
1280///
1281SDValue AVRTargetLowering::LowerCallResult(
1282 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1283 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, SelectionDAG &DAG,
1284 SmallVectorImpl<SDValue> &InVals) const {
1285
1286 // Assign locations to each value returned by this call.
1287 SmallVector<CCValAssign, 16> RVLocs;
1288 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1289 *DAG.getContext());
1290
1291 // Handle runtime calling convs.
1292 auto CCFunction = CCAssignFnForReturn(CallConv);
1293 CCInfo.AnalyzeCallResult(Ins, CCFunction);
1294
1295 if (CallConv != CallingConv::AVR_BUILTIN && RVLocs.size() > 1) {
1296 // Reverse splitted return values to get the "big endian" format required
1297 // to agree with the calling convention ABI.
1298 std::reverse(RVLocs.begin(), RVLocs.end());
1299 }
1300
1301 // Copy all of the result registers out of their specified physreg.
1302 for (CCValAssign const &RVLoc : RVLocs) {
1303 Chain = DAG.getCopyFromReg(Chain, dl, RVLoc.getLocReg(), RVLoc.getValVT(),
1304 InFlag)
1305 .getValue(1);
1306 InFlag = Chain.getValue(2);
1307 InVals.push_back(Chain.getValue(0));
1308 }
1309
1310 return Chain;
1311}
1312
1313//===----------------------------------------------------------------------===//
1314// Return Value Calling Convention Implementation
1315//===----------------------------------------------------------------------===//
1316
1317CCAssignFn *AVRTargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
1318 switch (CC) {
1319 case CallingConv::AVR_BUILTIN:
1320 return RetCC_AVR_BUILTIN;
1321 default:
1322 return RetCC_AVR;
1323 }
1324}
1325
1326bool
1327AVRTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1328 MachineFunction &MF, bool isVarArg,
1329 const SmallVectorImpl<ISD::OutputArg> &Outs,
1330 LLVMContext &Context) const
1331{
1332 SmallVector<CCValAssign, 16> RVLocs;
1333 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1334
1335 auto CCFunction = CCAssignFnForReturn(CallConv);
1336 return CCInfo.CheckReturn(Outs, CCFunction);
1337}
1338
1339SDValue
1340AVRTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1341 bool isVarArg,
1342 const SmallVectorImpl<ISD::OutputArg> &Outs,
1343 const SmallVectorImpl<SDValue> &OutVals,
1344 const SDLoc &dl, SelectionDAG &DAG) const {
1345 // CCValAssign - represent the assignment of the return value to locations.
1346 SmallVector<CCValAssign, 16> RVLocs;
1347
1348 // CCState - Info about the registers and stack slot.
1349 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1350 *DAG.getContext());
1351
1352 // Analyze return values.
1353 auto CCFunction = CCAssignFnForReturn(CallConv);
1354 CCInfo.AnalyzeReturn(Outs, CCFunction);
1355
1356 // If this is the first return lowered for this function, add the regs to
1357 // the liveout set for the function.
1358 MachineFunction &MF = DAG.getMachineFunction();
1359 unsigned e = RVLocs.size();
1360
1361 // Reverse splitted return values to get the "big endian" format required
1362 // to agree with the calling convention ABI.
1363 if (e > 1) {
1364 std::reverse(RVLocs.begin(), RVLocs.end());
1365 }
1366
1367 SDValue Flag;
1368 SmallVector<SDValue, 4> RetOps(1, Chain);
1369 // Copy the result values into the output registers.
1370 for (unsigned i = 0; i != e; ++i) {
1371 CCValAssign &VA = RVLocs[i];
1372 assert(VA.isRegLoc() && "Can only return in registers!");
1373
1374 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1375
1376 // Guarantee that all emitted copies are stuck together with flags.
1377 Flag = Chain.getValue(1);
1378 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1379 }
1380
1381 // Don't emit the ret/reti instruction when the naked attribute is present in
1382 // the function being compiled.
1383 if (MF.getFunction()->getAttributes().hasAttribute(
Reid Klecknerb5180542017-03-21 16:57:19 +00001384 AttributeList::FunctionIndex, Attribute::Naked)) {
Dylan McKay7549b0a2016-11-02 06:47:40 +00001385 return Chain;
1386 }
1387
1388 unsigned RetOpc =
1389 (CallConv == CallingConv::AVR_INTR || CallConv == CallingConv::AVR_SIGNAL)
1390 ? AVRISD::RETI_FLAG
1391 : AVRISD::RET_FLAG;
1392
1393 RetOps[0] = Chain; // Update chain.
1394
1395 if (Flag.getNode()) {
1396 RetOps.push_back(Flag);
1397 }
1398
1399 return DAG.getNode(RetOpc, dl, MVT::Other, RetOps);
1400}
1401
1402//===----------------------------------------------------------------------===//
1403// Custom Inserters
1404//===----------------------------------------------------------------------===//
1405
1406MachineBasicBlock *AVRTargetLowering::insertShift(MachineInstr &MI,
1407 MachineBasicBlock *BB) const {
1408 unsigned Opc;
1409 const TargetRegisterClass *RC;
1410 MachineFunction *F = BB->getParent();
1411 MachineRegisterInfo &RI = F->getRegInfo();
1412 const AVRTargetMachine &TM = (const AVRTargetMachine &)getTargetMachine();
1413 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
1414 DebugLoc dl = MI.getDebugLoc();
1415
1416 switch (MI.getOpcode()) {
1417 default:
1418 llvm_unreachable("Invalid shift opcode!");
1419 case AVR::Lsl8:
1420 Opc = AVR::LSLRd;
1421 RC = &AVR::GPR8RegClass;
1422 break;
1423 case AVR::Lsl16:
1424 Opc = AVR::LSLWRd;
1425 RC = &AVR::DREGSRegClass;
1426 break;
1427 case AVR::Asr8:
1428 Opc = AVR::ASRRd;
1429 RC = &AVR::GPR8RegClass;
1430 break;
1431 case AVR::Asr16:
1432 Opc = AVR::ASRWRd;
1433 RC = &AVR::DREGSRegClass;
1434 break;
1435 case AVR::Lsr8:
1436 Opc = AVR::LSRRd;
1437 RC = &AVR::GPR8RegClass;
1438 break;
1439 case AVR::Lsr16:
1440 Opc = AVR::LSRWRd;
1441 RC = &AVR::DREGSRegClass;
1442 break;
1443 }
1444
1445 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1446 MachineFunction::iterator I = BB->getParent()->begin();
1447 ++I;
1448
1449 // Create loop block.
1450 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1451 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB);
1452
1453 F->insert(I, LoopBB);
1454 F->insert(I, RemBB);
1455
1456 // Update machine-CFG edges by transferring all successors of the current
1457 // block to the block containing instructions after shift.
1458 RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
1459 BB->end());
1460 RemBB->transferSuccessorsAndUpdatePHIs(BB);
1461
1462 // Add adges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB.
1463 BB->addSuccessor(LoopBB);
1464 BB->addSuccessor(RemBB);
1465 LoopBB->addSuccessor(RemBB);
1466 LoopBB->addSuccessor(LoopBB);
1467
1468 unsigned ShiftAmtReg = RI.createVirtualRegister(&AVR::LD8RegClass);
1469 unsigned ShiftAmtReg2 = RI.createVirtualRegister(&AVR::LD8RegClass);
1470 unsigned ShiftReg = RI.createVirtualRegister(RC);
1471 unsigned ShiftReg2 = RI.createVirtualRegister(RC);
1472 unsigned ShiftAmtSrcReg = MI.getOperand(2).getReg();
1473 unsigned SrcReg = MI.getOperand(1).getReg();
1474 unsigned DstReg = MI.getOperand(0).getReg();
1475
1476 // BB:
1477 // cp 0, N
1478 // breq RemBB
1479 BuildMI(BB, dl, TII.get(AVR::CPRdRr)).addReg(ShiftAmtSrcReg).addReg(AVR::R0);
1480 BuildMI(BB, dl, TII.get(AVR::BREQk)).addMBB(RemBB);
1481
1482 // LoopBB:
1483 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1484 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
1485 // ShiftReg2 = shift ShiftReg
1486 // ShiftAmt2 = ShiftAmt - 1;
1487 BuildMI(LoopBB, dl, TII.get(AVR::PHI), ShiftReg)
1488 .addReg(SrcReg)
1489 .addMBB(BB)
1490 .addReg(ShiftReg2)
1491 .addMBB(LoopBB);
1492 BuildMI(LoopBB, dl, TII.get(AVR::PHI), ShiftAmtReg)
1493 .addReg(ShiftAmtSrcReg)
1494 .addMBB(BB)
1495 .addReg(ShiftAmtReg2)
1496 .addMBB(LoopBB);
1497 BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2).addReg(ShiftReg);
1498 BuildMI(LoopBB, dl, TII.get(AVR::SUBIRdK), ShiftAmtReg2)
1499 .addReg(ShiftAmtReg)
1500 .addImm(1);
1501 BuildMI(LoopBB, dl, TII.get(AVR::BRNEk)).addMBB(LoopBB);
1502
1503 // RemBB:
1504 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1505 BuildMI(*RemBB, RemBB->begin(), dl, TII.get(AVR::PHI), DstReg)
1506 .addReg(SrcReg)
1507 .addMBB(BB)
1508 .addReg(ShiftReg2)
1509 .addMBB(LoopBB);
1510
1511 MI.eraseFromParent(); // The pseudo instruction is gone now.
1512 return RemBB;
1513}
1514
1515static bool isCopyMulResult(MachineBasicBlock::iterator const &I) {
1516 if (I->getOpcode() == AVR::COPY) {
1517 unsigned SrcReg = I->getOperand(1).getReg();
1518 return (SrcReg == AVR::R0 || SrcReg == AVR::R1);
1519 }
1520
1521 return false;
1522}
1523
1524// The mul instructions wreak havock on our zero_reg R1. We need to clear it
1525// after the result has been evacuated. This is probably not the best way to do
1526// it, but it works for now.
1527MachineBasicBlock *AVRTargetLowering::insertMul(MachineInstr &MI,
1528 MachineBasicBlock *BB) const {
1529 const AVRTargetMachine &TM = (const AVRTargetMachine &)getTargetMachine();
1530 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
1531 MachineBasicBlock::iterator I(MI);
1532 ++I; // in any case insert *after* the mul instruction
1533 if (isCopyMulResult(I))
1534 ++I;
1535 if (isCopyMulResult(I))
1536 ++I;
1537 BuildMI(*BB, I, MI.getDebugLoc(), TII.get(AVR::EORRdRr), AVR::R1)
1538 .addReg(AVR::R1)
1539 .addReg(AVR::R1);
1540 return BB;
1541}
1542
1543MachineBasicBlock *
1544AVRTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1545 MachineBasicBlock *MBB) const {
1546 int Opc = MI.getOpcode();
1547
1548 // Pseudo shift instructions with a non constant shift amount are expanded
1549 // into a loop.
1550 switch (Opc) {
1551 case AVR::Lsl8:
1552 case AVR::Lsl16:
1553 case AVR::Lsr8:
1554 case AVR::Lsr16:
1555 case AVR::Asr8:
1556 case AVR::Asr16:
1557 return insertShift(MI, MBB);
1558 case AVR::MULRdRr:
1559 case AVR::MULSRdRr:
1560 return insertMul(MI, MBB);
1561 }
1562
1563 assert((Opc == AVR::Select16 || Opc == AVR::Select8) &&
1564 "Unexpected instr type to insert");
1565
1566 const AVRInstrInfo &TII = (const AVRInstrInfo &)*MI.getParent()
1567 ->getParent()
1568 ->getSubtarget()
1569 .getInstrInfo();
1570 DebugLoc dl = MI.getDebugLoc();
1571
1572 // To "insert" a SELECT instruction, we insert the diamond
1573 // control-flow pattern. The incoming instruction knows the
1574 // destination vreg to set, the condition code register to branch
1575 // on, the true/false values to select between, and a branch opcode
1576 // to use.
1577
1578 MachineFunction *MF = MBB->getParent();
1579 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1580 MachineBasicBlock *trueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1581 MachineBasicBlock *falseMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1582
1583 MachineFunction::iterator I = MBB->getParent()->begin();
1584 ++I;
1585 MF->insert(I, trueMBB);
1586 MF->insert(I, falseMBB);
1587
1588 // Transfer remaining instructions and all successors of the current
1589 // block to the block which will contain the Phi node for the
1590 // select.
1591 trueMBB->splice(trueMBB->begin(), MBB,
1592 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
1593 trueMBB->transferSuccessorsAndUpdatePHIs(MBB);
1594
1595 AVRCC::CondCodes CC = (AVRCC::CondCodes)MI.getOperand(3).getImm();
1596 BuildMI(MBB, dl, TII.getBrCond(CC)).addMBB(trueMBB);
1597 BuildMI(MBB, dl, TII.get(AVR::RJMPk)).addMBB(falseMBB);
1598 MBB->addSuccessor(falseMBB);
1599 MBB->addSuccessor(trueMBB);
1600
1601 // Unconditionally flow back to the true block
1602 BuildMI(falseMBB, dl, TII.get(AVR::RJMPk)).addMBB(trueMBB);
1603 falseMBB->addSuccessor(trueMBB);
1604
1605 // Set up the Phi node to determine where we came from
1606 BuildMI(*trueMBB, trueMBB->begin(), dl, TII.get(AVR::PHI), MI.getOperand(0).getReg())
1607 .addReg(MI.getOperand(1).getReg())
1608 .addMBB(MBB)
1609 .addReg(MI.getOperand(2).getReg())
1610 .addMBB(falseMBB) ;
1611
1612 MI.eraseFromParent(); // The pseudo instruction is gone now.
1613 return trueMBB;
1614}
1615
1616//===----------------------------------------------------------------------===//
1617// Inline Asm Support
1618//===----------------------------------------------------------------------===//
1619
1620AVRTargetLowering::ConstraintType
1621AVRTargetLowering::getConstraintType(StringRef Constraint) const {
1622 if (Constraint.size() == 1) {
1623 // See http://www.nongnu.org/avr-libc/user-manual/inline_asm.html
1624 switch (Constraint[0]) {
1625 case 'a': // Simple upper registers
1626 case 'b': // Base pointer registers pairs
1627 case 'd': // Upper register
1628 case 'l': // Lower registers
1629 case 'e': // Pointer register pairs
1630 case 'q': // Stack pointer register
1631 case 'r': // Any register
1632 case 'w': // Special upper register pairs
1633 return C_RegisterClass;
1634 case 't': // Temporary register
1635 case 'x': case 'X': // Pointer register pair X
1636 case 'y': case 'Y': // Pointer register pair Y
1637 case 'z': case 'Z': // Pointer register pair Z
1638 return C_Register;
1639 case 'Q': // A memory address based on Y or Z pointer with displacement.
1640 return C_Memory;
1641 case 'G': // Floating point constant
1642 case 'I': // 6-bit positive integer constant
1643 case 'J': // 6-bit negative integer constant
1644 case 'K': // Integer constant (Range: 2)
1645 case 'L': // Integer constant (Range: 0)
1646 case 'M': // 8-bit integer constant
1647 case 'N': // Integer constant (Range: -1)
1648 case 'O': // Integer constant (Range: 8, 16, 24)
1649 case 'P': // Integer constant (Range: 1)
1650 case 'R': // Integer constant (Range: -6 to 5)x
1651 return C_Other;
1652 default:
1653 break;
1654 }
1655 }
1656
1657 return TargetLowering::getConstraintType(Constraint);
1658}
1659
1660unsigned
1661AVRTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
1662 // Not sure if this is actually the right thing to do, but we got to do
1663 // *something* [agnat]
1664 switch (ConstraintCode[0]) {
1665 case 'Q':
1666 return InlineAsm::Constraint_Q;
1667 }
1668 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
1669}
1670
1671AVRTargetLowering::ConstraintWeight
1672AVRTargetLowering::getSingleConstraintMatchWeight(
1673 AsmOperandInfo &info, const char *constraint) const {
1674 ConstraintWeight weight = CW_Invalid;
1675 Value *CallOperandVal = info.CallOperandVal;
1676
1677 // If we don't have a value, we can't do a match,
1678 // but allow it at the lowest weight.
1679 // (this behaviour has been copied from the ARM backend)
1680 if (!CallOperandVal) {
1681 return CW_Default;
1682 }
1683
1684 // Look at the constraint type.
1685 switch (*constraint) {
1686 default:
1687 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1688 break;
1689 case 'd':
1690 case 'r':
1691 case 'l':
1692 weight = CW_Register;
1693 break;
1694 case 'a':
1695 case 'b':
1696 case 'e':
1697 case 'q':
1698 case 't':
1699 case 'w':
1700 case 'x': case 'X':
1701 case 'y': case 'Y':
1702 case 'z': case 'Z':
1703 weight = CW_SpecificReg;
1704 break;
1705 case 'G':
1706 if (const ConstantFP *C = dyn_cast<ConstantFP>(CallOperandVal)) {
1707 if (C->isZero()) {
1708 weight = CW_Constant;
1709 }
1710 }
1711 break;
1712 case 'I':
1713 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
1714 if (isUInt<6>(C->getZExtValue())) {
1715 weight = CW_Constant;
1716 }
1717 }
1718 break;
1719 case 'J':
1720 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
1721 if ((C->getSExtValue() >= -63) && (C->getSExtValue() <= 0)) {
1722 weight = CW_Constant;
1723 }
1724 }
1725 break;
1726 case 'K':
1727 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
1728 if (C->getZExtValue() == 2) {
1729 weight = CW_Constant;
1730 }
1731 }
1732 break;
1733 case 'L':
1734 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
1735 if (C->getZExtValue() == 0) {
1736 weight = CW_Constant;
1737 }
1738 }
1739 break;
1740 case 'M':
1741 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
1742 if (isUInt<8>(C->getZExtValue())) {
1743 weight = CW_Constant;
1744 }
1745 }
1746 break;
1747 case 'N':
1748 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
1749 if (C->getSExtValue() == -1) {
1750 weight = CW_Constant;
1751 }
1752 }
1753 break;
1754 case 'O':
1755 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
1756 if ((C->getZExtValue() == 8) || (C->getZExtValue() == 16) ||
1757 (C->getZExtValue() == 24)) {
1758 weight = CW_Constant;
1759 }
1760 }
1761 break;
1762 case 'P':
1763 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
1764 if (C->getZExtValue() == 1) {
1765 weight = CW_Constant;
1766 }
1767 }
1768 break;
1769 case 'R':
1770 if (const ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
1771 if ((C->getSExtValue() >= -6) && (C->getSExtValue() <= 5)) {
1772 weight = CW_Constant;
1773 }
1774 }
1775 break;
1776 case 'Q':
1777 weight = CW_Memory;
1778 break;
1779 }
1780
1781 return weight;
1782}
1783
1784std::pair<unsigned, const TargetRegisterClass *>
1785AVRTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1786 StringRef Constraint,
1787 MVT VT) const {
1788 auto STI = static_cast<const AVRTargetMachine &>(this->getTargetMachine())
1789 .getSubtargetImpl();
1790
1791 // We only support i8 and i16.
1792 //
1793 //:FIXME: remove this assert for now since it gets sometimes executed
1794 // assert((VT == MVT::i16 || VT == MVT::i8) && "Wrong operand type.");
1795
1796 if (Constraint.size() == 1) {
1797 switch (Constraint[0]) {
1798 case 'a': // Simple upper registers r16..r23.
1799 return std::make_pair(0U, &AVR::LD8loRegClass);
1800 case 'b': // Base pointer registers: y, z.
1801 return std::make_pair(0U, &AVR::PTRDISPREGSRegClass);
1802 case 'd': // Upper registers r16..r31.
1803 return std::make_pair(0U, &AVR::LD8RegClass);
1804 case 'l': // Lower registers r0..r15.
1805 return std::make_pair(0U, &AVR::GPR8loRegClass);
1806 case 'e': // Pointer register pairs: x, y, z.
1807 return std::make_pair(0U, &AVR::PTRREGSRegClass);
1808 case 'q': // Stack pointer register: SPH:SPL.
1809 return std::make_pair(0U, &AVR::GPRSPRegClass);
1810 case 'r': // Any register: r0..r31.
1811 if (VT == MVT::i8)
1812 return std::make_pair(0U, &AVR::GPR8RegClass);
1813
1814 assert(VT == MVT::i16 && "inline asm constraint too large");
1815 return std::make_pair(0U, &AVR::DREGSRegClass);
1816 case 't': // Temporary register: r0.
1817 return std::make_pair(unsigned(AVR::R0), &AVR::GPR8RegClass);
1818 case 'w': // Special upper register pairs: r24, r26, r28, r30.
1819 return std::make_pair(0U, &AVR::IWREGSRegClass);
1820 case 'x': // Pointer register pair X: r27:r26.
1821 case 'X':
1822 return std::make_pair(unsigned(AVR::R27R26), &AVR::PTRREGSRegClass);
1823 case 'y': // Pointer register pair Y: r29:r28.
1824 case 'Y':
1825 return std::make_pair(unsigned(AVR::R29R28), &AVR::PTRREGSRegClass);
1826 case 'z': // Pointer register pair Z: r31:r30.
1827 case 'Z':
1828 return std::make_pair(unsigned(AVR::R31R30), &AVR::PTRREGSRegClass);
1829 default:
1830 break;
1831 }
1832 }
1833
1834 return TargetLowering::getRegForInlineAsmConstraint(STI->getRegisterInfo(),
1835 Constraint, VT);
1836}
1837
1838void AVRTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
1839 std::string &Constraint,
1840 std::vector<SDValue> &Ops,
1841 SelectionDAG &DAG) const {
1842 SDValue Result(0, 0);
1843 SDLoc DL(Op);
1844 EVT Ty = Op.getValueType();
1845
1846 // Currently only support length 1 constraints.
1847 if (Constraint.length() != 1) {
1848 return;
1849 }
1850
1851 char ConstraintLetter = Constraint[0];
1852 switch (ConstraintLetter) {
1853 default:
1854 break;
1855 // Deal with integers first:
1856 case 'I':
1857 case 'J':
1858 case 'K':
1859 case 'L':
1860 case 'M':
1861 case 'N':
1862 case 'O':
1863 case 'P':
1864 case 'R': {
1865 const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1866 if (!C) {
1867 return;
1868 }
1869
1870 int64_t CVal64 = C->getSExtValue();
1871 uint64_t CUVal64 = C->getZExtValue();
1872 switch (ConstraintLetter) {
1873 case 'I': // 0..63
1874 if (!isUInt<6>(CUVal64))
1875 return;
1876 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
1877 break;
1878 case 'J': // -63..0
1879 if (CVal64 < -63 || CVal64 > 0)
1880 return;
1881 Result = DAG.getTargetConstant(CVal64, DL, Ty);
1882 break;
1883 case 'K': // 2
1884 if (CUVal64 != 2)
1885 return;
1886 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
1887 break;
1888 case 'L': // 0
1889 if (CUVal64 != 0)
1890 return;
1891 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
1892 break;
1893 case 'M': // 0..255
1894 if (!isUInt<8>(CUVal64))
1895 return;
1896 // i8 type may be printed as a negative number,
1897 // e.g. 254 would be printed as -2,
1898 // so we force it to i16 at least.
1899 if (Ty.getSimpleVT() == MVT::i8) {
1900 Ty = MVT::i16;
1901 }
1902 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
1903 break;
1904 case 'N': // -1
1905 if (CVal64 != -1)
1906 return;
1907 Result = DAG.getTargetConstant(CVal64, DL, Ty);
1908 break;
1909 case 'O': // 8, 16, 24
1910 if (CUVal64 != 8 && CUVal64 != 16 && CUVal64 != 24)
1911 return;
1912 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
1913 break;
1914 case 'P': // 1
1915 if (CUVal64 != 1)
1916 return;
1917 Result = DAG.getTargetConstant(CUVal64, DL, Ty);
1918 break;
1919 case 'R': // -6..5
1920 if (CVal64 < -6 || CVal64 > 5)
1921 return;
1922 Result = DAG.getTargetConstant(CVal64, DL, Ty);
1923 break;
1924 }
1925
1926 break;
1927 }
1928 case 'G':
1929 const ConstantFPSDNode *FC = dyn_cast<ConstantFPSDNode>(Op);
1930 if (!FC || !FC->isZero())
1931 return;
1932 // Soften float to i8 0
1933 Result = DAG.getTargetConstant(0, DL, MVT::i8);
1934 break;
1935 }
1936
1937 if (Result.getNode()) {
1938 Ops.push_back(Result);
1939 return;
1940 }
1941
1942 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
1943}
1944
Dylan McKay8fa6d8d2017-01-07 23:39:47 +00001945unsigned AVRTargetLowering::getRegisterByName(const char *RegName,
1946 EVT VT,
1947 SelectionDAG &DAG) const {
1948 unsigned Reg;
1949
1950 if (VT == MVT::i8) {
1951 Reg = StringSwitch<unsigned>(RegName)
1952 .Case("r0", AVR::R0).Case("r1", AVR::R1).Case("r2", AVR::R2)
1953 .Case("r3", AVR::R3).Case("r4", AVR::R4).Case("r5", AVR::R5)
1954 .Case("r6", AVR::R6).Case("r7", AVR::R7).Case("r8", AVR::R8)
1955 .Case("r9", AVR::R9).Case("r10", AVR::R10).Case("r11", AVR::R11)
1956 .Case("r12", AVR::R12).Case("r13", AVR::R13).Case("r14", AVR::R14)
1957 .Case("r15", AVR::R15).Case("r16", AVR::R16).Case("r17", AVR::R17)
1958 .Case("r18", AVR::R18).Case("r19", AVR::R19).Case("r20", AVR::R20)
1959 .Case("r21", AVR::R21).Case("r22", AVR::R22).Case("r23", AVR::R23)
1960 .Case("r24", AVR::R24).Case("r25", AVR::R25).Case("r26", AVR::R26)
1961 .Case("r27", AVR::R27).Case("r28", AVR::R28).Case("r29", AVR::R29)
1962 .Case("r30", AVR::R30).Case("r31", AVR::R31)
1963 .Case("X", AVR::R27R26).Case("Y", AVR::R29R28).Case("Z", AVR::R31R30)
1964 .Default(0);
1965 } else {
1966 Reg = StringSwitch<unsigned>(RegName)
1967 .Case("r0", AVR::R1R0).Case("r2", AVR::R3R2)
1968 .Case("r4", AVR::R5R4).Case("r6", AVR::R7R6)
1969 .Case("r8", AVR::R9R8).Case("r10", AVR::R11R10)
1970 .Case("r12", AVR::R13R12).Case("r14", AVR::R15R14)
1971 .Case("r16", AVR::R17R16).Case("r18", AVR::R19R18)
1972 .Case("r20", AVR::R21R20).Case("r22", AVR::R23R22)
1973 .Case("r24", AVR::R25R24).Case("r26", AVR::R27R26)
1974 .Case("r28", AVR::R29R28).Case("r30", AVR::R31R30)
1975 .Case("X", AVR::R27R26).Case("Y", AVR::R29R28).Case("Z", AVR::R31R30)
1976 .Default(0);
1977 }
1978
1979 if (Reg)
1980 return Reg;
1981
1982 report_fatal_error("Invalid register name global variable");
1983}
1984
Dylan McKay7549b0a2016-11-02 06:47:40 +00001985} // end of namespace llvm