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