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