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