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