add support for div/rem to the dag->dag isel. yay.
[oota-llvm.git] / lib / Target / IA64 / IA64ISelDAGToDAG.cpp
1 //===---- IA64ISelDAGToDAG.cpp - IA64 pattern matching inst selector ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Duraid Madina and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for IA64,
11 // converting a legalized dag to an IA64 dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "IA64.h"
16 #include "IA64TargetMachine.h"
17 #include "IA64ISelLowering.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Constants.h"
26 #include "llvm/GlobalValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/MathExtras.h"
29 using namespace llvm;
30
31 namespace {
32   Statistic<> FusedFP ("ia64-codegen", "Number of fused fp operations");
33   Statistic<> FrameOff("ia64-codegen", "Number of frame idx offsets collapsed");
34     
35   //===--------------------------------------------------------------------===//
36   /// IA64DAGToDAGISel - IA64 specific code to select IA64 machine
37   /// instructions for SelectionDAG operations.
38   ///
39   class IA64DAGToDAGISel : public SelectionDAGISel {
40     IA64TargetLowering IA64Lowering;
41     unsigned GlobalBaseReg;
42   public:
43     IA64DAGToDAGISel(TargetMachine &TM)
44       : SelectionDAGISel(IA64Lowering), IA64Lowering(TM) {}
45     
46     virtual bool runOnFunction(Function &Fn) {
47       // Make sure we re-emit a set of the global base reg if necessary
48       GlobalBaseReg = 0;
49       return SelectionDAGISel::runOnFunction(Fn);
50     }
51  
52     /// getI64Imm - Return a target constant with the specified value, of type
53     /// i64.
54     inline SDOperand getI64Imm(uint64_t Imm) {
55       return CurDAG->getTargetConstant(Imm, MVT::i64);
56     }
57
58     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
59     /// base register.  Return the virtual register that holds this value.
60     // SDOperand getGlobalBaseReg(); TODO: hmm
61     
62     // Select - Convert the specified operand from a target-independent to a
63     // target-specific node if it hasn't already been changed.
64     SDOperand Select(SDOperand Op);
65     
66     SDNode *SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
67                                    unsigned OCHi, unsigned OCLo,
68                                    bool IsArithmetic = false,
69                                    bool Negate = false);
70     SDNode *SelectBitfieldInsert(SDNode *N);
71
72     /// SelectCC - Select a comparison of the specified values with the
73     /// specified condition code, returning the CR# of the expression.
74     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
75
76     /// SelectAddr - Given the specified address, return the two operands for a
77     /// load/store instruction, and return true if it should be an indexed [r+r]
78     /// operation.
79     bool SelectAddr(SDOperand Addr, SDOperand &Op1, SDOperand &Op2);
80
81     SDOperand BuildSDIVSequence(SDNode *N);
82     SDOperand BuildUDIVSequence(SDNode *N);
83     
84     /// InstructionSelectBasicBlock - This callback is invoked by
85     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
86     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
87     
88     virtual const char *getPassName() const {
89       return "IA64 (Itanium) DAG->DAG Instruction Selector";
90     } 
91
92 // Include the pieces autogenerated from the target description.
93 #include "IA64GenDAGISel.inc"
94     
95 private:
96     SDOperand SelectDIV(SDOperand Op);
97     SDOperand SelectCALL(SDOperand Op);
98   };
99 }
100
101 /// InstructionSelectBasicBlock - This callback is invoked by
102 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
103 void IA64DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
104   DEBUG(BB->dump());
105   
106   // The selection process is inherently a bottom-up recursive process (users
107   // select their uses before themselves).  Given infinite stack space, we
108   // could just start selecting on the root and traverse the whole graph.  In
109   // practice however, this causes us to run out of stack space on large basic
110   // blocks.  To avoid this problem, select the entry node, then all its uses,
111   // iteratively instead of recursively.
112   std::vector<SDOperand> Worklist;
113   Worklist.push_back(DAG.getEntryNode());
114   
115   // Note that we can do this in the IA64 target (scanning forward across token
116   // chain edges) because no nodes ever get folded across these edges.  On a
117   // target like X86 which supports load/modify/store operations, this would
118   // have to be more careful.
119   while (!Worklist.empty()) {
120     SDOperand Node = Worklist.back();
121     Worklist.pop_back();
122     
123     // Chose from the least deep of the top two nodes.
124     if (!Worklist.empty() &&
125         Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
126       std::swap(Worklist.back(), Node);
127     
128     if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
129          Node.Val->getOpcode() < IA64ISD::FIRST_NUMBER) ||
130         CodeGenMap.count(Node)) continue;
131     
132     for (SDNode::use_iterator UI = Node.Val->use_begin(),
133          E = Node.Val->use_end(); UI != E; ++UI) {
134       // Scan the values.  If this use has a value that is a token chain, add it
135       // to the worklist.
136       SDNode *User = *UI;
137       for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
138         if (User->getValueType(i) == MVT::Other) {
139           Worklist.push_back(SDOperand(User, i));
140           break; 
141         }
142     }
143
144     // Finally, legalize this node.
145     Select(Node);
146   }
147     
148   // Select target instructions for the DAG.
149   DAG.setRoot(Select(DAG.getRoot()));
150   CodeGenMap.clear();
151   DAG.RemoveDeadNodes();
152   
153   // Emit machine code to BB. 
154   ScheduleAndEmitDAG(DAG);
155 }
156
157 SDOperand IA64DAGToDAGISel::SelectDIV(SDOperand Op) {
158   SDNode *N = Op.Val;
159   SDOperand Chain = Select(N->getOperand(0));
160
161   SDOperand Tmp1 = Select(N->getOperand(0));
162   SDOperand Tmp2 = Select(N->getOperand(1));
163
164   bool isFP=false;
165
166   if(MVT::isFloatingPoint(Tmp1.getValueType()))
167     isFP=true;
168     
169   bool isModulus=false; // is it a division or a modulus?
170   bool isSigned=false;
171
172   switch(N->getOpcode()) {
173     case ISD::FDIV:
174     case ISD::SDIV:  isModulus=false; isSigned=true;  break;
175     case ISD::UDIV:  isModulus=false; isSigned=false; break;
176     case ISD::FREM:
177     case ISD::SREM:  isModulus=true;  isSigned=true;  break;
178     case ISD::UREM:  isModulus=true;  isSigned=false; break;
179   }
180
181   // TODO: check for integer divides by powers of 2 (or other simple patterns?)
182
183     SDOperand TmpPR, TmpPR2;
184     SDOperand TmpF1, TmpF2, TmpF3, TmpF4, TmpF5, TmpF6, TmpF7, TmpF8;
185     SDOperand TmpF9, TmpF10,TmpF11,TmpF12,TmpF13,TmpF14,TmpF15;
186     SDOperand Result;
187     
188     // OK, emit some code:
189
190     if(!isFP) {
191       // first, load the inputs into FP regs.
192       TmpF1 = CurDAG->getTargetNode(IA64::SETFSIG, MVT::f64, Tmp1);
193       Chain = TmpF1.getValue(1);
194       TmpF2 = CurDAG->getTargetNode(IA64::SETFSIG, MVT::f64, Tmp2);
195       Chain = TmpF2.getValue(1);
196       
197       // next, convert the inputs to FP
198       if(isSigned) {
199         TmpF3 = CurDAG->getTargetNode(IA64::FCVTXF, MVT::f64, TmpF1);
200         Chain = TmpF3.getValue(1);
201         TmpF4 = CurDAG->getTargetNode(IA64::FCVTXF, MVT::f64, TmpF2);
202         Chain = TmpF4.getValue(1);
203       } else {
204         TmpF3 = CurDAG->getTargetNode(IA64::FCVTXUFS1, MVT::f64, TmpF1);
205         Chain = TmpF3.getValue(1);
206         TmpF4 = CurDAG->getTargetNode(IA64::FCVTXUFS1, MVT::f64, TmpF2);
207         Chain = TmpF4.getValue(1);
208       }
209
210     } else { // this is an FP divide/remainder, so we 'leak' some temp
211              // regs and assign TmpF3=Tmp1, TmpF4=Tmp2
212       TmpF3=Tmp1;
213       TmpF4=Tmp2;
214     }
215
216     // we start by computing an approximate reciprocal (good to 9 bits?)
217     // note, this instruction writes _both_ TmpF5 (answer) and TmpPR (predicate)
218     TmpF5 = CurDAG->getTargetNode(IA64::FRCPAS1, MVT::f64, MVT::i1,
219                                   TmpF3, TmpF4);
220     TmpPR = TmpF5.getValue(1);
221     Chain = TmpF5.getValue(2);
222
223     if(!isModulus) { // if this is a divide, we worry about div-by-zero
224         SDOperand bogusPR = CurDAG->getTargetNode(IA64::CMPEQ, MVT::i1, 
225           CurDAG->getRegister(IA64::r0, MVT::i64),
226           CurDAG->getRegister(IA64::r0, MVT::i64));
227         Chain = bogusPR.getValue(1);
228         TmpPR2 = CurDAG->getTargetNode(IA64::TPCMPNE, MVT::i1, bogusPR,
229           CurDAG->getRegister(IA64::r0, MVT::i64),
230           CurDAG->getRegister(IA64::r0, MVT::i64), TmpPR); 
231         Chain = TmpPR2.getValue(1);
232     }
233
234     SDOperand F0 = CurDAG->getRegister(IA64::F0, MVT::f64);
235     SDOperand F1 = CurDAG->getRegister(IA64::F1, MVT::f64);
236
237     // now we apply newton's method, thrice! (FIXME: this is ~72 bits of
238     // precision, don't need this much for f32/i32)
239     TmpF6 = CurDAG->getTargetNode(IA64::CFNMAS1, MVT::f64,
240       TmpF4, TmpF5, F1, TmpPR);
241     Chain = TmpF6.getValue(1);
242     TmpF7 = CurDAG->getTargetNode(IA64::CFMAS1, MVT::f64,
243       TmpF3, TmpF5, F0, TmpPR);
244     Chain = TmpF7.getValue(1);
245     TmpF8 = CurDAG->getTargetNode(IA64::CFMAS1, MVT::f64,
246       TmpF6, TmpF6, F0, TmpPR);
247     Chain = TmpF8.getValue(1);
248     TmpF9 = CurDAG->getTargetNode(IA64::CFMAS1, MVT::f64,
249       TmpF6, TmpF7, TmpF7, TmpPR);
250     Chain = TmpF9.getValue(1);
251     TmpF10 = CurDAG->getTargetNode(IA64::CFMAS1, MVT::f64,
252       TmpF6, TmpF5, TmpF5, TmpPR);
253     Chain = TmpF10.getValue(1);
254     TmpF11 = CurDAG->getTargetNode(IA64::CFMAS1, MVT::f64,
255       TmpF8, TmpF9, TmpF9, TmpPR);
256     Chain = TmpF11.getValue(1);
257     TmpF12 = CurDAG->getTargetNode(IA64::CFMAS1, MVT::f64,
258       TmpF8, TmpF10, TmpF10, TmpPR);
259     Chain = TmpF12.getValue(1);
260     TmpF13 = CurDAG->getTargetNode(IA64::CFNMAS1, MVT::f64,
261       TmpF4, TmpF11, TmpF3, TmpPR);
262     Chain = TmpF13.getValue(1);
263     
264        // FIXME: this is unfortunate :(
265        // the story is that the dest reg of the fnma above and the fma below
266        // (and therefore possibly the src of the fcvt.fx[u] as well) cannot
267        // be the same register, or this code breaks if the first argument is
268        // zero. (e.g. without this hack, 0%8 yields -64, not 0.)
269     TmpF14 = CurDAG->getTargetNode(IA64::CFMAS1, MVT::f64,
270       TmpF13, TmpF12, TmpF11, TmpPR);
271     Chain = TmpF14.getValue(1);
272     
273     if(isModulus) { // XXX: fragile! fixes _only_ mod, *breaks* div! !
274       SDOperand bogus = CurDAG->getTargetNode(IA64::IUSE, MVT::Other, TmpF13); // hack :(
275       Chain = bogus.getValue(0); // hmmm
276     }
277
278     if(!isFP) {
279       // round to an integer
280       if(isSigned) {
281         TmpF15 = CurDAG->getTargetNode(IA64::FCVTFXTRUNCS1, MVT::i64, TmpF14);
282         Chain = TmpF15.getValue(1);
283       }
284       else {
285         TmpF15 = CurDAG->getTargetNode(IA64::FCVTFXUTRUNCS1, MVT::i64, TmpF14);
286         Chain = TmpF15.getValue(1);
287       }
288     } else {
289       TmpF15 = TmpF14;
290      // EXERCISE: can you see why TmpF15=TmpF14 does not work here, and
291      // we really do need the above FMOV? ;)
292     }
293
294     if(!isModulus) {
295       if(isFP) { // extra worrying about div-by-zero
296       // we do a 'conditional fmov' (of the correct result, depending
297       // on how the frcpa predicate turned out)
298       SDOperand bogoResult = CurDAG->getTargetNode(IA64::PFMOV, MVT::f64,
299                                                    TmpF12, TmpPR2);
300       Chain = bogoResult.getValue(1);
301       Result = CurDAG->getTargetNode(IA64::CFMOV, MVT::f64, bogoResult,
302         TmpF15, TmpPR);
303       Chain = Result.getValue(1);
304       }
305       else {
306         Result = CurDAG->getTargetNode(IA64::GETFSIG, MVT::i64, TmpF15);
307         Chain = Result.getValue(1);
308       }
309     } else { // this is a modulus
310       if(!isFP) {
311         // answer = q * (-b) + a
312         SDOperand TmpI = CurDAG->getTargetNode(IA64::SUB, MVT::i64,
313           CurDAG->getRegister(IA64::r0, MVT::i64), Tmp2);
314         Chain = TmpI.getValue(1);
315         SDOperand TmpF = CurDAG->getTargetNode(IA64::SETFSIG, MVT::f64, TmpI);
316         Chain = TmpF.getValue(1);
317         SDOperand ModulusResult = CurDAG->getTargetNode(IA64::XMAL, MVT::f64,
318           TmpF15, TmpF, TmpF1);
319         Chain = ModulusResult.getValue(1);
320         Result = CurDAG->getTargetNode(IA64::GETFSIG, MVT::i64, ModulusResult);
321         Chain = Result.getValue(1);
322       } else { // FP modulus! The horror... the horror....
323         assert(0 && "sorry, no FP modulus just yet!\n!\n");
324       }
325     }
326
327   return Result;
328 }
329
330
331 SDOperand IA64DAGToDAGISel::SelectCALL(SDOperand Op) {
332   SDNode *N = Op.Val;
333   SDOperand Chain = Select(N->getOperand(0));
334   
335   unsigned CallOpcode;
336   std::vector<SDOperand> CallOperands;
337
338   // save the current GP, SP and RP : FIXME: do we need to do all 3 always?
339   SDOperand GPBeforeCall = CurDAG->getCopyFromReg(Chain, IA64::r1, MVT::i64);
340   Chain = GPBeforeCall.getValue(1);
341   SDOperand SPBeforeCall = CurDAG->getCopyFromReg(Chain, IA64::r12, MVT::i64);
342   Chain = SPBeforeCall.getValue(1);
343   SDOperand RPBeforeCall = CurDAG->getCopyFromReg(Chain, IA64::rp, MVT::i64);
344   Chain = RPBeforeCall.getValue(1);
345
346   // if we can call directly, do so
347   if (GlobalAddressSDNode *GASD =
348       dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
349     CallOpcode = IA64::BRCALL_IPREL;
350     CallOperands.push_back(CurDAG->getTargetGlobalAddress(GASD->getGlobal(),
351                                                           MVT::i64));
352   } else if (ExternalSymbolSDNode *ESSDN = // FIXME: we currently NEED this
353                                          // case for correctness, to avoid
354                                          // "non-pic code with imm reloc.n
355                                          // against dynamic symbol" errors
356              dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
357     CallOpcode = IA64::BRCALL_IPREL;
358     CallOperands.push_back(N->getOperand(1));
359   } else {
360     // otherwise we need to load the function descriptor,
361     // load the branch target (function)'s entry point and GP,
362     // branch (call) then restore the GP
363     
364     SDOperand FnDescriptor = Select(N->getOperand(1));
365    
366     // load the branch target's entry point [mem] and 
367     // GP value [mem+8]
368     SDOperand targetEntryPoint=CurDAG->getTargetNode(IA64::LD8, MVT::i64,
369                     FnDescriptor);
370     Chain = targetEntryPoint.getValue(1);
371     SDOperand targetGPAddr=CurDAG->getTargetNode(IA64::ADDS, MVT::i64, 
372                     FnDescriptor, CurDAG->getConstant(8, MVT::i64));
373     Chain = targetGPAddr.getValue(1);
374     SDOperand targetGP=CurDAG->getTargetNode(IA64::LD8, MVT::i64,
375                     targetGPAddr);
376     Chain = targetGP.getValue(1);
377
378 /* FIXME? (methcall still fails)
379     SDOperand targetEntryPoint=CurDAG->getLoad(MVT::i64, Chain, FnDescriptor,
380                                         CurDAG->getSrcValue(0));
381     SDOperand targetGPAddr=CurDAG->getNode(ISD::ADD, MVT::i64, FnDescriptor, 
382                             CurDAG->getConstant(8, MVT::i64));
383     SDOperand targetGP=CurDAG->getLoad(MVT::i64, Chain, targetGPAddr,
384                                        CurDAG->getSrcValue(0));
385     */
386
387     /* this is just the long way of writing the two lines below?
388     // Copy the callee GP into r1
389     SDOperand r1 = CurDAG->getRegister(IA64::r1, MVT::i64);
390     Chain = CurDAG->getNode(ISD::CopyToReg, MVT::i64, Chain, r1,
391                      targetGP);
392     
393
394     // Copy the callee address into the b6 branch register
395     SDOperand B6 = CurDAG->getRegister(IA64::B6, MVT::i64);
396     Chain = CurDAG->getNode(ISD::CopyToReg, MVT::i64, Chain, B6,
397                      targetEntryPoint);
398     */
399
400     Chain = CurDAG->getCopyToReg(Chain, IA64::r1, targetGP);
401     Chain = CurDAG->getCopyToReg(Chain, IA64::B6, targetEntryPoint);
402     
403     CallOperands.push_back(CurDAG->getRegister(IA64::B6, MVT::i64));
404     CallOpcode = IA64::BRCALL_INDIRECT;
405   }
406  
407   // see section 8.5.8 of "Itanium Software Conventions and
408   // Runtime Architecture Guide to see some examples of what's going
409   // on here. (in short: int args get mapped 1:1 'slot-wise' to out0->out7,
410   // while FP args get mapped to F8->F15 as needed)
411   
412   // TODO: support in-memory arguments
413  
414   unsigned used_FPArgs=0; // how many FP args have been used so far?
415
416   unsigned intArgs[] = {IA64::out0, IA64::out1, IA64::out2, IA64::out3,
417                         IA64::out4, IA64::out5, IA64::out6, IA64::out7 };
418   unsigned FPArgs[] = {IA64::F8, IA64::F9, IA64::F10, IA64::F11,
419                        IA64::F12, IA64::F13, IA64::F14, IA64::F15 };
420
421   SDOperand InFlag;  // Null incoming flag value.
422   
423   for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i) {
424     unsigned DestReg = 0;
425     MVT::ValueType RegTy = N->getOperand(i).getValueType();
426     if (RegTy == MVT::i64) {
427       assert((i-2) < 8 && "Too many int args");
428       DestReg = intArgs[i-2];
429     } else {
430       assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
431              "Unpromoted integer arg?");
432       assert(used_FPArgs < 8 && "Too many fp args");
433       DestReg = FPArgs[used_FPArgs++];
434     }
435     
436     if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
437       SDOperand Val = Select(N->getOperand(i));
438       if(MVT::isInteger(N->getOperand(i).getValueType())) {
439         Chain = CurDAG->getCopyToReg(Chain, DestReg, Val, InFlag);
440         InFlag = Chain.getValue(1);
441         CallOperands.push_back(CurDAG->getRegister(DestReg, RegTy));
442       }
443       // some functions (e.g. printf) want floating point arguments
444       // *also* passed as in-memory representations in integer registers
445       // this is FORTRAN legacy junk which we don't _always_ need
446       // to do, but to be on the safe side, we do. 
447       else if(MVT::isFloatingPoint(N->getOperand(i).getValueType())) {
448         assert((i-2) < 8 && "FP args alone would fit, but no int regs left");
449         // first copy into the appropriate FP reg
450         Chain = CurDAG->getCopyToReg(Chain, DestReg, Val);      
451         // then copy into the appropriate integer reg
452         DestReg = intArgs[i-2];
453         // GETFD takes an FP reg and writes a GP reg    
454         Chain = CurDAG->getTargetNode(IA64::GETFD, MVT::i64, Val);
455         // FIXME: this next line is a bit unfortunate 
456         Chain = CurDAG->getCopyToReg(Chain, DestReg, Chain, InFlag); 
457         InFlag = Chain.getValue(1);
458         CallOperands.push_back(CurDAG->getRegister(DestReg, MVT::i64));
459       }
460     }
461   }
462   
463   // Finally, once everything is in registers to pass to the call, emit the
464   // call itself.
465   if (InFlag.Val)
466     CallOperands.push_back(InFlag);   // Strong dep on register copies.
467   else
468     CallOperands.push_back(Chain);    // Weak dep on whatever occurs before
469   Chain = CurDAG->getTargetNode(CallOpcode, MVT::Other, MVT::Flag,
470                                 CallOperands);
471  
472   std::vector<SDOperand> CallResults;
473   
474   // If the call has results, copy the values out of the ret val registers.
475   switch (N->getValueType(0)) {
476     default: assert(0 && "Unexpected ret value!");
477     case MVT::Other: break;
478     case MVT::i1: {
479         // bools are returned as bytes 0/1 in r8
480         SDOperand byteval = CurDAG->getCopyFromReg(Chain, IA64::r8, MVT::i64,
481                                        Chain.getValue(1));
482         Chain = byteval.getValue(1);
483         Chain = CurDAG->getTargetNode(IA64::CMPNE, MVT::i1, MVT::Other,
484             byteval, CurDAG->getRegister(IA64::r0, MVT::i64)).getValue(1);
485         CallResults.push_back(Chain.getValue(0));
486         break;
487         }
488     case MVT::i64:
489         Chain = CurDAG->getCopyFromReg(Chain, IA64::r8, MVT::i64,
490                                        Chain.getValue(1)).getValue(1);
491         CallResults.push_back(Chain.getValue(0));
492       break;
493     case MVT::f64:
494       Chain = CurDAG->getCopyFromReg(Chain, IA64::F8, N->getValueType(0),
495                                      Chain.getValue(1)).getValue(1);
496       CallResults.push_back(Chain.getValue(0));
497       break;
498   }
499    
500   // restore GP, SP and RP - FIXME: this doesn't quite work (e.g.
501   // methcall / objinst both segfault on exit) and it *really*
502   // doesn't work unless you have -sched=none
503   Chain = CurDAG->getCopyToReg(Chain, IA64::r1, GPBeforeCall);
504   Chain = CurDAG->getCopyToReg(Chain, IA64::r12, SPBeforeCall);
505   Chain = CurDAG->getCopyToReg(Chain, IA64::rp, RPBeforeCall);
506   CallResults.push_back(Chain); // llc segfaults w/o this,
507                       // ary3(e.g.) SIGILLs with 3
508
509   for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
510     CodeGenMap[Op.getValue(i)] = CallResults[i];
511  
512   return CallResults[Op.ResNo];
513 }
514
515 // Select - Convert the specified operand from a target-independent to a
516 // target-specific node if it hasn't already been changed.
517 SDOperand IA64DAGToDAGISel::Select(SDOperand Op) {
518   SDNode *N = Op.Val;
519   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
520       N->getOpcode() < IA64ISD::FIRST_NUMBER)
521     return Op;   // Already selected.
522
523   // If this has already been converted, use it.
524   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
525   if (CGMI != CodeGenMap.end()) return CGMI->second;
526   
527   switch (N->getOpcode()) {
528   default: break;
529
530   case ISD::CALL:
531   case ISD::TAILCALL: return SelectCALL(Op);
532
533   case ISD::FDIV:
534   case ISD::SDIV:
535   case ISD::UDIV:
536   case ISD::SREM:
537   case ISD::UREM: return SelectDIV(Op);
538  
539 /* todo:
540  * case ISD::DYNAMIC_STACKALLOC:
541 */
542   case ISD::ConstantFP: {
543     SDOperand Chain = CurDAG->getEntryNode(); // this is a constant, so..
544
545     if (cast<ConstantFPSDNode>(N)->isExactlyValue(+0.0))
546       return CurDAG->getCopyFromReg(Chain, IA64::F0, MVT::f64);
547     else if (cast<ConstantFPSDNode>(N)->isExactlyValue(+1.0))
548       return CurDAG->getCopyFromReg(Chain, IA64::F1, MVT::f64);
549     else
550       assert(0 && "Unexpected FP constant!");
551   }
552
553   case ISD::FrameIndex: { // TODO: reduce creepyness
554     int FI = cast<FrameIndexSDNode>(N)->getIndex();
555     if (N->hasOneUse()) {
556       CurDAG->SelectNodeTo(N, IA64::MOV, MVT::i64,
557                            CurDAG->getTargetFrameIndex(FI, MVT::i64));
558       return SDOperand(N, 0);
559     }
560     return CurDAG->getTargetNode(IA64::MOV, MVT::i64,
561                                 CurDAG->getTargetFrameIndex(FI, MVT::i64));
562   }
563
564   case ISD::ConstantPool: {
565     Constant *C = cast<ConstantPoolSDNode>(N)->get();
566     SDOperand CPI = CurDAG->getTargetConstantPool(C, MVT::i64);
567     return CurDAG->getTargetNode(IA64::ADDL_GA, MVT::i64, // ?
568                               CurDAG->getRegister(IA64::r1, MVT::i64), CPI);
569   }
570
571   case ISD::GlobalAddress: {
572     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
573     SDOperand GA = CurDAG->getTargetGlobalAddress(GV, MVT::i64);
574     SDOperand Tmp = CurDAG->getTargetNode(IA64::ADDL_GA, MVT::i64, 
575                                   CurDAG->getRegister(IA64::r1, MVT::i64), GA);
576     return CurDAG->getTargetNode(IA64::LD8, MVT::i64, Tmp);
577   }
578                            
579   case ISD::LOAD:
580   case ISD::EXTLOAD:
581   case ISD::ZEXTLOAD: {
582     SDOperand Chain = Select(N->getOperand(0));
583     SDOperand Address = Select(N->getOperand(1));
584
585     MVT::ValueType TypeBeingLoaded = (N->getOpcode() == ISD::LOAD) ?
586       N->getValueType(0) : cast<VTSDNode>(N->getOperand(3))->getVT();
587     unsigned Opc;
588     switch (TypeBeingLoaded) {
589     default: N->dump(); assert(0 && "Cannot load this type!");
590     case MVT::i1: { // this is a bool
591       Opc = IA64::LD1; // first we load a byte, then compare for != 0
592       CurDAG->SelectNodeTo(N, IA64::CMPNE, MVT::i1, MVT::Other, 
593         CurDAG->getTargetNode(Opc, MVT::i64, Address),
594         CurDAG->getRegister(IA64::r0, MVT::i64), Chain);
595       return SDOperand(N, Op.ResNo); // XXX: early exit
596       }
597     case MVT::i8:  Opc = IA64::LD1; break;
598     case MVT::i16: Opc = IA64::LD2; break;
599     case MVT::i32: Opc = IA64::LD4; break;
600     case MVT::i64: Opc = IA64::LD8; break;
601     
602     case MVT::f32: Opc = IA64::LDF4; break;
603     case MVT::f64: Opc = IA64::LDF8; break;
604     }
605
606     CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), MVT::Other,
607                              Address, Chain); // TODO: comment this
608     
609     return SDOperand(N, Op.ResNo);
610   }
611   
612   case ISD::TRUNCSTORE:
613   case ISD::STORE: {
614     SDOperand Address = Select(N->getOperand(2));
615     SDOperand Chain = Select(N->getOperand(0));
616    
617     unsigned Opc;
618     if (N->getOpcode() == ISD::STORE) {
619       switch (N->getOperand(1).getValueType()) {
620       default: assert(0 && "unknown type in store");
621       case MVT::i1: { // this is a bool
622         Opc = IA64::ST1; // we store either 0 or 1 as a byte 
623         CurDAG->SelectNodeTo(N, Opc, MVT::Other, Address,
624             CurDAG->getTargetNode(IA64::PADDS, MVT::i64,
625               CurDAG->getRegister(IA64::r0, MVT::i64),
626               CurDAG->getConstant(1, MVT::i64),
627               Select(N->getOperand(1))),
628             Chain);
629         return SDOperand(N, 0); // XXX: early exit
630         }
631       case MVT::i64: Opc = IA64::ST8;  break;
632       case MVT::f64: Opc = IA64::STF8; break;
633       }
634     } else { //ISD::TRUNCSTORE
635       switch(cast<VTSDNode>(N->getOperand(4))->getVT()) {
636       default: assert(0 && "unknown type in truncstore");
637       case MVT::i8:  Opc = IA64::ST1;  break;
638       case MVT::i16: Opc = IA64::ST2;  break;
639       case MVT::i32: Opc = IA64::ST4;  break;
640       case MVT::f32: Opc = IA64::STF4; break;
641       }
642     }
643     
644     CurDAG->SelectNodeTo(N, Opc, MVT::Other, Select(N->getOperand(2)),
645                          Select(N->getOperand(1)), Chain);
646     return SDOperand(N, 0);
647   }
648
649   case ISD::BRCOND: {
650     SDOperand Chain = Select(N->getOperand(0));
651     SDOperand CC = Select(N->getOperand(1));
652     MachineBasicBlock *Dest =
653       cast<BasicBlockSDNode>(N->getOperand(2))->getBasicBlock();
654     //FIXME - we do NOT need long branches all the time
655     CurDAG->SelectNodeTo(N, IA64::BRLCOND_NOTCALL, MVT::Other, CC, CurDAG->getBasicBlock(Dest), Chain);
656     return SDOperand(N, 0);
657   }
658
659   case ISD::CALLSEQ_START:
660   case ISD::CALLSEQ_END: {
661     int64_t Amt = cast<ConstantSDNode>(N->getOperand(1))->getValue();
662     unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ?
663                        IA64::ADJUSTCALLSTACKDOWN : IA64::ADJUSTCALLSTACKUP;
664     CurDAG->SelectNodeTo(N, Opc, MVT::Other,
665                          getI64Imm(Amt), Select(N->getOperand(0)));
666     return SDOperand(N, 0);
667   }
668
669   case ISD::RET: {
670     SDOperand Chain = Select(N->getOperand(0));     // Token chain.
671
672     switch (N->getNumOperands()) {
673     default:
674       assert(0 && "Unknown return instruction!");
675     case 2: {
676       SDOperand RetVal = Select(N->getOperand(1));
677       switch (RetVal.getValueType()) {
678       default: assert(0 && "I don't know how to return this type! (promote?)");
679                // FIXME: do I need to add support for bools here?
680                // (return '0' or '1' in r8, basically...)
681                //
682                // FIXME: need to round floats - 80 bits is bad, the tester
683                // told me so
684       case MVT::i64:
685         // we mark r8 as live on exit up above in LowerArguments()
686         // BuildMI(BB, IA64::MOV, 1, IA64::r8).addReg(Tmp1);
687         Chain = CurDAG->getCopyToReg(Chain, IA64::r8, RetVal);
688         break;
689       case MVT::f64:
690         // we mark F8 as live on exit up above in LowerArguments()
691         // BuildMI(BB, IA64::FMOV, 1, IA64::F8).addReg(Tmp1);
692         Chain = CurDAG->getCopyToReg(Chain, IA64::F8, RetVal);
693         break;
694       }
695       break;
696       }
697     case 1:
698       break;
699     }
700
701     // we need to copy VirtGPR (the vreg (to become a real reg)) that holds
702     // the output of this function's alloc instruction back into ar.pfs
703     // before we return. this copy must not float up above the last 
704     // outgoing call in this function!!!
705     SDOperand AR_PFSVal = CurDAG->getCopyFromReg(Chain, IA64Lowering.VirtGPR,
706                                                   MVT::i64);
707     Chain = AR_PFSVal.getValue(1);
708     Chain = CurDAG->getCopyToReg(Chain, IA64::AR_PFS, AR_PFSVal);
709
710     CurDAG->SelectNodeTo(N, IA64::RET, MVT::Other, Chain); // and then just emit a 'ret' instruction
711     
712     // before returning, restore the ar.pfs register (set by the 'alloc' up top)
713     // BuildMI(BB, IA64::MOV, 1).addReg(IA64::AR_PFS).addReg(IA64Lowering.VirtGPR);
714     //
715     return SDOperand(N, 0);
716   }
717   
718   case ISD::BR:
719                  // FIXME: we don't need long branches all the time!
720     CurDAG->SelectNodeTo(N, IA64::BRL_NOTCALL, MVT::Other, N->getOperand(1),
721                          Select(N->getOperand(0)));
722     return SDOperand(N, 0);
723   
724   }
725   
726   return SelectCode(Op);
727 }
728
729
730 /// createIA64DAGToDAGInstructionSelector - This pass converts a legalized DAG
731 /// into an IA64-specific DAG, ready for instruction scheduling.
732 ///
733 FunctionPass *llvm::createIA64DAGToDAGInstructionSelector(TargetMachine &TM) {
734   return new IA64DAGToDAGISel(TM);
735 }
736