ac9a143bc24e0e3f76e85ca691e324dae03aa4e7
[oota-llvm.git] / lib / Target / PIC16 / PIC16ISelLowering.cpp
1 //
2 //                     The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source 
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that PIC16 uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "pic16-lower"
15
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"
26
27
28 using namespace llvm;
29
30 static const char *getIntrinsicName(unsigned opcode) {
31   std::string Basename;
32   switch(opcode) {
33   default: assert (0 && "do not know intrinsic name");
34   case PIC16ISD::SRA_I8: Basename = "sra.i8"; break;
35   case RTLIB::SRA_I16: Basename = "sra.i16"; break;
36   case RTLIB::SRA_I32: Basename = "sra.i32"; break;
37
38   case PIC16ISD::SLL_I8: Basename = "sll.i8"; break;
39   case RTLIB::SHL_I16: Basename = "sll.i16"; break;
40   case RTLIB::SHL_I32: Basename = "sll.i32"; break;
41
42   case PIC16ISD::SRL_I8: Basename = "srl.i8"; break;
43   case RTLIB::SRL_I16: Basename = "srl.i16"; break;
44   case RTLIB::SRL_I32: Basename = "srl.i32"; break;
45
46   case PIC16ISD::MUL_I8: Basename = "mul.i8"; break;
47   case RTLIB::MUL_I16: Basename = "mul.i16"; break;
48   case RTLIB::MUL_I32: Basename = "mul.i32"; break;
49
50   case RTLIB::SDIV_I16: Basename = "sdiv.i16"; break;
51   case RTLIB::SDIV_I32: Basename = "sdiv.i32"; break;
52   case RTLIB::UDIV_I16: Basename = "udiv.i16"; break;
53   case RTLIB::UDIV_I32: Basename = "udiv.i32"; break;
54
55   case RTLIB::SREM_I16: Basename = "srem.i16"; break;
56   case RTLIB::SREM_I32: Basename = "srem.i32"; break;
57   case RTLIB::UREM_I16: Basename = "urem.i16"; break;
58   case RTLIB::UREM_I32: Basename = "urem.i32"; break;
59   }
60   
61   std::string prefix = PAN::getTagName(PAN::PREFIX_SYMBOL);
62   std::string tagname = PAN::getTagName(PAN::LIBCALL);
63   std::string Fullname = prefix + tagname + Basename; 
64
65   // The name has to live through program life.
66   char *tmp = new char[Fullname.size() + 1];
67   strcpy (tmp, Fullname.c_str());
68   
69   return tmp;
70 }
71
72 // PIC16TargetLowering Constructor.
73 PIC16TargetLowering::PIC16TargetLowering(PIC16TargetMachine &TM)
74   : TargetLowering(TM), TmpSize(0) {
75   
76   Subtarget = &TM.getSubtarget<PIC16Subtarget>();
77
78   addRegisterClass(MVT::i8, PIC16::GPRRegisterClass);
79
80   setShiftAmountType(MVT::i8);
81   setShiftAmountFlavor(Extend);
82
83   // SRA library call names
84   setPIC16LibcallName(PIC16ISD::SRA_I8, getIntrinsicName(PIC16ISD::SRA_I8));
85   setLibcallName(RTLIB::SRA_I16, getIntrinsicName(RTLIB::SRA_I16));
86   setLibcallName(RTLIB::SRA_I32, getIntrinsicName(RTLIB::SRA_I32));
87
88   // SHL library call names
89   setPIC16LibcallName(PIC16ISD::SLL_I8, getIntrinsicName(PIC16ISD::SLL_I8));
90   setLibcallName(RTLIB::SHL_I16, getIntrinsicName(RTLIB::SHL_I16));
91   setLibcallName(RTLIB::SHL_I32, getIntrinsicName(RTLIB::SHL_I32));
92
93   // SRL library call names
94   setPIC16LibcallName(PIC16ISD::SRL_I8, getIntrinsicName(PIC16ISD::SRL_I8));
95   setLibcallName(RTLIB::SRL_I16, getIntrinsicName(RTLIB::SRL_I16));
96   setLibcallName(RTLIB::SRL_I32, getIntrinsicName(RTLIB::SRL_I32));
97
98   // MUL Library call names
99   setPIC16LibcallName(PIC16ISD::MUL_I8, getIntrinsicName(PIC16ISD::MUL_I8));
100   setLibcallName(RTLIB::MUL_I16, getIntrinsicName(RTLIB::MUL_I16));
101   setLibcallName(RTLIB::MUL_I32, getIntrinsicName(RTLIB::MUL_I32));
102
103   // Signed division lib call names
104   setLibcallName(RTLIB::SDIV_I16, getIntrinsicName(RTLIB::SDIV_I16));
105   setLibcallName(RTLIB::SDIV_I32, getIntrinsicName(RTLIB::SDIV_I32));
106   // Unsigned division lib call names
107   setLibcallName(RTLIB::UDIV_I16, getIntrinsicName(RTLIB::UDIV_I16));
108   setLibcallName(RTLIB::UDIV_I32, getIntrinsicName(RTLIB::UDIV_I32));
109
110   // Signed remainder lib call names
111   setLibcallName(RTLIB::SREM_I16, getIntrinsicName(RTLIB::SREM_I16));
112   setLibcallName(RTLIB::SREM_I32, getIntrinsicName(RTLIB::SREM_I32));
113   // Unsigned remainder lib call names
114   setLibcallName(RTLIB::UREM_I16, getIntrinsicName(RTLIB::UREM_I16));
115   setLibcallName(RTLIB::UREM_I32, getIntrinsicName(RTLIB::UREM_I32));
116   
117   setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
118   setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom);
119
120   setOperationAction(ISD::LOAD,   MVT::i8,  Legal);
121   setOperationAction(ISD::LOAD,   MVT::i16, Custom);
122   setOperationAction(ISD::LOAD,   MVT::i32, Custom);
123
124   setOperationAction(ISD::STORE,  MVT::i8,  Legal);
125   setOperationAction(ISD::STORE,  MVT::i16, Custom);
126   setOperationAction(ISD::STORE,  MVT::i32, Custom);
127
128   setOperationAction(ISD::ADDE,    MVT::i8,  Custom);
129   setOperationAction(ISD::ADDC,    MVT::i8,  Custom);
130   setOperationAction(ISD::SUBE,    MVT::i8,  Custom);
131   setOperationAction(ISD::SUBC,    MVT::i8,  Custom);
132   setOperationAction(ISD::SUB,    MVT::i8,  Custom);
133   setOperationAction(ISD::ADD,    MVT::i8,  Custom);
134   setOperationAction(ISD::ADD,    MVT::i16, Custom);
135
136   setOperationAction(ISD::OR,     MVT::i8,  Custom);
137   setOperationAction(ISD::AND,    MVT::i8,  Custom);
138   setOperationAction(ISD::XOR,    MVT::i8,  Custom);
139
140   setOperationAction(ISD::FrameIndex, MVT::i16, Custom);
141   setOperationAction(ISD::CALL,   MVT::i16, Custom);
142   setOperationAction(ISD::RET,    MVT::Other, Custom);
143
144   setOperationAction(ISD::MUL,    MVT::i8,  Custom); 
145   setOperationAction(ISD::MUL,    MVT::i16, Expand);
146   setOperationAction(ISD::MUL,    MVT::i32, Expand);
147
148   setOperationAction(ISD::SMUL_LOHI,    MVT::i8,  Expand);
149   setOperationAction(ISD::SMUL_LOHI,    MVT::i16, Expand);
150   setOperationAction(ISD::SMUL_LOHI,    MVT::i32, Expand);
151   setOperationAction(ISD::UMUL_LOHI,    MVT::i8,  Expand);
152   setOperationAction(ISD::UMUL_LOHI,    MVT::i16, Expand);
153   setOperationAction(ISD::UMUL_LOHI,    MVT::i32, Expand);
154   setOperationAction(ISD::MULHU,        MVT::i8, Expand);
155   setOperationAction(ISD::MULHU,        MVT::i16, Expand);
156   setOperationAction(ISD::MULHU,        MVT::i32, Expand);
157   setOperationAction(ISD::MULHS,        MVT::i8, Expand);
158   setOperationAction(ISD::MULHS,        MVT::i16, Expand);
159   setOperationAction(ISD::MULHS,        MVT::i32, Expand);
160
161   setOperationAction(ISD::SRA,    MVT::i8,  Custom);
162   setOperationAction(ISD::SRA,    MVT::i16, Expand);
163   setOperationAction(ISD::SRA,    MVT::i32, Expand);
164   setOperationAction(ISD::SHL,    MVT::i8,  Custom);
165   setOperationAction(ISD::SHL,    MVT::i16, Expand);
166   setOperationAction(ISD::SHL,    MVT::i32, Expand);
167   setOperationAction(ISD::SRL,    MVT::i8,  Custom);
168   setOperationAction(ISD::SRL,    MVT::i16, Expand);
169   setOperationAction(ISD::SRL,    MVT::i32, Expand);
170
171   // PIC16 does not support shift parts
172   setOperationAction(ISD::SRA_PARTS,    MVT::i8,  Expand);
173   setOperationAction(ISD::SRA_PARTS,    MVT::i16, Expand);
174   setOperationAction(ISD::SRA_PARTS,    MVT::i32, Expand);
175   setOperationAction(ISD::SHL_PARTS,    MVT::i8, Expand);
176   setOperationAction(ISD::SHL_PARTS,    MVT::i16, Expand);
177   setOperationAction(ISD::SHL_PARTS,    MVT::i32, Expand);
178   setOperationAction(ISD::SRL_PARTS,    MVT::i8, Expand);
179   setOperationAction(ISD::SRL_PARTS,    MVT::i16, Expand);
180   setOperationAction(ISD::SRL_PARTS,    MVT::i32, Expand);
181
182
183   // PIC16 does not have a SETCC, expand it to SELECT_CC.
184   setOperationAction(ISD::SETCC,  MVT::i8, Expand);
185   setOperationAction(ISD::SELECT,  MVT::i8, Expand);
186   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
187   setOperationAction(ISD::BRIND, MVT::Other, Expand);
188
189   setOperationAction(ISD::SELECT_CC,  MVT::i8, Custom);
190   setOperationAction(ISD::BR_CC,  MVT::i8, Custom);
191
192   //setOperationAction(ISD::TRUNCATE, MVT::i16, Custom);
193   setTruncStoreAction(MVT::i16,   MVT::i8,  Custom);
194
195   // Now deduce the information based on the above mentioned 
196   // actions
197   computeRegisterProperties();
198 }
199
200 // getOutFlag - Extract the flag result if the Op has it.
201 static SDValue getOutFlag(SDValue &Op) {
202   // Flag is the last value of the node.
203   SDValue Flag = Op.getValue(Op.getNode()->getNumValues() - 1);
204
205   assert (Flag.getValueType() == MVT::Flag 
206           && "Node does not have an out Flag");
207
208   return Flag;
209 }
210 // Get the TmpOffset for FrameIndex
211 unsigned PIC16TargetLowering::GetTmpOffsetForFI(unsigned FI, unsigned size) {
212   std::map<unsigned, unsigned>::iterator 
213             MapIt = FiTmpOffsetMap.find(FI);
214   if (MapIt != FiTmpOffsetMap.end())
215       return MapIt->second;
216
217   // This FI (FrameIndex) is not yet mapped, so map it
218   FiTmpOffsetMap[FI] = TmpSize; 
219   TmpSize += size;
220   return FiTmpOffsetMap[FI];
221 }
222
223 // To extract chain value from the SDValue Nodes
224 // This function will help to maintain the chain extracting
225 // code at one place. In case of any change in future it will
226 // help maintain the code.
227 static SDValue getChain(SDValue &Op) { 
228   SDValue Chain = Op.getValue(Op.getNode()->getNumValues() - 1);
229
230   // If the last value returned in Flag then the chain is
231   // second last value returned.
232   if (Chain.getValueType() == MVT::Flag)
233     Chain = Op.getValue(Op.getNode()->getNumValues() - 2);
234   
235   // All nodes may not produce a chain. Therefore following assert
236   // verifies that the node is returning a chain only.
237   assert (Chain.getValueType() == MVT::Other 
238           && "Node does not have a chain");
239
240   return Chain;
241 }
242
243 /// PopulateResults - Helper function to LowerOperation.
244 /// If a node wants to return multiple results after lowering,
245 /// it stuffs them into an array of SDValue called Results.
246
247 static void PopulateResults(SDValue N, SmallVectorImpl<SDValue>&Results) {
248   if (N.getOpcode() == ISD::MERGE_VALUES) {
249     int NumResults = N.getNumOperands();
250     for( int i = 0; i < NumResults; i++)
251       Results.push_back(N.getOperand(i));
252   }
253   else
254     Results.push_back(N);
255 }
256
257 MVT PIC16TargetLowering::getSetCCResultType(MVT ValType) const {
258   return MVT::i8;
259 }
260
261 /// The type legalizer framework of generating legalizer can generate libcalls
262 /// only when the operand/result types are illegal.
263 /// PIC16 needs to generate libcalls even for the legal types (i8) for some ops.
264 /// For example an arithmetic right shift. These functions are used to lower
265 /// such operations that generate libcall for legal types.
266
267 void 
268 PIC16TargetLowering::setPIC16LibcallName(PIC16ISD::PIC16Libcall Call,
269                                          const char *Name) {
270   PIC16LibcallNames[Call] = Name; 
271 }
272
273 const char *
274 PIC16TargetLowering::getPIC16LibcallName(PIC16ISD::PIC16Libcall Call) {
275   return PIC16LibcallNames[Call];
276 }
277
278 SDValue
279 PIC16TargetLowering::MakePIC16Libcall(PIC16ISD::PIC16Libcall Call,
280                                       MVT RetVT, const SDValue *Ops,
281                                       unsigned NumOps, bool isSigned,
282                                       SelectionDAG &DAG, DebugLoc dl) {
283
284   TargetLowering::ArgListTy Args;
285   Args.reserve(NumOps);
286
287   TargetLowering::ArgListEntry Entry;
288   for (unsigned i = 0; i != NumOps; ++i) {
289     Entry.Node = Ops[i];
290     Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
291     Entry.isSExt = isSigned;
292     Entry.isZExt = !isSigned;
293     Args.push_back(Entry);
294   }
295   SDValue Callee = DAG.getExternalSymbol(getPIC16LibcallName(Call), MVT::i8);
296
297    const Type *RetTy = RetVT.getTypeForMVT();
298    std::pair<SDValue,SDValue> CallInfo = 
299      LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
300                  false, CallingConv::C, false, Callee, Args, DAG, dl);
301
302   return CallInfo.first;
303 }
304
305 const char *PIC16TargetLowering::getTargetNodeName(unsigned Opcode) const {
306   switch (Opcode) {
307   default:                         return NULL;
308   case PIC16ISD::Lo:               return "PIC16ISD::Lo";
309   case PIC16ISD::Hi:               return "PIC16ISD::Hi";
310   case PIC16ISD::MTLO:             return "PIC16ISD::MTLO";
311   case PIC16ISD::MTHI:             return "PIC16ISD::MTHI";
312   case PIC16ISD::MTPCLATH:         return "PIC16ISD::MTPCLATH";
313   case PIC16ISD::PIC16Connect:     return "PIC16ISD::PIC16Connect";
314   case PIC16ISD::Banksel:          return "PIC16ISD::Banksel";
315   case PIC16ISD::PIC16Load:        return "PIC16ISD::PIC16Load";
316   case PIC16ISD::PIC16LdArg:       return "PIC16ISD::PIC16LdArg";
317   case PIC16ISD::PIC16LdWF:        return "PIC16ISD::PIC16LdWF";
318   case PIC16ISD::PIC16Store:       return "PIC16ISD::PIC16Store";
319   case PIC16ISD::PIC16StWF:        return "PIC16ISD::PIC16StWF";
320   case PIC16ISD::BCF:              return "PIC16ISD::BCF";
321   case PIC16ISD::LSLF:             return "PIC16ISD::LSLF";
322   case PIC16ISD::LRLF:             return "PIC16ISD::LRLF";
323   case PIC16ISD::RLF:              return "PIC16ISD::RLF";
324   case PIC16ISD::RRF:              return "PIC16ISD::RRF";
325   case PIC16ISD::CALL:             return "PIC16ISD::CALL";
326   case PIC16ISD::CALLW:            return "PIC16ISD::CALLW";
327   case PIC16ISD::SUBCC:            return "PIC16ISD::SUBCC";
328   case PIC16ISD::SELECT_ICC:       return "PIC16ISD::SELECT_ICC";
329   case PIC16ISD::BRCOND:           return "PIC16ISD::BRCOND";
330   case PIC16ISD::Dummy:            return "PIC16ISD::Dummy";
331   }
332 }
333
334 void PIC16TargetLowering::ReplaceNodeResults(SDNode *N,
335                                              SmallVectorImpl<SDValue>&Results,
336                                              SelectionDAG &DAG) {
337
338   switch (N->getOpcode()) {
339     case ISD::GlobalAddress:
340       Results.push_back(ExpandGlobalAddress(N, DAG));
341       return;
342     case ISD::ExternalSymbol:
343       Results.push_back(ExpandExternalSymbol(N, DAG));
344       return;
345     case ISD::STORE:
346       Results.push_back(ExpandStore(N, DAG));
347       return;
348     case ISD::LOAD:
349       PopulateResults(ExpandLoad(N, DAG), Results);
350       return;
351     case ISD::ADD:
352       // Results.push_back(ExpandAdd(N, DAG));
353       return;
354     case ISD::FrameIndex:
355       Results.push_back(ExpandFrameIndex(N, DAG));
356       return;
357     default:
358       assert (0 && "not implemented");
359       return;
360   }
361 }
362
363 SDValue PIC16TargetLowering::ExpandFrameIndex(SDNode *N, SelectionDAG &DAG) {
364
365   // Currently handling FrameIndex of size MVT::i16 only
366   // One example of this scenario is when return value is written on
367   // FrameIndex#0
368
369   if (N->getValueType(0) != MVT::i16)
370     return SDValue();
371
372   // Expand the FrameIndex into ExternalSymbol and a Constant node
373   // The constant will represent the frame index number
374   // Get the current function frame
375   MachineFunction &MF = DAG.getMachineFunction();
376   const Function *Func = MF.getFunction();
377   const std::string Name = Func->getName();
378   
379   FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(SDValue(N,0));
380   // FIXME there isn't really debug info here
381   DebugLoc dl = FR->getDebugLoc();
382
383   // Expand FrameIndex like GlobalAddress and ExternalSymbol
384   // Also use Offset field for lo and hi parts. The default 
385   // offset is zero.
386
387   SDValue ES;
388   int FrameOffset;
389   SDValue FI = SDValue(N,0);
390   LegalizeFrameIndex(FI, DAG, ES, FrameOffset);
391   SDValue Offset = DAG.getConstant(FrameOffset, MVT::i8);
392   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, ES, Offset);
393   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, ES, Offset);
394   return DAG.getNode(ISD::BUILD_PAIR, dl, N->getValueType(0), Lo, Hi);
395 }
396
397
398 SDValue PIC16TargetLowering::ExpandStore(SDNode *N, SelectionDAG &DAG) { 
399   StoreSDNode *St = cast<StoreSDNode>(N);
400   SDValue Chain = St->getChain();
401   SDValue Src = St->getValue();
402   SDValue Ptr = St->getBasePtr();
403   MVT ValueType = Src.getValueType();
404   unsigned StoreOffset = 0;
405   DebugLoc dl = N->getDebugLoc();
406
407   SDValue PtrLo, PtrHi;
408   LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, StoreOffset, dl);
409  
410   if (ValueType == MVT::i8) {
411     return DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, Src,
412                         PtrLo, PtrHi, 
413                         DAG.getConstant (0 + StoreOffset, MVT::i8));
414   }
415   else if (ValueType == MVT::i16) {
416     // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
417     SDValue SrcLo, SrcHi;
418     GetExpandedParts(Src, DAG, SrcLo, SrcHi);
419     SDValue ChainLo = Chain, ChainHi = Chain;
420     if (Chain.getOpcode() == ISD::TokenFactor) {
421       ChainLo = Chain.getOperand(0);
422       ChainHi = Chain.getOperand(1);
423     }
424     SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
425                                  ChainLo,
426                                  SrcLo, PtrLo, PtrHi,
427                                  DAG.getConstant (0 + StoreOffset, MVT::i8));
428
429     SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi, 
430                                  SrcHi, PtrLo, PtrHi,
431                                  DAG.getConstant (1 + StoreOffset, MVT::i8));
432
433     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, getChain(Store1),
434                        getChain(Store2));
435   }
436   else if (ValueType == MVT::i32) {
437     // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
438     SDValue SrcLo, SrcHi;
439     GetExpandedParts(Src, DAG, SrcLo, SrcHi);
440
441     // Get the expanded parts of each of SrcLo and SrcHi.
442     SDValue SrcLo1, SrcLo2, SrcHi1, SrcHi2;
443     GetExpandedParts(SrcLo, DAG, SrcLo1, SrcLo2);
444     GetExpandedParts(SrcHi, DAG, SrcHi1, SrcHi2);
445
446     SDValue ChainLo = Chain, ChainHi = Chain;
447     if (Chain.getOpcode() == ISD::TokenFactor) {  
448       ChainLo = Chain.getOperand(0);
449       ChainHi = Chain.getOperand(1);
450     }
451     SDValue ChainLo1 = ChainLo, ChainLo2 = ChainLo, ChainHi1 = ChainHi,
452             ChainHi2 = ChainHi;
453     if (ChainLo.getOpcode() == ISD::TokenFactor) {
454       ChainLo1 = ChainLo.getOperand(0);
455       ChainLo2 = ChainLo.getOperand(1);
456     }
457     if (ChainHi.getOpcode() == ISD::TokenFactor) {
458       ChainHi1 = ChainHi.getOperand(0);
459       ChainHi2 = ChainHi.getOperand(1);
460     }
461     SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
462                                  ChainLo1,
463                                  SrcLo1, PtrLo, PtrHi,
464                                  DAG.getConstant (0 + StoreOffset, MVT::i8));
465
466     SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainLo2,
467                                  SrcLo2, PtrLo, PtrHi,
468                                  DAG.getConstant (1 + StoreOffset, MVT::i8));
469
470     SDValue Store3 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi1,
471                                  SrcHi1, PtrLo, PtrHi,
472                                  DAG.getConstant (2 + StoreOffset, MVT::i8));
473
474     SDValue Store4 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi2,
475                                  SrcHi2, PtrLo, PtrHi,
476                                  DAG.getConstant (3 + StoreOffset, MVT::i8));
477
478     SDValue RetLo =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
479                                  getChain(Store1), getChain(Store2));
480     SDValue RetHi =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
481                                  getChain(Store3), getChain(Store4));
482     return  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, RetLo, RetHi);
483
484   }
485   else {
486     assert (0 && "value type not supported");
487     return SDValue();
488   }
489 }
490
491 SDValue PIC16TargetLowering::ExpandExternalSymbol(SDNode *N, SelectionDAG &DAG)
492 {
493   ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(SDValue(N, 0));
494   // FIXME there isn't really debug info here
495   DebugLoc dl = ES->getDebugLoc();
496
497   SDValue TES = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
498   SDValue Offset = DAG.getConstant(0, MVT::i8);
499   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TES, Offset);
500   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TES, Offset);
501
502   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
503 }
504
505 // ExpandGlobalAddress - 
506 SDValue PIC16TargetLowering::ExpandGlobalAddress(SDNode *N, SelectionDAG &DAG) {
507   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(SDValue(N, 0));
508   // FIXME there isn't really debug info here
509   DebugLoc dl = G->getDebugLoc();
510   
511   SDValue TGA = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i8,
512                                            G->getOffset());
513
514   SDValue Offset = DAG.getConstant(0, MVT::i8);
515   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TGA, Offset);
516   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TGA, Offset);
517
518   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
519 }
520
521 bool PIC16TargetLowering::isDirectAddress(const SDValue &Op) {
522   assert (Op.getNode() != NULL && "Can't operate on NULL SDNode!!");
523
524   if (Op.getOpcode() == ISD::BUILD_PAIR) {
525    if (Op.getOperand(0).getOpcode() == PIC16ISD::Lo) 
526      return true;
527   }
528   return false;
529 }
530
531 // Return true if DirectAddress is in ROM_SPACE
532 bool PIC16TargetLowering::isRomAddress(const SDValue &Op) {
533
534   // RomAddress is a GlobalAddress in ROM_SPACE_
535   // If the Op is not a GlobalAddress return NULL without checking
536   // anything further.
537   if (!isDirectAddress(Op))
538     return false; 
539
540   // Its a GlobalAddress.
541   // It is BUILD_PAIR((PIC16Lo TGA), (PIC16Hi TGA)) and Op is BUILD_PAIR
542   SDValue TGA = Op.getOperand(0).getOperand(0);
543   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(TGA);
544
545   if (GSDN->getAddressSpace() == PIC16ISD::ROM_SPACE)
546     return true;
547
548   // Any other address space return it false
549   return false;
550 }
551
552
553 // GetExpandedParts - This function is on the similiar lines as
554 // the GetExpandedInteger in type legalizer is. This returns expanded
555 // parts of Op in Lo and Hi. 
556
557 void PIC16TargetLowering::GetExpandedParts(SDValue Op, SelectionDAG &DAG,
558                                            SDValue &Lo, SDValue &Hi) {  
559   SDNode *N = Op.getNode();
560   DebugLoc dl = N->getDebugLoc();
561   MVT NewVT = getTypeToTransformTo(N->getValueType(0));
562
563   // Extract the lo component.
564   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
565                    DAG.getConstant(0, MVT::i8));
566
567   // extract the hi component
568   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
569                    DAG.getConstant(1, MVT::i8));
570 }
571
572 // Legalize FrameIndex into ExternalSymbol and offset.
573 void 
574 PIC16TargetLowering::LegalizeFrameIndex(SDValue Op, SelectionDAG &DAG,
575                                         SDValue &ES, int &Offset) {
576
577   MachineFunction &MF = DAG.getMachineFunction();
578   const Function *Func = MF.getFunction();
579   MachineFrameInfo *MFI = MF.getFrameInfo();
580   const std::string Name = Func->getName();
581
582   FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(Op);
583
584   // FrameIndices are not stack offsets. But they represent the request
585   // for space on stack. That space requested may be more than one byte. 
586   // Therefore, to calculate the stack offset that a FrameIndex aligns
587   // with, we need to traverse all the FrameIndices available earlier in 
588   // the list and add their requested size.
589   unsigned FIndex = FR->getIndex();
590   const char *tmpName;
591   if (FIndex < ReservedFrameCount) {
592     tmpName = createESName(PAN::getFrameLabel(Name));
593     ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
594     Offset = 0;
595     for (unsigned i=0; i<FIndex ; ++i) {
596       Offset += MFI->getObjectSize(i);
597     }
598   } else {
599    // FrameIndex has been made for some temporary storage 
600     tmpName = createESName(PAN::getTempdataLabel(Name));
601     ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
602     Offset = GetTmpOffsetForFI(FIndex, MFI->getObjectSize(FIndex));
603   }
604
605   return;
606 }
607
608 // This function legalizes the PIC16 Addresses. If the Pointer is  
609 //  -- Direct address variable residing 
610 //     --> then a Banksel for that variable will be created.
611 //  -- Rom variable            
612 //     --> then it will be treated as an indirect address.
613 //  -- Indirect address 
614 //     --> then the address will be loaded into FSR
615 //  -- ADD with constant operand
616 //     --> then constant operand of ADD will be returned as Offset
617 //         and non-constant operand of ADD will be treated as pointer.
618 // Returns the high and lo part of the address, and the offset(in case of ADD).
619
620 void PIC16TargetLowering::LegalizeAddress(SDValue Ptr, SelectionDAG &DAG, 
621                                           SDValue &Lo, SDValue &Hi,
622                                           unsigned &Offset, DebugLoc dl) {
623
624   // Offset, by default, should be 0
625   Offset = 0;
626
627   // If the pointer is ADD with constant,
628   // return the constant value as the offset  
629   if (Ptr.getOpcode() == ISD::ADD) {
630     SDValue OperLeft = Ptr.getOperand(0);
631     SDValue OperRight = Ptr.getOperand(1);
632     if (OperLeft.getOpcode() == ISD::Constant) {
633       Offset = dyn_cast<ConstantSDNode>(OperLeft)->getZExtValue();
634       Ptr = OperRight;
635     } else if (OperRight.getOpcode() == ISD::Constant) {
636       Offset = dyn_cast<ConstantSDNode>(OperRight)->getZExtValue();
637       Ptr = OperLeft;
638     }
639   }
640
641   // If the pointer is Type i8 and an external symbol
642   // then treat it as direct address.
643   // One example for such case is storing and loading
644   // from function frame during a call
645   if (Ptr.getValueType() == MVT::i8) {
646     switch (Ptr.getOpcode()) {
647     case ISD::TargetExternalSymbol:
648       Lo = Ptr;
649       Hi = DAG.getConstant(1, MVT::i8);
650       return;
651     }
652   }
653
654   // Expansion of FrameIndex has Lo/Hi parts
655   if (isDirectAddress(Ptr)) { 
656       SDValue TFI = Ptr.getOperand(0).getOperand(0); 
657       int FrameOffset;
658       if (TFI.getOpcode() == ISD::TargetFrameIndex) {
659         LegalizeFrameIndex(TFI, DAG, Lo, FrameOffset);
660         Hi = DAG.getConstant(1, MVT::i8);
661         Offset += FrameOffset; 
662         return;
663       } else if (TFI.getOpcode() == ISD::TargetExternalSymbol) {
664         // FrameIndex has already been expanded.
665         // Now just make use of its expansion
666         Lo = TFI;
667         Hi = DAG.getConstant(1, MVT::i8);
668         SDValue FOffset = Ptr.getOperand(0).getOperand(1);
669         assert (FOffset.getOpcode() == ISD::Constant && 
670                           "Invalid operand of PIC16ISD::Lo");
671         Offset += dyn_cast<ConstantSDNode>(FOffset)->getZExtValue();
672         return;
673       }
674   }
675
676   if (isDirectAddress(Ptr) && !isRomAddress(Ptr)) {
677     // Direct addressing case for RAM variables. The Hi part is constant
678     // and the Lo part is the TGA itself.
679     Lo = Ptr.getOperand(0).getOperand(0);
680
681     // For direct addresses Hi is a constant. Value 1 for the constant
682     // signifies that banksel needs to generated for it. Value 0 for
683     // the constant signifies that banksel does not need to be generated 
684     // for it. Mark it as 1 now and optimize later. 
685     Hi = DAG.getConstant(1, MVT::i8);
686     return; 
687   }
688
689   // Indirect addresses. Get the hi and lo parts of ptr. 
690   GetExpandedParts(Ptr, DAG, Lo, Hi);
691
692   // Put the hi and lo parts into FSR.
693   Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Lo);
694   Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Hi);
695
696   return;
697 }
698
699 SDValue PIC16TargetLowering::ExpandLoad(SDNode *N, SelectionDAG &DAG) {
700   LoadSDNode *LD = dyn_cast<LoadSDNode>(SDValue(N, 0));
701   SDValue Chain = LD->getChain();
702   SDValue Ptr = LD->getBasePtr();
703   DebugLoc dl = LD->getDebugLoc();
704
705   SDValue Load, Offset;
706   SDVTList Tys; 
707   MVT VT, NewVT;
708   SDValue PtrLo, PtrHi;
709   unsigned LoadOffset;
710
711   // Legalize direct/indirect addresses. This will give the lo and hi parts
712   // of the address and the offset.
713   LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, LoadOffset, dl);
714
715   // Load from the pointer (direct address or FSR) 
716   VT = N->getValueType(0);
717   unsigned NumLoads = VT.getSizeInBits() / 8; 
718   std::vector<SDValue> PICLoads;
719   unsigned iter;
720   MVT MemVT = LD->getMemoryVT();
721   if(ISD::isNON_EXTLoad(N)) {
722     for (iter=0; iter<NumLoads ; ++iter) {
723       // Add the pointer offset if any
724       Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
725       Tys = DAG.getVTList(MVT::i8, MVT::Other); 
726       Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
727                          Offset); 
728       PICLoads.push_back(Load);
729     }
730   } else {
731     // If it is extended load then use PIC16Load for Memory Bytes
732     // and for all extended bytes perform action based on type of
733     // extention - i.e. SignExtendedLoad or ZeroExtendedLoad
734
735     
736     // For extended loads this is the memory value type
737     // i.e. without any extension
738     MVT MemVT = LD->getMemoryVT();
739     unsigned MemBytes = MemVT.getSizeInBits() / 8;
740     unsigned ExtdBytes = VT.getSizeInBits() / 8;
741     Offset = DAG.getConstant(LoadOffset, MVT::i8);
742
743     Tys = DAG.getVTList(MVT::i8, MVT::Other); 
744     // For MemBytes generate PIC16Load with proper offset
745     for (iter=0; iter<MemBytes; ++iter) {
746       // Add the pointer offset if any
747       Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
748       Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
749                          Offset); 
750       PICLoads.push_back(Load);
751     }
752
753     // For SignExtendedLoad
754     if (ISD::isSEXTLoad(N)) {
755       // For all ExtdBytes use the Right Shifted(Arithmetic) Value of the 
756       // highest MemByte
757       SDValue SRA = DAG.getNode(ISD::SRA, dl, MVT::i8, Load, 
758                                 DAG.getConstant(7, MVT::i8));
759       for (iter=MemBytes; iter<ExtdBytes; ++iter) { 
760         PICLoads.push_back(SRA);
761       }
762     } else if (ISD::isZEXTLoad(N) || ISD::isEXTLoad(N)) {
763     //} else if (ISD::isZEXTLoad(N)) {
764       // ZeroExtendedLoad -- For all ExtdBytes use constant 0
765       SDValue ConstZero = DAG.getConstant(0, MVT::i8);
766       for (iter=MemBytes; iter<ExtdBytes; ++iter) { 
767         PICLoads.push_back(ConstZero);
768       }
769     }
770   }
771   SDValue BP;
772
773   if (VT == MVT::i8) {
774     // Operand of Load is illegal -- Load itself is legal
775     return PICLoads[0];
776   }
777   else if (VT == MVT::i16) {
778     BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, PICLoads[0], PICLoads[1]);
779     if (MemVT == MVT::i8)
780       Chain = getChain(PICLoads[0]);
781     else
782       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
783                           getChain(PICLoads[0]), getChain(PICLoads[1]));
784   } else if (VT == MVT::i32) {
785     SDValue BPs[2];
786     BPs[0] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, 
787                          PICLoads[0], PICLoads[1]);
788     BPs[1] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
789                          PICLoads[2], PICLoads[3]);
790     BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, BPs[0], BPs[1]);
791     if (MemVT == MVT::i8)
792       Chain = getChain(PICLoads[0]);
793     else if (MemVT == MVT::i16)
794       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
795                           getChain(PICLoads[0]), getChain(PICLoads[1]));
796     else {
797       SDValue Chains[2];
798       Chains[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
799                               getChain(PICLoads[0]), getChain(PICLoads[1]));
800       Chains[1] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
801                               getChain(PICLoads[2]), getChain(PICLoads[3]));
802       Chain =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
803                            Chains[0], Chains[1]);
804     }
805   }
806   Tys = DAG.getVTList(VT, MVT::Other); 
807   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, BP, Chain);
808 }
809
810 SDValue PIC16TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
811   // We should have handled larger operands in type legalizer itself.
812   assert (Op.getValueType() == MVT::i8 && "illegal shift to lower");
813  
814   SDNode *N = Op.getNode();
815   SDValue Value = N->getOperand(0);
816   SDValue Amt = N->getOperand(1);
817   PIC16ISD::PIC16Libcall CallCode;
818   switch (N->getOpcode()) {
819   case ISD::SRA:
820     CallCode = PIC16ISD::SRA_I8;
821     break;
822   case ISD::SHL:
823     CallCode = PIC16ISD::SLL_I8;
824     break;
825   case ISD::SRL:
826     CallCode = PIC16ISD::SRL_I8;
827     break;
828   default:
829     assert ( 0 && "This shift is not implemented yet.");
830     return SDValue();
831   }
832   SmallVector<SDValue, 2> Ops(2);
833   Ops[0] = Value;
834   Ops[1] = Amt;
835   SDValue Call = MakePIC16Libcall(CallCode, N->getValueType(0), &Ops[0], 2, 
836                                   true, DAG, N->getDebugLoc());
837   return Call;
838 }
839
840 void
841 PIC16TargetLowering::LowerOperationWrapper(SDNode *N,
842                                            SmallVectorImpl<SDValue>&Results,
843                                            SelectionDAG &DAG) {
844   SDValue Op = SDValue(N, 0);
845   SDValue Res;
846   unsigned i;
847   switch (Op.getOpcode()) {
848     case ISD::FORMAL_ARGUMENTS:
849       Res = LowerFORMAL_ARGUMENTS(Op, DAG); break;
850     case ISD::LOAD:
851       Res = ExpandLoad(Op.getNode(), DAG); break;
852     case ISD::CALL:
853       Res = LowerCALL(Op, DAG); break;
854     default: {
855       // All other operations are handled in LowerOperation.
856       Res = LowerOperation(Op, DAG);
857       if (Res.getNode())
858         Results.push_back(Res);
859         
860       return; 
861     }
862   }
863
864   N = Res.getNode();
865   unsigned NumValues = N->getNumValues(); 
866   for (i = 0; i < NumValues ; i++) {
867     Results.push_back(SDValue(N, i)); 
868   }
869 }
870
871 SDValue PIC16TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
872   switch (Op.getOpcode()) {
873     case ISD::FORMAL_ARGUMENTS:
874       return LowerFORMAL_ARGUMENTS(Op, DAG);
875     case ISD::ADD:
876     case ISD::ADDC:
877     case ISD::ADDE:
878       return LowerADD(Op, DAG);
879     case ISD::SUB:
880     case ISD::SUBC:
881     case ISD::SUBE:
882       return LowerSUB(Op, DAG);
883     case ISD::LOAD:
884       return ExpandLoad(Op.getNode(), DAG);
885     case ISD::STORE:
886       return ExpandStore(Op.getNode(), DAG);
887     case ISD::SHL:
888     case ISD::SRA:
889     case ISD::SRL:
890       return LowerShift(Op, DAG);
891     case ISD::OR:
892     case ISD::AND:
893     case ISD::XOR:
894       return LowerBinOp(Op, DAG);
895     case ISD::CALL:
896       return LowerCALL(Op, DAG);
897     case ISD::RET:
898       return LowerRET(Op, DAG);
899     case ISD::BR_CC:
900       return LowerBR_CC(Op, DAG);
901     case ISD::SELECT_CC:
902       return LowerSELECT_CC(Op, DAG);
903   }
904   return SDValue();
905 }
906
907 SDValue PIC16TargetLowering::ConvertToMemOperand(SDValue Op,
908                                                  SelectionDAG &DAG,
909                                                  DebugLoc dl) {
910   assert (Op.getValueType() == MVT::i8 
911           && "illegal value type to store on stack.");
912
913   MachineFunction &MF = DAG.getMachineFunction();
914   const Function *Func = MF.getFunction();
915   const std::string FuncName = Func->getName();
916
917
918   // Put the value on stack.
919   // Get a stack slot index and convert to es.
920   int FI = MF.getFrameInfo()->CreateStackObject(1, 1);
921   const char *tmpName = createESName(PAN::getTempdataLabel(FuncName));
922   SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
923
924   // Store the value to ES.
925   SDValue Store = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other,
926                                DAG.getEntryNode(),
927                                Op, ES, 
928                                DAG.getConstant (1, MVT::i8), // Banksel.
929                                DAG.getConstant (GetTmpOffsetForFI(FI, 1), 
930                                                 MVT::i8));
931
932   // Load the value from ES.
933   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other);
934   SDValue Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Store,
935                              ES, DAG.getConstant (1, MVT::i8),
936                              DAG.getConstant (GetTmpOffsetForFI(FI, 1), 
937                              MVT::i8));
938     
939   return Load.getValue(0);
940 }
941
942 SDValue PIC16TargetLowering::
943 LowerIndirectCallArguments(SDValue Op, SDValue Chain, SDValue InFlag,
944                            SDValue DataAddr_Lo, SDValue DataAddr_Hi,
945                            SelectionDAG &DAG) {
946   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
947   unsigned NumOps = TheCall->getNumArgs();
948   DebugLoc dl = TheCall->getDebugLoc();
949
950   // If call has no arguments then do nothing and return.
951   if (NumOps == 0)
952     return Chain;
953
954   std::vector<SDValue> Ops;
955   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
956   SDValue Arg, StoreRet;
957
958   // For PIC16 ABI the arguments come after the return value. 
959   unsigned RetVals = TheCall->getNumRetVals();
960   for (unsigned i = 0, ArgOffset = RetVals; i < NumOps; i++) {
961     // Get the arguments
962     Arg = TheCall->getArg(i);
963     
964     Ops.clear();
965     Ops.push_back(Chain);
966     Ops.push_back(Arg);
967     Ops.push_back(DataAddr_Lo);
968     Ops.push_back(DataAddr_Hi);
969     Ops.push_back(DAG.getConstant(ArgOffset, MVT::i8));
970     Ops.push_back(InFlag);
971
972     StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
973
974     Chain = getChain(StoreRet);
975     InFlag = getOutFlag(StoreRet);
976     ArgOffset++;
977   }
978   return Chain;
979 }
980
981 SDValue PIC16TargetLowering::
982 LowerDirectCallArguments(SDValue Op, SDValue Chain, SDValue ArgLabel, 
983                          SDValue InFlag, SelectionDAG &DAG) {
984   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
985   unsigned NumOps = TheCall->getNumArgs();
986   DebugLoc dl = TheCall->getDebugLoc();
987   std::string Name;
988   SDValue Arg, StoreAt;
989   MVT ArgVT;
990   unsigned Size=0;
991   unsigned ArgCount=0;
992
993   // If call has no arguments then do nothing and return.
994   if (NumOps == 0)
995     return Chain; 
996
997   // FIXME: This portion of code currently assumes only
998   // primitive types being passed as arguments.
999
1000   // Legalize the address before use
1001   SDValue PtrLo, PtrHi;
1002   unsigned AddressOffset;
1003   int StoreOffset = 0;
1004   LegalizeAddress(ArgLabel, DAG, PtrLo, PtrHi, AddressOffset, dl);
1005   SDValue StoreRet;
1006
1007   std::vector<SDValue> Ops;
1008   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1009   for (unsigned i=ArgCount, Offset = 0; i<NumOps; i++) {
1010     // Get the argument
1011     Arg = TheCall->getArg(i);
1012     StoreOffset = (Offset + AddressOffset);
1013    
1014     // Store the argument on frame
1015
1016     Ops.clear();
1017     Ops.push_back(Chain);
1018     Ops.push_back(Arg);
1019     Ops.push_back(PtrLo);
1020     Ops.push_back(PtrHi);
1021     Ops.push_back(DAG.getConstant(StoreOffset, MVT::i8));
1022     Ops.push_back(InFlag);
1023
1024     StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
1025
1026     Chain = getChain(StoreRet);
1027     InFlag = getOutFlag(StoreRet);
1028
1029     // Update the frame offset to be used for next argument
1030     ArgVT = Arg.getValueType();
1031     Size = ArgVT.getSizeInBits();
1032     Size = Size/8;    // Calculate size in bytes
1033     Offset += Size;   // Increase the frame offset
1034   }
1035   return Chain;
1036 }
1037
1038 SDValue PIC16TargetLowering::
1039 LowerIndirectCallReturn (SDValue Op, SDValue Chain, SDValue InFlag,
1040                          SDValue DataAddr_Lo, SDValue DataAddr_Hi,
1041                          SelectionDAG &DAG) {
1042   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1043   DebugLoc dl = TheCall->getDebugLoc();
1044   unsigned RetVals = TheCall->getNumRetVals();
1045
1046   // If call does not have anything to return
1047   // then do nothing and go back.
1048   if (RetVals == 0)
1049     return Chain;
1050
1051   // Call has something to return
1052   std::vector<SDValue> ResultVals;
1053   SDValue LoadRet;
1054
1055   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1056   for(unsigned i=0;i<RetVals;i++) {
1057     LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, DataAddr_Lo,
1058                           DataAddr_Hi, DAG.getConstant(i, MVT::i8),
1059                           InFlag);
1060     InFlag = getOutFlag(LoadRet);
1061     Chain = getChain(LoadRet);
1062     ResultVals.push_back(LoadRet);
1063   }
1064   ResultVals.push_back(Chain);
1065   SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
1066   return Res;
1067 }
1068
1069 SDValue PIC16TargetLowering::
1070 LowerDirectCallReturn(SDValue Op, SDValue Chain, SDValue RetLabel,
1071                       SDValue InFlag, SelectionDAG &DAG) {
1072   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1073   DebugLoc dl = TheCall->getDebugLoc();
1074   // Currently handling primitive types only. They will come in
1075   // i8 parts
1076   unsigned RetVals = TheCall->getNumRetVals();
1077   
1078   std::vector<SDValue> ResultVals;
1079
1080   // Return immediately if the return type is void
1081   if (RetVals == 0)
1082     return Chain;
1083
1084   // Call has something to return
1085   
1086   // Legalize the address before use
1087   SDValue LdLo, LdHi;
1088   unsigned LdOffset;
1089   LegalizeAddress(RetLabel, DAG, LdLo, LdHi, LdOffset, dl);
1090
1091   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1092   SDValue LoadRet;
1093  
1094   for(unsigned i=0, Offset=0;i<RetVals;i++) {
1095
1096     LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, LdLo, LdHi,
1097                           DAG.getConstant(LdOffset + Offset, MVT::i8),
1098                           InFlag);
1099
1100     InFlag = getOutFlag(LoadRet);
1101
1102     Chain = getChain(LoadRet);
1103     Offset++;
1104     ResultVals.push_back(LoadRet);
1105   }
1106
1107   // To return use MERGE_VALUES
1108   ResultVals.push_back(Chain);
1109   SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
1110   return Res;
1111 }
1112
1113 SDValue PIC16TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
1114   SDValue Chain = Op.getOperand(0);
1115   DebugLoc dl = Op.getDebugLoc();
1116
1117   if (Op.getNumOperands() == 1)   // return void
1118     return Op;
1119
1120   // return should have odd number of operands
1121   if ((Op.getNumOperands() % 2) == 0 ) {
1122     assert(0 && "Do not know how to return this many arguments!");
1123     abort();
1124   }
1125   
1126   // Number of values to return 
1127   unsigned NumRet = (Op.getNumOperands() / 2);
1128
1129   // Function returns value always on stack with the offset starting
1130   // from 0 
1131   MachineFunction &MF = DAG.getMachineFunction();
1132   const Function *F = MF.getFunction();
1133   std::string FuncName = F->getName();
1134
1135   const char *tmpName = createESName(PAN::getFrameLabel(FuncName));
1136   SDVTList VTs  = DAG.getVTList (MVT::i8, MVT::Other);
1137   SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1138   SDValue BS = DAG.getConstant(1, MVT::i8);
1139   SDValue RetVal;
1140   for(unsigned i=0;i<NumRet; ++i) {
1141     RetVal = Op.getNode()->getOperand(2*i + 1);
1142     Chain =  DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, RetVal,
1143                         ES, BS,
1144                         DAG.getConstant (i, MVT::i8));
1145       
1146   }
1147   return DAG.getNode(ISD::RET, dl, MVT::Other, Chain);
1148 }
1149
1150 // CALL node may have some operands non-legal to PIC16. Generate new CALL
1151 // node with all the operands legal.
1152 // Currently only Callee operand of the CALL node is non-legal. This function
1153 // legalizes the Callee operand and uses all other operands as are to generate
1154 // new CALL node.
1155
1156 SDValue PIC16TargetLowering::LegalizeCALL(SDValue Op, SelectionDAG &DAG) {
1157     CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1158     SDValue Chain = TheCall->getChain();
1159     SDValue Callee = TheCall->getCallee();
1160     DebugLoc dl = TheCall->getDebugLoc();
1161     unsigned i =0;
1162
1163     assert(Callee.getValueType() == MVT::i16 &&
1164            "Don't know how to legalize this call node!!!");
1165     assert(Callee.getOpcode() == ISD::BUILD_PAIR &&
1166            "Don't know how to legalize this call node!!!");
1167
1168     if (isDirectAddress(Callee)) {
1169        // Come here for direct calls
1170        Callee = Callee.getOperand(0).getOperand(0);
1171     } else {
1172       // Come here for indirect calls
1173       SDValue Lo, Hi;
1174       // Indirect addresses. Get the hi and lo parts of ptr.
1175       GetExpandedParts(Callee, DAG, Lo, Hi);
1176       // Connect Lo and Hi parts of the callee with the PIC16Connect
1177       Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Lo, Hi);
1178     }
1179     std::vector<SDValue> Ops;
1180     Ops.push_back(Chain);
1181     Ops.push_back(Callee);
1182
1183     // Add the call arguments and their flags
1184     unsigned NumArgs = TheCall->getNumArgs();
1185     for(i=0;i<NumArgs;i++) {
1186        Ops.push_back(TheCall->getArg(i));
1187        Ops.push_back(TheCall->getArgFlagsVal(i));
1188     }
1189     std::vector<MVT> NodeTys;
1190     unsigned NumRets = TheCall->getNumRetVals();
1191     for(i=0;i<NumRets;i++)
1192        NodeTys.push_back(TheCall->getRetValType(i));
1193
1194    // Return a Chain as well
1195    NodeTys.push_back(MVT::Other);
1196    
1197    SDVTList VTs = DAG.getVTList(&NodeTys[0], NodeTys.size());
1198    // Generate new call with all the operands legal
1199    return DAG.getCall(TheCall->getCallingConv(), dl,
1200                       TheCall->isVarArg(), TheCall->isTailCall(),
1201                       TheCall->isInreg(), VTs, &Ops[0], Ops.size());
1202 }
1203
1204 void PIC16TargetLowering::
1205 GetDataAddress(DebugLoc dl, SDValue Callee, SDValue &Chain, 
1206                SDValue &DataAddr_Lo, SDValue &DataAddr_Hi,
1207                SelectionDAG &DAG) {
1208    assert (Callee.getOpcode() == PIC16ISD::PIC16Connect
1209            && "Don't know what to do of such callee!!");
1210    SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1211    SDValue SeqStart  = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1212    Chain = getChain(SeqStart);
1213    SDValue OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1214
1215    // Get the Lo and Hi part of code address
1216    SDValue Lo = Callee.getOperand(0);
1217    SDValue Hi = Callee.getOperand(1);
1218
1219    SDValue Data_Lo, Data_Hi;
1220    SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1221    // Subtract 2 from Address to get the Lower part of DataAddress.
1222    SDVTList VTList = DAG.getVTList(MVT::i8, MVT::Flag);
1223    Data_Lo = DAG.getNode(ISD::SUBC, dl, VTList, Lo, 
1224                          DAG.getConstant(2, MVT::i8));
1225    SDValue Ops[3] = { Hi, DAG.getConstant(0, MVT::i8), Data_Lo.getValue(1)};
1226    Data_Hi = DAG.getNode(ISD::SUBE, dl, VTList, Ops, 3);
1227    SDValue PCLATH = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, Data_Hi);
1228    Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Data_Lo, PCLATH);
1229    SDValue Call = DAG.getNode(PIC16ISD::CALLW, dl, Tys, Chain, Callee,
1230                               OperFlag);
1231    Chain = getChain(Call);
1232    OperFlag = getOutFlag(Call);
1233    SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1234                                        OperFlag);
1235    Chain = getChain(SeqEnd);
1236    OperFlag = getOutFlag(SeqEnd);
1237
1238    // Low part of Data Address 
1239    DataAddr_Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Call, OperFlag);
1240
1241    // Make the second call.
1242    SeqStart  = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1243    Chain = getChain(SeqStart);
1244    OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1245
1246    // Subtract 1 from Address to get high part of data address.
1247    Data_Lo = DAG.getNode(ISD::SUBC, dl, VTList, Lo, 
1248                          DAG.getConstant(1, MVT::i8));
1249    SDValue HiOps[3] = { Hi, DAG.getConstant(0, MVT::i8), Data_Lo.getValue(1)};
1250    Data_Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1251    PCLATH = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, Data_Hi);
1252
1253    // Use new Lo to make another CALLW
1254    Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Data_Lo, PCLATH);
1255    Call = DAG.getNode(PIC16ISD::CALLW, dl, Tys, Chain, Callee, OperFlag);
1256    Chain = getChain(Call);
1257    OperFlag = getOutFlag(Call);
1258    SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1259                                         OperFlag);
1260    Chain = getChain(SeqEnd);
1261    OperFlag = getOutFlag(SeqEnd);
1262    // Hi part of Data Address
1263    DataAddr_Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Call, OperFlag);
1264 }
1265
1266
1267 SDValue PIC16TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1268     CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1269     SDValue Chain = TheCall->getChain();
1270     SDValue Callee = TheCall->getCallee();
1271     DebugLoc dl = TheCall->getDebugLoc();
1272     if (Callee.getValueType() == MVT::i16 &&
1273       Callee.getOpcode() == ISD::BUILD_PAIR) {
1274           // Control should come here only from TypeLegalizer for lowering
1275           
1276           // Legalize the non-legal arguments of call and return the
1277           // new call with legal arguments.
1278           return LegalizeCALL(Op, DAG);
1279     }
1280     // Control should come here from Legalize DAG.
1281     // Here all the operands of CALL node should be legal.
1282     
1283     // If this is an indirect call then to pass the arguments
1284     // and read the return value back, we need the data address
1285     // of the function being called. 
1286     // To get the data address two more calls need to be made.
1287
1288     // The flag to track if this is a direct or indirect call.
1289     bool IsDirectCall = true;    
1290     unsigned RetVals = TheCall->getNumRetVals();
1291     unsigned NumArgs = TheCall->getNumArgs();
1292
1293     SDValue DataAddr_Lo, DataAddr_Hi; 
1294     if (Callee.getOpcode() == PIC16ISD::PIC16Connect) { 
1295        IsDirectCall = false;    // This is indirect call
1296        // Read DataAddress only if we have to pass arguments or 
1297        // read return value. 
1298        if ((RetVals > 0) || (NumArgs > 0)) 
1299          GetDataAddress(dl, Callee, Chain, DataAddr_Lo, DataAddr_Hi, DAG);
1300     }
1301
1302     SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1303
1304     // Start the call sequence.
1305     // Carring the Constant 0 along the CALLSEQSTART
1306     // because there is nothing else to carry.
1307     SDValue SeqStart  = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1308     Chain = getChain(SeqStart);
1309     SDValue OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1310     std::string Name;
1311
1312     // For any direct call - callee will be GlobalAddressNode or
1313     // ExternalSymbol
1314     SDValue ArgLabel, RetLabel;
1315     if (IsDirectCall) { 
1316        // Considering the GlobalAddressNode case here.
1317        if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1318           GlobalValue *GV = G->getGlobal();
1319           Callee = DAG.getTargetGlobalAddress(GV, MVT::i8);
1320           Name = G->getGlobal()->getName();
1321        } else {// Considering the ExternalSymbol case here
1322           ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee);
1323           Callee = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8); 
1324           Name = ES->getSymbol();
1325        }
1326
1327        // Label for argument passing
1328        const char *argFrame = createESName(PAN::getArgsLabel(Name));
1329        ArgLabel = DAG.getTargetExternalSymbol(argFrame, MVT::i8);
1330
1331        // Label for reading return value
1332        const char *retName = createESName(PAN::getRetvalLabel(Name));
1333        RetLabel = DAG.getTargetExternalSymbol(retName, MVT::i8);
1334     } else {
1335        // if indirect call
1336        SDValue CodeAddr_Lo = Callee.getOperand(0);
1337        SDValue CodeAddr_Hi = Callee.getOperand(1);
1338
1339        /*CodeAddr_Lo = DAG.getNode(ISD::ADD, dl, MVT::i8, CodeAddr_Lo,
1340                                  DAG.getConstant(2, MVT::i8));*/
1341
1342        // move Hi part in PCLATH
1343        CodeAddr_Hi = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, CodeAddr_Hi);
1344        Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, CodeAddr_Lo,
1345                             CodeAddr_Hi);
1346     } 
1347
1348     // Pass the argument to function before making the call.
1349     SDValue CallArgs;
1350     if (IsDirectCall) {
1351       CallArgs = LowerDirectCallArguments(Op, Chain, ArgLabel, OperFlag, DAG);
1352       Chain = getChain(CallArgs);
1353       OperFlag = getOutFlag(CallArgs);
1354     } else {
1355       CallArgs = LowerIndirectCallArguments(Op, Chain, OperFlag, DataAddr_Lo, 
1356                                             DataAddr_Hi, DAG);
1357       Chain = getChain(CallArgs);
1358       OperFlag = getOutFlag(CallArgs);
1359     }
1360
1361     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1362     SDValue PICCall = DAG.getNode(PIC16ISD::CALL, dl, Tys, Chain, Callee,
1363                                   OperFlag);
1364     Chain = getChain(PICCall);
1365     OperFlag = getOutFlag(PICCall);
1366
1367
1368     // Carrying the Constant 0 along the CALLSEQSTART
1369     // because there is nothing else to carry.
1370     SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1371                                         OperFlag);
1372     Chain = getChain(SeqEnd);
1373     OperFlag = getOutFlag(SeqEnd);
1374
1375     // Lower the return value reading after the call.
1376     if (IsDirectCall)
1377       return LowerDirectCallReturn(Op, Chain, RetLabel, OperFlag, DAG);
1378     else
1379       return LowerIndirectCallReturn(Op, Chain, OperFlag, DataAddr_Lo,
1380                                      DataAddr_Hi, DAG);
1381 }
1382
1383 bool PIC16TargetLowering::isDirectLoad(const SDValue Op) {
1384   if (Op.getOpcode() == PIC16ISD::PIC16Load)
1385     if (Op.getOperand(1).getOpcode() == ISD::TargetGlobalAddress
1386      || Op.getOperand(1).getOpcode() == ISD::TargetExternalSymbol)
1387       return true;
1388   return false;
1389 }
1390
1391 // NeedToConvertToMemOp - Returns true if one of the operands of the
1392 // operation 'Op' needs to be put into memory. Also returns the
1393 // operand no. of the operand to be converted in 'MemOp'. Remember, PIC16 has 
1394 // no instruction that can operation on two registers. Most insns take
1395 // one register and one memory operand (addwf) / Constant (addlw).
1396 bool PIC16TargetLowering::NeedToConvertToMemOp(SDValue Op, unsigned &MemOp) {
1397   // If one of the operand is a constant, return false.
1398   if (Op.getOperand(0).getOpcode() == ISD::Constant ||
1399       Op.getOperand(1).getOpcode() == ISD::Constant)
1400     return false;    
1401
1402   // Return false if one of the operands is already a direct
1403   // load and that operand has only one use.
1404   if (isDirectLoad(Op.getOperand(0))) {
1405     if (Op.getOperand(0).hasOneUse())
1406       return false;
1407     else 
1408       MemOp = 0;
1409   }
1410   if (isDirectLoad(Op.getOperand(1))) {
1411     if (Op.getOperand(1).hasOneUse())
1412       return false;
1413     else 
1414       MemOp = 1; 
1415   }
1416   return true;
1417 }  
1418
1419 // LowerBinOp - Lower a commutative binary operation that does not
1420 // affect status flag carry.
1421 SDValue PIC16TargetLowering::LowerBinOp(SDValue Op, SelectionDAG &DAG) {
1422   DebugLoc dl = Op.getDebugLoc();
1423
1424   // We should have handled larger operands in type legalizer itself.
1425   assert (Op.getValueType() == MVT::i8 && "illegal Op to lower");
1426
1427   unsigned MemOp = 1;
1428   if (NeedToConvertToMemOp(Op, MemOp)) {
1429     // Put one value on stack.
1430     SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1431
1432     return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1433     NewVal);
1434   }
1435   else {
1436     return Op;
1437   }
1438 }
1439
1440 // LowerADD - Lower all types of ADD operations including the ones
1441 // that affects carry.
1442 SDValue PIC16TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) {
1443   // We should have handled larger operands in type legalizer itself.
1444   assert (Op.getValueType() == MVT::i8 && "illegal add to lower");
1445   DebugLoc dl = Op.getDebugLoc();
1446   unsigned MemOp = 1;
1447   if (NeedToConvertToMemOp(Op, MemOp)) {
1448     // Put one value on stack.
1449     SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1450     
1451     // ADDC and ADDE produce two results.
1452     SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1453
1454     // ADDE has three operands, the last one is the carry bit.
1455     if (Op.getOpcode() == ISD::ADDE)
1456       return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1457                          NewVal, Op.getOperand(2));
1458     // ADDC has two operands.
1459     else if (Op.getOpcode() == ISD::ADDC)
1460       return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1461                          NewVal);
1462     // ADD it is. It produces only one result.
1463     else
1464       return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1465                          NewVal);
1466   }
1467   else
1468     return Op;
1469 }
1470
1471 SDValue PIC16TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) {
1472   DebugLoc dl = Op.getDebugLoc();
1473   // We should have handled larger operands in type legalizer itself.
1474   assert (Op.getValueType() == MVT::i8 && "illegal sub to lower");
1475
1476   // Nothing to do if the first operand is already a direct load and it has
1477   // only one use.
1478   if (isDirectLoad(Op.getOperand(0)) && Op.getOperand(0).hasOneUse())
1479     return Op;
1480
1481   // Put first operand on stack.
1482   SDValue NewVal = ConvertToMemOperand (Op.getOperand(0), DAG, dl);
1483
1484   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1485   if (Op.getOpcode() == ISD::SUBE)
1486     return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1),
1487                        Op.getOperand(2));
1488   else
1489     return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1));
1490 }
1491
1492 void PIC16TargetLowering::InitReservedFrameCount(const Function *F) {
1493   unsigned NumArgs = F->arg_size();
1494
1495   bool isVoidFunc = (F->getReturnType()->getTypeID() == Type::VoidTyID);
1496
1497   if (isVoidFunc)
1498     ReservedFrameCount = NumArgs;
1499   else
1500     ReservedFrameCount = NumArgs + 1;
1501 }
1502
1503 // LowerFORMAL_ARGUMENTS - Argument values are loaded from the
1504 // <fname>.args + offset. All arguments are already broken to leaglized
1505 // types, so the offset just runs from 0 to NumArgVals - 1.
1506
1507 SDValue PIC16TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, 
1508                                                    SelectionDAG &DAG) {
1509   SmallVector<SDValue, 8> ArgValues;
1510   unsigned NumArgVals = Op.getNode()->getNumValues() - 1;
1511   DebugLoc dl = Op.getDebugLoc();
1512   SDValue Chain = Op.getOperand(0);    // Formal arguments' chain
1513
1514
1515   // Get the callee's name to create the <fname>.args label to pass args.
1516   MachineFunction &MF = DAG.getMachineFunction();
1517   const Function *F = MF.getFunction();
1518   std::string FuncName = F->getName();
1519
1520   // Reset the map of FI and TmpOffset 
1521   ResetTmpOffsetMap();
1522   // Initialize the ReserveFrameCount
1523   InitReservedFrameCount(F);
1524
1525   // Create the <fname>.args external symbol.
1526   const char *tmpName = createESName(PAN::getArgsLabel(FuncName));
1527   SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1528
1529   // Load arg values from the label + offset.
1530   SDVTList VTs  = DAG.getVTList (MVT::i8, MVT::Other);
1531   SDValue BS = DAG.getConstant(1, MVT::i8);
1532   for (unsigned i = 0; i < NumArgVals ; ++i) {
1533     SDValue Offset = DAG.getConstant(i, MVT::i8);
1534     SDValue PICLoad = DAG.getNode(PIC16ISD::PIC16LdArg, dl, VTs, Chain, ES, BS,
1535                                   Offset);
1536     Chain = getChain(PICLoad);
1537     ArgValues.push_back(PICLoad);
1538   }
1539
1540   // Return a MERGE_VALUE node.
1541   ArgValues.push_back(Op.getOperand(0));
1542   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(), 
1543                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1544 }
1545
1546 // Perform DAGCombine of PIC16Load.
1547 // FIXME - Need a more elaborate comment here.
1548 SDValue PIC16TargetLowering::
1549 PerformPIC16LoadCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1550   SelectionDAG &DAG = DCI.DAG;
1551   SDValue Chain = N->getOperand(0); 
1552   if (N->hasNUsesOfValue(0, 0)) {
1553     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), Chain);
1554   }
1555   return SDValue();
1556 }
1557
1558 // For all the functions with arguments some STORE nodes are generated 
1559 // that store the argument on the frameindex. However in PIC16 the arguments
1560 // are passed on stack only. Therefore these STORE nodes are redundant. 
1561 // To remove these STORE nodes will be removed in PerformStoreCombine 
1562 //
1563 // Currently this function is doint nothing and will be updated for removing
1564 // unwanted store operations
1565 SDValue PIC16TargetLowering::
1566 PerformStoreCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1567   return SDValue(N, 0);
1568   /*
1569   // Storing an undef value is of no use, so remove it
1570   if (isStoringUndef(N, Chain, DAG)) {
1571     return Chain; // remove the store and return the chain
1572   }
1573   //else everything is ok.
1574   return SDValue(N, 0);
1575   */
1576 }
1577
1578 SDValue PIC16TargetLowering::PerformDAGCombine(SDNode *N, 
1579                                                DAGCombinerInfo &DCI) const {
1580   switch (N->getOpcode()) {
1581   case ISD::STORE:   
1582    return PerformStoreCombine(N, DCI); 
1583   case PIC16ISD::PIC16Load:   
1584     return PerformPIC16LoadCombine(N, DCI);
1585   }
1586   return SDValue();
1587 }
1588
1589 static PIC16CC::CondCodes IntCCToPIC16CC(ISD::CondCode CC) {
1590   switch (CC) {
1591   default: assert(0 && "Unknown condition code!");
1592   case ISD::SETNE:  return PIC16CC::NE;
1593   case ISD::SETEQ:  return PIC16CC::EQ;
1594   case ISD::SETGT:  return PIC16CC::GT;
1595   case ISD::SETGE:  return PIC16CC::GE;
1596   case ISD::SETLT:  return PIC16CC::LT;
1597   case ISD::SETLE:  return PIC16CC::LE;
1598   case ISD::SETULT: return PIC16CC::ULT;
1599   case ISD::SETULE: return PIC16CC::ULE;
1600   case ISD::SETUGE: return PIC16CC::UGE;
1601   case ISD::SETUGT: return PIC16CC::UGT;
1602   }
1603 }
1604
1605 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
1606 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1607 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1608                              ISD::CondCode CC, unsigned &SPCC) {
1609   if (isa<ConstantSDNode>(RHS) &&
1610       cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1611       CC == ISD::SETNE &&
1612       (LHS.getOpcode() == PIC16ISD::SELECT_ICC &&
1613         LHS.getOperand(3).getOpcode() == PIC16ISD::SUBCC) &&
1614       isa<ConstantSDNode>(LHS.getOperand(0)) &&
1615       isa<ConstantSDNode>(LHS.getOperand(1)) &&
1616       cast<ConstantSDNode>(LHS.getOperand(0))->getZExtValue() == 1 &&
1617       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 0) {
1618     SDValue CMPCC = LHS.getOperand(3);
1619     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1620     LHS = CMPCC.getOperand(0);
1621     RHS = CMPCC.getOperand(1);
1622   }
1623 }
1624
1625 // Returns appropriate CMP insn and corresponding condition code in PIC16CC
1626 SDValue PIC16TargetLowering::getPIC16Cmp(SDValue LHS, SDValue RHS, 
1627                                          unsigned CC, SDValue &PIC16CC, 
1628                                          SelectionDAG &DAG, DebugLoc dl) {
1629   PIC16CC::CondCodes CondCode = (PIC16CC::CondCodes) CC;
1630
1631   // PIC16 sub is literal - W. So Swap the operands and condition if needed.
1632   // i.e. a < 12 can be rewritten as 12 > a.
1633   if (RHS.getOpcode() == ISD::Constant) {
1634
1635     SDValue Tmp = LHS;
1636     LHS = RHS;
1637     RHS = Tmp;
1638
1639     switch (CondCode) {
1640     default: break;
1641     case PIC16CC::LT:
1642       CondCode = PIC16CC::GT; 
1643       break;
1644     case PIC16CC::GT:
1645       CondCode = PIC16CC::LT; 
1646       break;
1647     case PIC16CC::ULT:
1648       CondCode = PIC16CC::UGT; 
1649       break;
1650     case PIC16CC::UGT:
1651       CondCode = PIC16CC::ULT; 
1652       break;
1653     case PIC16CC::GE:
1654       CondCode = PIC16CC::LE; 
1655       break;
1656     case PIC16CC::LE:
1657       CondCode = PIC16CC::GE;
1658       break;
1659     case PIC16CC::ULE:
1660       CondCode = PIC16CC::UGE;
1661       break;
1662     case PIC16CC::UGE:
1663       CondCode = PIC16CC::ULE;
1664       break;
1665     }
1666   }
1667
1668   PIC16CC = DAG.getConstant(CondCode, MVT::i8);
1669
1670   // These are signed comparisons. 
1671   SDValue Mask = DAG.getConstant(128, MVT::i8);
1672   if (isSignedComparison(CondCode)) {
1673     LHS = DAG.getNode (ISD::XOR, dl, MVT::i8, LHS, Mask);
1674     RHS = DAG.getNode (ISD::XOR, dl, MVT::i8, RHS, Mask); 
1675   }
1676
1677   SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Flag);
1678   // We can use a subtract operation to set the condition codes. But
1679   // we need to put one operand in memory if required.
1680   // Nothing to do if the first operand is already a valid type (direct load 
1681   // for subwf and literal for sublw) and it is used by this operation only. 
1682   if ((LHS.getOpcode() == ISD::Constant || isDirectLoad(LHS)) 
1683       && LHS.hasOneUse())
1684     return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1685
1686   // else convert the first operand to mem.
1687   LHS = ConvertToMemOperand (LHS, DAG, dl);
1688   return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1689 }
1690
1691
1692 SDValue PIC16TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1693   SDValue LHS = Op.getOperand(0);
1694   SDValue RHS = Op.getOperand(1);
1695   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1696   SDValue TrueVal = Op.getOperand(2);
1697   SDValue FalseVal = Op.getOperand(3);
1698   unsigned ORIGCC = ~0;
1699   DebugLoc dl = Op.getDebugLoc();
1700
1701   // If this is a select_cc of a "setcc", and if the setcc got lowered into
1702   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1703   // i.e.
1704   // A setcc: lhs, rhs, cc is expanded by llvm to 
1705   // select_cc: result of setcc, 0, 1, 0, setne
1706   // We can think of it as:
1707   // select_cc: lhs, rhs, 1, 0, cc
1708   LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1709   if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1710
1711   SDValue PIC16CC;
1712   SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1713
1714   return DAG.getNode (PIC16ISD::SELECT_ICC, dl, TrueVal.getValueType(), TrueVal,
1715                       FalseVal, PIC16CC, Cmp.getValue(1)); 
1716 }
1717
1718 MachineBasicBlock *
1719 PIC16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1720                                                  MachineBasicBlock *BB) const {
1721   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1722   unsigned CC = (PIC16CC::CondCodes)MI->getOperand(3).getImm();
1723   DebugLoc dl = MI->getDebugLoc();
1724
1725   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1726   // control-flow pattern.  The incoming instruction knows the destination vreg
1727   // to set, the condition code register to branch on, the true/false values to
1728   // select between, and a branch opcode to use.
1729   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1730   MachineFunction::iterator It = BB;
1731   ++It;
1732
1733   //  thisMBB:
1734   //  ...
1735   //   TrueVal = ...
1736   //   [f]bCC copy1MBB
1737   //   fallthrough --> copy0MBB
1738   MachineBasicBlock *thisMBB = BB;
1739   MachineFunction *F = BB->getParent();
1740   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1741   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1742   BuildMI(BB, dl, TII.get(PIC16::pic16brcond)).addMBB(sinkMBB).addImm(CC);
1743   F->insert(It, copy0MBB);
1744   F->insert(It, sinkMBB);
1745
1746   // Update machine-CFG edges by transferring all successors of the current
1747   // block to the new block which will contain the Phi node for the select.
1748   sinkMBB->transferSuccessors(BB);
1749   // Next, add the true and fallthrough blocks as its successors.
1750   BB->addSuccessor(copy0MBB);
1751   BB->addSuccessor(sinkMBB);
1752
1753   //  copy0MBB:
1754   //   %FalseValue = ...
1755   //   # fallthrough to sinkMBB
1756   BB = copy0MBB;
1757
1758   // Update machine-CFG edges
1759   BB->addSuccessor(sinkMBB);
1760
1761   //  sinkMBB:
1762   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1763   //  ...
1764   BB = sinkMBB;
1765   BuildMI(BB, dl, TII.get(PIC16::PHI), MI->getOperand(0).getReg())
1766     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1767     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1768
1769   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
1770   return BB;
1771 }
1772
1773
1774 SDValue PIC16TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1775   SDValue Chain = Op.getOperand(0);
1776   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1777   SDValue LHS = Op.getOperand(2);   // LHS of the condition.
1778   SDValue RHS = Op.getOperand(3);   // RHS of the condition.
1779   SDValue Dest = Op.getOperand(4);  // BB to jump to
1780   unsigned ORIGCC = ~0;
1781   DebugLoc dl = Op.getDebugLoc();
1782
1783   // If this is a br_cc of a "setcc", and if the setcc got lowered into
1784   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1785   LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1786   if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1787
1788   // Get the Compare insn and condition code.
1789   SDValue PIC16CC;
1790   SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1791
1792   return DAG.getNode(PIC16ISD::BRCOND, dl, MVT::Other, Chain, Dest, PIC16CC, 
1793                      Cmp.getValue(1));
1794 }
1795