Remove fake instruction 'subc' (mnemonic for subfc).
[oota-llvm.git] / lib / Target / PowerPC / PPCISelPattern.cpp
1 //===-- PPC32ISelPattern.cpp - A pattern matching inst selector for PPC32 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Nate Begeman 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 32 bit PowerPC.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PowerPC.h"
15 #include "PowerPCInstrBuilder.h"
16 #include "PowerPCInstrInfo.h"
17 #include "PPC32RegisterInfo.h"
18 #include "llvm/Constants.h"                   // FIXME: REMOVE
19 #include "llvm/Function.h"
20 #include "llvm/CodeGen/MachineConstantPool.h" // FIXME: REMOVE
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/ADT/Statistic.h"
31 #include <set>
32 #include <algorithm>
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 //  PPC32TargetLowering - PPC32 Implementation of the TargetLowering interface
37 namespace {
38   class PPC32TargetLowering : public TargetLowering {
39     int VarArgsFrameIndex;            // FrameIndex for start of varargs area.
40     int ReturnAddrIndex;              // FrameIndex for return slot.
41   public:
42     PPC32TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
43       // Set up the TargetLowering object.
44
45       // Set up the register classes.
46       addRegisterClass(MVT::i32, PPC32::GPRCRegisterClass);
47       addRegisterClass(MVT::f32, PPC32::FPRCRegisterClass);
48       addRegisterClass(MVT::f64, PPC32::FPRCRegisterClass);
49       
50       computeRegisterProperties();
51     }
52
53     /// LowerArguments - This hook must be implemented to indicate how we should
54     /// lower the arguments for the specified function, into the specified DAG.
55     virtual std::vector<SDOperand>
56     LowerArguments(Function &F, SelectionDAG &DAG);
57     
58     /// LowerCallTo - This hook lowers an abstract call to a function into an
59     /// actual call.
60     virtual std::pair<SDOperand, SDOperand>
61     LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
62                 SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
63     
64     virtual std::pair<SDOperand, SDOperand>
65     LowerVAStart(SDOperand Chain, SelectionDAG &DAG);
66     
67     virtual std::pair<SDOperand,SDOperand>
68     LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
69                    const Type *ArgTy, SelectionDAG &DAG);
70
71     virtual std::pair<SDOperand, SDOperand>
72     LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
73                             SelectionDAG &DAG);
74   };
75 }
76
77
78 std::vector<SDOperand>
79 PPC32TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
80   //
81   // add beautiful description of PPC stack frame format, or at least some docs
82   //
83   MachineFunction &MF = DAG.getMachineFunction();
84   MachineFrameInfo *MFI = MF.getFrameInfo();
85   MachineBasicBlock& BB = MF.front();
86   std::vector<SDOperand> ArgValues;
87   
88   // Due to the rather complicated nature of the PowerPC ABI, rather than a 
89   // fixed size array of physical args, for the sake of simplicity let the STL
90   // handle tracking them for us.
91   std::vector<unsigned> argVR, argPR, argOp;
92   unsigned ArgOffset = 24;
93   unsigned GPR_remaining = 8;
94   unsigned FPR_remaining = 13;
95   unsigned GPR_idx = 0, FPR_idx = 0;
96   static const unsigned GPR[] = { 
97     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
98     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
99   };
100   static const unsigned FPR[] = {
101     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
102     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
103   };
104
105   // Add DAG nodes to load the arguments...  On entry to a function on PPC,
106   // the arguments start at offset 24, although they are likely to be passed
107   // in registers.
108   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
109     SDOperand newroot, argt;
110     unsigned ObjSize;
111     bool needsLoad = false;
112     MVT::ValueType ObjectVT = getValueType(I->getType());
113     
114     switch (ObjectVT) {
115     default: assert(0 && "Unhandled argument type!");
116     case MVT::i1:
117     case MVT::i8:
118     case MVT::i16:
119     case MVT::i32: 
120       ObjSize = 4;
121       if (GPR_remaining > 0) {
122         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
123         unsigned virtReg = 
124           MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i32));
125         argt = newroot = DAG.getCopyFromReg(virtReg, MVT::i32, DAG.getRoot());
126         if (ObjectVT != MVT::i32)
127           argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, newroot);
128         argVR.push_back(virtReg);
129         argPR.push_back(GPR[GPR_idx]);
130         argOp.push_back(PPC::OR);
131       } else {
132         needsLoad = true;
133       }
134       break;
135       case MVT::i64: ObjSize = 8;
136       // FIXME: can split 64b load between reg/mem if it is last arg in regs
137       if (GPR_remaining > 1) {
138         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
139         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx+1]);
140         SDOperand root = DAG.getRoot();
141         SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, 
142           root, DAG.getConstant(1, MVT::i32));
143         SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, 
144           root, DAG.getConstant(0, MVT::i32));
145         
146         // Create the pair of virtual registers
147         MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i32));
148         unsigned virtReg = MF.getSSARegMap()->createVirtualRegister(getRegClassFor(MVT::i32))-1;
149         
150         // Copy the extracted halves into the virtual registers
151         SDOperand argHi = DAG.getCopyFromReg(virtReg, MVT::i32, Hi);
152         SDOperand argLo = DAG.getCopyFromReg(virtReg+1, MVT::i32, Lo);
153           
154         // Build the outgoing arg thingy
155         argt = newroot = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
156         argVR.push_back(virtReg);       argVR.push_back(virtReg+1);
157         argPR.push_back(GPR[GPR_idx]);  argPR.push_back(GPR[GPR_idx+1]);
158         argOp.push_back(PPC::OR);       argOp.push_back(PPC::OR);
159       } else {
160         needsLoad = true; 
161       }
162       break;
163       case MVT::f32: ObjSize = 4;
164       case MVT::f64: ObjSize = 8;
165       if (FPR_remaining > 0) {
166         BuildMI(&BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
167         unsigned virtReg = 
168           MF.getSSARegMap()->createVirtualRegister(getRegClassFor(ObjectVT));
169         argt = newroot = DAG.getCopyFromReg(virtReg, ObjectVT, DAG.getRoot());
170         argVR.push_back(virtReg);
171         argPR.push_back(FPR[FPR_idx]);
172         argOp.push_back(PPC::FMR);
173         --FPR_remaining;
174         ++FPR_idx;
175       } else {
176         needsLoad = true;
177       }
178       break;
179     }
180     
181     // We need to load the argument to a virtual register if we determined above
182     // that we ran out of physical registers of the appropriate type 
183     if (needsLoad) {
184       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
185       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
186       argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN);
187     }
188     
189     // Every 4 bytes of argument space consumes one of the GPRs available for
190     // argument passing.
191     if (GPR_remaining > 0) {
192       unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
193       GPR_remaining -= delta;
194       GPR_idx += delta;
195     }
196     ArgOffset += ObjSize;
197     
198     DAG.setRoot(newroot.getValue(1));
199     ArgValues.push_back(argt);
200   }
201
202   for (int i = 0, count = argVR.size(); i < count; ++i) {
203     if (argOp[i] == PPC::FMR)
204       BuildMI(&BB, argOp[i], 1, argVR[i]).addReg(argPR[i]);
205     else
206       BuildMI(&BB, argOp[i], 2, argVR[i]).addReg(argPR[i]).addReg(argPR[i]);
207   }
208
209   // If the function takes variable number of arguments, make a frame index for
210   // the start of the first vararg value... for expansion of llvm.va_start.
211   if (F.isVarArg())
212     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
213
214   return ArgValues;
215 }
216
217 std::pair<SDOperand, SDOperand>
218 PPC32TargetLowering::LowerCallTo(SDOperand Chain,
219                                  const Type *RetTy, bool isVarArg,
220          SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG) {
221   // args_to_use will accumulate outgoing args for the ISD::CALL case in
222   // SelectExpr to use to put the arguments in the appropriate registers.
223   std::vector<SDOperand> args_to_use;
224
225   // Count how many bytes are to be pushed on the stack, including the linkage
226   // area, and parameter passing area.
227   unsigned NumBytes = 24;
228
229   if (Args.empty()) {
230     NumBytes = 0;    // Save zero bytes.
231   } else {
232     for (unsigned i = 0, e = Args.size(); i != e; ++i)
233       switch (getValueType(Args[i].second)) {
234       default: assert(0 && "Unknown value type!");
235       case MVT::i1:
236       case MVT::i8:
237       case MVT::i16:
238       case MVT::i32:
239       case MVT::f32:
240         NumBytes += 4;
241         break;
242       case MVT::i64:
243       case MVT::f64:
244         NumBytes += 8;
245         break;
246       }
247     
248     // Just to be safe, we'll always reserve the full 24 bytes of linkage area 
249     // plus 32 bytes of argument space in case any called code gets funky on us.
250     if (NumBytes < 56) NumBytes = 56;
251
252     // Adjust the stack pointer for the new arguments...
253     // These operations are automatically eliminated by the prolog/epilog pass
254     Chain = DAG.getNode(ISD::ADJCALLSTACKDOWN, MVT::Other, Chain,
255                         DAG.getConstant(NumBytes, getPointerTy()));
256
257     // Set up a copy of the stack pointer for use loading and storing any
258     // arguments that may not fit in the registers available for argument
259     // passing.
260     SDOperand StackPtr = DAG.getCopyFromReg(PPC::R1, MVT::i32,
261                                             DAG.getEntryNode());
262     
263     // Figure out which arguments are going to go in registers, and which in
264     // memory.  Also, if this is a vararg function, floating point operations
265     // must be stored to our stack, and loaded into integer regs as well, if
266     // any integer regs are available for argument passing.
267     unsigned ArgOffset = 24;
268     unsigned GPR_remaining = 8;
269     unsigned FPR_remaining = 13;
270     std::vector<SDOperand> Stores;
271     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
272       // PtrOff will be used to store the current argument to the stack if a
273       // register cannot be found for it.
274       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
275       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
276       MVT::ValueType ArgVT = getValueType(Args[i].second);
277       
278       switch (ArgVT) {
279       default: assert(0 && "Unexpected ValueType for argument!");
280       case MVT::i1:
281       case MVT::i8:
282       case MVT::i16:
283         // Promote the integer to 32 bits.  If the input type is signed use a
284         // sign extend, otherwise use a zero extend.
285         if (Args[i].second->isSigned())
286           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
287         else
288           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
289         // FALL THROUGH
290       case MVT::i32:
291         if (GPR_remaining > 0) {
292           args_to_use.push_back(Args[i].first);
293           --GPR_remaining;
294         } else {
295           Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
296                                        Args[i].first, PtrOff));
297         }
298         ArgOffset += 4;
299         break;
300       case MVT::i64:
301         // If we have one free GPR left, we can place the upper half of the i64
302         // in it, and store the other half to the stack.  If we have two or more
303         // free GPRs, then we can pass both halves of the i64 in registers.
304         if (GPR_remaining > 0) {
305           SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, 
306             Args[i].first, DAG.getConstant(1, MVT::i32));
307           SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, 
308             Args[i].first, DAG.getConstant(0, MVT::i32));
309           args_to_use.push_back(Hi);
310           if (GPR_remaining > 1) {
311             args_to_use.push_back(Lo);
312             GPR_remaining -= 2;
313           } else {
314             SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
315             PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
316             Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
317                                          Lo, PtrOff));
318             --GPR_remaining;
319           }
320         } else {
321           Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
322                                        Args[i].first, PtrOff));
323         }
324         ArgOffset += 8;
325         break;
326       case MVT::f32:
327       case MVT::f64:
328         if (FPR_remaining > 0) {
329           if (isVarArg) {
330             // FIXME: Need FunctionType information so we can conditionally
331             // store only the non-fixed arguments in a vararg function.
332             Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
333                                          Args[i].first, PtrOff));
334             // FIXME: Need a way to communicate to the ISD::CALL select code
335             // that a particular argument is non-fixed so that we can load them
336             // into the correct GPR to shadow the FPR
337           }
338           args_to_use.push_back(Args[i].first);
339           --FPR_remaining;
340           // If we have any FPRs remaining, we may also have GPRs remaining.
341           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
342           // GPRs.
343           if (GPR_remaining > 0) --GPR_remaining;
344           if (GPR_remaining > 0 && MVT::f64 == ArgVT) --GPR_remaining;
345         } else {
346           Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
347                                        Args[i].first, PtrOff));
348         }
349         ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
350         break;
351       }
352     }
353     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
354   }
355   
356   std::vector<MVT::ValueType> RetVals;
357   MVT::ValueType RetTyVT = getValueType(RetTy);
358   if (RetTyVT != MVT::isVoid)
359     RetVals.push_back(RetTyVT);
360   RetVals.push_back(MVT::Other);
361
362   SDOperand TheCall = SDOperand(DAG.getCall(RetVals, 
363                                             Chain, Callee, args_to_use), 0);
364   Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
365   Chain = DAG.getNode(ISD::ADJCALLSTACKUP, MVT::Other, Chain,
366                       DAG.getConstant(NumBytes, getPointerTy()));
367   return std::make_pair(TheCall, Chain);
368 }
369
370 std::pair<SDOperand, SDOperand>
371 PPC32TargetLowering::LowerVAStart(SDOperand Chain, SelectionDAG &DAG) {
372   //vastart just returns the address of the VarArgsFrameIndex slot.
373   return std::make_pair(DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32), Chain);
374 }
375
376 std::pair<SDOperand,SDOperand> PPC32TargetLowering::
377 LowerVAArgNext(bool isVANext, SDOperand Chain, SDOperand VAList,
378                const Type *ArgTy, SelectionDAG &DAG) {
379   MVT::ValueType ArgVT = getValueType(ArgTy);
380   SDOperand Result;
381   if (!isVANext) {
382     Result = DAG.getLoad(ArgVT, DAG.getEntryNode(), VAList);
383   } else {
384     unsigned Amt;
385     if (ArgVT == MVT::i32 || ArgVT == MVT::f32)
386       Amt = 4;
387     else {
388       assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
389              "Other types should have been promoted for varargs!");
390       Amt = 8;
391     }
392     Result = DAG.getNode(ISD::ADD, VAList.getValueType(), VAList,
393                          DAG.getConstant(Amt, VAList.getValueType()));
394   }
395   return std::make_pair(Result, Chain);
396 }
397                
398
399 std::pair<SDOperand, SDOperand> PPC32TargetLowering::
400 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
401                         SelectionDAG &DAG) {
402   abort();
403 }
404
405 namespace {
406
407 //===--------------------------------------------------------------------===//
408 /// ISel - PPC32 specific code to select PPC32 machine instructions for
409 /// SelectionDAG operations.
410 //===--------------------------------------------------------------------===//
411 class ISel : public SelectionDAGISel {
412   
413   /// Comment Here.
414   PPC32TargetLowering PPC32Lowering;
415   
416   /// ExprMap - As shared expressions are codegen'd, we keep track of which
417   /// vreg the value is produced in, so we only emit one copy of each compiled
418   /// tree.
419   std::map<SDOperand, unsigned> ExprMap;
420
421   unsigned GlobalBaseReg;
422   bool GlobalBaseInitialized;
423   
424 public:
425   ISel(TargetMachine &TM) : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM) 
426   {}
427   
428   /// runOnFunction - Override this function in order to reset our per-function
429   /// variables.
430   virtual bool runOnFunction(Function &Fn) {
431     // Make sure we re-emit a set of the global base reg if necessary
432     GlobalBaseInitialized = false;
433     return SelectionDAGISel::runOnFunction(Fn);
434   } 
435   
436   /// InstructionSelectBasicBlock - This callback is invoked by
437   /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
438   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
439     DEBUG(BB->dump());
440     // Codegen the basic block.
441     Select(DAG.getRoot());
442     
443     // Clear state used for selection.
444     ExprMap.clear();
445   }
446   
447   unsigned ISel::getGlobalBaseReg();
448   unsigned SelectExpr(SDOperand N);
449   unsigned SelectExprFP(SDOperand N, unsigned Result);
450   void Select(SDOperand N);
451   
452   void SelectAddr(SDOperand N, unsigned& Reg, int& offset);
453   void SelectBranchCC(SDOperand N);
454 };
455
456 /// canUseAsImmediateForOpcode - This method returns a value indicating whether
457 /// the ConstantSDNode N can be used as an immediate to Opcode.  The return
458 /// values are either 0, 1 or 2.  0 indicates that either N is not a
459 /// ConstantSDNode, or is not suitable for use by that opcode.  A return value 
460 /// of 1 indicates that the constant may be used in normal immediate form.  A
461 /// return value of 2 indicates that the constant may be used in shifted
462 /// immediate form.  If the return value is nonzero, the constant value is
463 /// placed in Imm.
464 ///
465 static unsigned canUseAsImmediateForOpcode(SDOperand N, unsigned Opcode,
466                                            unsigned& Imm) {
467   if (N.getOpcode() != ISD::Constant) return 0;
468
469   int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
470   
471   switch(Opcode) {
472   default: return 0;
473   case ISD::ADD:
474     if (v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
475     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
476     break;
477   case ISD::AND:
478   case ISD::XOR:
479   case ISD::OR:
480     if (v >= 0 && v <= 65535) { Imm = v & 0xFFFF; return 1; }
481     if ((v & 0x0000FFFF) == 0) { Imm = v >> 16; return 2; }
482     break;
483   case ISD::MUL:
484     if (v <= 32767 && v >= -32768) { Imm = v & 0xFFFF; return 1; }
485     break;
486   }
487   return 0;
488 }
489 }
490
491 /// getGlobalBaseReg - Output the instructions required to put the
492 /// base address to use for accessing globals into a register.
493 ///
494 unsigned ISel::getGlobalBaseReg() {
495   if (!GlobalBaseInitialized) {
496     // Insert the set of GlobalBaseReg into the first MBB of the function
497     MachineBasicBlock &FirstMBB = BB->getParent()->front();
498     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
499     GlobalBaseReg = MakeReg(MVT::i32);
500     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
501     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg).addReg(PPC::LR);
502     GlobalBaseInitialized = true;
503   }
504   return GlobalBaseReg;
505 }
506
507 //Check to see if the load is a constant offset from a base register
508 void ISel::SelectAddr(SDOperand N, unsigned& Reg, int& offset)
509 {
510   Reg = SelectExpr(N);
511   offset = 0;
512   return;
513 }
514
515 void ISel::SelectBranchCC(SDOperand N)
516 {
517   assert(N.getOpcode() == ISD::BRCOND && "Not a BranchCC???");
518   MachineBasicBlock *Dest = 
519     cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
520   unsigned Opc;
521   
522   Select(N.getOperand(0));  //chain
523   SDOperand CC = N.getOperand(1);
524   
525   //Giveup and do the stupid thing
526   unsigned Tmp1 = SelectExpr(CC);
527   BuildMI(BB, PPC::BNE, 2).addReg(Tmp1).addMBB(Dest);
528   return;
529 }
530
531 unsigned ISel::SelectExprFP(SDOperand N, unsigned Result)
532 {
533   unsigned Tmp1, Tmp2, Tmp3;
534   unsigned Opc = 0;
535   SDNode *Node = N.Val;
536   MVT::ValueType DestType = N.getValueType();
537   unsigned opcode = N.getOpcode();
538
539   switch (opcode) {
540   default:
541     Node->dump();
542     assert(0 && "Node not handled!\n");
543
544   case ISD::SELECT:
545     abort();
546     
547   case ISD::FP_ROUND:
548     assert (DestType == MVT::f32 && 
549             N.getOperand(0).getValueType() == MVT::f64 && 
550             "only f64 to f32 conversion supported here");
551     Tmp1 = SelectExpr(N.getOperand(0));
552     BuildMI(BB, PPC::FRSP, 1, Result).addReg(Tmp1);
553     return Result;
554
555   case ISD::FP_EXTEND:
556     assert (DestType == MVT::f64 && 
557             N.getOperand(0).getValueType() == MVT::f32 && 
558             "only f32 to f64 conversion supported here");
559     Tmp1 = SelectExpr(N.getOperand(0));
560     BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
561     return Result;
562
563   case ISD::CopyFromReg:
564     if (Result == 1)
565       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
566     Tmp1 = dyn_cast<RegSDNode>(Node)->getReg();
567     BuildMI(BB, PPC::FMR, 1, Result).addReg(Tmp1);
568     return Result;
569     
570   case ISD::LOAD:
571   case ISD::EXTLOAD: {
572     MVT::ValueType TypeBeingLoaded = (ISD::LOAD == opcode) ?
573       Node->getValueType(0) : cast<MVTSDNode>(Node)->getExtraValueType();
574
575     // Make sure we generate both values.
576     if (Result != 1)
577       ExprMap[N.getValue(1)] = 1;   // Generate the token
578     else
579       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
580
581     SDOperand Chain   = N.getOperand(0);
582     SDOperand Address = N.getOperand(1);
583     Select(Chain);
584
585     switch (TypeBeingLoaded) {
586     default: assert(0 && "Cannot fp load this type!");
587     case MVT::f32:  Opc = PPC::LFS; break;
588     case MVT::f64:  Opc = PPC::LFD; break;
589     }
590     
591     if(Address.getOpcode() == ISD::FrameIndex) {
592       BuildMI(BB, Opc, 2, Result)
593       .addFrameIndex(cast<FrameIndexSDNode>(Address)->getIndex())
594       .addReg(PPC::R1);
595     } else {
596       int offset;
597       SelectAddr(Address, Tmp1, offset);
598       BuildMI(BB, Opc, 2, Result).addSImm(offset).addReg(Tmp1);
599     }
600     return Result;
601   }
602     
603   case ISD::ConstantFP:
604     assert(0 && "ISD::ConstantFP Unimplemented");
605     abort();
606     
607   case ISD::MUL:
608   case ISD::ADD:
609   case ISD::SUB:
610   case ISD::SDIV:
611     switch( opcode ) {
612     case ISD::MUL:  Opc = DestType == MVT::f64 ? PPC::FMUL : PPC::FMULS; break;
613     case ISD::ADD:  Opc = DestType == MVT::f64 ? PPC::FADD : PPC::FADDS; break;
614     case ISD::SUB:  Opc = DestType == MVT::f64 ? PPC::FSUB : PPC::FSUBS; break;
615     case ISD::SDIV: Opc = DestType == MVT::f64 ? PPC::FDIV : PPC::FDIVS; break;
616     };
617
618     Tmp1 = SelectExpr(N.getOperand(0));
619     Tmp2 = SelectExpr(N.getOperand(1));
620     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
621     return Result;
622
623   case ISD::UINT_TO_FP:
624   case ISD::SINT_TO_FP:
625     abort();
626   }
627   assert(0 && "should not get here");
628   return 0;
629 }
630
631 unsigned ISel::SelectExpr(SDOperand N) {
632   unsigned Result;
633   unsigned Tmp1, Tmp2, Tmp3;
634   unsigned Opc = 0;
635   unsigned opcode = N.getOpcode();
636
637   SDNode *Node = N.Val;
638   MVT::ValueType DestType = N.getValueType();
639
640   unsigned &Reg = ExprMap[N];
641   if (Reg) return Reg;
642
643   if (N.getOpcode() != ISD::CALL && N.getOpcode() != ISD::ADD_PARTS &&
644       N.getOpcode() != ISD::SUB_PARTS)
645     Reg = Result = (N.getValueType() != MVT::Other) ?
646       MakeReg(N.getValueType()) : 1;
647   else {
648     // If this is a call instruction, make sure to prepare ALL of the result
649     // values as well as the chain.
650     if (N.getOpcode() == ISD::CALL) {
651       if (Node->getNumValues() == 1)
652         Reg = Result = 1;  // Void call, just a chain.
653       else {
654         Result = MakeReg(Node->getValueType(0));
655         ExprMap[N.getValue(0)] = Result;
656         for (unsigned i = 1, e = N.Val->getNumValues()-1; i != e; ++i)
657           ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
658         ExprMap[SDOperand(Node, Node->getNumValues()-1)] = 1;
659       }
660     } else {
661       Result = MakeReg(Node->getValueType(0));
662       ExprMap[N.getValue(0)] = Result;
663       for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
664         ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
665     }
666   }
667
668   if (DestType == MVT::f64 || DestType == MVT::f32)
669     return SelectExprFP(N, Result);
670
671   switch (opcode) {
672   default:
673     Node->dump();
674     assert(0 && "Node not handled!\n");
675  
676   case ISD::DYNAMIC_STACKALLOC:
677     // Generate both result values.  FIXME: Need a better commment here?
678     if (Result != 1)
679       ExprMap[N.getValue(1)] = 1;
680     else
681       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
682
683     // FIXME: We are currently ignoring the requested alignment for handling
684     // greater than the stack alignment.  This will need to be revisited at some
685     // point.  Align = N.getOperand(2);
686     if (!isa<ConstantSDNode>(N.getOperand(2)) ||
687         cast<ConstantSDNode>(N.getOperand(2))->getValue() != 0) {
688       std::cerr << "Cannot allocate stack object with greater alignment than"
689                 << " the stack alignment yet!";
690       abort();
691     }
692     Select(N.getOperand(0));
693     Tmp1 = SelectExpr(N.getOperand(1));
694     // Subtract size from stack pointer, thereby allocating some space.
695     BuildMI(BB, PPC::SUBF, 2, PPC::R1).addReg(Tmp1).addReg(PPC::R1);
696     // Put a pointer to the space into the result register by copying the SP
697     BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R1).addReg(PPC::R1);
698     return Result;
699
700   case ISD::ConstantPool:
701     Tmp1 = cast<ConstantPoolSDNode>(N)->getIndex();
702     Tmp2 = MakeReg(MVT::i32);
703     BuildMI(BB, PPC::LOADHiAddr, 2, Tmp2).addReg(getGlobalBaseReg())
704       .addConstantPoolIndex(Tmp1);
705     BuildMI(BB, PPC::LA, 2, Result).addReg(Tmp2).addConstantPoolIndex(Tmp1);
706     return Result;
707
708   case ISD::FrameIndex:
709     assert(0 && "ISD::FrameIndex Unimplemented");
710     abort();
711   
712   case ISD::GlobalAddress: {
713     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
714     Tmp1 = MakeReg(MVT::i32);
715     BuildMI(BB, PPC::LOADHiAddr, 2, Tmp1).addReg(getGlobalBaseReg())
716       .addGlobalAddress(GV);
717     if (GV->hasWeakLinkage() || GV->isExternal()) {
718       BuildMI(BB, PPC::LWZ, 2, Result).addGlobalAddress(GV).addReg(Tmp1);
719     } else {
720       BuildMI(BB, PPC::LA, 2, Result).addReg(Tmp1).addGlobalAddress(GV);
721     }
722     return Result;
723   }
724
725   case ISD::LOAD:
726   case ISD::EXTLOAD:
727   case ISD::ZEXTLOAD:
728   case ISD::SEXTLOAD: {
729     bool sext = (ISD::SEXTLOAD == opcode);
730     bool byte = (MVT::i8 == Node->getValueType(0));
731     MVT::ValueType TypeBeingLoaded = (ISD::LOAD == opcode) ?
732       Node->getValueType(0) : cast<MVTSDNode>(Node)->getExtraValueType();
733       
734     // Make sure we generate both values.
735     if (Result != 1)
736       ExprMap[N.getValue(1)] = 1;   // Generate the token
737     else
738       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
739
740     SDOperand Chain   = N.getOperand(0);
741     SDOperand Address = N.getOperand(1);
742     Select(Chain);
743
744     switch (TypeBeingLoaded) {
745     default: assert(0 && "Cannot load this type!");
746     case MVT::i1:  Opc = PPC::LBZ; break;
747     case MVT::i8:  Opc = PPC::LBZ; break;
748     case MVT::i16: Opc = sext ? PPC::LHA : PPC::LHZ; break;
749     case MVT::i32: Opc = PPC::LWZ; break;
750     }
751     
752     // Since there's no load byte & sign extend instruction we have to split
753     // byte SEXTLOADs into lbz + extsb.  This requires we make a temp register.
754     if (sext && byte) {
755       Tmp3 = Result;
756       Result = MakeReg(MVT::i32);
757     }
758     if(Address.getOpcode() == ISD::FrameIndex) {
759       BuildMI(BB, Opc, 2, Result)
760       .addFrameIndex(cast<FrameIndexSDNode>(Address)->getIndex())
761       .addReg(PPC::R1);
762     } else {
763       int offset;
764       SelectAddr(Address, Tmp1, offset);
765       BuildMI(BB, Opc, 2, Result).addSImm(offset).addReg(Tmp1);
766     }
767     if (sext && byte) {
768       BuildMI(BB, PPC::EXTSB, 1, Tmp3).addReg(Result);
769       Result = Tmp3;
770     }
771     return Result;
772   }
773     
774   case ISD::CALL: {
775     // Lower the chain for this call.
776     Select(N.getOperand(0));
777     ExprMap[N.getValue(Node->getNumValues()-1)] = 1;
778       
779     // get the virtual reg for each argument
780     std::vector<unsigned> VRegs;
781     for(int i = 2, e = Node->getNumOperands(); i < e; ++i)
782       VRegs.push_back(SelectExpr(N.getOperand(i)));
783     
784     // The ABI specifies that the first 32 bytes of args may be passed in GPRs,
785     // and that 13 FPRs may also be used for passing any floating point args.
786     int GPR_remaining = 8, FPR_remaining = 13;
787     unsigned GPR_idx = 0, FPR_idx = 0;
788     static const unsigned GPR[] = { 
789       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
790       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
791     };
792     static const unsigned FPR[] = {
793       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, 
794       PPC::F7, PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, 
795       PPC::F13
796     };
797
798     // move the vregs into the appropriate architected register or stack slot
799     for(int i = 0, e = VRegs.size(); i < e; ++i) {
800         unsigned OperandType = N.getOperand(i+2).getValueType();
801         switch(OperandType) {
802         default: 
803           Node->dump(); 
804           N.getOperand(i).Val->dump();
805           std::cerr << "Type for " << i << " is: " << 
806             N.getOperand(i+2).getValueType() << "\n";
807           assert(0 && "Unknown value type for call");
808         case MVT::i1:
809         case MVT::i8:
810         case MVT::i16:
811         case MVT::i32:
812           if (GPR_remaining > 0)
813             BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(VRegs[i])
814               .addReg(VRegs[i]);
815           break;
816         case MVT::f32:
817         case MVT::f64:
818           if (FPR_remaining > 0) {
819             BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(VRegs[i]);
820             ++FPR_idx;
821             --FPR_remaining;
822           }
823           break;
824         }
825         // All arguments consume GPRs available for argument passing
826         if (GPR_remaining > 0) { 
827           ++GPR_idx; 
828           --GPR_remaining;
829         }
830         if (MVT::f64 == OperandType && GPR_remaining > 0) {
831           ++GPR_idx;
832           --GPR_remaining;
833         }
834     }
835
836     // Emit the correct call instruction based on the type of symbol called.
837     if (GlobalAddressSDNode *GASD = 
838         dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
839       BuildMI(BB, PPC::CALLpcrel, 1).addGlobalAddress(GASD->getGlobal(), true);
840     } else if (ExternalSymbolSDNode *ESSDN = 
841                dyn_cast<ExternalSymbolSDNode>(N.getOperand(1))) {
842       BuildMI(BB, PPC::CALLpcrel, 1).addExternalSymbol(ESSDN->getSymbol(), true);
843     } else {
844       Tmp1 = SelectExpr(N.getOperand(1));
845       BuildMI(BB, PPC::OR, 2, PPC::R12).addReg(Tmp1).addReg(Tmp1);
846       BuildMI(BB, PPC::MTCTR, 1).addReg(PPC::R12);
847       BuildMI(BB, PPC::CALLindirect, 3).addImm(20).addImm(0).addReg(PPC::R12);
848     }
849
850     switch (Node->getValueType(0)) {
851     default: assert(0 && "Unknown value type for call result!");
852     case MVT::Other: return 1;
853     case MVT::i1:
854     case MVT::i8:
855     case MVT::i16:
856     case MVT::i32:
857       BuildMI(BB, PPC::OR, 2, Result).addReg(PPC::R3).addReg(PPC::R3);
858       if (Node->getValueType(1) == MVT::i32)
859         BuildMI(BB, PPC::OR, 2, Result+1).addReg(PPC::R4).addReg(PPC::R4);
860       break;
861     case MVT::f32:
862     case MVT::f64:
863       BuildMI(BB, PPC::FMR, 1, Result).addReg(PPC::F1);
864       break;
865     }
866     return Result+N.ResNo;
867   }
868
869   case ISD::SIGN_EXTEND:
870   case ISD::SIGN_EXTEND_INREG:
871     Tmp1 = SelectExpr(N.getOperand(0));
872     switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
873     default: Node->dump(); assert(0 && "Unhandled SIGN_EXTEND type"); break;
874     case MVT::i16:  
875       BuildMI(BB, PPC::EXTSH, 1, Result).addReg(Tmp1); 
876       break;
877     case MVT::i8:   
878       BuildMI(BB, PPC::EXTSB, 1, Result).addReg(Tmp1); 
879       break;
880     }
881     return Result;
882     
883   case ISD::ZERO_EXTEND_INREG:
884     Tmp1 = SelectExpr(N.getOperand(0));
885     switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
886     default: Node->dump(); assert(0 && "Unhandled ZERO_EXTEND type"); break;
887     case MVT::i16:  Tmp2 = 16; break;
888     case MVT::i8:   Tmp2 = 24; break;
889     case MVT::i1:   Tmp2 = 31; break;
890     }
891     BuildMI(BB, PPC::RLWINM, 5, Result).addReg(Tmp1).addImm(0).addImm(0)
892       .addImm(Tmp2).addImm(31);
893     return Result;
894     
895   case ISD::CopyFromReg:
896     if (Result == 1)
897       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
898     Tmp1 = dyn_cast<RegSDNode>(Node)->getReg();
899     BuildMI(BB, PPC::OR, 2, Result).addReg(Tmp1).addReg(Tmp1);
900     return Result;
901
902   case ISD::SHL:
903     Tmp1 = SelectExpr(N.getOperand(0));
904     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
905       Tmp2 = CN->getValue() & 0x1F;
906       BuildMI(BB, PPC::RLWINM, 5, Result).addReg(Tmp1).addImm(Tmp2).addImm(0)
907         .addImm(31-Tmp2);
908     } else {
909       Tmp2 = SelectExpr(N.getOperand(1));
910       BuildMI(BB, PPC::SLW, 2, Result).addReg(Tmp1).addReg(Tmp2);
911     }
912     return Result;
913     
914   case ISD::SRL:
915     Tmp1 = SelectExpr(N.getOperand(0));
916     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
917       Tmp2 = CN->getValue() & 0x1F;
918       BuildMI(BB, PPC::RLWINM, 5, Result).addReg(Tmp1).addImm(32-Tmp2)
919         .addImm(Tmp2).addImm(31);
920     } else {
921       Tmp2 = SelectExpr(N.getOperand(1));
922       BuildMI(BB, PPC::SRW, 2, Result).addReg(Tmp1).addReg(Tmp2);
923     }
924     return Result;
925     
926   case ISD::SRA:
927     Tmp1 = SelectExpr(N.getOperand(0));
928     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
929       Tmp2 = CN->getValue() & 0x1F;
930       BuildMI(BB, PPC::SRAWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
931     } else {
932       Tmp2 = SelectExpr(N.getOperand(1));
933       BuildMI(BB, PPC::SRAW, 2, Result).addReg(Tmp1).addReg(Tmp2);
934     }
935     return Result;
936   
937   case ISD::ADD:
938     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
939     Tmp1 = SelectExpr(N.getOperand(0));
940     switch(canUseAsImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
941       default: assert(0 && "unhandled result code");
942       case 0: // No immediate
943         Tmp2 = SelectExpr(N.getOperand(1));
944         BuildMI(BB, PPC::ADD, 2, Result).addReg(Tmp1).addReg(Tmp2);
945         break;
946       case 1: // Low immediate
947         BuildMI(BB, PPC::ADDI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
948         break;
949       case 2: // Shifted immediate
950         BuildMI(BB, PPC::ADDIS, 2, Result).addReg(Tmp1).addSImm(Tmp2);
951         break;
952     }
953     return Result;
954
955   case ISD::AND:
956   case ISD::OR:
957   case ISD::XOR:
958     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
959     Tmp1 = SelectExpr(N.getOperand(0));
960     switch(canUseAsImmediateForOpcode(N.getOperand(1), opcode, Tmp2)) {
961       default: assert(0 && "unhandled result code");
962       case 0: // No immediate
963         Tmp2 = SelectExpr(N.getOperand(1));
964         switch (opcode) {
965         case ISD::AND: Opc = PPC::AND; break;
966         case ISD::OR:  Opc = PPC::OR;  break;
967         case ISD::XOR: Opc = PPC::XOR; break;
968         }
969         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
970         break;
971       case 1: // Low immediate
972         switch (opcode) {
973         case ISD::AND: Opc = PPC::ANDIo; break;
974         case ISD::OR:  Opc = PPC::ORI;   break;
975         case ISD::XOR: Opc = PPC::XORI;  break;
976         }
977         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(Tmp2);
978         break;
979       case 2: // Shifted immediate
980         switch (opcode) {
981         case ISD::AND: Opc = PPC::ANDISo;  break;
982         case ISD::OR:  Opc = PPC::ORIS;    break;
983         case ISD::XOR: Opc = PPC::XORIS;   break;
984         }
985         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(Tmp2);
986         break;
987     }
988     return Result;
989
990   case ISD::SUB:
991     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
992     Tmp1 = SelectExpr(N.getOperand(0));
993     Tmp2 = SelectExpr(N.getOperand(1));
994     BuildMI(BB, PPC::SUBF, 2, Result).addReg(Tmp2).addReg(Tmp1);
995     return Result;
996     
997   case ISD::MUL:
998     assert (DestType == MVT::i32 && "Only do arithmetic on i32s!");
999     Tmp1 = SelectExpr(N.getOperand(0));
1000     if (1 == canUseAsImmediateForOpcode(N.getOperand(1), opcode, Tmp2))
1001       BuildMI(BB, PPC::MULLI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
1002     else {
1003       Tmp2 = SelectExpr(N.getOperand(1));
1004       BuildMI(BB, PPC::MULLW, 2, Result).addReg(Tmp1).addReg(Tmp2);
1005     }
1006     return Result;
1007
1008   case ISD::ADD_PARTS:
1009   case ISD::SUB_PARTS: {
1010     assert(N.getNumOperands() == 4 && N.getValueType() == MVT::i32 &&
1011            "Not an i64 add/sub!");
1012     // Emit all of the operands.
1013     std::vector<unsigned> InVals;
1014     for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)
1015       InVals.push_back(SelectExpr(N.getOperand(i)));
1016     if (N.getOpcode() == ISD::ADD_PARTS) {
1017       BuildMI(BB, PPC::ADDC, 2, Result+1).addReg(InVals[1]).addReg(InVals[3]);
1018       BuildMI(BB, PPC::ADDE, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
1019     } else {
1020       BuildMI(BB, PPC::SUBFC, 2, Result+1).addReg(InVals[1]).addReg(InVals[3]);
1021       BuildMI(BB, PPC::SUBFE, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
1022     }
1023     return Result+N.ResNo;
1024   }
1025     
1026   case ISD::UREM:
1027   case ISD::SREM:
1028   case ISD::SDIV:
1029   case ISD::UDIV:
1030     abort();
1031
1032   case ISD::FP_TO_UINT:
1033   case ISD::FP_TO_SINT:
1034     abort();
1035  
1036   case ISD::SETCC:
1037     abort();
1038     
1039   case ISD::SELECT:
1040     abort();
1041
1042   case ISD::Constant:
1043     switch (N.getValueType()) {
1044     default: assert(0 && "Cannot use constants of this type!");
1045     case MVT::i1:
1046       BuildMI(BB, PPC::LI, 1, Result)
1047         .addSImm(!cast<ConstantSDNode>(N)->isNullValue());
1048       break;
1049     case MVT::i32:
1050       {
1051         int v = (int)cast<ConstantSDNode>(N)->getSignExtended();
1052         if (v < 32768 && v >= -32768) {
1053           BuildMI(BB, PPC::LI, 1, Result).addSImm(v);
1054         } else {
1055           Tmp1 = MakeReg(MVT::i32);
1056           BuildMI(BB, PPC::LIS, 1, Tmp1).addSImm(v >> 16);
1057           BuildMI(BB, PPC::ORI, 2, Result).addReg(Tmp1).addImm(v & 0xFFFF);
1058         }
1059       }
1060     }
1061     return Result;
1062   }
1063
1064   return 0;
1065 }
1066
1067 void ISel::Select(SDOperand N) {
1068   unsigned Tmp1, Tmp2, Opc;
1069   unsigned opcode = N.getOpcode();
1070
1071   if (!ExprMap.insert(std::make_pair(N, 1)).second)
1072     return;  // Already selected.
1073
1074   SDNode *Node = N.Val;
1075   
1076   switch (Node->getOpcode()) {
1077   default:
1078     Node->dump(); std::cerr << "\n";
1079     assert(0 && "Node not handled yet!");
1080   case ISD::EntryToken: return;  // Noop
1081   case ISD::TokenFactor:
1082     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1083       Select(Node->getOperand(i));
1084     return;
1085   case ISD::ADJCALLSTACKDOWN:
1086   case ISD::ADJCALLSTACKUP:
1087     Select(N.getOperand(0));
1088     Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
1089     Opc = N.getOpcode() == ISD::ADJCALLSTACKDOWN ? PPC::ADJCALLSTACKDOWN :
1090       PPC::ADJCALLSTACKUP;
1091     BuildMI(BB, Opc, 1).addImm(Tmp1);
1092     return;
1093   case ISD::BR: {
1094     MachineBasicBlock *Dest =
1095       cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
1096     Select(N.getOperand(0));
1097     BuildMI(BB, PPC::B, 1).addMBB(Dest);
1098     return;
1099   }
1100   case ISD::BRCOND: 
1101     SelectBranchCC(N);
1102     return;
1103   case ISD::CopyToReg:
1104     Select(N.getOperand(0));
1105     Tmp1 = SelectExpr(N.getOperand(1));
1106     Tmp2 = cast<RegSDNode>(N)->getReg();
1107     
1108     if (Tmp1 != Tmp2) {
1109       if (N.getOperand(1).getValueType() == MVT::f64 || 
1110           N.getOperand(1).getValueType() == MVT::f32)
1111         BuildMI(BB, PPC::FMR, 1, Tmp2).addReg(Tmp1);
1112       else
1113         BuildMI(BB, PPC::OR, 2, Tmp2).addReg(Tmp1).addReg(Tmp1);
1114     }
1115     return;
1116   case ISD::ImplicitDef:
1117     Select(N.getOperand(0));
1118     BuildMI(BB, PPC::IMPLICIT_DEF, 0, cast<RegSDNode>(N)->getReg());
1119     return;
1120   case ISD::RET:
1121     switch (N.getNumOperands()) {
1122     default:
1123       assert(0 && "Unknown return instruction!");
1124     case 3:
1125       assert(N.getOperand(1).getValueType() == MVT::i32 &&
1126              N.getOperand(2).getValueType() == MVT::i32 &&
1127                    "Unknown two-register value!");
1128       Select(N.getOperand(0));
1129       Tmp1 = SelectExpr(N.getOperand(1));
1130       Tmp2 = SelectExpr(N.getOperand(2));
1131       BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(Tmp1).addReg(Tmp1);
1132       BuildMI(BB, PPC::OR, 2, PPC::R4).addReg(Tmp2).addReg(Tmp2);
1133       break;
1134     case 2:
1135       Select(N.getOperand(0));
1136       Tmp1 = SelectExpr(N.getOperand(1));
1137       switch (N.getOperand(1).getValueType()) {
1138         default:
1139           assert(0 && "Unknown return type!");
1140         case MVT::f64:
1141         case MVT::f32:
1142           BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(Tmp1);
1143           break;
1144         case MVT::i32:
1145           BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(Tmp1).addReg(Tmp1);
1146           break;
1147       }
1148     case 1:
1149       Select(N.getOperand(0));
1150       break;
1151     }
1152     BuildMI(BB, PPC::BLR, 0); // Just emit a 'ret' instruction
1153     return;
1154   case ISD::TRUNCSTORE: 
1155   case ISD::STORE: 
1156     {
1157       SDOperand Chain   = N.getOperand(0);
1158       SDOperand Value   = N.getOperand(1);
1159       SDOperand Address = N.getOperand(2);
1160       Select(Chain);
1161
1162       Tmp1 = SelectExpr(Value); //value
1163
1164       if (opcode == ISD::STORE) {
1165         switch(Value.getValueType()) {
1166         default: assert(0 && "unknown Type in store");
1167         case MVT::i32: Opc = PPC::STW; break;
1168         case MVT::f64: Opc = PPC::STFD; break;
1169         case MVT::f32: Opc = PPC::STFS; break;
1170         }
1171       } else { //ISD::TRUNCSTORE
1172         switch(cast<MVTSDNode>(Node)->getExtraValueType()) {
1173         default: assert(0 && "unknown Type in store");
1174         case MVT::i1: //FIXME: DAG does not promote this load
1175         case MVT::i8: Opc  = PPC::STB; break;
1176         case MVT::i16: Opc = PPC::STH; break;
1177         }
1178       }
1179
1180       if (Address.getOpcode() == ISD::GlobalAddress)
1181       {
1182         BuildMI(BB, Opc, 2).addReg(Tmp1)
1183           .addGlobalAddress(cast<GlobalAddressSDNode>(Address)->getGlobal());
1184       }
1185       else if(Address.getOpcode() == ISD::FrameIndex)
1186       {
1187         BuildMI(BB, Opc, 2).addReg(Tmp1)
1188           .addFrameIndex(cast<FrameIndexSDNode>(Address)->getIndex());
1189       }
1190       else
1191       {
1192         int offset;
1193         SelectAddr(Address, Tmp2, offset);
1194         BuildMI(BB, Opc, 3).addReg(Tmp1).addImm(offset).addReg(Tmp2);
1195       }
1196       return;
1197     }
1198   case ISD::EXTLOAD:
1199   case ISD::SEXTLOAD:
1200   case ISD::ZEXTLOAD:
1201   case ISD::LOAD:
1202   case ISD::CopyFromReg:
1203   case ISD::CALL:
1204   case ISD::DYNAMIC_STACKALLOC:
1205     ExprMap.erase(N);
1206     SelectExpr(N);
1207     return;
1208   }
1209   assert(0 && "Should not be reached!");
1210 }
1211
1212
1213 /// createPPC32PatternInstructionSelector - This pass converts an LLVM function
1214 /// into a machine code representation using pattern matching and a machine
1215 /// description file.
1216 ///
1217 FunctionPass *llvm::createPPC32ISelPattern(TargetMachine &TM) {
1218   return new ISel(TM);  
1219 }
1220