133f8283950a701d031d7ba846b61a7b3665d390
[oota-llvm.git] / lib / Target / Sparc / SparcISelLowering.cpp
1 //===-- SparcISelLowering.cpp - Sparc DAG Lowering Implementation ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interfaces that Sparc uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SparcISelLowering.h"
16 #include "SparcTargetMachine.h"
17 #include "llvm/Function.h"
18 #include "llvm/CodeGen/CallingConvLower.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/Target/TargetLoweringObjectFile.h"
25 #include "llvm/ADT/VectorExtras.h"
26 #include "llvm/Support/ErrorHandling.h"
27 using namespace llvm;
28
29
30 //===----------------------------------------------------------------------===//
31 // Calling Convention Implementation
32 //===----------------------------------------------------------------------===//
33
34 #include "SparcGenCallingConv.inc"
35
36 SDValue
37 SparcTargetLowering::LowerReturn(SDValue Chain,
38                                  CallingConv::ID CallConv, bool isVarArg,
39                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
40                                  DebugLoc dl, SelectionDAG &DAG) {
41
42   // CCValAssign - represent the assignment of the return value to locations.
43   SmallVector<CCValAssign, 16> RVLocs;
44
45   // CCState - Info about the registers and stack slot.
46   CCState CCInfo(CallConv, isVarArg, DAG.getTarget(),
47                  RVLocs, *DAG.getContext());
48
49   // Analize return values.
50   CCInfo.AnalyzeReturn(Outs, RetCC_Sparc32);
51
52   // If this is the first return lowered for this function, add the regs to the
53   // liveout set for the function.
54   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
55     for (unsigned i = 0; i != RVLocs.size(); ++i)
56       if (RVLocs[i].isRegLoc())
57         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
58   }
59
60   SDValue Flag;
61
62   // Copy the result values into the output registers.
63   for (unsigned i = 0; i != RVLocs.size(); ++i) {
64     CCValAssign &VA = RVLocs[i];
65     assert(VA.isRegLoc() && "Can only return in registers!");
66
67     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 
68                              Outs[i].Val, Flag);
69
70     // Guarantee that all emitted copies are stuck together with flags.
71     Flag = Chain.getValue(1);
72   }
73
74   if (Flag.getNode())
75     return DAG.getNode(SPISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
76   return DAG.getNode(SPISD::RET_FLAG, dl, MVT::Other, Chain);
77 }
78
79 /// LowerFormalArguments - V8 uses a very simple ABI, where all values are
80 /// passed in either one or two GPRs, including FP values.  TODO: we should
81 /// pass FP values in FP registers for fastcc functions.
82 SDValue
83 SparcTargetLowering::LowerFormalArguments(SDValue Chain,
84                                           CallingConv::ID CallConv, bool isVarArg,
85                                           const SmallVectorImpl<ISD::InputArg>
86                                             &Ins,
87                                           DebugLoc dl, SelectionDAG &DAG,
88                                           SmallVectorImpl<SDValue> &InVals) {
89
90   MachineFunction &MF = DAG.getMachineFunction();
91   MachineRegisterInfo &RegInfo = MF.getRegInfo();
92
93   // Assign locations to all of the incoming arguments.
94   SmallVector<CCValAssign, 16> ArgLocs;
95   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
96                  ArgLocs, *DAG.getContext());
97   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc32);
98
99   static const unsigned ArgRegs[] = {
100     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
101   };
102   const unsigned *CurArgReg = ArgRegs, *ArgRegEnd = ArgRegs+6;
103   unsigned ArgOffset = 68;
104
105   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
106     SDValue ArgValue;
107     CCValAssign &VA = ArgLocs[i];
108     // FIXME: We ignore the register assignments of AnalyzeFormalArguments
109     // because it doesn't know how to split a double into two i32 registers.
110     EVT ObjectVT = VA.getValVT();
111     switch (ObjectVT.getSimpleVT().SimpleTy) {
112     default: llvm_unreachable("Unhandled argument type!");
113     case MVT::i1:
114     case MVT::i8:
115     case MVT::i16:
116     case MVT::i32:
117       if (!Ins[i].Used) {                  // Argument is dead.
118         if (CurArgReg < ArgRegEnd) ++CurArgReg;
119         InVals.push_back(DAG.getUNDEF(ObjectVT));
120       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
121         unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
122         MF.getRegInfo().addLiveIn(*CurArgReg++, VReg);
123         SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
124         if (ObjectVT != MVT::i32) {
125           unsigned AssertOp = ISD::AssertSext;
126           Arg = DAG.getNode(AssertOp, dl, MVT::i32, Arg,
127                             DAG.getValueType(ObjectVT));
128           Arg = DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, Arg);
129         }
130         InVals.push_back(Arg);
131       } else {
132         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
133                                                             true, false);
134         SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
135         SDValue Load;
136         if (ObjectVT == MVT::i32) {
137           Load = DAG.getLoad(MVT::i32, dl, Chain, FIPtr, NULL, 0);
138         } else {
139           ISD::LoadExtType LoadOp = ISD::SEXTLOAD;
140
141           // Sparc is big endian, so add an offset based on the ObjectVT.
142           unsigned Offset = 4-std::max(1U, ObjectVT.getSizeInBits()/8);
143           FIPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIPtr,
144                               DAG.getConstant(Offset, MVT::i32));
145           Load = DAG.getExtLoad(LoadOp, dl, MVT::i32, Chain, FIPtr,
146                                 NULL, 0, ObjectVT);
147           Load = DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, Load);
148         }
149         InVals.push_back(Load);
150       }
151
152       ArgOffset += 4;
153       break;
154     case MVT::f32:
155       if (!Ins[i].Used) {                  // Argument is dead.
156         if (CurArgReg < ArgRegEnd) ++CurArgReg;
157         InVals.push_back(DAG.getUNDEF(ObjectVT));
158       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
159         // FP value is passed in an integer register.
160         unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
161         MF.getRegInfo().addLiveIn(*CurArgReg++, VReg);
162         SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
163
164         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Arg);
165         InVals.push_back(Arg);
166       } else {
167         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
168                                                             true, false);
169         SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
170         SDValue Load = DAG.getLoad(MVT::f32, dl, Chain, FIPtr, NULL, 0);
171         InVals.push_back(Load);
172       }
173       ArgOffset += 4;
174       break;
175
176     case MVT::i64:
177     case MVT::f64:
178       if (!Ins[i].Used) {                // Argument is dead.
179         if (CurArgReg < ArgRegEnd) ++CurArgReg;
180         if (CurArgReg < ArgRegEnd) ++CurArgReg;
181         InVals.push_back(DAG.getUNDEF(ObjectVT));
182       } else {
183         SDValue HiVal;
184         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
185           unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
186           MF.getRegInfo().addLiveIn(*CurArgReg++, VRegHi);
187           HiVal = DAG.getCopyFromReg(Chain, dl, VRegHi, MVT::i32);
188         } else {
189           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
190                                                               true, false);
191           SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
192           HiVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr, NULL, 0);
193         }
194
195         SDValue LoVal;
196         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
197           unsigned VRegLo = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
198           MF.getRegInfo().addLiveIn(*CurArgReg++, VRegLo);
199           LoVal = DAG.getCopyFromReg(Chain, dl, VRegLo, MVT::i32);
200         } else {
201           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset+4,
202                                                               true, false);
203           SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
204           LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr, NULL, 0);
205         }
206
207         // Compose the two halves together into an i64 unit.
208         SDValue WholeValue =
209           DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
210
211         // If we want a double, do a bit convert.
212         if (ObjectVT == MVT::f64)
213           WholeValue = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, WholeValue);
214
215         InVals.push_back(WholeValue);
216       }
217       ArgOffset += 8;
218       break;
219     }
220   }
221
222   // Store remaining ArgRegs to the stack if this is a varargs function.
223   if (isVarArg) {
224     // Remember the vararg offset for the va_start implementation.
225     VarArgsFrameOffset = ArgOffset;
226
227     std::vector<SDValue> OutChains;
228
229     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
230       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
231       MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
232       SDValue Arg = DAG.getCopyFromReg(DAG.getRoot(), dl, VReg, MVT::i32);
233
234       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
235                                                           true, false);
236       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
237
238       OutChains.push_back(DAG.getStore(DAG.getRoot(), dl, Arg, FIPtr, NULL, 0));
239       ArgOffset += 4;
240     }
241
242     if (!OutChains.empty()) {
243       OutChains.push_back(Chain);
244       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
245                           &OutChains[0], OutChains.size());
246     }
247   }
248
249   return Chain;
250 }
251
252 SDValue
253 SparcTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
254                                CallingConv::ID CallConv, bool isVarArg,
255                                bool isTailCall,
256                                const SmallVectorImpl<ISD::OutputArg> &Outs,
257                                const SmallVectorImpl<ISD::InputArg> &Ins,
258                                DebugLoc dl, SelectionDAG &DAG,
259                                SmallVectorImpl<SDValue> &InVals) {
260
261 #if 0
262   // Analyze operands of the call, assigning locations to each operand.
263   SmallVector<CCValAssign, 16> ArgLocs;
264   CCState CCInfo(CallConv, isVarArg, DAG.getTarget(), ArgLocs);
265   CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
266
267   // Get the size of the outgoing arguments stack space requirement.
268   unsigned ArgsSize = CCInfo.getNextStackOffset();
269   // FIXME: We can't use this until f64 is known to take two GPRs.
270 #else
271   (void)CC_Sparc32;
272
273   // Count the size of the outgoing arguments.
274   unsigned ArgsSize = 0;
275   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
276     switch (Outs[i].Val.getValueType().getSimpleVT().SimpleTy) {
277       default: llvm_unreachable("Unknown value type!");
278       case MVT::i1:
279       case MVT::i8:
280       case MVT::i16:
281       case MVT::i32:
282       case MVT::f32:
283         ArgsSize += 4;
284         break;
285       case MVT::i64:
286       case MVT::f64:
287         ArgsSize += 8;
288         break;
289     }
290   }
291   if (ArgsSize > 4*6)
292     ArgsSize -= 4*6;    // Space for first 6 arguments is prereserved.
293   else
294     ArgsSize = 0;
295 #endif
296
297   // Keep stack frames 8-byte aligned.
298   ArgsSize = (ArgsSize+7) & ~7;
299
300   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true));
301
302   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
303   SmallVector<SDValue, 8> MemOpChains;
304
305 #if 0
306   // Walk the register/memloc assignments, inserting copies/loads.
307   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
308     CCValAssign &VA = ArgLocs[i];
309     SDValue Arg = Outs[i].Val;
310
311     // Promote the value if needed.
312     switch (VA.getLocInfo()) {
313     default: llvm_unreachable("Unknown loc info!");
314     case CCValAssign::Full: break;
315     case CCValAssign::SExt:
316       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
317       break;
318     case CCValAssign::ZExt:
319       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
320       break;
321     case CCValAssign::AExt:
322       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
323       break;
324     }
325
326     // Arguments that can be passed on register must be kept at
327     // RegsToPass vector
328     if (VA.isRegLoc()) {
329       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
330       continue;
331     }
332
333     assert(VA.isMemLoc());
334
335     // Create a store off the stack pointer for this argument.
336     SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
337     // FIXME: VERIFY THAT 68 IS RIGHT.
338     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset()+68);
339     PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
340     MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
341   }
342
343 #else
344   static const unsigned ArgRegs[] = {
345     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
346   };
347   unsigned ArgOffset = 68;
348
349   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
350     SDValue Val = Outs[i].Val;
351     EVT ObjectVT = Val.getValueType();
352     SDValue ValToStore(0, 0);
353     unsigned ObjSize;
354     switch (ObjectVT.getSimpleVT().SimpleTy) {
355     default: llvm_unreachable("Unhandled argument type!");
356     case MVT::i32:
357       ObjSize = 4;
358
359       if (RegsToPass.size() >= 6) {
360         ValToStore = Val;
361       } else {
362         RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Val));
363       }
364       break;
365     case MVT::f32:
366       ObjSize = 4;
367       if (RegsToPass.size() >= 6) {
368         ValToStore = Val;
369       } else {
370         // Convert this to a FP value in an int reg.
371         Val = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Val);
372         RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Val));
373       }
374       break;
375     case MVT::f64: {
376       ObjSize = 8;
377       if (RegsToPass.size() >= 6) {
378         ValToStore = Val;    // Whole thing is passed in memory.
379         break;
380       }
381
382       // Break into top and bottom parts by storing to the stack and loading
383       // out the parts as integers.  Top part goes in a reg.
384       SDValue StackPtr = DAG.CreateStackTemporary(MVT::f64, MVT::i32);
385       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, 
386                                    Val, StackPtr, NULL, 0);
387       // Sparc is big-endian, so the high part comes first.
388       SDValue Hi = DAG.getLoad(MVT::i32, dl, Store, StackPtr, NULL, 0, 0);
389       // Increment the pointer to the other half.
390       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
391                              DAG.getIntPtrConstant(4));
392       // Load the low part.
393       SDValue Lo = DAG.getLoad(MVT::i32, dl, Store, StackPtr, NULL, 0, 0);
394
395       RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Hi));
396
397       if (RegsToPass.size() >= 6) {
398         ValToStore = Lo;
399         ArgOffset += 4;
400         ObjSize = 4;
401       } else {
402         RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Lo));
403       }
404       break;
405     }
406     case MVT::i64: {
407       ObjSize = 8;
408       if (RegsToPass.size() >= 6) {
409         ValToStore = Val;    // Whole thing is passed in memory.
410         break;
411       }
412
413       // Split the value into top and bottom part.  Top part goes in a reg.
414       SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Val,
415                                  DAG.getConstant(1, MVT::i32));
416       SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Val,
417                                  DAG.getConstant(0, MVT::i32));
418       RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Hi));
419
420       if (RegsToPass.size() >= 6) {
421         ValToStore = Lo;
422         ArgOffset += 4;
423         ObjSize = 4;
424       } else {
425         RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Lo));
426       }
427       break;
428     }
429     }
430
431     if (ValToStore.getNode()) {
432       SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
433       SDValue PtrOff = DAG.getConstant(ArgOffset, MVT::i32);
434       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
435       MemOpChains.push_back(DAG.getStore(Chain, dl, ValToStore, 
436                                          PtrOff, NULL, 0));
437     }
438     ArgOffset += ObjSize;
439   }
440 #endif
441
442   // Emit all stores, make sure the occur before any copies into physregs.
443   if (!MemOpChains.empty())
444     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
445                         &MemOpChains[0], MemOpChains.size());
446
447   // Build a sequence of copy-to-reg nodes chained together with token
448   // chain and flag operands which copy the outgoing args into registers.
449   // The InFlag in necessary since all emited instructions must be
450   // stuck together.
451   SDValue InFlag;
452   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
453     unsigned Reg = RegsToPass[i].first;
454     // Remap I0->I7 -> O0->O7.
455     if (Reg >= SP::I0 && Reg <= SP::I7)
456       Reg = Reg-SP::I0+SP::O0;
457
458     Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
459     InFlag = Chain.getValue(1);
460   }
461
462   // If the callee is a GlobalAddress node (quite common, every direct call is)
463   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
464   // Likewise ExternalSymbol -> TargetExternalSymbol.
465   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
466     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
467   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
468     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
469
470   std::vector<EVT> NodeTys;
471   NodeTys.push_back(MVT::Other);   // Returns a chain
472   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
473   SDValue Ops[] = { Chain, Callee, InFlag };
474   Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, Ops, InFlag.getNode() ? 3 : 2);
475   InFlag = Chain.getValue(1);
476
477   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
478                              DAG.getIntPtrConstant(0, true), InFlag);
479   InFlag = Chain.getValue(1);
480
481   // Assign locations to each value returned by this call.
482   SmallVector<CCValAssign, 16> RVLocs;
483   CCState RVInfo(CallConv, isVarArg, DAG.getTarget(),
484                  RVLocs, *DAG.getContext());
485
486   RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
487
488   // Copy all of the result registers out of their specified physreg.
489   for (unsigned i = 0; i != RVLocs.size(); ++i) {
490     unsigned Reg = RVLocs[i].getLocReg();
491
492     // Remap I0->I7 -> O0->O7.
493     if (Reg >= SP::I0 && Reg <= SP::I7)
494       Reg = Reg-SP::I0+SP::O0;
495
496     Chain = DAG.getCopyFromReg(Chain, dl, Reg,
497                                RVLocs[i].getValVT(), InFlag).getValue(1);
498     InFlag = Chain.getValue(2);
499     InVals.push_back(Chain.getValue(0));
500   }
501
502   return Chain;
503 }
504
505
506
507 //===----------------------------------------------------------------------===//
508 // TargetLowering Implementation
509 //===----------------------------------------------------------------------===//
510
511 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
512 /// condition.
513 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
514   switch (CC) {
515   default: llvm_unreachable("Unknown integer condition code!");
516   case ISD::SETEQ:  return SPCC::ICC_E;
517   case ISD::SETNE:  return SPCC::ICC_NE;
518   case ISD::SETLT:  return SPCC::ICC_L;
519   case ISD::SETGT:  return SPCC::ICC_G;
520   case ISD::SETLE:  return SPCC::ICC_LE;
521   case ISD::SETGE:  return SPCC::ICC_GE;
522   case ISD::SETULT: return SPCC::ICC_CS;
523   case ISD::SETULE: return SPCC::ICC_LEU;
524   case ISD::SETUGT: return SPCC::ICC_GU;
525   case ISD::SETUGE: return SPCC::ICC_CC;
526   }
527 }
528
529 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
530 /// FCC condition.
531 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
532   switch (CC) {
533   default: llvm_unreachable("Unknown fp condition code!");
534   case ISD::SETEQ:
535   case ISD::SETOEQ: return SPCC::FCC_E;
536   case ISD::SETNE:
537   case ISD::SETUNE: return SPCC::FCC_NE;
538   case ISD::SETLT:
539   case ISD::SETOLT: return SPCC::FCC_L;
540   case ISD::SETGT:
541   case ISD::SETOGT: return SPCC::FCC_G;
542   case ISD::SETLE:
543   case ISD::SETOLE: return SPCC::FCC_LE;
544   case ISD::SETGE:
545   case ISD::SETOGE: return SPCC::FCC_GE;
546   case ISD::SETULT: return SPCC::FCC_UL;
547   case ISD::SETULE: return SPCC::FCC_ULE;
548   case ISD::SETUGT: return SPCC::FCC_UG;
549   case ISD::SETUGE: return SPCC::FCC_UGE;
550   case ISD::SETUO:  return SPCC::FCC_U;
551   case ISD::SETO:   return SPCC::FCC_O;
552   case ISD::SETONE: return SPCC::FCC_LG;
553   case ISD::SETUEQ: return SPCC::FCC_UE;
554   }
555 }
556
557 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
558   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
559
560   // Set up the register classes.
561   addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
562   addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
563   addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);
564
565   // Turn FP extload into load/fextend
566   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
567   // Sparc doesn't have i1 sign extending load
568   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
569   // Turn FP truncstore into trunc + store.
570   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
571
572   // Custom legalize GlobalAddress nodes into LO/HI parts.
573   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
574   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
575   setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
576
577   // Sparc doesn't have sext_inreg, replace them with shl/sra
578   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
579   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
580   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
581
582   // Sparc has no REM or DIVREM operations.
583   setOperationAction(ISD::UREM, MVT::i32, Expand);
584   setOperationAction(ISD::SREM, MVT::i32, Expand);
585   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
586   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
587
588   // Custom expand fp<->sint
589   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
590   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
591
592   // Expand fp<->uint
593   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
594   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
595
596   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
597   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
598
599   // Sparc has no select or setcc: expand to SELECT_CC.
600   setOperationAction(ISD::SELECT, MVT::i32, Expand);
601   setOperationAction(ISD::SELECT, MVT::f32, Expand);
602   setOperationAction(ISD::SELECT, MVT::f64, Expand);
603   setOperationAction(ISD::SETCC, MVT::i32, Expand);
604   setOperationAction(ISD::SETCC, MVT::f32, Expand);
605   setOperationAction(ISD::SETCC, MVT::f64, Expand);
606
607   // Sparc doesn't have BRCOND either, it has BR_CC.
608   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
609   setOperationAction(ISD::BRIND, MVT::Other, Expand);
610   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
611   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
612   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
613   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
614
615   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
616   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
617   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
618
619   // SPARC has no intrinsics for these particular operations.
620   setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
621
622   setOperationAction(ISD::FSIN , MVT::f64, Expand);
623   setOperationAction(ISD::FCOS , MVT::f64, Expand);
624   setOperationAction(ISD::FREM , MVT::f64, Expand);
625   setOperationAction(ISD::FSIN , MVT::f32, Expand);
626   setOperationAction(ISD::FCOS , MVT::f32, Expand);
627   setOperationAction(ISD::FREM , MVT::f32, Expand);
628   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
629   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
630   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
631   setOperationAction(ISD::ROTL , MVT::i32, Expand);
632   setOperationAction(ISD::ROTR , MVT::i32, Expand);
633   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
634   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
635   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
636   setOperationAction(ISD::FPOW , MVT::f64, Expand);
637   setOperationAction(ISD::FPOW , MVT::f32, Expand);
638
639   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
640   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
641   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
642
643   // FIXME: Sparc provides these multiplies, but we don't have them yet.
644   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
645   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
646
647   // We don't have line number support yet.
648   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
649   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
650   setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
651   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
652
653   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
654   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
655   // VAARG needs to be lowered to not do unaligned accesses for doubles.
656   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
657
658   // Use the default implementation.
659   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
660   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
661   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
662   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
663   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
664
665   // No debug info support yet.
666   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
667   setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
668   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
669
670   setStackPointerRegisterToSaveRestore(SP::O6);
671
672   if (TM.getSubtarget<SparcSubtarget>().isV9())
673     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
674
675   computeRegisterProperties();
676 }
677
678 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
679   switch (Opcode) {
680   default: return 0;
681   case SPISD::CMPICC:     return "SPISD::CMPICC";
682   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
683   case SPISD::BRICC:      return "SPISD::BRICC";
684   case SPISD::BRFCC:      return "SPISD::BRFCC";
685   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
686   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
687   case SPISD::Hi:         return "SPISD::Hi";
688   case SPISD::Lo:         return "SPISD::Lo";
689   case SPISD::FTOI:       return "SPISD::FTOI";
690   case SPISD::ITOF:       return "SPISD::ITOF";
691   case SPISD::CALL:       return "SPISD::CALL";
692   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
693   }
694 }
695
696 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
697 /// be zero. Op is expected to be a target specific node. Used by DAG
698 /// combiner.
699 void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
700                                                          const APInt &Mask,
701                                                          APInt &KnownZero,
702                                                          APInt &KnownOne,
703                                                          const SelectionDAG &DAG,
704                                                          unsigned Depth) const {
705   APInt KnownZero2, KnownOne2;
706   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
707
708   switch (Op.getOpcode()) {
709   default: break;
710   case SPISD::SELECT_ICC:
711   case SPISD::SELECT_FCC:
712     DAG.ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne,
713                           Depth+1);
714     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2,
715                           Depth+1);
716     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
717     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
718
719     // Only known if known in both the LHS and RHS.
720     KnownOne &= KnownOne2;
721     KnownZero &= KnownZero2;
722     break;
723   }
724 }
725
726 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
727 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
728 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
729                              ISD::CondCode CC, unsigned &SPCC) {
730   if (isa<ConstantSDNode>(RHS) &&
731       cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
732       CC == ISD::SETNE &&
733       ((LHS.getOpcode() == SPISD::SELECT_ICC &&
734         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
735        (LHS.getOpcode() == SPISD::SELECT_FCC &&
736         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
737       isa<ConstantSDNode>(LHS.getOperand(0)) &&
738       isa<ConstantSDNode>(LHS.getOperand(1)) &&
739       cast<ConstantSDNode>(LHS.getOperand(0))->getZExtValue() == 1 &&
740       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 0) {
741     SDValue CMPCC = LHS.getOperand(3);
742     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
743     LHS = CMPCC.getOperand(0);
744     RHS = CMPCC.getOperand(1);
745   }
746 }
747
748 SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op, 
749                                                 SelectionDAG &DAG) {
750   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
751   // FIXME there isn't really any debug info here
752   DebugLoc dl = Op.getDebugLoc();
753   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
754   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, GA);
755   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, GA);
756
757   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 
758     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
759   
760   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
761                                    getPointerTy());
762   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
763   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, 
764                                 GlobalBase, RelAddr);
765   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 
766                      AbsAddr, NULL, 0);
767 }
768
769 SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
770                                                SelectionDAG &DAG) {
771   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
772   // FIXME there isn't really any debug info here
773   DebugLoc dl = Op.getDebugLoc();
774   Constant *C = N->getConstVal();
775   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
776   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, CP);
777   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, CP);
778   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 
779     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
780
781   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl, 
782                                    getPointerTy());
783   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
784   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
785                                 GlobalBase, RelAddr);
786   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 
787                      AbsAddr, NULL, 0);
788 }
789
790 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
791   DebugLoc dl = Op.getDebugLoc();
792   // Convert the fp value to integer in an FP register.
793   assert(Op.getValueType() == MVT::i32);
794   Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
795   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
796 }
797
798 static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
799   DebugLoc dl = Op.getDebugLoc();
800   assert(Op.getOperand(0).getValueType() == MVT::i32);
801   SDValue Tmp = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
802   // Convert the int value to FP in an FP register.
803   return DAG.getNode(SPISD::ITOF, dl, Op.getValueType(), Tmp);
804 }
805
806 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
807   SDValue Chain = Op.getOperand(0);
808   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
809   SDValue LHS = Op.getOperand(2);
810   SDValue RHS = Op.getOperand(3);
811   SDValue Dest = Op.getOperand(4);
812   DebugLoc dl = Op.getDebugLoc();
813   unsigned Opc, SPCC = ~0U;
814
815   // If this is a br_cc of a "setcc", and if the setcc got lowered into
816   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
817   LookThroughSetCC(LHS, RHS, CC, SPCC);
818
819   // Get the condition flag.
820   SDValue CompareFlag;
821   if (LHS.getValueType() == MVT::i32) {
822     std::vector<EVT> VTs;
823     VTs.push_back(MVT::i32);
824     VTs.push_back(MVT::Flag);
825     SDValue Ops[2] = { LHS, RHS };
826     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
827     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
828     Opc = SPISD::BRICC;
829   } else {
830     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Flag, LHS, RHS);
831     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
832     Opc = SPISD::BRFCC;
833   }
834   return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
835                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
836 }
837
838 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
839   SDValue LHS = Op.getOperand(0);
840   SDValue RHS = Op.getOperand(1);
841   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
842   SDValue TrueVal = Op.getOperand(2);
843   SDValue FalseVal = Op.getOperand(3);
844   DebugLoc dl = Op.getDebugLoc();
845   unsigned Opc, SPCC = ~0U;
846
847   // If this is a select_cc of a "setcc", and if the setcc got lowered into
848   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
849   LookThroughSetCC(LHS, RHS, CC, SPCC);
850
851   SDValue CompareFlag;
852   if (LHS.getValueType() == MVT::i32) {
853     std::vector<EVT> VTs;
854     VTs.push_back(LHS.getValueType());   // subcc returns a value
855     VTs.push_back(MVT::Flag);
856     SDValue Ops[2] = { LHS, RHS };
857     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
858     Opc = SPISD::SELECT_ICC;
859     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
860   } else {
861     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Flag, LHS, RHS);
862     Opc = SPISD::SELECT_FCC;
863     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
864   }
865   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
866                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
867 }
868
869 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
870                               SparcTargetLowering &TLI) {
871   // vastart just stores the address of the VarArgsFrameIndex slot into the
872   // memory location argument.
873   DebugLoc dl = Op.getDebugLoc();
874   SDValue Offset = DAG.getNode(ISD::ADD, dl, MVT::i32,
875                                  DAG.getRegister(SP::I6, MVT::i32),
876                                  DAG.getConstant(TLI.getVarArgsFrameOffset(),
877                                                  MVT::i32));
878   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
879   return DAG.getStore(Op.getOperand(0), dl, Offset, Op.getOperand(1), SV, 0);
880 }
881
882 static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
883   SDNode *Node = Op.getNode();
884   EVT VT = Node->getValueType(0);
885   SDValue InChain = Node->getOperand(0);
886   SDValue VAListPtr = Node->getOperand(1);
887   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
888   DebugLoc dl = Node->getDebugLoc();
889   SDValue VAList = DAG.getLoad(MVT::i32, dl, InChain, VAListPtr, SV, 0);
890   // Increment the pointer, VAList, to the next vaarg
891   SDValue NextPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, VAList,
892                                   DAG.getConstant(VT.getSizeInBits()/8,
893                                                   MVT::i32));
894   // Store the incremented VAList to the legalized pointer
895   InChain = DAG.getStore(VAList.getValue(1), dl, NextPtr,
896                          VAListPtr, SV, 0);
897   // Load the actual argument out of the pointer VAList, unless this is an
898   // f64 load.
899   if (VT != MVT::f64)
900     return DAG.getLoad(VT, dl, InChain, VAList, NULL, 0);
901
902   // Otherwise, load it as i64, then do a bitconvert.
903   SDValue V = DAG.getLoad(MVT::i64, dl, InChain, VAList, NULL, 0);
904
905   // Bit-Convert the value to f64.
906   SDValue Ops[2] = {
907     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, V),
908     V.getValue(1)
909   };
910   return DAG.getMergeValues(Ops, 2, dl);
911 }
912
913 static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
914   SDValue Chain = Op.getOperand(0);  // Legalize the chain.
915   SDValue Size  = Op.getOperand(1);  // Legalize the size.
916   DebugLoc dl = Op.getDebugLoc();
917
918   unsigned SPReg = SP::O6;
919   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
920   SDValue NewSP = DAG.getNode(ISD::SUB, dl, MVT::i32, SP, Size); // Value
921   Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
922
923   // The resultant pointer is actually 16 words from the bottom of the stack,
924   // to provide a register spill area.
925   SDValue NewVal = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
926                                  DAG.getConstant(96, MVT::i32));
927   SDValue Ops[2] = { NewVal, Chain };
928   return DAG.getMergeValues(Ops, 2, dl);
929 }
930
931
932 SDValue SparcTargetLowering::
933 LowerOperation(SDValue Op, SelectionDAG &DAG) {
934   switch (Op.getOpcode()) {
935   default: llvm_unreachable("Should not custom lower this!");
936   // Frame & Return address.  Currently unimplemented
937   case ISD::RETURNADDR: return SDValue();
938   case ISD::FRAMEADDR:  return SDValue();
939   case ISD::GlobalTLSAddress:
940     llvm_unreachable("TLS not implemented for Sparc.");
941   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
942   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
943   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
944   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
945   case ISD::BR_CC:              return LowerBR_CC(Op, DAG);
946   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
947   case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
948   case ISD::VAARG:              return LowerVAARG(Op, DAG);
949   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
950   }
951 }
952
953 MachineBasicBlock *
954 SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
955                                                  MachineBasicBlock *BB,
956                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
957   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
958   unsigned BROpcode;
959   unsigned CC;
960   DebugLoc dl = MI->getDebugLoc();
961   // Figure out the conditional branch opcode to use for this select_cc.
962   switch (MI->getOpcode()) {
963   default: llvm_unreachable("Unknown SELECT_CC!");
964   case SP::SELECT_CC_Int_ICC:
965   case SP::SELECT_CC_FP_ICC:
966   case SP::SELECT_CC_DFP_ICC:
967     BROpcode = SP::BCOND;
968     break;
969   case SP::SELECT_CC_Int_FCC:
970   case SP::SELECT_CC_FP_FCC:
971   case SP::SELECT_CC_DFP_FCC:
972     BROpcode = SP::FBCOND;
973     break;
974   }
975
976   CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
977
978   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
979   // control-flow pattern.  The incoming instruction knows the destination vreg
980   // to set, the condition code register to branch on, the true/false values to
981   // select between, and a branch opcode to use.
982   const BasicBlock *LLVM_BB = BB->getBasicBlock();
983   MachineFunction::iterator It = BB;
984   ++It;
985
986   //  thisMBB:
987   //  ...
988   //   TrueVal = ...
989   //   [f]bCC copy1MBB
990   //   fallthrough --> copy0MBB
991   MachineBasicBlock *thisMBB = BB;
992   MachineFunction *F = BB->getParent();
993   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
994   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
995   BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
996   F->insert(It, copy0MBB);
997   F->insert(It, sinkMBB);
998   // Update machine-CFG edges by first adding all successors of the current
999   // block to the new block which will contain the Phi node for the select.
1000   // Also inform sdisel of the edge changes.
1001   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(), 
1002          E = BB->succ_end(); I != E; ++I) {
1003     EM->insert(std::make_pair(*I, sinkMBB));
1004     sinkMBB->addSuccessor(*I);
1005   }
1006   // Next, remove all successors of the current block, and add the true
1007   // and fallthrough blocks as its successors.
1008   while (!BB->succ_empty())
1009     BB->removeSuccessor(BB->succ_begin());
1010   // Next, add the true and fallthrough blocks as its successors.
1011   BB->addSuccessor(copy0MBB);
1012   BB->addSuccessor(sinkMBB);
1013
1014   //  copy0MBB:
1015   //   %FalseValue = ...
1016   //   # fallthrough to sinkMBB
1017   BB = copy0MBB;
1018
1019   // Update machine-CFG edges
1020   BB->addSuccessor(sinkMBB);
1021
1022   //  sinkMBB:
1023   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1024   //  ...
1025   BB = sinkMBB;
1026   BuildMI(BB, dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
1027     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1028     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1029
1030   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
1031   return BB;
1032 }
1033
1034 //===----------------------------------------------------------------------===//
1035 //                         Sparc Inline Assembly Support
1036 //===----------------------------------------------------------------------===//
1037
1038 /// getConstraintType - Given a constraint letter, return the type of
1039 /// constraint it is for this target.
1040 SparcTargetLowering::ConstraintType
1041 SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
1042   if (Constraint.size() == 1) {
1043     switch (Constraint[0]) {
1044     default:  break;
1045     case 'r': return C_RegisterClass;
1046     }
1047   }
1048
1049   return TargetLowering::getConstraintType(Constraint);
1050 }
1051
1052 std::pair<unsigned, const TargetRegisterClass*>
1053 SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1054                                                   EVT VT) const {
1055   if (Constraint.size() == 1) {
1056     switch (Constraint[0]) {
1057     case 'r':
1058       return std::make_pair(0U, SP::IntRegsRegisterClass);
1059     }
1060   }
1061
1062   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1063 }
1064
1065 std::vector<unsigned> SparcTargetLowering::
1066 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1067                                   EVT VT) const {
1068   if (Constraint.size() != 1)
1069     return std::vector<unsigned>();
1070
1071   switch (Constraint[0]) {
1072   default: break;
1073   case 'r':
1074     return make_vector<unsigned>(SP::L0, SP::L1, SP::L2, SP::L3,
1075                                  SP::L4, SP::L5, SP::L6, SP::L7,
1076                                  SP::I0, SP::I1, SP::I2, SP::I3,
1077                                  SP::I4, SP::I5,
1078                                  SP::O0, SP::O1, SP::O2, SP::O3,
1079                                  SP::O4, SP::O5, SP::O7, 0);
1080   }
1081
1082   return std::vector<unsigned>();
1083 }
1084
1085 bool
1086 SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1087   // The Sparc target isn't yet aware of offsets.
1088   return false;
1089 }
1090
1091 /// getFunctionAlignment - Return the Log2 alignment of this function.
1092 unsigned SparcTargetLowering::getFunctionAlignment(const Function *) const {
1093   return 2;
1094 }