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