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