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