2 // The LLVM Compiler Infrastructure
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
9 // This file defines the interfaces that PIC16 uses to lower LLVM code into a
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "pic16-lower"
16 #include "PIC16ISelLowering.h"
17 #include "PIC16TargetMachine.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/GlobalValue.h"
20 #include "llvm/Function.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 // PIC16TargetLowering Constructor.
33 PIC16TargetLowering::PIC16TargetLowering(PIC16TargetMachine &TM)
34 : TargetLowering(TM) {
36 Subtarget = &TM.getSubtarget<PIC16Subtarget>();
38 addRegisterClass(MVT::i8, PIC16::GPRRegisterClass);
40 setShiftAmountType(MVT::i8);
41 setShiftAmountFlavor(Extend);
43 // SRA library call names
44 setPIC16LibcallName(PIC16ISD::SRA_I8, "__intrinsics.sra.i8");
45 setLibcallName(RTLIB::SRA_I16, "__intrinsics.sra.i16");
46 setLibcallName(RTLIB::SRA_I32, "__intrinsics.sra.i32");
48 // SHL library call names
49 setPIC16LibcallName(PIC16ISD::SLL_I8, "__intrinsics.sll.i8");
50 setLibcallName(RTLIB::SHL_I16, "__intrinsics.sll.i16");
51 setLibcallName(RTLIB::SHL_I32, "__intrinsics.sll.i32");
53 // SRL library call names
54 setPIC16LibcallName(PIC16ISD::SRL_I8, "__intrinsics.srl.i8");
55 setLibcallName(RTLIB::SRL_I16, "__intrinsics.srl.i16");
56 setLibcallName(RTLIB::SRL_I32, "__intrinsics.srl.i32");
58 // MUL Library call names
59 setPIC16LibcallName(PIC16ISD::MUL_I8, "__intrinsics.mul.i8");
60 setLibcallName(RTLIB::MUL_I16, "__intrinsics.mul.i16");
61 setLibcallName(RTLIB::MUL_I32, "__intrinsics.mul.i32");
63 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
64 setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom);
66 setOperationAction(ISD::LOAD, MVT::i8, Legal);
67 setOperationAction(ISD::LOAD, MVT::i16, Custom);
68 setOperationAction(ISD::LOAD, MVT::i32, Custom);
70 setOperationAction(ISD::STORE, MVT::i8, Legal);
71 setOperationAction(ISD::STORE, MVT::i16, Custom);
72 setOperationAction(ISD::STORE, MVT::i32, Custom);
74 setOperationAction(ISD::ADDE, MVT::i8, Custom);
75 setOperationAction(ISD::ADDC, MVT::i8, Custom);
76 setOperationAction(ISD::SUBE, MVT::i8, Custom);
77 setOperationAction(ISD::SUBC, MVT::i8, Custom);
78 setOperationAction(ISD::ADD, MVT::i8, Custom);
79 setOperationAction(ISD::ADD, MVT::i16, Custom);
81 setOperationAction(ISD::OR, MVT::i8, Custom);
82 setOperationAction(ISD::AND, MVT::i8, Custom);
83 setOperationAction(ISD::XOR, MVT::i8, Custom);
85 setOperationAction(ISD::FrameIndex, MVT::i16, Custom);
86 setOperationAction(ISD::CALL, MVT::i16, Custom);
87 setOperationAction(ISD::RET, MVT::Other, Custom);
89 setOperationAction(ISD::MUL, MVT::i8, Custom);
90 setOperationAction(ISD::MUL, MVT::i16, Expand);
91 setOperationAction(ISD::MUL, MVT::i32, Expand);
93 setOperationAction(ISD::SMUL_LOHI, MVT::i8, Expand);
94 setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand);
95 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
96 setOperationAction(ISD::UMUL_LOHI, MVT::i8, Expand);
97 setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand);
98 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
99 setOperationAction(ISD::MULHU, MVT::i8, Expand);
100 setOperationAction(ISD::MULHU, MVT::i16, Expand);
101 setOperationAction(ISD::MULHU, MVT::i32, Expand);
102 setOperationAction(ISD::MULHS, MVT::i8, Expand);
103 setOperationAction(ISD::MULHS, MVT::i16, Expand);
104 setOperationAction(ISD::MULHS, MVT::i32, Expand);
106 setOperationAction(ISD::SRA, MVT::i8, Custom);
107 setOperationAction(ISD::SRA, MVT::i16, Expand);
108 setOperationAction(ISD::SRA, MVT::i32, Expand);
109 setOperationAction(ISD::SHL, MVT::i8, Custom);
110 setOperationAction(ISD::SHL, MVT::i16, Expand);
111 setOperationAction(ISD::SHL, MVT::i32, Expand);
112 setOperationAction(ISD::SRL, MVT::i8, Custom);
113 setOperationAction(ISD::SRL, MVT::i16, Expand);
114 setOperationAction(ISD::SRL, MVT::i32, Expand);
116 // PIC16 does not support shift parts
117 setOperationAction(ISD::SRA_PARTS, MVT::i8, Expand);
118 setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand);
119 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
120 setOperationAction(ISD::SHL_PARTS, MVT::i8, Expand);
121 setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand);
122 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
123 setOperationAction(ISD::SRL_PARTS, MVT::i8, Expand);
124 setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand);
125 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
128 // PIC16 does not have a SETCC, expand it to SELECT_CC.
129 setOperationAction(ISD::SETCC, MVT::i8, Expand);
130 setOperationAction(ISD::SELECT, MVT::i8, Expand);
131 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
132 setOperationAction(ISD::BRIND, MVT::Other, Expand);
134 setOperationAction(ISD::SELECT_CC, MVT::i8, Custom);
135 setOperationAction(ISD::BR_CC, MVT::i8, Custom);
137 //setOperationAction(ISD::TRUNCATE, MVT::i16, Custom);
138 setTruncStoreAction(MVT::i16, MVT::i8, Custom);
140 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Custom);
142 // Now deduce the information based on the above mentioned
144 computeRegisterProperties();
147 // getOutFlag - Extract the flag result if the Op has it.
148 static SDValue getOutFlag(SDValue &Op) {
149 // Flag is the last value of the node.
150 SDValue Flag = Op.getValue(Op.getNode()->getNumValues() - 1);
152 assert (Flag.getValueType() == MVT::Flag
153 && "Node does not have an out Flag");
158 // To extract chain value from the SDValue Nodes
159 // This function will help to maintain the chain extracting
160 // code at one place. In case of any change in future it will
161 // help maintain the code.
162 static SDValue getChain(SDValue &Op) {
163 SDValue Chain = Op.getValue(Op.getNode()->getNumValues() - 1);
165 // If the last value returned in Flag then the chain is
166 // second last value returned.
167 if (Chain.getValueType() == MVT::Flag)
168 Chain = Op.getValue(Op.getNode()->getNumValues() - 2);
170 // All nodes may not produce a chain. Therefore following assert
171 // verifies that the node is returning a chain only.
172 assert (Chain.getValueType() == MVT::Other
173 && "Node does not have a chain");
178 /// PopulateResults - Helper function to LowerOperation.
179 /// If a node wants to return multiple results after lowering,
180 /// it stuffs them into an array of SDValue called Results.
182 static void PopulateResults(SDValue N, SmallVectorImpl<SDValue>&Results) {
183 if (N.getOpcode() == ISD::MERGE_VALUES) {
184 int NumResults = N.getNumOperands();
185 for( int i = 0; i < NumResults; i++)
186 Results.push_back(N.getOperand(i));
189 Results.push_back(N);
192 MVT PIC16TargetLowering::getSetCCResultType(MVT ValType) const {
196 /// The type legalizer framework of generating legalizer can generate libcalls
197 /// only when the operand/result types are illegal.
198 /// PIC16 needs to generate libcalls even for the legal types (i8) for some ops.
199 /// For example an arithmetic right shift. These functions are used to lower
200 /// such operations that generate libcall for legal types.
203 PIC16TargetLowering::setPIC16LibcallName(PIC16ISD::PIC16Libcall Call,
205 PIC16LibcallNames[Call] = Name;
209 PIC16TargetLowering::getPIC16LibcallName(PIC16ISD::PIC16Libcall Call) {
210 return PIC16LibcallNames[Call];
214 PIC16TargetLowering::MakePIC16Libcall(PIC16ISD::PIC16Libcall Call,
215 MVT RetVT, const SDValue *Ops,
216 unsigned NumOps, bool isSigned,
217 SelectionDAG &DAG, DebugLoc dl) {
219 TargetLowering::ArgListTy Args;
220 Args.reserve(NumOps);
222 TargetLowering::ArgListEntry Entry;
223 for (unsigned i = 0; i != NumOps; ++i) {
225 Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
226 Entry.isSExt = isSigned;
227 Entry.isZExt = !isSigned;
228 Args.push_back(Entry);
230 SDValue Callee = DAG.getExternalSymbol(getPIC16LibcallName(Call), MVT::i8);
232 const Type *RetTy = RetVT.getTypeForMVT();
233 std::pair<SDValue,SDValue> CallInfo =
234 LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
235 false, CallingConv::C, false, Callee, Args, DAG, dl);
237 return CallInfo.first;
240 const char *PIC16TargetLowering::getTargetNodeName(unsigned Opcode) const {
242 default: return NULL;
243 case PIC16ISD::Lo: return "PIC16ISD::Lo";
244 case PIC16ISD::Hi: return "PIC16ISD::Hi";
245 case PIC16ISD::MTLO: return "PIC16ISD::MTLO";
246 case PIC16ISD::MTHI: return "PIC16ISD::MTHI";
247 case PIC16ISD::Banksel: return "PIC16ISD::Banksel";
248 case PIC16ISD::PIC16Load: return "PIC16ISD::PIC16Load";
249 case PIC16ISD::PIC16LdArg: return "PIC16ISD::PIC16LdArg";
250 case PIC16ISD::PIC16LdWF: return "PIC16ISD::PIC16LdWF";
251 case PIC16ISD::PIC16Store: return "PIC16ISD::PIC16Store";
252 case PIC16ISD::PIC16StWF: return "PIC16ISD::PIC16StWF";
253 case PIC16ISD::BCF: return "PIC16ISD::BCF";
254 case PIC16ISD::LSLF: return "PIC16ISD::LSLF";
255 case PIC16ISD::LRLF: return "PIC16ISD::LRLF";
256 case PIC16ISD::RLF: return "PIC16ISD::RLF";
257 case PIC16ISD::RRF: return "PIC16ISD::RRF";
258 case PIC16ISD::CALL: return "PIC16ISD::CALL";
259 case PIC16ISD::SUBCC: return "PIC16ISD::SUBCC";
260 case PIC16ISD::SELECT_ICC: return "PIC16ISD::SELECT_ICC";
261 case PIC16ISD::BRCOND: return "PIC16ISD::BRCOND";
262 case PIC16ISD::Dummy: return "PIC16ISD::Dummy";
263 case PIC16ISD::PIC16StopPoint: return "PIC16ISD::PIC16StopPoint";
267 void PIC16TargetLowering::ReplaceNodeResults(SDNode *N,
268 SmallVectorImpl<SDValue>&Results,
271 switch (N->getOpcode()) {
272 case ISD::GlobalAddress:
273 Results.push_back(ExpandGlobalAddress(N, DAG));
275 case ISD::ExternalSymbol:
276 Results.push_back(ExpandExternalSymbol(N, DAG));
279 Results.push_back(ExpandStore(N, DAG));
282 PopulateResults(ExpandLoad(N, DAG), Results);
285 // Results.push_back(ExpandAdd(N, DAG));
287 case ISD::FrameIndex:
288 Results.push_back(ExpandFrameIndex(N, DAG));
291 assert (0 && "not implemented");
296 SDValue PIC16TargetLowering::ExpandFrameIndex(SDNode *N, SelectionDAG &DAG) {
298 // Currently handling FrameIndex of size MVT::i16 only
299 // One example of this scenario is when return value is written on
302 if (N->getValueType(0) != MVT::i16)
305 // Expand the FrameIndex into ExternalSymbol and a Constant node
306 // The constant will represent the frame index number
307 // Get the current function frame
308 MachineFunction &MF = DAG.getMachineFunction();
309 const Function *Func = MF.getFunction();
310 const std::string Name = Func->getName();
312 FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(SDValue(N,0));
313 // FIXME there isn't really debug info here
314 DebugLoc dl = FR->getDebugLoc();
315 int Index = FR->getIndex();
318 FI[0] = DAG.getTargetFrameIndex(Index, MVT::i8);
319 FI[1] = DAG.getTargetFrameIndex(Index + 1, MVT::i8);
320 return DAG.getNode(ISD::BUILD_PAIR, dl, N->getValueType(0), FI[0], FI[1]);
324 SDValue PIC16TargetLowering::ExpandStore(SDNode *N, SelectionDAG &DAG) {
325 StoreSDNode *St = cast<StoreSDNode>(N);
326 SDValue Chain = St->getChain();
327 SDValue Src = St->getValue();
328 SDValue Ptr = St->getBasePtr();
329 MVT ValueType = Src.getValueType();
330 unsigned StoreOffset = 0;
331 DebugLoc dl = N->getDebugLoc();
333 SDValue PtrLo, PtrHi;
334 LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, StoreOffset, dl);
336 if (ValueType == MVT::i8) {
337 return DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, Src,
339 DAG.getConstant (0 + StoreOffset, MVT::i8));
341 else if (ValueType == MVT::i16) {
342 // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
343 SDValue SrcLo, SrcHi;
344 GetExpandedParts(Src, DAG, SrcLo, SrcHi);
345 SDValue ChainLo = Chain, ChainHi = Chain;
346 if (Chain.getOpcode() == ISD::TokenFactor) {
347 ChainLo = Chain.getOperand(0);
348 ChainHi = Chain.getOperand(1);
350 SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
353 DAG.getConstant (0 + StoreOffset, MVT::i8));
355 SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi,
357 DAG.getConstant (1 + StoreOffset, MVT::i8));
359 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, getChain(Store1),
362 else if (ValueType == MVT::i32) {
363 // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
364 SDValue SrcLo, SrcHi;
365 GetExpandedParts(Src, DAG, SrcLo, SrcHi);
367 // Get the expanded parts of each of SrcLo and SrcHi.
368 SDValue SrcLo1, SrcLo2, SrcHi1, SrcHi2;
369 GetExpandedParts(SrcLo, DAG, SrcLo1, SrcLo2);
370 GetExpandedParts(SrcHi, DAG, SrcHi1, SrcHi2);
372 SDValue ChainLo = Chain, ChainHi = Chain;
373 if (Chain.getOpcode() == ISD::TokenFactor) {
374 ChainLo = Chain.getOperand(0);
375 ChainHi = Chain.getOperand(1);
377 SDValue ChainLo1 = ChainLo, ChainLo2 = ChainLo, ChainHi1 = ChainHi,
379 if (ChainLo.getOpcode() == ISD::TokenFactor) {
380 ChainLo1 = ChainLo.getOperand(0);
381 ChainLo2 = ChainLo.getOperand(1);
383 if (ChainHi.getOpcode() == ISD::TokenFactor) {
384 ChainHi1 = ChainHi.getOperand(0);
385 ChainHi2 = ChainHi.getOperand(1);
387 SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
389 SrcLo1, PtrLo, PtrHi,
390 DAG.getConstant (0 + StoreOffset, MVT::i8));
392 SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainLo2,
393 SrcLo2, PtrLo, PtrHi,
394 DAG.getConstant (1 + StoreOffset, MVT::i8));
396 SDValue Store3 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi1,
397 SrcHi1, PtrLo, PtrHi,
398 DAG.getConstant (2 + StoreOffset, MVT::i8));
400 SDValue Store4 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi2,
401 SrcHi2, PtrLo, PtrHi,
402 DAG.getConstant (3 + StoreOffset, MVT::i8));
404 SDValue RetLo = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
405 getChain(Store1), getChain(Store2));
406 SDValue RetHi = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
407 getChain(Store3), getChain(Store4));
408 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, RetLo, RetHi);
412 assert (0 && "value type not supported");
417 SDValue PIC16TargetLowering::ExpandExternalSymbol(SDNode *N, SelectionDAG &DAG)
419 ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(SDValue(N, 0));
420 // FIXME there isn't really debug info here
421 DebugLoc dl = ES->getDebugLoc();
423 SDValue TES = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
425 SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TES);
426 SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TES);
428 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
431 // ExpandGlobalAddress -
432 SDValue PIC16TargetLowering::ExpandGlobalAddress(SDNode *N, SelectionDAG &DAG) {
433 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(SDValue(N, 0));
434 // FIXME there isn't really debug info here
435 DebugLoc dl = G->getDebugLoc();
437 SDValue TGA = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i8,
440 SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TGA);
441 SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TGA);
443 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
446 bool PIC16TargetLowering::isDirectAddress(const SDValue &Op) {
447 assert (Op.getNode() != NULL && "Can't operate on NULL SDNode!!");
449 if (Op.getOpcode() == ISD::BUILD_PAIR) {
450 if (Op.getOperand(0).getOpcode() == PIC16ISD::Lo)
456 // Return true if DirectAddress is in ROM_SPACE
457 bool PIC16TargetLowering::isRomAddress(const SDValue &Op) {
459 // RomAddress is a GlobalAddress in ROM_SPACE_
460 // If the Op is not a GlobalAddress return NULL without checking
462 if (!isDirectAddress(Op))
465 // Its a GlobalAddress.
466 // It is BUILD_PAIR((PIC16Lo TGA), (PIC16Hi TGA)) and Op is BUILD_PAIR
467 SDValue TGA = Op.getOperand(0).getOperand(0);
468 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(TGA);
469 const Type *ValueType = GSDN->getGlobal()->getType();
471 if (!isa<PointerType>(ValueType)) {
472 assert(0 && "TGA must be of a PointerType");
475 int AddrSpace = dyn_cast<PointerType>(ValueType)->getAddressSpace();
476 if (AddrSpace == PIC16ISD::ROM_SPACE)
479 // Any other address space return it false
484 // GetExpandedParts - This function is on the similiar lines as
485 // the GetExpandedInteger in type legalizer is. This returns expanded
486 // parts of Op in Lo and Hi.
488 void PIC16TargetLowering::GetExpandedParts(SDValue Op, SelectionDAG &DAG,
489 SDValue &Lo, SDValue &Hi) {
490 SDNode *N = Op.getNode();
491 DebugLoc dl = N->getDebugLoc();
492 MVT NewVT = getTypeToTransformTo(N->getValueType(0));
494 // Extract the lo component.
495 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
496 DAG.getConstant(0, MVT::i8));
498 // extract the hi component
499 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
500 DAG.getConstant(1, MVT::i8));
503 // Legalize FrameIndex into ExternalSymbol and offset.
505 PIC16TargetLowering::LegalizeFrameIndex(SDValue Op, SelectionDAG &DAG,
506 SDValue &ES, int &Offset) {
508 MachineFunction &MF = DAG.getMachineFunction();
509 const Function *Func = MF.getFunction();
510 MachineFrameInfo *MFI = MF.getFrameInfo();
511 const std::string Name = Func->getName();
513 char *tmpName = new char [strlen(Name.c_str()) + 8];
514 sprintf(tmpName, "%s.frame", Name.c_str());
515 ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
516 FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(Op);
518 // FrameIndices are not stack offsets. But they represent the request
519 // for space on stack. That space requested may be more than one byte.
520 // Therefore, to calculate the stack offset that a FrameIndex aligns
521 // with, we need to traverse all the FrameIndices available earlier in
522 // the list and add their requested size.
523 unsigned FIndex = FR->getIndex();
525 for (unsigned i=0; i<FIndex ; ++i) {
526 Offset += MFI->getObjectSize(i);
532 // This function legalizes the PIC16 Addresses. If the Pointer is
533 // -- Direct address variable residing
534 // --> then a Banksel for that variable will be created.
536 // --> then it will be treated as an indirect address.
537 // -- Indirect address
538 // --> then the address will be loaded into FSR
539 // -- ADD with constant operand
540 // --> then constant operand of ADD will be returned as Offset
541 // and non-constant operand of ADD will be treated as pointer.
542 // Returns the high and lo part of the address, and the offset(in case of ADD).
544 void PIC16TargetLowering:: LegalizeAddress(SDValue Ptr, SelectionDAG &DAG,
545 SDValue &Lo, SDValue &Hi,
546 unsigned &Offset, DebugLoc dl) {
548 // Offset, by default, should be 0
551 // If the pointer is ADD with constant,
552 // return the constant value as the offset
553 if (Ptr.getOpcode() == ISD::ADD) {
554 SDValue OperLeft = Ptr.getOperand(0);
555 SDValue OperRight = Ptr.getOperand(1);
556 if (OperLeft.getOpcode() == ISD::Constant) {
557 Offset = dyn_cast<ConstantSDNode>(OperLeft)->getZExtValue();
559 } else if (OperRight.getOpcode() == ISD::Constant) {
560 Offset = dyn_cast<ConstantSDNode>(OperRight)->getZExtValue();
565 // If the pointer is Type i8 and an external symbol
566 // then treat it as direct address.
567 // One example for such case is storing and loading
568 // from function frame during a call
569 if (Ptr.getValueType() == MVT::i8) {
570 switch (Ptr.getOpcode()) {
571 case ISD::TargetExternalSymbol:
573 Hi = DAG.getConstant(1, MVT::i8);
578 if (Ptr.getOpcode() == ISD::BUILD_PAIR &&
579 Ptr.getOperand(0).getOpcode() == ISD::TargetFrameIndex) {
582 LegalizeFrameIndex(Ptr.getOperand(0), DAG, Lo, FrameOffset);
583 Hi = DAG.getConstant(1, MVT::i8);
584 Offset += FrameOffset;
588 if (isDirectAddress(Ptr) && !isRomAddress(Ptr)) {
589 // Direct addressing case for RAM variables. The Hi part is constant
590 // and the Lo part is the TGA itself.
591 Lo = Ptr.getOperand(0).getOperand(0);
593 // For direct addresses Hi is a constant. Value 1 for the constant
594 // signifies that banksel needs to generated for it. Value 0 for
595 // the constant signifies that banksel does not need to be generated
596 // for it. Mark it as 1 now and optimize later.
597 Hi = DAG.getConstant(1, MVT::i8);
601 // Indirect addresses. Get the hi and lo parts of ptr.
602 GetExpandedParts(Ptr, DAG, Lo, Hi);
604 // Put the hi and lo parts into FSR.
605 Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Lo);
606 Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Hi);
611 SDValue PIC16TargetLowering::ExpandLoad(SDNode *N, SelectionDAG &DAG) {
612 LoadSDNode *LD = dyn_cast<LoadSDNode>(SDValue(N, 0));
613 SDValue Chain = LD->getChain();
614 SDValue Ptr = LD->getBasePtr();
615 DebugLoc dl = LD->getDebugLoc();
617 SDValue Load, Offset;
620 SDValue PtrLo, PtrHi;
623 // Legalize direct/indirect addresses. This will give the lo and hi parts
624 // of the address and the offset.
625 LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, LoadOffset, dl);
627 // Load from the pointer (direct address or FSR)
628 VT = N->getValueType(0);
629 unsigned NumLoads = VT.getSizeInBits() / 8;
630 std::vector<SDValue> PICLoads;
632 MVT MemVT = LD->getMemoryVT();
633 if(ISD::isNON_EXTLoad(N)) {
634 for (iter=0; iter<NumLoads ; ++iter) {
635 // Add the pointer offset if any
636 Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
637 Tys = DAG.getVTList(MVT::i8, MVT::Other);
638 Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
640 PICLoads.push_back(Load);
643 // If it is extended load then use PIC16Load for Memory Bytes
644 // and for all extended bytes perform action based on type of
645 // extention - i.e. SignExtendedLoad or ZeroExtendedLoad
648 // For extended loads this is the memory value type
649 // i.e. without any extension
650 MVT MemVT = LD->getMemoryVT();
651 unsigned MemBytes = MemVT.getSizeInBits() / 8;
652 unsigned ExtdBytes = VT.getSizeInBits() / 8;
653 Offset = DAG.getConstant(LoadOffset, MVT::i8);
655 Tys = DAG.getVTList(MVT::i8, MVT::Other);
656 // For MemBytes generate PIC16Load with proper offset
657 for (iter=0; iter<MemBytes; ++iter) {
658 // Add the pointer offset if any
659 Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
660 Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
662 PICLoads.push_back(Load);
665 // For SignExtendedLoad
666 if (ISD::isSEXTLoad(N)) {
667 // For all ExtdBytes use the Right Shifted(Arithmetic) Value of the
669 SDValue SRA = DAG.getNode(ISD::SRA, dl, MVT::i8, Load,
670 DAG.getConstant(7, MVT::i8));
671 for (iter=MemBytes; iter<ExtdBytes; ++iter) {
672 PICLoads.push_back(SRA);
674 } else if (ISD::isZEXTLoad(N)) {
675 // ZeroExtendedLoad -- For all ExtdBytes use constant 0
676 SDValue ConstZero = DAG.getConstant(0, MVT::i8);
677 for (iter=MemBytes; iter<ExtdBytes; ++iter) {
678 PICLoads.push_back(ConstZero);
685 // Operand of Load is illegal -- Load itself is legal
688 else if (VT == MVT::i16) {
689 BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, PICLoads[0], PICLoads[1]);
690 if (MemVT == MVT::i8)
691 Chain = getChain(PICLoads[0]);
693 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
694 getChain(PICLoads[0]), getChain(PICLoads[1]));
695 } else if (VT == MVT::i32) {
697 BPs[0] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
698 PICLoads[0], PICLoads[1]);
699 BPs[1] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
700 PICLoads[2], PICLoads[3]);
701 BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, BPs[0], BPs[1]);
702 if (MemVT == MVT::i8)
703 Chain = getChain(PICLoads[0]);
704 else if (MemVT == MVT::i16)
705 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
706 getChain(PICLoads[0]), getChain(PICLoads[1]));
709 Chains[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
710 getChain(PICLoads[0]), getChain(PICLoads[1]));
711 Chains[1] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
712 getChain(PICLoads[2]), getChain(PICLoads[3]));
713 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
714 Chains[0], Chains[1]);
717 Tys = DAG.getVTList(VT, MVT::Other);
718 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, BP, Chain);
721 SDValue PIC16TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
722 // We should have handled larger operands in type legalizer itself.
723 assert (Op.getValueType() == MVT::i8 && "illegal shift to lower");
725 SDNode *N = Op.getNode();
726 SDValue Value = N->getOperand(0);
727 SDValue Amt = N->getOperand(1);
728 PIC16ISD::PIC16Libcall CallCode;
729 switch (N->getOpcode()) {
731 CallCode = PIC16ISD::SRA_I8;
734 CallCode = PIC16ISD::SLL_I8;
737 CallCode = PIC16ISD::SRL_I8;
740 assert ( 0 && "This shift is not implemented yet.");
743 SmallVector<SDValue, 2> Ops(2);
746 SDValue Call = MakePIC16Libcall(CallCode, N->getValueType(0), &Ops[0], 2,
747 true, DAG, N->getDebugLoc());
752 PIC16TargetLowering::LowerOperationWrapper(SDNode *N,
753 SmallVectorImpl<SDValue>&Results,
755 SDValue Op = SDValue(N, 0);
758 switch (Op.getOpcode()) {
759 case ISD::FORMAL_ARGUMENTS:
760 Res = LowerFORMAL_ARGUMENTS(Op, DAG); break;
762 Res = ExpandLoad(Op.getNode(), DAG); break;
764 Res = LowerCALL(Op, DAG); break;
766 // All other operations are handled in LowerOperation.
767 Res = LowerOperation(Op, DAG);
769 Results.push_back(Res);
776 unsigned NumValues = N->getNumValues();
777 for (i = 0; i < NumValues ; i++) {
778 Results.push_back(SDValue(N, i));
782 SDValue PIC16TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
783 switch (Op.getOpcode()) {
784 case ISD::FORMAL_ARGUMENTS:
785 return LowerFORMAL_ARGUMENTS(Op, DAG);
789 return LowerADD(Op, DAG);
793 return LowerSUB(Op, DAG);
795 return ExpandLoad(Op.getNode(), DAG);
797 return ExpandStore(Op.getNode(), DAG);
801 return LowerShift(Op, DAG);
805 return LowerBinOp(Op, DAG);
807 return LowerCALL(Op, DAG);
809 return LowerRET(Op, DAG);
811 return LowerBR_CC(Op, DAG);
813 return LowerSELECT_CC(Op, DAG);
814 case ISD::DBG_STOPPOINT:
815 return LowerStopPoint(Op, DAG);
820 SDValue PIC16TargetLowering::LowerStopPoint(SDValue Op, SelectionDAG &DAG) {
821 DbgStopPointSDNode *SP = dyn_cast<DbgStopPointSDNode>(Op);
822 unsigned line = SP->getLine();
823 SDValue LineNode = DAG.getConstant(line, MVT::i8);
824 DebugLoc dl = Op.getDebugLoc();
825 return DAG.getNode(PIC16ISD::PIC16StopPoint, dl, MVT::Other,
826 Op.getOperand(0), LineNode);
829 SDValue PIC16TargetLowering::ConvertToMemOperand(SDValue Op,
832 assert (Op.getValueType() == MVT::i8
833 && "illegal value type to store on stack.");
835 MachineFunction &MF = DAG.getMachineFunction();
836 const Function *Func = MF.getFunction();
837 const std::string FuncName = Func->getName();
839 char *tmpName = new char [strlen(FuncName.c_str()) + 8];
841 // Put the value on stack.
842 // Get a stack slot index and convert to es.
843 int FI = MF.getFrameInfo()->CreateStackObject(1, 1);
844 sprintf(tmpName, "%s.tmp", FuncName.c_str());
845 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
847 // Store the value to ES.
848 SDValue Store = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other,
851 DAG.getConstant (1, MVT::i8), // Banksel.
852 DAG.getConstant (FI, MVT::i8));
854 // Load the value from ES.
855 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other);
856 SDValue Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Store,
857 ES, DAG.getConstant (1, MVT::i8),
858 DAG.getConstant (FI, MVT::i8));
860 return Load.getValue(0);
864 PIC16TargetLowering::LowerCallArguments(SDValue Op, SDValue Chain,
865 SDValue FrameAddress,
868 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
869 unsigned NumOps = TheCall->getNumArgs();
870 DebugLoc dl = TheCall->getDebugLoc();
872 SDValue Arg, StoreAt;
878 // FIXME: This portion of code currently assumes only
879 // primitive types being passed as arguments.
881 // Legalize the address before use
882 SDValue PtrLo, PtrHi;
883 unsigned AddressOffset;
885 LegalizeAddress(FrameAddress, DAG, PtrLo, PtrHi, AddressOffset, dl);
888 std::vector<SDValue> Ops;
889 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
890 for (unsigned i=ArgCount, Offset = 0; i<NumOps; i++) {
892 Arg = TheCall->getArg(i);
894 StoreOffset = (Offset + AddressOffset);
896 // Store the argument on frame
899 Ops.push_back(Chain);
900 Ops.push_back(Arg.getValue(0));
901 Ops.push_back(PtrLo);
902 Ops.push_back(PtrHi);
903 Ops.push_back(DAG.getConstant(StoreOffset, MVT::i8));
904 Ops.push_back(InFlag);
906 StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
908 Chain = getChain(StoreRet);
909 InFlag = getOutFlag(StoreRet);
911 // Update the frame offset to be used for next argument
912 ArgVT = Arg.getValueType();
913 Size = ArgVT.getSizeInBits();
914 Size = Size/8; // Calculate size in bytes
915 Offset += Size; // Increase the frame offset
921 PIC16TargetLowering::LowerCallReturn(SDValue Op, SDValue Chain,
922 SDValue FrameAddress,
925 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
926 DebugLoc dl = TheCall->getDebugLoc();
927 // Currently handling primitive types only. They will come in
929 unsigned RetVals = TheCall->getNumRetVals();
931 std::vector<SDValue> ResultVals;
933 // Return immediately if the return type is void
937 // Call has something to return
939 // Legalize the address before use
942 LegalizeAddress(FrameAddress, DAG, LdLo, LdHi, LdOffset, dl);
944 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
947 for(unsigned i=0, Offset=0;i<RetVals;i++) {
949 LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, LdLo, LdHi,
950 DAG.getConstant(LdOffset + Offset, MVT::i8),
953 InFlag = getOutFlag(LoadRet);
955 Chain = getChain(LoadRet);
957 ResultVals.push_back(LoadRet);
960 // To return use MERGE_VALUES
961 ResultVals.push_back(Chain);
962 SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
966 SDValue PIC16TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
967 SDValue Chain = Op.getOperand(0);
968 DebugLoc dl = Op.getDebugLoc();
970 if (Op.getNumOperands() == 1) // return void
973 // return should have odd number of operands
974 if ((Op.getNumOperands() % 2) == 0 ) {
975 assert(0 && "Do not know how to return this many arguments!");
979 // Number of values to return
980 unsigned NumRet = (Op.getNumOperands() / 2);
982 // Function returns value always on stack with the offset starting
984 MachineFunction &MF = DAG.getMachineFunction();
985 const Function *F = MF.getFunction();
986 std::string FuncName = F->getName();
988 char *tmpName = new char [strlen(FuncName.c_str()) + 8];
989 sprintf(tmpName, "%s.frame", FuncName.c_str());
990 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Other);
991 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
992 SDValue BS = DAG.getConstant(1, MVT::i8);
994 for(unsigned i=0;i<NumRet; ++i) {
995 RetVal = Op.getNode()->getOperand(2*i + 1);
996 Chain = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, RetVal,
998 DAG.getConstant (i, MVT::i8));
1001 return DAG.getNode(ISD::RET, dl, MVT::Other, Chain);
1004 SDValue PIC16TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1005 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1006 SDValue Chain = TheCall->getChain();
1007 SDValue Callee = TheCall->getCallee();
1008 DebugLoc dl = TheCall->getDebugLoc();
1010 if (Callee.getValueType() == MVT::i16 &&
1011 Callee.getOpcode() == ISD::BUILD_PAIR) {
1012 // It has come from TypeLegalizer for lowering
1014 Callee = Callee.getOperand(0).getOperand(0);
1016 std::vector<SDValue> Ops;
1017 Ops.push_back(Chain);
1018 Ops.push_back(Callee);
1020 // Add the call arguments and their flags
1021 unsigned NumArgs = TheCall->getNumArgs();
1022 for(i=0;i<NumArgs;i++) {
1023 Ops.push_back(TheCall->getArg(i));
1024 Ops.push_back(TheCall->getArgFlagsVal(i));
1027 std::vector<MVT> NodeTys;
1028 unsigned NumRets = TheCall->getNumRetVals();
1029 for(i=0;i<NumRets;i++)
1030 NodeTys.push_back(TheCall->getRetValType(i));
1032 // Return a Chain as well
1033 NodeTys.push_back(MVT::Other);
1035 SDVTList VTs = DAG.getVTList(&NodeTys[0], NodeTys.size());
1037 DAG.getCall(TheCall->getCallingConv(), dl,
1038 TheCall->isVarArg(), TheCall->isTailCall(),
1039 TheCall->isInreg(), VTs, &Ops[0], Ops.size());
1044 SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1046 // Start the call sequence.
1047 // Carring the Constant 0 along the CALLSEQSTART
1048 // because there is nothing else to carry.
1049 SDValue SeqStart = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1050 Chain = getChain(SeqStart);
1052 // For any direct call - callee will be GlobalAddressNode or
1055 // Considering the GlobalAddressNode case here.
1056 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1057 GlobalValue *GV = G->getGlobal();
1058 Callee = DAG.getTargetGlobalAddress(GV, MVT::i8);
1061 // Considering the ExternalSymbol case here
1062 if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1063 Callee = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
1066 SDValue OperFlag = getOutFlag(Chain); // To manage the data dependency
1070 // Considering GlobalAddress here
1071 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1072 Name = G->getGlobal()->getName();
1074 // Considering ExternalSymbol here
1075 if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee))
1076 Name = ES->getSymbol();
1078 char *argFrame = new char [strlen(Name.c_str()) + 8];
1079 sprintf(argFrame, "%s.args", Name.c_str());
1080 SDValue ArgLabel = DAG.getTargetExternalSymbol(argFrame, MVT::i8);
1082 char *retName = new char [strlen(Name.c_str()) + 8];
1083 sprintf(retName, "%s.retval", Name.c_str());
1084 SDValue RetLabel = DAG.getTargetExternalSymbol(retName, MVT::i8);
1086 // Pass the argument to function before making the call.
1087 SDValue CallArgs = LowerCallArguments(Op, Chain, ArgLabel, OperFlag, DAG);
1088 Chain = getChain(CallArgs);
1089 OperFlag = getOutFlag(CallArgs);
1091 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1092 SDValue PICCall = DAG.getNode(PIC16ISD::CALL, dl, Tys, Chain, Callee,
1094 Chain = getChain(PICCall);
1095 OperFlag = getOutFlag(PICCall);
1098 // Carrying the Constant 0 along the CALLSEQSTART
1099 // because there is nothing else to carry.
1100 SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1102 Chain = getChain(SeqEnd);
1103 OperFlag = getOutFlag(SeqEnd);
1105 // Lower the return value reading after the call.
1106 return LowerCallReturn(Op, Chain, RetLabel, OperFlag, DAG);
1109 bool PIC16TargetLowering::isDirectLoad(const SDValue Op) {
1110 if (Op.getOpcode() == PIC16ISD::PIC16Load)
1111 if (Op.getOperand(1).getOpcode() == ISD::TargetGlobalAddress
1112 || Op.getOperand(1).getOpcode() == ISD::TargetExternalSymbol)
1117 // NeedToConvertToMemOp - Returns true if one of the operands of the
1118 // operation 'Op' needs to be put into memory. Also returns the
1119 // operand no. of the operand to be converted in 'MemOp'. Remember, PIC16 has
1120 // no instruction that can operation on two registers. Most insns take
1121 // one register and one memory operand (addwf) / Constant (addlw).
1122 bool PIC16TargetLowering::NeedToConvertToMemOp(SDValue Op, unsigned &MemOp) {
1123 // If one of the operand is a constant, return false.
1124 if (Op.getOperand(0).getOpcode() == ISD::Constant ||
1125 Op.getOperand(1).getOpcode() == ISD::Constant)
1128 // Return false if one of the operands is already a direct
1129 // load and that operand has only one use.
1130 if (isDirectLoad(Op.getOperand(0))) {
1131 if (Op.getOperand(0).hasOneUse())
1136 if (isDirectLoad(Op.getOperand(1))) {
1137 if (Op.getOperand(1).hasOneUse())
1145 // LowerBinOp - Lower a commutative binary operation that does not
1146 // affect status flag carry.
1147 SDValue PIC16TargetLowering::LowerBinOp(SDValue Op, SelectionDAG &DAG) {
1148 DebugLoc dl = Op.getDebugLoc();
1150 // We should have handled larger operands in type legalizer itself.
1151 assert (Op.getValueType() == MVT::i8 && "illegal Op to lower");
1154 if (NeedToConvertToMemOp(Op, MemOp)) {
1155 // Put one value on stack.
1156 SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1158 return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1166 // LowerADD - Lower all types of ADD operations including the ones
1167 // that affects carry.
1168 SDValue PIC16TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) {
1169 // We should have handled larger operands in type legalizer itself.
1170 assert (Op.getValueType() == MVT::i8 && "illegal add to lower");
1171 DebugLoc dl = Op.getDebugLoc();
1173 if (NeedToConvertToMemOp(Op, MemOp)) {
1174 // Put one value on stack.
1175 SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1177 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1179 if (Op.getOpcode() == ISD::ADDE)
1180 return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1181 NewVal, Op.getOperand(2));
1183 return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1186 else if (Op.getOpcode() == ISD::ADD) {
1194 SDValue PIC16TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) {
1195 DebugLoc dl = Op.getDebugLoc();
1196 // We should have handled larger operands in type legalizer itself.
1197 assert (Op.getValueType() == MVT::i8 && "illegal sub to lower");
1199 // Nothing to do if the first operand is already a direct load and it has
1201 if (isDirectLoad(Op.getOperand(0)) && Op.getOperand(0).hasOneUse())
1204 // Put first operand on stack.
1205 SDValue NewVal = ConvertToMemOperand (Op.getOperand(0), DAG, dl);
1207 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1208 if (Op.getOpcode() == ISD::SUBE)
1209 return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1),
1212 return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1));
1215 // LowerFORMAL_ARGUMENTS - In Lowering FORMAL ARGUMENTS - MERGE_VALUES nodes
1216 // is returned. MERGE_VALUES nodes number of operands and number of values are
1217 // equal. Therefore to construct MERGE_VALUE node, UNDEF nodes equal to the
1218 // number of arguments of function have been created.
1220 SDValue PIC16TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op,
1221 SelectionDAG &DAG) {
1222 SmallVector<SDValue, 8> ArgValues;
1223 unsigned NumArgs = Op.getNode()->getNumValues()-1;
1224 DebugLoc dl = Op.getDebugLoc();
1225 SDValue Chain = Op.getOperand(0); // Formal arguments' chain
1227 MachineFunction &MF = DAG.getMachineFunction();
1228 //const TargetData *TD = getTargetData();
1229 const Function *F = MF.getFunction();
1230 std::string FuncName = F->getName();
1232 char *tmpName = new char [strlen(FuncName.c_str()) + 6];
1233 sprintf(tmpName, "%s.args", FuncName.c_str());
1234 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Other);
1235 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1236 SDValue BS = DAG.getConstant(1, MVT::i8);
1237 for (unsigned i=0; i<NumArgs ; ++i) {
1238 SDValue Offset = DAG.getConstant(i, MVT::i8);
1239 SDValue PICLoad = DAG.getNode(PIC16ISD::PIC16LdArg, dl, VTs, Chain, ES, BS,
1241 Chain = getChain(PICLoad);
1242 ArgValues.push_back(PICLoad);
1245 ArgValues.push_back(Op.getOperand(0));
1246 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1248 ArgValues.size()).getValue(Op.getResNo());
1251 // Perform DAGCombine of PIC16Load.
1252 // FIXME - Need a more elaborate comment here.
1253 SDValue PIC16TargetLowering::
1254 PerformPIC16LoadCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1255 SelectionDAG &DAG = DCI.DAG;
1256 SDValue Chain = N->getOperand(0);
1257 if (N->hasNUsesOfValue(0, 0)) {
1258 DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), Chain);
1263 // For all the functions with arguments some STORE nodes are generated
1264 // that store the argument on the frameindex. However in PIC16 the arguments
1265 // are passed on stack only. Therefore these STORE nodes are redundant.
1266 // To remove these STORE nodes will be removed in PerformStoreCombine
1268 // Currently this function is doint nothing and will be updated for removing
1269 // unwanted store operations
1270 SDValue PIC16TargetLowering::
1271 PerformStoreCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1272 return SDValue(N, 0);
1274 // Storing an undef value is of no use, so remove it
1275 if (isStoringUndef(N, Chain, DAG)) {
1276 return Chain; // remove the store and return the chain
1278 //else everything is ok.
1279 return SDValue(N, 0);
1283 SDValue PIC16TargetLowering::PerformDAGCombine(SDNode *N,
1284 DAGCombinerInfo &DCI) const {
1285 switch (N->getOpcode()) {
1287 return PerformStoreCombine(N, DCI);
1288 case PIC16ISD::PIC16Load:
1289 return PerformPIC16LoadCombine(N, DCI);
1294 static PIC16CC::CondCodes IntCCToPIC16CC(ISD::CondCode CC) {
1296 default: assert(0 && "Unknown condition code!");
1297 case ISD::SETNE: return PIC16CC::NE;
1298 case ISD::SETEQ: return PIC16CC::EQ;
1299 case ISD::SETGT: return PIC16CC::GT;
1300 case ISD::SETGE: return PIC16CC::GE;
1301 case ISD::SETLT: return PIC16CC::LT;
1302 case ISD::SETLE: return PIC16CC::LE;
1303 case ISD::SETULT: return PIC16CC::ULT;
1304 case ISD::SETULE: return PIC16CC::LE;
1305 case ISD::SETUGE: return PIC16CC::GE;
1306 case ISD::SETUGT: return PIC16CC::UGT;
1310 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction. If so
1311 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1312 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1313 ISD::CondCode CC, unsigned &SPCC) {
1314 if (isa<ConstantSDNode>(RHS) &&
1315 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1317 (LHS.getOpcode() == PIC16ISD::SELECT_ICC &&
1318 LHS.getOperand(3).getOpcode() == PIC16ISD::SUBCC) &&
1319 isa<ConstantSDNode>(LHS.getOperand(0)) &&
1320 isa<ConstantSDNode>(LHS.getOperand(1)) &&
1321 cast<ConstantSDNode>(LHS.getOperand(0))->getZExtValue() == 1 &&
1322 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 0) {
1323 SDValue CMPCC = LHS.getOperand(3);
1324 SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1325 LHS = CMPCC.getOperand(0);
1326 RHS = CMPCC.getOperand(1);
1330 // Returns appropriate CMP insn and corresponding condition code in PIC16CC
1331 SDValue PIC16TargetLowering::getPIC16Cmp(SDValue LHS, SDValue RHS,
1332 unsigned CC, SDValue &PIC16CC,
1333 SelectionDAG &DAG, DebugLoc dl) {
1334 PIC16CC::CondCodes CondCode = (PIC16CC::CondCodes) CC;
1336 // PIC16 sub is literal - W. So Swap the operands and condition if needed.
1337 // i.e. a < 12 can be rewritten as 12 > a.
1338 if (RHS.getOpcode() == ISD::Constant) {
1347 CondCode = PIC16CC::GT;
1350 CondCode = PIC16CC::LT;
1353 CondCode = PIC16CC::UGT;
1356 CondCode = PIC16CC::ULT;
1359 CondCode = PIC16CC::LE;
1362 CondCode = PIC16CC::GE;
1365 CondCode = PIC16CC::UGE;
1368 CondCode = PIC16CC::ULE;
1373 PIC16CC = DAG.getConstant(CondCode, MVT::i8);
1375 // These are signed comparisons.
1376 SDValue Mask = DAG.getConstant(128, MVT::i8);
1377 if (isSignedComparison(CondCode)) {
1378 LHS = DAG.getNode (ISD::XOR, dl, MVT::i8, LHS, Mask);
1379 RHS = DAG.getNode (ISD::XOR, dl, MVT::i8, RHS, Mask);
1382 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Flag);
1383 // We can use a subtract operation to set the condition codes. But
1384 // we need to put one operand in memory if required.
1385 // Nothing to do if the first operand is already a valid type (direct load
1386 // for subwf and literal for sublw) and it is used by this operation only.
1387 if ((LHS.getOpcode() == ISD::Constant || isDirectLoad(LHS))
1389 return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1391 // else convert the first operand to mem.
1392 LHS = ConvertToMemOperand (LHS, DAG, dl);
1393 return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1397 SDValue PIC16TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1398 SDValue LHS = Op.getOperand(0);
1399 SDValue RHS = Op.getOperand(1);
1400 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1401 SDValue TrueVal = Op.getOperand(2);
1402 SDValue FalseVal = Op.getOperand(3);
1403 unsigned ORIGCC = ~0;
1404 DebugLoc dl = Op.getDebugLoc();
1406 // If this is a select_cc of a "setcc", and if the setcc got lowered into
1407 // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1409 // A setcc: lhs, rhs, cc is expanded by llvm to
1410 // select_cc: result of setcc, 0, 1, 0, setne
1411 // We can think of it as:
1412 // select_cc: lhs, rhs, 1, 0, cc
1413 LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1414 if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1417 SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1419 return DAG.getNode (PIC16ISD::SELECT_ICC, dl, TrueVal.getValueType(), TrueVal,
1420 FalseVal, PIC16CC, Cmp.getValue(1));
1424 PIC16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1425 MachineBasicBlock *BB) const {
1426 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1427 unsigned CC = (PIC16CC::CondCodes)MI->getOperand(3).getImm();
1428 DebugLoc dl = MI->getDebugLoc();
1430 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1431 // control-flow pattern. The incoming instruction knows the destination vreg
1432 // to set, the condition code register to branch on, the true/false values to
1433 // select between, and a branch opcode to use.
1434 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1435 MachineFunction::iterator It = BB;
1442 // fallthrough --> copy0MBB
1443 MachineBasicBlock *thisMBB = BB;
1444 MachineFunction *F = BB->getParent();
1445 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1446 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1447 BuildMI(BB, dl, TII.get(PIC16::pic16brcond)).addMBB(sinkMBB).addImm(CC);
1448 F->insert(It, copy0MBB);
1449 F->insert(It, sinkMBB);
1451 // Update machine-CFG edges by transferring all successors of the current
1452 // block to the new block which will contain the Phi node for the select.
1453 sinkMBB->transferSuccessors(BB);
1454 // Next, add the true and fallthrough blocks as its successors.
1455 BB->addSuccessor(copy0MBB);
1456 BB->addSuccessor(sinkMBB);
1459 // %FalseValue = ...
1460 // # fallthrough to sinkMBB
1463 // Update machine-CFG edges
1464 BB->addSuccessor(sinkMBB);
1467 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1470 BuildMI(BB, dl, TII.get(PIC16::PHI), MI->getOperand(0).getReg())
1471 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1472 .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1474 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1479 SDValue PIC16TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1480 SDValue Chain = Op.getOperand(0);
1481 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1482 SDValue LHS = Op.getOperand(2); // LHS of the condition.
1483 SDValue RHS = Op.getOperand(3); // RHS of the condition.
1484 SDValue Dest = Op.getOperand(4); // BB to jump to
1485 unsigned ORIGCC = ~0;
1486 DebugLoc dl = Op.getDebugLoc();
1488 // If this is a br_cc of a "setcc", and if the setcc got lowered into
1489 // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1490 LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1491 if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1493 // Get the Compare insn and condition code.
1495 SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1497 return DAG.getNode(PIC16ISD::BRCOND, dl, MVT::Other, Chain, Dest, PIC16CC,