CodeGen still defaults to non-verbose asm, but llc now overrides it and default to...
[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) {
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
156 // To extract chain value from the SDValue Nodes
157 // This function will help to maintain the chain extracting
158 // code at one place. In case of any change in future it will
159 // help maintain the code.
160 static SDValue getChain(SDValue &Op) { 
161   SDValue Chain = Op.getValue(Op.getNode()->getNumValues() - 1);
162
163   // If the last value returned in Flag then the chain is
164   // second last value returned.
165   if (Chain.getValueType() == MVT::Flag)
166     Chain = Op.getValue(Op.getNode()->getNumValues() - 2);
167   
168   // All nodes may not produce a chain. Therefore following assert
169   // verifies that the node is returning a chain only.
170   assert (Chain.getValueType() == MVT::Other 
171           && "Node does not have a chain");
172
173   return Chain;
174 }
175
176 /// PopulateResults - Helper function to LowerOperation.
177 /// If a node wants to return multiple results after lowering,
178 /// it stuffs them into an array of SDValue called Results.
179
180 static void PopulateResults(SDValue N, SmallVectorImpl<SDValue>&Results) {
181   if (N.getOpcode() == ISD::MERGE_VALUES) {
182     int NumResults = N.getNumOperands();
183     for( int i = 0; i < NumResults; i++)
184       Results.push_back(N.getOperand(i));
185   }
186   else
187     Results.push_back(N);
188 }
189
190 MVT PIC16TargetLowering::getSetCCResultType(MVT ValType) const {
191   return MVT::i8;
192 }
193
194 /// The type legalizer framework of generating legalizer can generate libcalls
195 /// only when the operand/result types are illegal.
196 /// PIC16 needs to generate libcalls even for the legal types (i8) for some ops.
197 /// For example an arithmetic right shift. These functions are used to lower
198 /// such operations that generate libcall for legal types.
199
200 void 
201 PIC16TargetLowering::setPIC16LibcallName(PIC16ISD::PIC16Libcall Call,
202                                          const char *Name) {
203   PIC16LibcallNames[Call] = Name; 
204 }
205
206 const char *
207 PIC16TargetLowering::getPIC16LibcallName(PIC16ISD::PIC16Libcall Call) {
208   return PIC16LibcallNames[Call];
209 }
210
211 SDValue
212 PIC16TargetLowering::MakePIC16Libcall(PIC16ISD::PIC16Libcall Call,
213                                       MVT RetVT, const SDValue *Ops,
214                                       unsigned NumOps, bool isSigned,
215                                       SelectionDAG &DAG, DebugLoc dl) {
216
217   TargetLowering::ArgListTy Args;
218   Args.reserve(NumOps);
219
220   TargetLowering::ArgListEntry Entry;
221   for (unsigned i = 0; i != NumOps; ++i) {
222     Entry.Node = Ops[i];
223     Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
224     Entry.isSExt = isSigned;
225     Entry.isZExt = !isSigned;
226     Args.push_back(Entry);
227   }
228   SDValue Callee = DAG.getExternalSymbol(getPIC16LibcallName(Call), MVT::i8);
229
230    const Type *RetTy = RetVT.getTypeForMVT();
231    std::pair<SDValue,SDValue> CallInfo = 
232      LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
233                  false, CallingConv::C, false, Callee, Args, DAG, dl);
234
235   return CallInfo.first;
236 }
237
238 const char *PIC16TargetLowering::getTargetNodeName(unsigned Opcode) const {
239   switch (Opcode) {
240   default:                         return NULL;
241   case PIC16ISD::Lo:               return "PIC16ISD::Lo";
242   case PIC16ISD::Hi:               return "PIC16ISD::Hi";
243   case PIC16ISD::MTLO:             return "PIC16ISD::MTLO";
244   case PIC16ISD::MTHI:             return "PIC16ISD::MTHI";
245   case PIC16ISD::Banksel:          return "PIC16ISD::Banksel";
246   case PIC16ISD::PIC16Load:        return "PIC16ISD::PIC16Load";
247   case PIC16ISD::PIC16LdWF:        return "PIC16ISD::PIC16LdWF";
248   case PIC16ISD::PIC16Store:       return "PIC16ISD::PIC16Store";
249   case PIC16ISD::PIC16StWF:        return "PIC16ISD::PIC16StWF";
250   case PIC16ISD::BCF:              return "PIC16ISD::BCF";
251   case PIC16ISD::LSLF:             return "PIC16ISD::LSLF";
252   case PIC16ISD::LRLF:             return "PIC16ISD::LRLF";
253   case PIC16ISD::RLF:              return "PIC16ISD::RLF";
254   case PIC16ISD::RRF:              return "PIC16ISD::RRF";
255   case PIC16ISD::CALL:             return "PIC16ISD::CALL";
256   case PIC16ISD::SUBCC:            return "PIC16ISD::SUBCC";
257   case PIC16ISD::SELECT_ICC:       return "PIC16ISD::SELECT_ICC";
258   case PIC16ISD::BRCOND:           return "PIC16ISD::BRCOND";
259   case PIC16ISD::Dummy:            return "PIC16ISD::Dummy";
260   }
261 }
262
263 void PIC16TargetLowering::ReplaceNodeResults(SDNode *N,
264                                              SmallVectorImpl<SDValue>&Results,
265                                              SelectionDAG &DAG) {
266
267   switch (N->getOpcode()) {
268     case ISD::GlobalAddress:
269       Results.push_back(ExpandGlobalAddress(N, DAG));
270       return;
271     case ISD::ExternalSymbol:
272       Results.push_back(ExpandExternalSymbol(N, DAG));
273       return;
274     case ISD::STORE:
275       Results.push_back(ExpandStore(N, DAG));
276       return;
277     case ISD::LOAD:
278       PopulateResults(ExpandLoad(N, DAG), Results);
279       return;
280     case ISD::ADD:
281       // Results.push_back(ExpandAdd(N, DAG));
282       return;
283     case ISD::FrameIndex:
284       Results.push_back(ExpandFrameIndex(N, DAG));
285       return;
286     default:
287       assert (0 && "not implemented");
288       return;
289   }
290 }
291
292 SDValue PIC16TargetLowering::ExpandFrameIndex(SDNode *N, SelectionDAG &DAG) {
293
294   // Currently handling FrameIndex of size MVT::i16 only
295   // One example of this scenario is when return value is written on
296   // FrameIndex#0
297
298   if (N->getValueType(0) != MVT::i16)
299     return SDValue();
300
301   // Expand the FrameIndex into ExternalSymbol and a Constant node
302   // The constant will represent the frame index number
303   // Get the current function frame
304   MachineFunction &MF = DAG.getMachineFunction();
305   const Function *Func = MF.getFunction();
306   const std::string Name = Func->getName();
307   
308   FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(SDValue(N,0));
309   // FIXME there isn't really debug info here
310   DebugLoc dl = FR->getDebugLoc();
311   int Index = FR->getIndex();
312
313   SDValue FI[2];
314   FI[0] = DAG.getTargetFrameIndex(Index, MVT::i8);
315   FI[1] = DAG.getTargetFrameIndex(Index + 1, MVT::i8);
316   return DAG.getNode(ISD::BUILD_PAIR, dl, N->getValueType(0), FI[0], FI[1]);
317 }
318
319
320 SDValue PIC16TargetLowering::ExpandStore(SDNode *N, SelectionDAG &DAG) { 
321   StoreSDNode *St = cast<StoreSDNode>(N);
322   SDValue Chain = St->getChain();
323   SDValue Src = St->getValue();
324   SDValue Ptr = St->getBasePtr();
325   MVT ValueType = Src.getValueType();
326   unsigned StoreOffset = 0;
327   DebugLoc dl = N->getDebugLoc();
328
329   SDValue PtrLo, PtrHi;
330   LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, StoreOffset, dl);
331  
332   if (ValueType == MVT::i8) {
333     return DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, Src,
334                         PtrLo, PtrHi, 
335                         DAG.getConstant (0 + StoreOffset, MVT::i8));
336   }
337   else if (ValueType == MVT::i16) {
338     // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
339     SDValue SrcLo, SrcHi;
340     GetExpandedParts(Src, DAG, SrcLo, SrcHi);
341     SDValue ChainLo = Chain, ChainHi = Chain;
342     if (Chain.getOpcode() == ISD::TokenFactor) {
343       ChainLo = Chain.getOperand(0);
344       ChainHi = Chain.getOperand(1);
345     }
346     SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
347                                  ChainLo,
348                                  SrcLo, PtrLo, PtrHi,
349                                  DAG.getConstant (0 + StoreOffset, MVT::i8));
350
351     SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi, 
352                                  SrcHi, PtrLo, PtrHi,
353                                  DAG.getConstant (1 + StoreOffset, MVT::i8));
354
355     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, getChain(Store1),
356                        getChain(Store2));
357   }
358   else if (ValueType == MVT::i32) {
359     // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
360     SDValue SrcLo, SrcHi;
361     GetExpandedParts(Src, DAG, SrcLo, SrcHi);
362
363     // Get the expanded parts of each of SrcLo and SrcHi.
364     SDValue SrcLo1, SrcLo2, SrcHi1, SrcHi2;
365     GetExpandedParts(SrcLo, DAG, SrcLo1, SrcLo2);
366     GetExpandedParts(SrcHi, DAG, SrcHi1, SrcHi2);
367
368     SDValue ChainLo = Chain, ChainHi = Chain;
369     if (Chain.getOpcode() == ISD::TokenFactor) {  
370       ChainLo = Chain.getOperand(0);
371       ChainHi = Chain.getOperand(1);
372     }
373     SDValue ChainLo1 = ChainLo, ChainLo2 = ChainLo, ChainHi1 = ChainHi,
374             ChainHi2 = ChainHi;
375     if (ChainLo.getOpcode() == ISD::TokenFactor) {
376       ChainLo1 = ChainLo.getOperand(0);
377       ChainLo2 = ChainLo.getOperand(1);
378     }
379     if (ChainHi.getOpcode() == ISD::TokenFactor) {
380       ChainHi1 = ChainHi.getOperand(0);
381       ChainHi2 = ChainHi.getOperand(1);
382     }
383     SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
384                                  ChainLo1,
385                                  SrcLo1, PtrLo, PtrHi,
386                                  DAG.getConstant (0 + StoreOffset, MVT::i8));
387
388     SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainLo2,
389                                  SrcLo2, PtrLo, PtrHi,
390                                  DAG.getConstant (1 + StoreOffset, MVT::i8));
391
392     SDValue Store3 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi1,
393                                  SrcHi1, PtrLo, PtrHi,
394                                  DAG.getConstant (2 + StoreOffset, MVT::i8));
395
396     SDValue Store4 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi2,
397                                  SrcHi2, PtrLo, PtrHi,
398                                  DAG.getConstant (3 + StoreOffset, MVT::i8));
399
400     SDValue RetLo =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
401                                  getChain(Store1), getChain(Store2));
402     SDValue RetHi =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
403                                  getChain(Store3), getChain(Store4));
404     return  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, RetLo, RetHi);
405
406   }
407   else {
408     assert (0 && "value type not supported");
409     return SDValue();
410   }
411 }
412
413 SDValue PIC16TargetLowering::ExpandExternalSymbol(SDNode *N, SelectionDAG &DAG)
414 {
415   ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(SDValue(N, 0));
416   // FIXME there isn't really debug info here
417   DebugLoc dl = ES->getDebugLoc();
418
419   SDValue TES = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
420
421   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TES);
422   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TES);
423
424   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
425 }
426
427 // ExpandGlobalAddress - 
428 SDValue PIC16TargetLowering::ExpandGlobalAddress(SDNode *N, SelectionDAG &DAG) {
429   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(SDValue(N, 0));
430   // FIXME there isn't really debug info here
431   DebugLoc dl = G->getDebugLoc();
432   
433   SDValue TGA = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i8,
434                                            G->getOffset());
435
436   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TGA);
437   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TGA);
438
439   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
440 }
441
442 bool PIC16TargetLowering::isDirectAddress(const SDValue &Op) {
443   assert (Op.getNode() != NULL && "Can't operate on NULL SDNode!!");
444
445   if (Op.getOpcode() == ISD::BUILD_PAIR) {
446    if (Op.getOperand(0).getOpcode() == PIC16ISD::Lo) 
447      return true;
448   }
449   return false;
450 }
451
452 // Return true if DirectAddress is in ROM_SPACE
453 bool PIC16TargetLowering::isRomAddress(const SDValue &Op) {
454
455   // RomAddress is a GlobalAddress in ROM_SPACE_
456   // If the Op is not a GlobalAddress return NULL without checking
457   // anything further.
458   if (!isDirectAddress(Op))
459     return false; 
460
461   // Its a GlobalAddress.
462   // It is BUILD_PAIR((PIC16Lo TGA), (PIC16Hi TGA)) and Op is BUILD_PAIR
463   SDValue TGA = Op.getOperand(0).getOperand(0);
464   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(TGA);
465   const Type *ValueType = GSDN->getGlobal()->getType();
466
467   if (!isa<PointerType>(ValueType)) {
468     assert(0 && "TGA must be of a PointerType");
469   }
470
471   int AddrSpace = dyn_cast<PointerType>(ValueType)->getAddressSpace();
472   if (AddrSpace == PIC16ISD::ROM_SPACE)
473     return true;
474
475   // Any other address space return it false
476   return false;
477 }
478
479
480 // GetExpandedParts - This function is on the similiar lines as
481 // the GetExpandedInteger in type legalizer is. This returns expanded
482 // parts of Op in Lo and Hi. 
483
484 void PIC16TargetLowering::GetExpandedParts(SDValue Op, SelectionDAG &DAG,
485                                            SDValue &Lo, SDValue &Hi) {  
486   SDNode *N = Op.getNode();
487   DebugLoc dl = N->getDebugLoc();
488   MVT NewVT = getTypeToTransformTo(N->getValueType(0));
489
490   // Extract the lo component.
491   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
492                    DAG.getConstant(0, MVT::i8));
493                    
494   // extract the hi component
495   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
496                    DAG.getConstant(1, MVT::i8));
497 }
498
499 // Legalize FrameIndex into ExternalSymbol and offset.
500 void 
501 PIC16TargetLowering::LegalizeFrameIndex(SDValue Op, SelectionDAG &DAG,
502                                         SDValue &ES, int &Offset) {
503
504   MachineFunction &MF = DAG.getMachineFunction();
505   const Function *Func = MF.getFunction();
506   const std::string Name = Func->getName();
507
508   char *tmpName = new char [strlen(Name.c_str()) +  8];
509   sprintf(tmpName, "%s.args", Name.c_str());
510   ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
511   FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(Op);
512   Offset = FR->getIndex();
513
514   return;
515 }
516
517 // This function legalizes the PIC16 Addresses. If the Pointer is  
518 //  -- Direct address variable residing 
519 //     --> then a Banksel for that variable will be created.
520 //  -- Rom variable            
521 //     --> then it will be treated as an indirect address.
522 //  -- Indirect address 
523 //     --> then the address will be loaded into FSR
524 //  -- ADD with constant operand
525 //     --> then constant operand of ADD will be returned as Offset
526 //         and non-constant operand of ADD will be treated as pointer.
527 // Returns the high and lo part of the address, and the offset(in case of ADD).
528
529 void PIC16TargetLowering:: LegalizeAddress(SDValue Ptr, SelectionDAG &DAG, 
530                                            SDValue &Lo, SDValue &Hi,
531                                            unsigned &Offset, DebugLoc dl) {
532
533   // Offset, by default, should be 0
534   Offset = 0;
535
536   // If the pointer is ADD with constant,
537   // return the constant value as the offset  
538   if (Ptr.getOpcode() == ISD::ADD) {
539     SDValue OperLeft = Ptr.getOperand(0);
540     SDValue OperRight = Ptr.getOperand(1);
541     if (OperLeft.getOpcode() == ISD::Constant) {
542       Offset = dyn_cast<ConstantSDNode>(OperLeft)->getZExtValue();
543       Ptr = OperRight;
544     } else if (OperRight.getOpcode() == ISD::Constant) {
545       Offset = dyn_cast<ConstantSDNode>(OperRight)->getZExtValue();
546       Ptr = OperLeft;
547     }
548   }
549
550   // If the pointer is Type i8 and an external symbol
551   // then treat it as direct address.
552   // One example for such case is storing and loading
553   // from function frame during a call
554   if (Ptr.getValueType() == MVT::i8) {
555     switch (Ptr.getOpcode()) {
556     case ISD::TargetExternalSymbol:
557       Lo = Ptr;
558       Hi = DAG.getConstant(1, MVT::i8);
559       return;
560     }
561   }
562
563   if (Ptr.getOpcode() == ISD::BUILD_PAIR && 
564       Ptr.getOperand(0).getOpcode() == ISD::TargetFrameIndex) {
565
566     int FrameOffset;
567     LegalizeFrameIndex(Ptr.getOperand(0), DAG, Lo, FrameOffset);
568     Hi = DAG.getConstant(1, MVT::i8);
569     Offset += FrameOffset; 
570     return;
571   }
572
573   if (isDirectAddress(Ptr) && !isRomAddress(Ptr)) {
574     // Direct addressing case for RAM variables. The Hi part is constant
575     // and the Lo part is the TGA itself.
576     Lo = Ptr.getOperand(0).getOperand(0);
577
578     // For direct addresses Hi is a constant. Value 1 for the constant
579     // signifies that banksel needs to generated for it. Value 0 for
580     // the constant signifies that banksel does not need to be generated 
581     // for it. Mark it as 1 now and optimize later. 
582     Hi = DAG.getConstant(1, MVT::i8);
583     return; 
584   }
585
586   // Indirect addresses. Get the hi and lo parts of ptr. 
587   GetExpandedParts(Ptr, DAG, Lo, Hi);
588
589   // Put the hi and lo parts into FSR.
590   Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Lo);
591   Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Hi);
592
593   return;
594 }
595
596 SDValue PIC16TargetLowering::ExpandLoad(SDNode *N, SelectionDAG &DAG) {
597   LoadSDNode *LD = dyn_cast<LoadSDNode>(SDValue(N, 0));
598   SDValue Chain = LD->getChain();
599   SDValue Ptr = LD->getBasePtr();
600   DebugLoc dl = LD->getDebugLoc();
601
602   SDValue Load, Offset;
603   SDVTList Tys; 
604   MVT VT, NewVT;
605   SDValue PtrLo, PtrHi;
606   unsigned LoadOffset;
607
608   // Legalize direct/indirect addresses. This will give the lo and hi parts
609   // of the address and the offset.
610   LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, LoadOffset, dl);
611
612   // Load from the pointer (direct address or FSR) 
613   VT = N->getValueType(0);
614   unsigned NumLoads = VT.getSizeInBits() / 8; 
615   std::vector<SDValue> PICLoads;
616   unsigned iter;
617   MVT MemVT = LD->getMemoryVT();
618   if(ISD::isNON_EXTLoad(N)) {
619     for (iter=0; iter<NumLoads ; ++iter) {
620       // Add the pointer offset if any
621       Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
622       Tys = DAG.getVTList(MVT::i8, MVT::Other); 
623       Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
624                          Offset); 
625       PICLoads.push_back(Load);
626     }
627   } else {
628     // If it is extended load then use PIC16Load for Memory Bytes
629     // and for all extended bytes perform action based on type of
630     // extention - i.e. SignExtendedLoad or ZeroExtendedLoad
631
632     
633     // For extended loads this is the memory value type
634     // i.e. without any extension
635     MVT MemVT = LD->getMemoryVT();
636     unsigned MemBytes = MemVT.getSizeInBits() / 8;
637     unsigned ExtdBytes = VT.getSizeInBits() / 8;
638     Offset = DAG.getConstant(LoadOffset, MVT::i8);
639
640     Tys = DAG.getVTList(MVT::i8, MVT::Other); 
641     // For MemBytes generate PIC16Load with proper offset
642     for (iter=0; iter<MemBytes; ++iter) {
643       // Add the pointer offset if any
644       Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
645       Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
646                          Offset); 
647       PICLoads.push_back(Load);
648     }
649
650     // For SignExtendedLoad
651     if (ISD::isSEXTLoad(N)) {
652       // For all ExtdBytes use the Right Shifted(Arithmetic) Value of the 
653       // highest MemByte
654       SDValue SRA = DAG.getNode(ISD::SRA, dl, MVT::i8, Load, 
655                                 DAG.getConstant(7, MVT::i8));
656       for (iter=MemBytes; iter<ExtdBytes; ++iter) { 
657         PICLoads.push_back(SRA);
658       }
659     } else if (ISD::isZEXTLoad(N)) {
660       // ZeroExtendedLoad -- For all ExtdBytes use constant 0
661       SDValue ConstZero = DAG.getConstant(0, MVT::i8);
662       for (iter=MemBytes; iter<ExtdBytes; ++iter) { 
663         PICLoads.push_back(ConstZero);
664       }
665     }
666   }
667   SDValue BP;
668
669   if (VT == MVT::i8) {
670     // Operand of Load is illegal -- Load itself is legal
671     return PICLoads[0];
672   }
673   else if (VT == MVT::i16) {
674     BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, PICLoads[0], PICLoads[1]);
675     if (MemVT == MVT::i8)
676       Chain = getChain(PICLoads[0]);
677     else
678       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
679                           getChain(PICLoads[0]), getChain(PICLoads[1]));
680   } else if (VT == MVT::i32) {
681     SDValue BPs[2];
682     BPs[0] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, 
683                          PICLoads[0], PICLoads[1]);
684     BPs[1] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
685                          PICLoads[2], PICLoads[3]);
686     BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, BPs[0], BPs[1]);
687     if (MemVT == MVT::i8)
688       Chain = getChain(PICLoads[0]);
689     else if (MemVT == MVT::i16)
690       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
691                           getChain(PICLoads[0]), getChain(PICLoads[1]));
692     else {
693       SDValue Chains[2];
694       Chains[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
695                               getChain(PICLoads[0]), getChain(PICLoads[1]));
696       Chains[1] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
697                               getChain(PICLoads[2]), getChain(PICLoads[3]));
698       Chain =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
699                            Chains[0], Chains[1]);
700     }
701   }
702   Tys = DAG.getVTList(VT, MVT::Other); 
703   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, BP, Chain);
704 }
705
706 SDValue PIC16TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
707   // We should have handled larger operands in type legalizer itself.
708   assert (Op.getValueType() == MVT::i8 && "illegal shift to lower");
709  
710   SDNode *N = Op.getNode();
711   SDValue Value = N->getOperand(0);
712   SDValue Amt = N->getOperand(1);
713   PIC16ISD::PIC16Libcall CallCode;
714   switch (N->getOpcode()) {
715   case ISD::SRA:
716     CallCode = PIC16ISD::SRA_I8;
717     break;
718   case ISD::SHL:
719     CallCode = PIC16ISD::SLL_I8;
720     break;
721   case ISD::SRL:
722     CallCode = PIC16ISD::SRL_I8;
723     break;
724   default:
725     assert ( 0 && "This shift is not implemented yet.");
726     return SDValue();
727   }
728   SmallVector<SDValue, 2> Ops(2);
729   Ops[0] = Value;
730   Ops[1] = Amt;
731   SDValue Call = MakePIC16Libcall(CallCode, N->getValueType(0), &Ops[0], 2, 
732                                   true, DAG, N->getDebugLoc());
733   return Call;
734 }
735
736 void
737 PIC16TargetLowering::LowerOperationWrapper(SDNode *N,
738                                            SmallVectorImpl<SDValue>&Results,
739                                            SelectionDAG &DAG) {
740   SDValue Op = SDValue(N, 0);
741   SDValue Res;
742   unsigned i;
743   switch (Op.getOpcode()) {
744     case ISD::FORMAL_ARGUMENTS:
745       Res = LowerFORMAL_ARGUMENTS(Op, DAG); break;
746     case ISD::LOAD:
747       Res = ExpandLoad(Op.getNode(), DAG); break;
748     case ISD::CALL:
749       Res = LowerCALL(Op, DAG); break;
750     default: {
751       // All other operations are handled in LowerOperation.
752       Res = LowerOperation(Op, DAG);
753       if (Res.getNode())
754         Results.push_back(Res);
755         
756       return; 
757     }
758   }
759
760   N = Res.getNode();
761   unsigned NumValues = N->getNumValues(); 
762   for (i = 0; i < NumValues ; i++) {
763     Results.push_back(SDValue(N, i)); 
764   }
765 }
766
767 SDValue PIC16TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
768   switch (Op.getOpcode()) {
769     case ISD::FORMAL_ARGUMENTS:
770       return LowerFORMAL_ARGUMENTS(Op, DAG);
771     case ISD::ADD:
772     case ISD::ADDC:
773     case ISD::ADDE:
774       return LowerADD(Op, DAG);
775     case ISD::SUB:
776     case ISD::SUBC:
777     case ISD::SUBE:
778       return LowerSUB(Op, DAG);
779     case ISD::LOAD:
780       return ExpandLoad(Op.getNode(), DAG);
781     case ISD::STORE:
782       return ExpandStore(Op.getNode(), DAG);
783     case ISD::SHL:
784     case ISD::SRA:
785     case ISD::SRL:
786       return LowerShift(Op, DAG);
787     case ISD::OR:
788     case ISD::AND:
789     case ISD::XOR:
790       return LowerBinOp(Op, DAG);
791     case ISD::CALL:
792       return LowerCALL(Op, DAG);
793     case ISD::RET:
794       return LowerRET(Op, DAG);
795     case ISD::BR_CC:
796       return LowerBR_CC(Op, DAG);
797     case ISD::SELECT_CC:
798       return LowerSELECT_CC(Op, DAG);
799   }
800   return SDValue();
801 }
802
803 SDValue PIC16TargetLowering::ConvertToMemOperand(SDValue Op,
804                                                  SelectionDAG &DAG,
805                                                  DebugLoc dl) {
806   assert (Op.getValueType() == MVT::i8 
807           && "illegal value type to store on stack.");
808
809   MachineFunction &MF = DAG.getMachineFunction();
810   const Function *Func = MF.getFunction();
811   const std::string FuncName = Func->getName();
812
813   char *tmpName = new char [strlen(FuncName.c_str()) +  6];
814
815   // Put the value on stack.
816   // Get a stack slot index and convert to es.
817   int FI = MF.getFrameInfo()->CreateStackObject(1, 1);
818   sprintf(tmpName, "%s.tmp", FuncName.c_str());
819   SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
820
821   // Store the value to ES.
822   SDValue Store = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other,
823                                DAG.getEntryNode(),
824                                Op, ES, 
825                                DAG.getConstant (1, MVT::i8), // Banksel.
826                                DAG.getConstant (FI, MVT::i8));
827
828   // Load the value from ES.
829   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other);
830   SDValue Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Store,
831                              ES, DAG.getConstant (1, MVT::i8),
832                              DAG.getConstant (FI, MVT::i8));
833     
834   return Load.getValue(0);
835 }
836           
837 SDValue
838 PIC16TargetLowering::LowerCallArguments(SDValue Op, SDValue Chain,
839                                         SDValue FrameAddress, 
840                                         SDValue InFlag,
841                                         SelectionDAG &DAG) {
842   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
843   unsigned NumOps = TheCall->getNumArgs();
844   DebugLoc dl = TheCall->getDebugLoc();
845   std::string Name;
846   SDValue Arg, StoreAt;
847   MVT ArgVT;
848   unsigned Size=0;
849   unsigned ArgCount=0;
850
851
852   // FIXME: This portion of code currently assumes only
853   // primitive types being passed as arguments.
854
855   // Legalize the address before use
856   SDValue PtrLo, PtrHi;
857   unsigned AddressOffset;
858   int StoreOffset = 0;
859   LegalizeAddress(FrameAddress, DAG, PtrLo, PtrHi, AddressOffset, dl);
860   SDValue StoreRet;
861
862   std::vector<SDValue> Ops;
863   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
864   for (unsigned i=ArgCount, Offset = 0; i<NumOps; i++) {
865     // Get the argument
866     Arg = TheCall->getArg(i);
867
868     StoreOffset = (Offset + AddressOffset);
869    
870     // Store the argument on frame
871
872     Ops.clear();
873     Ops.push_back(Chain);
874     Ops.push_back(Arg.getValue(0));
875     Ops.push_back(PtrLo);
876     Ops.push_back(PtrHi);
877     Ops.push_back(DAG.getConstant(StoreOffset, MVT::i8));
878     Ops.push_back(InFlag);
879
880     StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
881
882     Chain = getChain(StoreRet);
883     InFlag = getOutFlag(StoreRet);
884
885     // Update the frame offset to be used for next argument
886     ArgVT = Arg.getValueType();
887     Size = ArgVT.getSizeInBits();
888     Size = Size/8;    // Calculate size in bytes
889     Offset += Size;   // Increase the frame offset
890   }
891   return Chain;
892 }
893
894 SDValue
895 PIC16TargetLowering::LowerCallReturn(SDValue Op, SDValue Chain,
896                                      SDValue FrameAddress,
897                                      SDValue InFlag,
898                                      SelectionDAG &DAG) {
899   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
900   DebugLoc dl = TheCall->getDebugLoc();
901   // Currently handling primitive types only. They will come in
902   // i8 parts
903   unsigned RetVals = TheCall->getNumRetVals();
904   
905   std::vector<SDValue> ResultVals;
906
907   // Return immediately if the return type is void
908   if (RetVals == 0)
909     return Chain;
910
911   // Call has something to return
912   
913   // Legalize the address before use
914   SDValue LdLo, LdHi;
915   unsigned LdOffset;
916   LegalizeAddress(FrameAddress, DAG, LdLo, LdHi, LdOffset, dl);
917
918   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
919   SDValue LoadRet;
920  
921   for(unsigned i=0, Offset=0;i<RetVals;i++) {
922
923     LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, LdLo, LdHi,
924                           DAG.getConstant(LdOffset + Offset, MVT::i8),
925                           InFlag);
926
927     InFlag = getOutFlag(LoadRet);
928
929     Chain = getChain(LoadRet);
930     Offset++;
931     ResultVals.push_back(LoadRet);
932   }
933
934   // To return use MERGE_VALUES
935   ResultVals.push_back(Chain);
936   SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
937   return Res;
938 }
939
940 SDValue PIC16TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
941  //int NumOps = Op.getNode()->getNumOperands();
942
943  // For default cases LLVM returns the value on the function frame 
944  // So let LLVM do this for all the cases other than character
945  return Op; 
946 }
947
948 SDValue PIC16TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
949     CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
950     SDValue Chain = TheCall->getChain();
951     SDValue Callee = TheCall->getCallee();
952     DebugLoc dl = TheCall->getDebugLoc();
953     unsigned i =0;
954     if (Callee.getValueType() == MVT::i16 &&
955       Callee.getOpcode() == ISD::BUILD_PAIR) {
956       // It has come from TypeLegalizer for lowering
957
958       Callee = Callee.getOperand(0).getOperand(0);
959
960       std::vector<SDValue> Ops;
961       Ops.push_back(Chain);
962       Ops.push_back(Callee);
963
964       // Add the call arguments and their flags
965       unsigned NumArgs = TheCall->getNumArgs();
966       for(i=0;i<NumArgs;i++) { 
967         Ops.push_back(TheCall->getArg(i));
968         Ops.push_back(TheCall->getArgFlagsVal(i));
969       }
970
971       std::vector<MVT> NodeTys;
972       unsigned NumRets = TheCall->getNumRetVals();
973       for(i=0;i<NumRets;i++)
974         NodeTys.push_back(TheCall->getRetValType(i));
975
976       // Return a Chain as well
977       NodeTys.push_back(MVT::Other);
978
979       SDVTList VTs = DAG.getVTList(&NodeTys[0], NodeTys.size());
980       SDValue NewCall = 
981               DAG.getCall(TheCall->getCallingConv(), dl,
982                           TheCall->isVarArg(), TheCall->isTailCall(), 
983                           TheCall->isInreg(), VTs, &Ops[0], Ops.size());
984
985       return NewCall;
986     }
987     
988     SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
989
990     // Start the call sequence.
991     // Carring the Constant 0 along the CALLSEQSTART
992     // because there is nothing else to carry.
993     SDValue SeqStart  = DAG.getCALLSEQ_START(Chain, ZeroOperand);
994     Chain = getChain(SeqStart);
995
996     // For any direct call - callee will be GlobalAddressNode or
997     // ExternalSymbol
998
999     // Considering the GlobalAddressNode case here.
1000     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1001       GlobalValue *GV = G->getGlobal();
1002       Callee = DAG.getTargetGlobalAddress(GV, MVT::i8);
1003     }
1004
1005     // Considering the ExternalSymbol case here
1006     if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1007       Callee = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8); 
1008     }
1009
1010     SDValue OperFlag = getOutFlag(Chain); // To manage the data dependency
1011
1012     std::string Name;
1013
1014     // Considering GlobalAddress here
1015     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1016        Name = G->getGlobal()->getName();
1017
1018     // Considering ExternalSymbol here
1019     if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee))
1020        Name = ES->getSymbol();
1021
1022     char *argFrame = new char [strlen(Name.c_str()) +  8];
1023     sprintf(argFrame, "%s.args", Name.c_str());
1024     SDValue ArgLabel = DAG.getTargetExternalSymbol(argFrame, MVT::i8);
1025
1026     char *retName = new char [strlen(Name.c_str()) +  8];
1027     sprintf(retName, "%s.retval", Name.c_str());
1028     SDValue RetLabel = DAG.getTargetExternalSymbol(retName, MVT::i8);
1029
1030     // Pass the argument to function before making the call.
1031     SDValue CallArgs = LowerCallArguments(Op, Chain, ArgLabel, OperFlag, DAG);
1032     Chain = getChain(CallArgs);
1033     OperFlag = getOutFlag(CallArgs);
1034
1035     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1036     SDValue PICCall = DAG.getNode(PIC16ISD::CALL, dl, Tys, Chain, Callee,
1037                                   OperFlag);
1038     Chain = getChain(PICCall);
1039     OperFlag = getOutFlag(PICCall);
1040
1041
1042     // Carrying the Constant 0 along the CALLSEQSTART
1043     // because there is nothing else to carry.
1044     SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1045                                         OperFlag);
1046     Chain = getChain(SeqEnd);
1047     OperFlag = getOutFlag(SeqEnd);
1048
1049     // Lower the return value reading after the call.
1050     return LowerCallReturn(Op, Chain, RetLabel, OperFlag, DAG);
1051 }
1052
1053 bool PIC16TargetLowering::isDirectLoad(const SDValue Op) {
1054   if (Op.getOpcode() == PIC16ISD::PIC16Load)
1055     if (Op.getOperand(1).getOpcode() == ISD::TargetGlobalAddress
1056      || Op.getOperand(1).getOpcode() == ISD::TargetExternalSymbol)
1057       return true;
1058   return false;
1059 }
1060
1061 // NeedToConvertToMemOp - Returns true if one of the operands of the
1062 // operation 'Op' needs to be put into memory. Also returns the
1063 // operand no. of the operand to be converted in 'MemOp'. Remember, PIC16 has 
1064 // no instruction that can operation on two registers. Most insns take
1065 // one register and one memory operand (addwf) / Constant (addlw).
1066 bool PIC16TargetLowering::NeedToConvertToMemOp(SDValue Op, unsigned &MemOp) {
1067   // If one of the operand is a constant, return false.
1068   if (Op.getOperand(0).getOpcode() == ISD::Constant ||
1069       Op.getOperand(1).getOpcode() == ISD::Constant)
1070     return false;    
1071
1072   // Return false if one of the operands is already a direct
1073   // load and that operand has only one use.
1074   if (isDirectLoad(Op.getOperand(0))) {
1075     if (Op.getOperand(0).hasOneUse())
1076       return false;
1077     else 
1078       MemOp = 0;
1079   }
1080   if (isDirectLoad(Op.getOperand(1))) {
1081     if (Op.getOperand(1).hasOneUse())
1082       return false;
1083     else 
1084       MemOp = 1; 
1085   }
1086   return true;
1087 }  
1088
1089 // LowerBinOp - Lower a commutative binary operation that does not
1090 // affect status flag carry.
1091 SDValue PIC16TargetLowering::LowerBinOp(SDValue Op, SelectionDAG &DAG) {
1092   DebugLoc dl = Op.getDebugLoc();
1093
1094   // We should have handled larger operands in type legalizer itself.
1095   assert (Op.getValueType() == MVT::i8 && "illegal Op to lower");
1096
1097   unsigned MemOp = 1;
1098   if (NeedToConvertToMemOp(Op, MemOp)) {
1099     // Put one value on stack.
1100     SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1101
1102     return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1103     NewVal);
1104   }
1105   else {
1106     return Op;
1107   }
1108 }
1109
1110 // LowerADD - Lower all types of ADD operations including the ones
1111 // that affects carry.
1112 SDValue PIC16TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) {
1113   // We should have handled larger operands in type legalizer itself.
1114   assert (Op.getValueType() == MVT::i8 && "illegal add to lower");
1115   DebugLoc dl = Op.getDebugLoc();
1116   unsigned MemOp = 1;
1117   if (NeedToConvertToMemOp(Op, MemOp)) {
1118     // Put one value on stack.
1119     SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1120     
1121     SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1122
1123     if (Op.getOpcode() == ISD::ADDE)
1124       return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1125                          NewVal, Op.getOperand(2));
1126     else
1127       return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1128                          NewVal);
1129   }
1130   else if (Op.getOpcode() == ISD::ADD) {
1131     return Op;
1132   }
1133   else {
1134     return SDValue();
1135   }
1136 }
1137
1138 SDValue PIC16TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) {
1139   DebugLoc dl = Op.getDebugLoc();
1140   // We should have handled larger operands in type legalizer itself.
1141   assert (Op.getValueType() == MVT::i8 && "illegal sub to lower");
1142
1143   // Nothing to do if the first operand is already a direct load and it has
1144   // only one use.
1145   if (isDirectLoad(Op.getOperand(0)) && Op.getOperand(0).hasOneUse())
1146     return SDValue();
1147
1148   // Put first operand on stack.
1149   SDValue NewVal = ConvertToMemOperand (Op.getOperand(0), DAG, dl);
1150
1151   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1152   if (Op.getOpcode() == ISD::SUBE)
1153     return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1),
1154                        Op.getOperand(2));
1155   else
1156     return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1));
1157 }
1158
1159 // LowerFORMAL_ARGUMENTS - In Lowering FORMAL ARGUMENTS - MERGE_VALUES nodes
1160 // is returned. MERGE_VALUES nodes number of operands and number of values are
1161 // equal. Therefore to construct MERGE_VALUE node, UNDEF nodes equal to the
1162 // number of arguments of function have been created.
1163
1164 SDValue PIC16TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, 
1165                                                     SelectionDAG &DAG) {
1166   SmallVector<SDValue, 8> ArgValues;
1167   unsigned NumArgs = Op.getNumOperands() - 3;
1168   DebugLoc dl = Op.getDebugLoc();
1169
1170   // Creating UNDEF nodes to meet the requirement of MERGE_VALUES node.
1171   for(unsigned i = 0 ; i<NumArgs ; i++) {
1172     SDValue TempNode = DAG.getUNDEF(Op.getNode()->getValueType(i));
1173     ArgValues.push_back(TempNode);
1174   }
1175
1176   ArgValues.push_back(Op.getOperand(0));
1177   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(), 
1178                      &ArgValues[0],
1179                      ArgValues.size()).getValue(Op.getResNo());
1180 }
1181
1182 // Perform DAGCombine of PIC16Load.
1183 // FIXME - Need a more elaborate comment here.
1184 SDValue PIC16TargetLowering::
1185 PerformPIC16LoadCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1186   SelectionDAG &DAG = DCI.DAG;
1187   SDValue Chain = N->getOperand(0); 
1188   if (N->hasNUsesOfValue(0, 0)) {
1189     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), Chain);
1190   }
1191   return SDValue();
1192 }
1193
1194
1195 SDValue PIC16TargetLowering::PerformDAGCombine(SDNode *N, 
1196                                                DAGCombinerInfo &DCI) const {
1197   switch (N->getOpcode()) {
1198   case PIC16ISD::PIC16Load:
1199     return PerformPIC16LoadCombine(N, DCI);
1200   }
1201   return SDValue();
1202 }
1203
1204 static PIC16CC::CondCodes IntCCToPIC16CC(ISD::CondCode CC) {
1205   switch (CC) {
1206   default: assert(0 && "Unknown condition code!");
1207   case ISD::SETNE:  return PIC16CC::NE;
1208   case ISD::SETEQ:  return PIC16CC::EQ;
1209   case ISD::SETGT:  return PIC16CC::GT;
1210   case ISD::SETGE:  return PIC16CC::GE;
1211   case ISD::SETLT:  return PIC16CC::LT;
1212   case ISD::SETLE:  return PIC16CC::LE;
1213   case ISD::SETULT: return PIC16CC::ULT;
1214   case ISD::SETULE: return PIC16CC::LE;
1215   case ISD::SETUGE: return PIC16CC::GE;
1216   case ISD::SETUGT: return PIC16CC::UGT;
1217   }
1218 }
1219
1220 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
1221 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1222 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1223                              ISD::CondCode CC, unsigned &SPCC) {
1224   if (isa<ConstantSDNode>(RHS) &&
1225       cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1226       CC == ISD::SETNE &&
1227       (LHS.getOpcode() == PIC16ISD::SELECT_ICC &&
1228         LHS.getOperand(3).getOpcode() == PIC16ISD::SUBCC) &&
1229       isa<ConstantSDNode>(LHS.getOperand(0)) &&
1230       isa<ConstantSDNode>(LHS.getOperand(1)) &&
1231       cast<ConstantSDNode>(LHS.getOperand(0))->getZExtValue() == 1 &&
1232       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 0) {
1233     SDValue CMPCC = LHS.getOperand(3);
1234     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1235     LHS = CMPCC.getOperand(0);
1236     RHS = CMPCC.getOperand(1);
1237   }
1238 }
1239
1240 // Returns appropriate CMP insn and corresponding condition code in PIC16CC
1241 SDValue PIC16TargetLowering::getPIC16Cmp(SDValue LHS, SDValue RHS, 
1242                                          unsigned CC, SDValue &PIC16CC, 
1243                                          SelectionDAG &DAG, DebugLoc dl) {
1244   PIC16CC::CondCodes CondCode = (PIC16CC::CondCodes) CC;
1245
1246   // PIC16 sub is literal - W. So Swap the operands and condition if needed.
1247   // i.e. a < 12 can be rewritten as 12 > a.
1248   if (RHS.getOpcode() == ISD::Constant) {
1249
1250     SDValue Tmp = LHS;
1251     LHS = RHS;
1252     RHS = Tmp;
1253
1254     switch (CondCode) {
1255     default: break;
1256     case PIC16CC::LT:
1257       CondCode = PIC16CC::GT; 
1258       break;
1259     case PIC16CC::GT:
1260       CondCode = PIC16CC::LT; 
1261       break;
1262     case PIC16CC::ULT:
1263       CondCode = PIC16CC::UGT; 
1264       break;
1265     case PIC16CC::UGT:
1266       CondCode = PIC16CC::ULT; 
1267       break;
1268     case PIC16CC::GE:
1269       CondCode = PIC16CC::LE; 
1270       break;
1271     case PIC16CC::LE:
1272       CondCode = PIC16CC::GE;
1273       break;
1274     case PIC16CC::ULE:
1275       CondCode = PIC16CC::UGE;
1276       break;
1277     case PIC16CC::UGE:
1278       CondCode = PIC16CC::ULE;
1279       break;
1280     }
1281   }
1282
1283   PIC16CC = DAG.getConstant(CondCode, MVT::i8);
1284
1285   // These are signed comparisons. 
1286   SDValue Mask = DAG.getConstant(128, MVT::i8);
1287   if (isSignedComparison(CondCode)) {
1288     LHS = DAG.getNode (ISD::XOR, dl, MVT::i8, LHS, Mask);
1289     RHS = DAG.getNode (ISD::XOR, dl, MVT::i8, RHS, Mask); 
1290   }
1291
1292   SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Flag);
1293   // We can use a subtract operation to set the condition codes. But
1294   // we need to put one operand in memory if required.
1295   // Nothing to do if the first operand is already a valid type (direct load 
1296   // for subwf and literal for sublw) and it is used by this operation only. 
1297   if ((LHS.getOpcode() == ISD::Constant || isDirectLoad(LHS)) 
1298       && LHS.hasOneUse())
1299     return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1300
1301   // else convert the first operand to mem.
1302   LHS = ConvertToMemOperand (LHS, DAG, dl);
1303   return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1304 }
1305
1306
1307 SDValue PIC16TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1308   SDValue LHS = Op.getOperand(0);
1309   SDValue RHS = Op.getOperand(1);
1310   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1311   SDValue TrueVal = Op.getOperand(2);
1312   SDValue FalseVal = Op.getOperand(3);
1313   unsigned ORIGCC = ~0;
1314   DebugLoc dl = Op.getDebugLoc();
1315
1316   // If this is a select_cc of a "setcc", and if the setcc got lowered into
1317   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1318   // i.e.
1319   // A setcc: lhs, rhs, cc is expanded by llvm to 
1320   // select_cc: result of setcc, 0, 1, 0, setne
1321   // We can think of it as:
1322   // select_cc: lhs, rhs, 1, 0, cc
1323   LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1324   if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1325
1326   SDValue PIC16CC;
1327   SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1328
1329   return DAG.getNode (PIC16ISD::SELECT_ICC, dl, TrueVal.getValueType(), TrueVal,
1330                       FalseVal, PIC16CC, Cmp.getValue(1)); 
1331 }
1332
1333 MachineBasicBlock *
1334 PIC16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1335                                                  MachineBasicBlock *BB) const {
1336   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1337   unsigned CC = (PIC16CC::CondCodes)MI->getOperand(3).getImm();
1338   DebugLoc dl = MI->getDebugLoc();
1339
1340   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1341   // control-flow pattern.  The incoming instruction knows the destination vreg
1342   // to set, the condition code register to branch on, the true/false values to
1343   // select between, and a branch opcode to use.
1344   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1345   MachineFunction::iterator It = BB;
1346   ++It;
1347
1348   //  thisMBB:
1349   //  ...
1350   //   TrueVal = ...
1351   //   [f]bCC copy1MBB
1352   //   fallthrough --> copy0MBB
1353   MachineBasicBlock *thisMBB = BB;
1354   MachineFunction *F = BB->getParent();
1355   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1356   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1357   BuildMI(BB, dl, TII.get(PIC16::pic16brcond)).addMBB(sinkMBB).addImm(CC);
1358   F->insert(It, copy0MBB);
1359   F->insert(It, sinkMBB);
1360
1361   // Update machine-CFG edges by transferring all successors of the current
1362   // block to the new block which will contain the Phi node for the select.
1363   sinkMBB->transferSuccessors(BB);
1364   // Next, add the true and fallthrough blocks as its successors.
1365   BB->addSuccessor(copy0MBB);
1366   BB->addSuccessor(sinkMBB);
1367
1368   //  copy0MBB:
1369   //   %FalseValue = ...
1370   //   # fallthrough to sinkMBB
1371   BB = copy0MBB;
1372
1373   // Update machine-CFG edges
1374   BB->addSuccessor(sinkMBB);
1375
1376   //  sinkMBB:
1377   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1378   //  ...
1379   BB = sinkMBB;
1380   BuildMI(BB, dl, TII.get(PIC16::PHI), MI->getOperand(0).getReg())
1381     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1382     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1383
1384   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
1385   return BB;
1386 }
1387
1388
1389 SDValue PIC16TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1390   SDValue Chain = Op.getOperand(0);
1391   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1392   SDValue LHS = Op.getOperand(2);   // LHS of the condition.
1393   SDValue RHS = Op.getOperand(3);   // RHS of the condition.
1394   SDValue Dest = Op.getOperand(4);  // BB to jump to
1395   unsigned ORIGCC = ~0;
1396   DebugLoc dl = Op.getDebugLoc();
1397
1398   // If this is a br_cc of a "setcc", and if the setcc got lowered into
1399   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1400   LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1401   if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1402
1403   // Get the Compare insn and condition code.
1404   SDValue PIC16CC;
1405   SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1406
1407   return DAG.getNode(PIC16ISD::BRCOND, dl, MVT::Other, Chain, Dest, PIC16CC, 
1408                      Cmp.getValue(1));
1409 }
1410
1411