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