Fix PR19144: Incorrect offset generated for int-to-fp conversion at -O0.
[oota-llvm.git] / lib / Target / PowerPC / PPCFastISel.cpp
1 //===-- PPCFastISel.cpp - PowerPC FastISel 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 defines the PowerPC-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // PPCGenFastISel.inc, which is #included here.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "ppcfastisel"
17 #include "PPC.h"
18 #include "MCTargetDesc/PPCPredicates.h"
19 #include "PPCISelLowering.h"
20 #include "PPCSubtarget.h"
21 #include "PPCTargetMachine.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/FastISel.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/GetElementPtrTypeIterator.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39
40 //===----------------------------------------------------------------------===//
41 //
42 // TBD:
43 //   FastLowerArguments: Handle simple cases.
44 //   PPCMaterializeGV: Handle TLS.
45 //   SelectCall: Handle function pointers.
46 //   SelectCall: Handle multi-register return values.
47 //   SelectCall: Optimize away nops for local calls.
48 //   processCallArgs: Handle bit-converted arguments.
49 //   finishCall: Handle multi-register return values.
50 //   PPCComputeAddress: Handle parameter references as FrameIndex's.
51 //   PPCEmitCmp: Handle immediate as operand 1.
52 //   SelectCall: Handle small byval arguments.
53 //   SelectIntrinsicCall: Implement.
54 //   SelectSelect: Implement.
55 //   Consider factoring isTypeLegal into the base class.
56 //   Implement switches and jump tables.
57 //
58 //===----------------------------------------------------------------------===//
59 using namespace llvm;
60
61 namespace {
62
63 typedef struct Address {
64   enum {
65     RegBase,
66     FrameIndexBase
67   } BaseType;
68
69   union {
70     unsigned Reg;
71     int FI;
72   } Base;
73
74   long Offset;
75
76   // Innocuous defaults for our address.
77   Address()
78    : BaseType(RegBase), Offset(0) {
79      Base.Reg = 0;
80    }
81 } Address;
82
83 class PPCFastISel final : public FastISel {
84
85   const TargetMachine &TM;
86   const TargetInstrInfo &TII;
87   const TargetLowering &TLI;
88   const PPCSubtarget &PPCSubTarget;
89   LLVMContext *Context;
90
91   public:
92     explicit PPCFastISel(FunctionLoweringInfo &FuncInfo,
93                          const TargetLibraryInfo *LibInfo)
94     : FastISel(FuncInfo, LibInfo),
95       TM(FuncInfo.MF->getTarget()),
96       TII(*TM.getInstrInfo()),
97       TLI(*TM.getTargetLowering()),
98       PPCSubTarget(
99        *((static_cast<const PPCTargetMachine *>(&TM))->getSubtargetImpl())
100       ),
101       Context(&FuncInfo.Fn->getContext()) { }
102
103   // Backend specific FastISel code.
104   private:
105     virtual bool TargetSelectInstruction(const Instruction *I);
106     virtual unsigned TargetMaterializeConstant(const Constant *C);
107     virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
108     virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
109                                      const LoadInst *LI);
110     virtual bool FastLowerArguments();
111     virtual unsigned FastEmit_i(MVT Ty, MVT RetTy, unsigned Opc, uint64_t Imm);
112     virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
113                                      const TargetRegisterClass *RC,
114                                      unsigned Op0, bool Op0IsKill,
115                                      uint64_t Imm);
116     virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
117                                     const TargetRegisterClass *RC,
118                                     unsigned Op0, bool Op0IsKill);
119     virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
120                                      const TargetRegisterClass *RC,
121                                      unsigned Op0, bool Op0IsKill,
122                                      unsigned Op1, bool Op1IsKill);
123
124   // Instruction selection routines.
125   private:
126     bool SelectLoad(const Instruction *I);
127     bool SelectStore(const Instruction *I);
128     bool SelectBranch(const Instruction *I);
129     bool SelectIndirectBr(const Instruction *I);
130     bool SelectCmp(const Instruction *I);
131     bool SelectFPExt(const Instruction *I);
132     bool SelectFPTrunc(const Instruction *I);
133     bool SelectIToFP(const Instruction *I, bool IsSigned);
134     bool SelectFPToI(const Instruction *I, bool IsSigned);
135     bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
136     bool SelectCall(const Instruction *I);
137     bool SelectRet(const Instruction *I);
138     bool SelectTrunc(const Instruction *I);
139     bool SelectIntExt(const Instruction *I);
140
141   // Utility routines.
142   private:
143     bool isTypeLegal(Type *Ty, MVT &VT);
144     bool isLoadTypeLegal(Type *Ty, MVT &VT);
145     bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
146                     bool isZExt, unsigned DestReg);
147     bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
148                      const TargetRegisterClass *RC, bool IsZExt = true,
149                      unsigned FP64LoadOpc = PPC::LFD);
150     bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
151     bool PPCComputeAddress(const Value *Obj, Address &Addr);
152     void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
153                             unsigned &IndexReg);
154     bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
155                            unsigned DestReg, bool IsZExt);
156     unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
157     unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
158     unsigned PPCMaterializeInt(const Constant *C, MVT VT);
159     unsigned PPCMaterialize32BitInt(int64_t Imm,
160                                     const TargetRegisterClass *RC);
161     unsigned PPCMaterialize64BitInt(int64_t Imm,
162                                     const TargetRegisterClass *RC);
163     unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
164                              unsigned SrcReg, bool IsSigned);
165     unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
166
167   // Call handling routines.
168   private:
169     bool processCallArgs(SmallVectorImpl<Value*> &Args,
170                          SmallVectorImpl<unsigned> &ArgRegs,
171                          SmallVectorImpl<MVT> &ArgVTs,
172                          SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
173                          SmallVectorImpl<unsigned> &RegArgs,
174                          CallingConv::ID CC,
175                          unsigned &NumBytes,
176                          bool IsVarArg);
177     void finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
178                     const Instruction *I, CallingConv::ID CC,
179                     unsigned &NumBytes, bool IsVarArg);
180     CCAssignFn *usePPC32CCs(unsigned Flag);
181
182   private:
183   #include "PPCGenFastISel.inc"
184
185 };
186
187 } // end anonymous namespace
188
189 #include "PPCGenCallingConv.inc"
190
191 // Function whose sole purpose is to kill compiler warnings 
192 // stemming from unused functions included from PPCGenCallingConv.inc.
193 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
194   if (Flag == 1)
195     return CC_PPC32_SVR4;
196   else if (Flag == 2)
197     return CC_PPC32_SVR4_ByVal;
198   else if (Flag == 3)
199     return CC_PPC32_SVR4_VarArg;
200   else
201     return RetCC_PPC;
202 }
203
204 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
205   switch (Pred) {
206     // These are not representable with any single compare.
207     case CmpInst::FCMP_FALSE:
208     case CmpInst::FCMP_UEQ:
209     case CmpInst::FCMP_UGT:
210     case CmpInst::FCMP_UGE:
211     case CmpInst::FCMP_ULT:
212     case CmpInst::FCMP_ULE:
213     case CmpInst::FCMP_UNE:
214     case CmpInst::FCMP_TRUE:
215     default:
216       return Optional<PPC::Predicate>();
217
218     case CmpInst::FCMP_OEQ:
219     case CmpInst::ICMP_EQ:
220       return PPC::PRED_EQ;
221
222     case CmpInst::FCMP_OGT:
223     case CmpInst::ICMP_UGT:
224     case CmpInst::ICMP_SGT:
225       return PPC::PRED_GT;
226
227     case CmpInst::FCMP_OGE:
228     case CmpInst::ICMP_UGE:
229     case CmpInst::ICMP_SGE:
230       return PPC::PRED_GE;
231
232     case CmpInst::FCMP_OLT:
233     case CmpInst::ICMP_ULT:
234     case CmpInst::ICMP_SLT:
235       return PPC::PRED_LT;
236
237     case CmpInst::FCMP_OLE:
238     case CmpInst::ICMP_ULE:
239     case CmpInst::ICMP_SLE:
240       return PPC::PRED_LE;
241
242     case CmpInst::FCMP_ONE:
243     case CmpInst::ICMP_NE:
244       return PPC::PRED_NE;
245
246     case CmpInst::FCMP_ORD:
247       return PPC::PRED_NU;
248
249     case CmpInst::FCMP_UNO:
250       return PPC::PRED_UN;
251   }
252 }
253
254 // Determine whether the type Ty is simple enough to be handled by
255 // fast-isel, and return its equivalent machine type in VT.
256 // FIXME: Copied directly from ARM -- factor into base class?
257 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
258   EVT Evt = TLI.getValueType(Ty, true);
259
260   // Only handle simple types.
261   if (Evt == MVT::Other || !Evt.isSimple()) return false;
262   VT = Evt.getSimpleVT();
263
264   // Handle all legal types, i.e. a register that will directly hold this
265   // value.
266   return TLI.isTypeLegal(VT);
267 }
268
269 // Determine whether the type Ty is simple enough to be handled by
270 // fast-isel as a load target, and return its equivalent machine type in VT.
271 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
272   if (isTypeLegal(Ty, VT)) return true;
273
274   // If this is a type than can be sign or zero-extended to a basic operation
275   // go ahead and accept it now.
276   if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
277     return true;
278   }
279
280   return false;
281 }
282
283 // Given a value Obj, create an Address object Addr that represents its
284 // address.  Return false if we can't handle it.
285 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
286   const User *U = NULL;
287   unsigned Opcode = Instruction::UserOp1;
288   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
289     // Don't walk into other basic blocks unless the object is an alloca from
290     // another block, otherwise it may not have a virtual register assigned.
291     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
292         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
293       Opcode = I->getOpcode();
294       U = I;
295     }
296   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
297     Opcode = C->getOpcode();
298     U = C;
299   }
300
301   switch (Opcode) {
302     default:
303       break;
304     case Instruction::BitCast:
305       // Look through bitcasts.
306       return PPCComputeAddress(U->getOperand(0), Addr);
307     case Instruction::IntToPtr:
308       // Look past no-op inttoptrs.
309       if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
310         return PPCComputeAddress(U->getOperand(0), Addr);
311       break;
312     case Instruction::PtrToInt:
313       // Look past no-op ptrtoints.
314       if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
315         return PPCComputeAddress(U->getOperand(0), Addr);
316       break;
317     case Instruction::GetElementPtr: {
318       Address SavedAddr = Addr;
319       long TmpOffset = Addr.Offset;
320
321       // Iterate through the GEP folding the constants into offsets where
322       // we can.
323       gep_type_iterator GTI = gep_type_begin(U);
324       for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
325            II != IE; ++II, ++GTI) {
326         const Value *Op = *II;
327         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
328           const StructLayout *SL = DL.getStructLayout(STy);
329           unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
330           TmpOffset += SL->getElementOffset(Idx);
331         } else {
332           uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
333           for (;;) {
334             if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
335               // Constant-offset addressing.
336               TmpOffset += CI->getSExtValue() * S;
337               break;
338             }
339             if (canFoldAddIntoGEP(U, Op)) {
340               // A compatible add with a constant operand. Fold the constant.
341               ConstantInt *CI =
342               cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
343               TmpOffset += CI->getSExtValue() * S;
344               // Iterate on the other operand.
345               Op = cast<AddOperator>(Op)->getOperand(0);
346               continue;
347             }
348             // Unsupported
349             goto unsupported_gep;
350           }
351         }
352       }
353
354       // Try to grab the base operand now.
355       Addr.Offset = TmpOffset;
356       if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
357
358       // We failed, restore everything and try the other options.
359       Addr = SavedAddr;
360
361       unsupported_gep:
362       break;
363     }
364     case Instruction::Alloca: {
365       const AllocaInst *AI = cast<AllocaInst>(Obj);
366       DenseMap<const AllocaInst*, int>::iterator SI =
367         FuncInfo.StaticAllocaMap.find(AI);
368       if (SI != FuncInfo.StaticAllocaMap.end()) {
369         Addr.BaseType = Address::FrameIndexBase;
370         Addr.Base.FI = SI->second;
371         return true;
372       }
373       break;
374     }
375   }
376
377   // FIXME: References to parameters fall through to the behavior
378   // below.  They should be able to reference a frame index since
379   // they are stored to the stack, so we can get "ld rx, offset(r1)"
380   // instead of "addi ry, r1, offset / ld rx, 0(ry)".  Obj will
381   // just contain the parameter.  Try to handle this with a FI.
382
383   // Try to get this in a register if nothing else has worked.
384   if (Addr.Base.Reg == 0)
385     Addr.Base.Reg = getRegForValue(Obj);
386
387   // Prevent assignment of base register to X0, which is inappropriate
388   // for loads and stores alike.
389   if (Addr.Base.Reg != 0)
390     MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
391
392   return Addr.Base.Reg != 0;
393 }
394
395 // Fix up some addresses that can't be used directly.  For example, if
396 // an offset won't fit in an instruction field, we may need to move it
397 // into an index register.
398 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
399                                      unsigned &IndexReg) {
400
401   // Check whether the offset fits in the instruction field.
402   if (!isInt<16>(Addr.Offset))
403     UseOffset = false;
404
405   // If this is a stack pointer and the offset needs to be simplified then
406   // put the alloca address into a register, set the base type back to
407   // register and continue. This should almost never happen.
408   if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
409     unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
410     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
411             ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
412     Addr.Base.Reg = ResultReg;
413     Addr.BaseType = Address::RegBase;
414   }
415
416   if (!UseOffset) {
417     IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
418                              : Type::getInt64Ty(*Context));
419     const ConstantInt *Offset =
420       ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
421     IndexReg = PPCMaterializeInt(Offset, MVT::i64);
422     assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
423   }
424 }
425
426 // Emit a load instruction if possible, returning true if we succeeded,
427 // otherwise false.  See commentary below for how the register class of
428 // the load is determined. 
429 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
430                               const TargetRegisterClass *RC,
431                               bool IsZExt, unsigned FP64LoadOpc) {
432   unsigned Opc;
433   bool UseOffset = true;
434
435   // If ResultReg is given, it determines the register class of the load.
436   // Otherwise, RC is the register class to use.  If the result of the
437   // load isn't anticipated in this block, both may be zero, in which
438   // case we must make a conservative guess.  In particular, don't assign
439   // R0 or X0 to the result register, as the result may be used in a load,
440   // store, add-immediate, or isel that won't permit this.  (Though
441   // perhaps the spill and reload of live-exit values would handle this?)
442   const TargetRegisterClass *UseRC =
443     (ResultReg ? MRI.getRegClass(ResultReg) :
444      (RC ? RC :
445       (VT == MVT::f64 ? &PPC::F8RCRegClass :
446        (VT == MVT::f32 ? &PPC::F4RCRegClass :
447         (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
448          &PPC::GPRC_and_GPRC_NOR0RegClass)))));
449
450   bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
451
452   switch (VT.SimpleTy) {
453     default: // e.g., vector types not handled
454       return false;
455     case MVT::i8:
456       Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
457       break;
458     case MVT::i16:
459       Opc = (IsZExt ?
460              (Is32BitInt ? PPC::LHZ : PPC::LHZ8) : 
461              (Is32BitInt ? PPC::LHA : PPC::LHA8));
462       break;
463     case MVT::i32:
464       Opc = (IsZExt ? 
465              (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
466              (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
467       if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
468         UseOffset = false;
469       break;
470     case MVT::i64:
471       Opc = PPC::LD;
472       assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) && 
473              "64-bit load with 32-bit target??");
474       UseOffset = ((Addr.Offset & 3) == 0);
475       break;
476     case MVT::f32:
477       Opc = PPC::LFS;
478       break;
479     case MVT::f64:
480       Opc = FP64LoadOpc;
481       break;
482   }
483
484   // If necessary, materialize the offset into a register and use
485   // the indexed form.  Also handle stack pointers with special needs.
486   unsigned IndexReg = 0;
487   PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
488   if (ResultReg == 0)
489     ResultReg = createResultReg(UseRC);
490
491   // Note: If we still have a frame index here, we know the offset is
492   // in range, as otherwise PPCSimplifyAddress would have converted it
493   // into a RegBase.
494   if (Addr.BaseType == Address::FrameIndexBase) {
495
496     MachineMemOperand *MMO =
497       FuncInfo.MF->getMachineMemOperand(
498         MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
499         MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
500         MFI.getObjectAlignment(Addr.Base.FI));
501
502     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
503       .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
504
505   // Base reg with offset in range.
506   } else if (UseOffset) {
507
508     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
509       .addImm(Addr.Offset).addReg(Addr.Base.Reg);
510
511   // Indexed form.
512   } else {
513     // Get the RR opcode corresponding to the RI one.  FIXME: It would be
514     // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
515     // is hard to get at.
516     switch (Opc) {
517       default:        llvm_unreachable("Unexpected opcode!");
518       case PPC::LBZ:    Opc = PPC::LBZX;    break;
519       case PPC::LBZ8:   Opc = PPC::LBZX8;   break;
520       case PPC::LHZ:    Opc = PPC::LHZX;    break;
521       case PPC::LHZ8:   Opc = PPC::LHZX8;   break;
522       case PPC::LHA:    Opc = PPC::LHAX;    break;
523       case PPC::LHA8:   Opc = PPC::LHAX8;   break;
524       case PPC::LWZ:    Opc = PPC::LWZX;    break;
525       case PPC::LWZ8:   Opc = PPC::LWZX8;   break;
526       case PPC::LWA:    Opc = PPC::LWAX;    break;
527       case PPC::LWA_32: Opc = PPC::LWAX_32; break;
528       case PPC::LD:     Opc = PPC::LDX;     break;
529       case PPC::LFS:    Opc = PPC::LFSX;    break;
530       case PPC::LFD:    Opc = PPC::LFDX;    break;
531     }
532     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
533       .addReg(Addr.Base.Reg).addReg(IndexReg);
534   }
535
536   return true;
537 }
538
539 // Attempt to fast-select a load instruction.
540 bool PPCFastISel::SelectLoad(const Instruction *I) {
541   // FIXME: No atomic loads are supported.
542   if (cast<LoadInst>(I)->isAtomic())
543     return false;
544
545   // Verify we have a legal type before going any further.
546   MVT VT;
547   if (!isLoadTypeLegal(I->getType(), VT))
548     return false;
549
550   // See if we can handle this address.
551   Address Addr;
552   if (!PPCComputeAddress(I->getOperand(0), Addr))
553     return false;
554
555   // Look at the currently assigned register for this instruction
556   // to determine the required register class.  This is necessary
557   // to constrain RA from using R0/X0 when this is not legal.
558   unsigned AssignedReg = FuncInfo.ValueMap[I];
559   const TargetRegisterClass *RC =
560     AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
561
562   unsigned ResultReg = 0;
563   if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
564     return false;
565   UpdateValueMap(I, ResultReg);
566   return true;
567 }
568
569 // Emit a store instruction to store SrcReg at Addr.
570 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
571   assert(SrcReg && "Nothing to store!");
572   unsigned Opc;
573   bool UseOffset = true;
574
575   const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
576   bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
577
578   switch (VT.SimpleTy) {
579     default: // e.g., vector types not handled
580       return false;
581     case MVT::i8:
582       Opc = Is32BitInt ? PPC::STB : PPC::STB8;
583       break;
584     case MVT::i16:
585       Opc = Is32BitInt ? PPC::STH : PPC::STH8;
586       break;
587     case MVT::i32:
588       assert(Is32BitInt && "Not GPRC for i32??");
589       Opc = PPC::STW;
590       break;
591     case MVT::i64:
592       Opc = PPC::STD;
593       UseOffset = ((Addr.Offset & 3) == 0);
594       break;
595     case MVT::f32:
596       Opc = PPC::STFS;
597       break;
598     case MVT::f64:
599       Opc = PPC::STFD;
600       break;
601   }
602
603   // If necessary, materialize the offset into a register and use
604   // the indexed form.  Also handle stack pointers with special needs.
605   unsigned IndexReg = 0;
606   PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
607
608   // Note: If we still have a frame index here, we know the offset is
609   // in range, as otherwise PPCSimplifyAddress would have converted it
610   // into a RegBase.
611   if (Addr.BaseType == Address::FrameIndexBase) {
612     MachineMemOperand *MMO =
613       FuncInfo.MF->getMachineMemOperand(
614         MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
615         MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
616         MFI.getObjectAlignment(Addr.Base.FI));
617
618     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
619         .addReg(SrcReg)
620         .addImm(Addr.Offset)
621         .addFrameIndex(Addr.Base.FI)
622         .addMemOperand(MMO);
623
624   // Base reg with offset in range.
625   } else if (UseOffset)
626     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
627       .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
628
629   // Indexed form.
630   else {
631     // Get the RR opcode corresponding to the RI one.  FIXME: It would be
632     // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
633     // is hard to get at.
634     switch (Opc) {
635       default:        llvm_unreachable("Unexpected opcode!");
636       case PPC::STB:  Opc = PPC::STBX;  break;
637       case PPC::STH : Opc = PPC::STHX;  break;
638       case PPC::STW : Opc = PPC::STWX;  break;
639       case PPC::STB8: Opc = PPC::STBX8; break;
640       case PPC::STH8: Opc = PPC::STHX8; break;
641       case PPC::STW8: Opc = PPC::STWX8; break;
642       case PPC::STD:  Opc = PPC::STDX;  break;
643       case PPC::STFS: Opc = PPC::STFSX; break;
644       case PPC::STFD: Opc = PPC::STFDX; break;
645     }
646     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
647       .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
648   }
649
650   return true;
651 }
652
653 // Attempt to fast-select a store instruction.
654 bool PPCFastISel::SelectStore(const Instruction *I) {
655   Value *Op0 = I->getOperand(0);
656   unsigned SrcReg = 0;
657
658   // FIXME: No atomics loads are supported.
659   if (cast<StoreInst>(I)->isAtomic())
660     return false;
661
662   // Verify we have a legal type before going any further.
663   MVT VT;
664   if (!isLoadTypeLegal(Op0->getType(), VT))
665     return false;
666
667   // Get the value to be stored into a register.
668   SrcReg = getRegForValue(Op0);
669   if (SrcReg == 0)
670     return false;
671
672   // See if we can handle this address.
673   Address Addr;
674   if (!PPCComputeAddress(I->getOperand(1), Addr))
675     return false;
676
677   if (!PPCEmitStore(VT, SrcReg, Addr))
678     return false;
679
680   return true;
681 }
682
683 // Attempt to fast-select a branch instruction.
684 bool PPCFastISel::SelectBranch(const Instruction *I) {
685   const BranchInst *BI = cast<BranchInst>(I);
686   MachineBasicBlock *BrBB = FuncInfo.MBB;
687   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
688   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
689
690   // For now, just try the simplest case where it's fed by a compare.
691   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
692     Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
693     if (!OptPPCPred)
694       return false;
695
696     PPC::Predicate PPCPred = OptPPCPred.getValue();
697
698     // Take advantage of fall-through opportunities.
699     if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
700       std::swap(TBB, FBB);
701       PPCPred = PPC::InvertPredicate(PPCPred);
702     }
703
704     unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
705
706     if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
707                     CondReg))
708       return false;
709
710     BuildMI(*BrBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCC))
711       .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
712     FastEmitBranch(FBB, DbgLoc);
713     FuncInfo.MBB->addSuccessor(TBB);
714     return true;
715
716   } else if (const ConstantInt *CI =
717              dyn_cast<ConstantInt>(BI->getCondition())) {
718     uint64_t Imm = CI->getZExtValue();
719     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
720     FastEmitBranch(Target, DbgLoc);
721     return true;
722   }
723
724   // FIXME: ARM looks for a case where the block containing the compare
725   // has been split from the block containing the branch.  If this happens,
726   // there is a vreg available containing the result of the compare.  I'm
727   // not sure we can do much, as we've lost the predicate information with
728   // the compare instruction -- we have a 4-bit CR but don't know which bit
729   // to test here.
730   return false;
731 }
732
733 // Attempt to emit a compare of the two source values.  Signed and unsigned
734 // comparisons are supported.  Return false if we can't handle it.
735 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
736                              bool IsZExt, unsigned DestReg) {
737   Type *Ty = SrcValue1->getType();
738   EVT SrcEVT = TLI.getValueType(Ty, true);
739   if (!SrcEVT.isSimple())
740     return false;
741   MVT SrcVT = SrcEVT.getSimpleVT();
742
743   if (SrcVT == MVT::i1 && PPCSubTarget.useCRBits())
744     return false;
745
746   // See if operand 2 is an immediate encodeable in the compare.
747   // FIXME: Operands are not in canonical order at -O0, so an immediate
748   // operand in position 1 is a lost opportunity for now.  We are
749   // similar to ARM in this regard.
750   long Imm = 0;
751   bool UseImm = false;
752
753   // Only 16-bit integer constants can be represented in compares for 
754   // PowerPC.  Others will be materialized into a register.
755   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
756     if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
757         SrcVT == MVT::i8 || SrcVT == MVT::i1) {
758       const APInt &CIVal = ConstInt->getValue();
759       Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
760       if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
761         UseImm = true;
762     }
763   }
764
765   unsigned CmpOpc;
766   bool NeedsExt = false;
767   switch (SrcVT.SimpleTy) {
768     default: return false;
769     case MVT::f32:
770       CmpOpc = PPC::FCMPUS;
771       break;
772     case MVT::f64:
773       CmpOpc = PPC::FCMPUD;
774       break;
775     case MVT::i1:
776     case MVT::i8:
777     case MVT::i16:
778       NeedsExt = true;
779       // Intentional fall-through.
780     case MVT::i32:
781       if (!UseImm)
782         CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
783       else
784         CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
785       break;
786     case MVT::i64:
787       if (!UseImm)
788         CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
789       else
790         CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
791       break;
792   }
793
794   unsigned SrcReg1 = getRegForValue(SrcValue1);
795   if (SrcReg1 == 0)
796     return false;
797
798   unsigned SrcReg2 = 0;
799   if (!UseImm) {
800     SrcReg2 = getRegForValue(SrcValue2);
801     if (SrcReg2 == 0)
802       return false;
803   }
804
805   if (NeedsExt) {
806     unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
807     if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
808       return false;
809     SrcReg1 = ExtReg;
810
811     if (!UseImm) {
812       unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
813       if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
814         return false;
815       SrcReg2 = ExtReg;
816     }
817   }
818
819   if (!UseImm)
820     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
821       .addReg(SrcReg1).addReg(SrcReg2);
822   else
823     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
824       .addReg(SrcReg1).addImm(Imm);
825
826   return true;
827 }
828
829 // Attempt to fast-select a floating-point extend instruction.
830 bool PPCFastISel::SelectFPExt(const Instruction *I) {
831   Value *Src  = I->getOperand(0);
832   EVT SrcVT  = TLI.getValueType(Src->getType(), true);
833   EVT DestVT = TLI.getValueType(I->getType(), true);
834
835   if (SrcVT != MVT::f32 || DestVT != MVT::f64)
836     return false;
837
838   unsigned SrcReg = getRegForValue(Src);
839   if (!SrcReg)
840     return false;
841
842   // No code is generated for a FP extend.
843   UpdateValueMap(I, SrcReg);
844   return true;
845 }
846
847 // Attempt to fast-select a floating-point truncate instruction.
848 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
849   Value *Src  = I->getOperand(0);
850   EVT SrcVT  = TLI.getValueType(Src->getType(), true);
851   EVT DestVT = TLI.getValueType(I->getType(), true);
852
853   if (SrcVT != MVT::f64 || DestVT != MVT::f32)
854     return false;
855
856   unsigned SrcReg = getRegForValue(Src);
857   if (!SrcReg)
858     return false;
859
860   // Round the result to single precision.
861   unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
862   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP), DestReg)
863     .addReg(SrcReg);
864
865   UpdateValueMap(I, DestReg);
866   return true;
867 }
868
869 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
870 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
871 // those should be used instead of moving via a stack slot when the
872 // subtarget permits.
873 // FIXME: The code here is sloppy for the 4-byte case.  Can use a 4-byte
874 // stack slot and 4-byte store/load sequence.  Or just sext the 4-byte
875 // case to 8 bytes which produces tighter code but wastes stack space.
876 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
877                                      bool IsSigned) {
878
879   // If necessary, extend 32-bit int to 64-bit.
880   if (SrcVT == MVT::i32) {
881     unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
882     if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
883       return 0;
884     SrcReg = TmpReg;
885   }
886
887   // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
888   Address Addr;
889   Addr.BaseType = Address::FrameIndexBase;
890   Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
891
892   // Store the value from the GPR.
893   if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
894     return 0;
895
896   // Load the integer value into an FPR.  The kind of load used depends
897   // on a number of conditions.
898   unsigned LoadOpc = PPC::LFD;
899
900   if (SrcVT == MVT::i32) {
901     if (!IsSigned) {
902       LoadOpc = PPC::LFIWZX;
903       Addr.Offset = 4;
904     } else if (PPCSubTarget.hasLFIWAX()) {
905       LoadOpc = PPC::LFIWAX;
906       Addr.Offset = 4;
907     }
908   }
909
910   const TargetRegisterClass *RC = &PPC::F8RCRegClass;
911   unsigned ResultReg = 0;
912   if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
913     return 0;
914
915   return ResultReg;
916 }
917
918 // Attempt to fast-select an integer-to-floating-point conversion.
919 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
920   MVT DstVT;
921   Type *DstTy = I->getType();
922   if (!isTypeLegal(DstTy, DstVT))
923     return false;
924
925   if (DstVT != MVT::f32 && DstVT != MVT::f64)
926     return false;
927
928   Value *Src = I->getOperand(0);
929   EVT SrcEVT = TLI.getValueType(Src->getType(), true);
930   if (!SrcEVT.isSimple())
931     return false;
932
933   MVT SrcVT = SrcEVT.getSimpleVT();
934
935   if (SrcVT != MVT::i8  && SrcVT != MVT::i16 &&
936       SrcVT != MVT::i32 && SrcVT != MVT::i64)
937     return false;
938
939   unsigned SrcReg = getRegForValue(Src);
940   if (SrcReg == 0)
941     return false;
942
943   // We can only lower an unsigned convert if we have the newer
944   // floating-point conversion operations.
945   if (!IsSigned && !PPCSubTarget.hasFPCVT())
946     return false;
947
948   // FIXME: For now we require the newer floating-point conversion operations
949   // (which are present only on P7 and A2 server models) when converting
950   // to single-precision float.  Otherwise we have to generate a lot of
951   // fiddly code to avoid double rounding.  If necessary, the fiddly code
952   // can be found in PPCTargetLowering::LowerINT_TO_FP().
953   if (DstVT == MVT::f32 && !PPCSubTarget.hasFPCVT())
954     return false;
955
956   // Extend the input if necessary.
957   if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
958     unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
959     if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
960       return false;
961     SrcVT = MVT::i64;
962     SrcReg = TmpReg;
963   }
964
965   // Move the integer value to an FPR.
966   unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
967   if (FPReg == 0)
968     return false;
969
970   // Determine the opcode for the conversion.
971   const TargetRegisterClass *RC = &PPC::F8RCRegClass;
972   unsigned DestReg = createResultReg(RC);
973   unsigned Opc;
974
975   if (DstVT == MVT::f32)
976     Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
977   else
978     Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
979
980   // Generate the convert.
981   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
982     .addReg(FPReg);
983
984   UpdateValueMap(I, DestReg);
985   return true;
986 }
987
988 // Move the floating-point value in SrcReg into an integer destination
989 // register, and return the register (or zero if we can't handle it).
990 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
991 // those should be used instead of moving via a stack slot when the
992 // subtarget permits.
993 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
994                                       unsigned SrcReg, bool IsSigned) {
995   // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
996   // Note that if have STFIWX available, we could use a 4-byte stack
997   // slot for i32, but this being fast-isel we'll just go with the
998   // easiest code gen possible.
999   Address Addr;
1000   Addr.BaseType = Address::FrameIndexBase;
1001   Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
1002
1003   // Store the value from the FPR.
1004   if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
1005     return 0;
1006
1007   // Reload it into a GPR.  If we want an i32, modify the address
1008   // to have a 4-byte offset so we load from the right place.
1009   if (VT == MVT::i32)
1010     Addr.Offset = 4;
1011
1012   // Look at the currently assigned register for this instruction
1013   // to determine the required register class.
1014   unsigned AssignedReg = FuncInfo.ValueMap[I];
1015   const TargetRegisterClass *RC =
1016     AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
1017
1018   unsigned ResultReg = 0;
1019   if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1020     return 0;
1021
1022   return ResultReg;
1023 }
1024
1025 // Attempt to fast-select a floating-point-to-integer conversion.
1026 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1027   MVT DstVT, SrcVT;
1028   Type *DstTy = I->getType();
1029   if (!isTypeLegal(DstTy, DstVT))
1030     return false;
1031
1032   if (DstVT != MVT::i32 && DstVT != MVT::i64)
1033     return false;
1034
1035   Value *Src = I->getOperand(0);
1036   Type *SrcTy = Src->getType();
1037   if (!isTypeLegal(SrcTy, SrcVT))
1038     return false;
1039
1040   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1041     return false;
1042
1043   unsigned SrcReg = getRegForValue(Src);
1044   if (SrcReg == 0)
1045     return false;
1046
1047   // Convert f32 to f64 if necessary.  This is just a meaningless copy
1048   // to get the register class right.  COPY_TO_REGCLASS is needed since
1049   // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1050   const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1051   if (InRC == &PPC::F4RCRegClass) {
1052     unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1053     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1054             TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1055       .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1056     SrcReg = TmpReg;
1057   }
1058
1059   // Determine the opcode for the conversion, which takes place
1060   // entirely within FPRs.
1061   unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1062   unsigned Opc;
1063
1064   if (DstVT == MVT::i32)
1065     if (IsSigned)
1066       Opc = PPC::FCTIWZ;
1067     else
1068       Opc = PPCSubTarget.hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1069   else
1070     Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1071
1072   // Generate the convert.
1073   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1074     .addReg(SrcReg);
1075
1076   // Now move the integer value from a float register to an integer register.
1077   unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1078   if (IntReg == 0)
1079     return false;
1080
1081   UpdateValueMap(I, IntReg);
1082   return true;
1083 }
1084
1085 // Attempt to fast-select a binary integer operation that isn't already
1086 // handled automatically.
1087 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1088   EVT DestVT  = TLI.getValueType(I->getType(), true);
1089
1090   // We can get here in the case when we have a binary operation on a non-legal
1091   // type and the target independent selector doesn't know how to handle it.
1092   if (DestVT != MVT::i16 && DestVT != MVT::i8)
1093     return false;
1094
1095   // Look at the currently assigned register for this instruction
1096   // to determine the required register class.  If there is no register,
1097   // make a conservative choice (don't assign R0).
1098   unsigned AssignedReg = FuncInfo.ValueMap[I];
1099   const TargetRegisterClass *RC =
1100     (AssignedReg ? MRI.getRegClass(AssignedReg) :
1101      &PPC::GPRC_and_GPRC_NOR0RegClass);
1102   bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1103
1104   unsigned Opc;
1105   switch (ISDOpcode) {
1106     default: return false;
1107     case ISD::ADD:
1108       Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1109       break;
1110     case ISD::OR:
1111       Opc = IsGPRC ? PPC::OR : PPC::OR8;
1112       break;
1113     case ISD::SUB:
1114       Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1115       break;
1116   }
1117
1118   unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1119   unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1120   if (SrcReg1 == 0) return false;
1121
1122   // Handle case of small immediate operand.
1123   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1124     const APInt &CIVal = ConstInt->getValue();
1125     int Imm = (int)CIVal.getSExtValue();
1126     bool UseImm = true;
1127     if (isInt<16>(Imm)) {
1128       switch (Opc) {
1129         default:
1130           llvm_unreachable("Missing case!");
1131         case PPC::ADD4:
1132           Opc = PPC::ADDI;
1133           MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1134           break;
1135         case PPC::ADD8:
1136           Opc = PPC::ADDI8;
1137           MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1138           break;
1139         case PPC::OR:
1140           Opc = PPC::ORI;
1141           break;
1142         case PPC::OR8:
1143           Opc = PPC::ORI8;
1144           break;
1145         case PPC::SUBF:
1146           if (Imm == -32768)
1147             UseImm = false;
1148           else {
1149             Opc = PPC::ADDI;
1150             MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1151             Imm = -Imm;
1152           }
1153           break;
1154         case PPC::SUBF8:
1155           if (Imm == -32768)
1156             UseImm = false;
1157           else {
1158             Opc = PPC::ADDI8;
1159             MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1160             Imm = -Imm;
1161           }
1162           break;
1163       }
1164
1165       if (UseImm) {
1166         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1167                 ResultReg)
1168             .addReg(SrcReg1)
1169             .addImm(Imm);
1170         UpdateValueMap(I, ResultReg);
1171         return true;
1172       }
1173     }
1174   }
1175
1176   // Reg-reg case.
1177   unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1178   if (SrcReg2 == 0) return false;
1179
1180   // Reverse operands for subtract-from.
1181   if (ISDOpcode == ISD::SUB)
1182     std::swap(SrcReg1, SrcReg2);
1183
1184   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1185     .addReg(SrcReg1).addReg(SrcReg2);
1186   UpdateValueMap(I, ResultReg);
1187   return true;
1188 }
1189
1190 // Handle arguments to a call that we're attempting to fast-select.
1191 // Return false if the arguments are too complex for us at the moment.
1192 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1193                                   SmallVectorImpl<unsigned> &ArgRegs,
1194                                   SmallVectorImpl<MVT> &ArgVTs,
1195                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1196                                   SmallVectorImpl<unsigned> &RegArgs,
1197                                   CallingConv::ID CC,
1198                                   unsigned &NumBytes,
1199                                   bool IsVarArg) {
1200   SmallVector<CCValAssign, 16> ArgLocs;
1201   CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, ArgLocs, *Context);
1202   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1203
1204   // Bail out if we can't handle any of the arguments.
1205   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1206     CCValAssign &VA = ArgLocs[I];
1207     MVT ArgVT = ArgVTs[VA.getValNo()];
1208
1209     // Skip vector arguments for now, as well as long double and
1210     // uint128_t, and anything that isn't passed in a register.
1211     if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 || ArgVT == MVT::i1 ||
1212         !VA.isRegLoc() || VA.needsCustom())
1213       return false;
1214
1215     // Skip bit-converted arguments for now.
1216     if (VA.getLocInfo() == CCValAssign::BCvt)
1217       return false;
1218   }
1219
1220   // Get a count of how many bytes are to be pushed onto the stack.
1221   NumBytes = CCInfo.getNextStackOffset();
1222
1223   // Issue CALLSEQ_START.
1224   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1225           TII.get(TII.getCallFrameSetupOpcode()))
1226     .addImm(NumBytes);
1227
1228   // Prepare to assign register arguments.  Every argument uses up a
1229   // GPR protocol register even if it's passed in a floating-point
1230   // register.
1231   unsigned NextGPR = PPC::X3;
1232   unsigned NextFPR = PPC::F1;
1233
1234   // Process arguments.
1235   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1236     CCValAssign &VA = ArgLocs[I];
1237     unsigned Arg = ArgRegs[VA.getValNo()];
1238     MVT ArgVT = ArgVTs[VA.getValNo()];
1239
1240     // Handle argument promotion and bitcasts.
1241     switch (VA.getLocInfo()) {
1242       default:
1243         llvm_unreachable("Unknown loc info!");
1244       case CCValAssign::Full:
1245         break;
1246       case CCValAssign::SExt: {
1247         MVT DestVT = VA.getLocVT();
1248         const TargetRegisterClass *RC =
1249           (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1250         unsigned TmpReg = createResultReg(RC);
1251         if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1252           llvm_unreachable("Failed to emit a sext!");
1253         ArgVT = DestVT;
1254         Arg = TmpReg;
1255         break;
1256       }
1257       case CCValAssign::AExt:
1258       case CCValAssign::ZExt: {
1259         MVT DestVT = VA.getLocVT();
1260         const TargetRegisterClass *RC =
1261           (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1262         unsigned TmpReg = createResultReg(RC);
1263         if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1264           llvm_unreachable("Failed to emit a zext!");
1265         ArgVT = DestVT;
1266         Arg = TmpReg;
1267         break;
1268       }
1269       case CCValAssign::BCvt: {
1270         // FIXME: Not yet handled.
1271         llvm_unreachable("Should have bailed before getting here!");
1272         break;
1273       }
1274     }
1275
1276     // Copy this argument to the appropriate register.
1277     unsigned ArgReg;
1278     if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1279       ArgReg = NextFPR++;
1280       ++NextGPR;
1281     } else
1282       ArgReg = NextGPR++;
1283
1284     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1285             TII.get(TargetOpcode::COPY), ArgReg).addReg(Arg);
1286     RegArgs.push_back(ArgReg);
1287   }
1288
1289   return true;
1290 }
1291
1292 // For a call that we've determined we can fast-select, finish the
1293 // call sequence and generate a copy to obtain the return value (if any).
1294 void PPCFastISel::finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1295                              const Instruction *I, CallingConv::ID CC,
1296                              unsigned &NumBytes, bool IsVarArg) {
1297   // Issue CallSEQ_END.
1298   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1299           TII.get(TII.getCallFrameDestroyOpcode()))
1300     .addImm(NumBytes).addImm(0);
1301
1302   // Next, generate a copy to obtain the return value.
1303   // FIXME: No multi-register return values yet, though I don't foresee
1304   // any real difficulties there.
1305   if (RetVT != MVT::isVoid) {
1306     SmallVector<CCValAssign, 16> RVLocs;
1307     CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1308     CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1309     CCValAssign &VA = RVLocs[0];
1310     assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1311     assert(VA.isRegLoc() && "Can only return in registers!");
1312
1313     MVT DestVT = VA.getValVT();
1314     MVT CopyVT = DestVT;
1315
1316     // Ints smaller than a register still arrive in a full 64-bit
1317     // register, so make sure we recognize this.
1318     if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1319       CopyVT = MVT::i64;
1320
1321     unsigned SourcePhysReg = VA.getLocReg();
1322     unsigned ResultReg = 0;
1323
1324     if (RetVT == CopyVT) {
1325       const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1326       ResultReg = createResultReg(CpyRC);
1327
1328       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1329               TII.get(TargetOpcode::COPY), ResultReg)
1330         .addReg(SourcePhysReg);
1331
1332     // If necessary, round the floating result to single precision.
1333     } else if (CopyVT == MVT::f64) {
1334       ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1335       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP),
1336               ResultReg).addReg(SourcePhysReg);
1337
1338     // If only the low half of a general register is needed, generate
1339     // a GPRC copy instead of a G8RC copy.  (EXTRACT_SUBREG can't be
1340     // used along the fast-isel path (not lowered), and downstream logic
1341     // also doesn't like a direct subreg copy on a physical reg.)
1342     } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1343       ResultReg = createResultReg(&PPC::GPRCRegClass);
1344       // Convert physical register from G8RC to GPRC.
1345       SourcePhysReg -= PPC::X0 - PPC::R0;
1346       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1347               TII.get(TargetOpcode::COPY), ResultReg)
1348         .addReg(SourcePhysReg);
1349     }
1350
1351     assert(ResultReg && "ResultReg unset!");
1352     UsedRegs.push_back(SourcePhysReg);
1353     UpdateValueMap(I, ResultReg);
1354   }
1355 }
1356
1357 // Attempt to fast-select a call instruction.
1358 bool PPCFastISel::SelectCall(const Instruction *I) {
1359   const CallInst *CI = cast<CallInst>(I);
1360   const Value *Callee = CI->getCalledValue();
1361
1362   // Can't handle inline asm.
1363   if (isa<InlineAsm>(Callee))
1364     return false;
1365
1366   // Allow SelectionDAG isel to handle tail calls.
1367   if (CI->isTailCall())
1368     return false;
1369
1370   // Obtain calling convention.
1371   ImmutableCallSite CS(CI);
1372   CallingConv::ID CC = CS.getCallingConv();
1373
1374   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1375   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1376   bool IsVarArg = FTy->isVarArg();
1377
1378   // Not ready for varargs yet.
1379   if (IsVarArg)
1380     return false;
1381
1382   // Handle simple calls for now, with legal return types and
1383   // those that can be extended.
1384   Type *RetTy = I->getType();
1385   MVT RetVT;
1386   if (RetTy->isVoidTy())
1387     RetVT = MVT::isVoid;
1388   else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1389            RetVT != MVT::i8)
1390     return false;
1391
1392   // FIXME: No multi-register return values yet.
1393   if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1394       RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1395       RetVT != MVT::f64) {
1396     SmallVector<CCValAssign, 16> RVLocs;
1397     CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1398     CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1399     if (RVLocs.size() > 1)
1400       return false;
1401   }
1402
1403   // Bail early if more than 8 arguments, as we only currently
1404   // handle arguments passed in registers.
1405   unsigned NumArgs = CS.arg_size();
1406   if (NumArgs > 8)
1407     return false;
1408
1409   // Set up the argument vectors.
1410   SmallVector<Value*, 8> Args;
1411   SmallVector<unsigned, 8> ArgRegs;
1412   SmallVector<MVT, 8> ArgVTs;
1413   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1414
1415   Args.reserve(NumArgs);
1416   ArgRegs.reserve(NumArgs);
1417   ArgVTs.reserve(NumArgs);
1418   ArgFlags.reserve(NumArgs);
1419
1420   for (ImmutableCallSite::arg_iterator II = CS.arg_begin(), IE = CS.arg_end();
1421        II != IE; ++II) {
1422     // FIXME: ARM does something for intrinsic calls here, check into that.
1423
1424     unsigned AttrIdx = II - CS.arg_begin() + 1;
1425     
1426     // Only handle easy calls for now.  It would be reasonably easy
1427     // to handle <= 8-byte structures passed ByVal in registers, but we
1428     // have to ensure they are right-justified in the register.
1429     if (CS.paramHasAttr(AttrIdx, Attribute::InReg) ||
1430         CS.paramHasAttr(AttrIdx, Attribute::StructRet) ||
1431         CS.paramHasAttr(AttrIdx, Attribute::Nest) ||
1432         CS.paramHasAttr(AttrIdx, Attribute::ByVal))
1433       return false;
1434
1435     ISD::ArgFlagsTy Flags;
1436     if (CS.paramHasAttr(AttrIdx, Attribute::SExt))
1437       Flags.setSExt();
1438     if (CS.paramHasAttr(AttrIdx, Attribute::ZExt))
1439       Flags.setZExt();
1440
1441     Type *ArgTy = (*II)->getType();
1442     MVT ArgVT;
1443     if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1444       return false;
1445
1446     if (ArgVT.isVector())
1447       return false;
1448
1449     unsigned Arg = getRegForValue(*II);
1450     if (Arg == 0)
1451       return false;
1452
1453     unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
1454     Flags.setOrigAlign(OriginalAlignment);
1455
1456     Args.push_back(*II);
1457     ArgRegs.push_back(Arg);
1458     ArgVTs.push_back(ArgVT);
1459     ArgFlags.push_back(Flags);
1460   }
1461
1462   // Process the arguments.
1463   SmallVector<unsigned, 8> RegArgs;
1464   unsigned NumBytes;
1465
1466   if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1467                        RegArgs, CC, NumBytes, IsVarArg))
1468     return false;
1469
1470   // FIXME: No handling for function pointers yet.  This requires
1471   // implementing the function descriptor (OPD) setup.
1472   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1473   if (!GV)
1474     return false;
1475
1476   // Build direct call with NOP for TOC restore.
1477   // FIXME: We can and should optimize away the NOP for local calls.
1478   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1479                                     TII.get(PPC::BL8_NOP));
1480   // Add callee.
1481   MIB.addGlobalAddress(GV);
1482
1483   // Add implicit physical register uses to the call.
1484   for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1485     MIB.addReg(RegArgs[II], RegState::Implicit);
1486
1487   // Add a register mask with the call-preserved registers.  Proper
1488   // defs for return values will be added by setPhysRegsDeadExcept().
1489   MIB.addRegMask(TRI.getCallPreservedMask(CC));
1490
1491   // Finish off the call including any return values.
1492   SmallVector<unsigned, 4> UsedRegs;
1493   finishCall(RetVT, UsedRegs, I, CC, NumBytes, IsVarArg);
1494
1495   // Set all unused physregs defs as dead.
1496   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1497
1498   return true;
1499 }
1500
1501 // Attempt to fast-select a return instruction.
1502 bool PPCFastISel::SelectRet(const Instruction *I) {
1503
1504   if (!FuncInfo.CanLowerReturn)
1505     return false;
1506
1507   const ReturnInst *Ret = cast<ReturnInst>(I);
1508   const Function &F = *I->getParent()->getParent();
1509
1510   // Build a list of return value registers.
1511   SmallVector<unsigned, 4> RetRegs;
1512   CallingConv::ID CC = F.getCallingConv();
1513
1514   if (Ret->getNumOperands() > 0) {
1515     SmallVector<ISD::OutputArg, 4> Outs;
1516     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1517
1518     // Analyze operands of the call, assigning locations to each operand.
1519     SmallVector<CCValAssign, 16> ValLocs;
1520     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
1521     CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1522     const Value *RV = Ret->getOperand(0);
1523     
1524     // FIXME: Only one output register for now.
1525     if (ValLocs.size() > 1)
1526       return false;
1527
1528     // Special case for returning a constant integer of any size.
1529     // Materialize the constant as an i64 and copy it to the return
1530     // register.  This avoids an unnecessary extend or truncate.
1531     if (isa<ConstantInt>(*RV)) {
1532       const Constant *C = cast<Constant>(RV);
1533       unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
1534       unsigned RetReg = ValLocs[0].getLocReg();
1535       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1536               TII.get(TargetOpcode::COPY), RetReg).addReg(SrcReg);
1537       RetRegs.push_back(RetReg);
1538
1539     } else {
1540       unsigned Reg = getRegForValue(RV);
1541
1542       if (Reg == 0)
1543         return false;
1544
1545       // Copy the result values into the output registers.
1546       for (unsigned i = 0; i < ValLocs.size(); ++i) {
1547
1548         CCValAssign &VA = ValLocs[i];
1549         assert(VA.isRegLoc() && "Can only return in registers!");
1550         RetRegs.push_back(VA.getLocReg());
1551         unsigned SrcReg = Reg + VA.getValNo();
1552
1553         EVT RVEVT = TLI.getValueType(RV->getType());
1554         if (!RVEVT.isSimple())
1555           return false;
1556         MVT RVVT = RVEVT.getSimpleVT();
1557         MVT DestVT = VA.getLocVT();
1558
1559         if (RVVT != DestVT && RVVT != MVT::i8 &&
1560             RVVT != MVT::i16 && RVVT != MVT::i32)
1561           return false;
1562       
1563         if (RVVT != DestVT) {
1564           switch (VA.getLocInfo()) {
1565             default:
1566               llvm_unreachable("Unknown loc info!");
1567             case CCValAssign::Full:
1568               llvm_unreachable("Full value assign but types don't match?");
1569             case CCValAssign::AExt:
1570             case CCValAssign::ZExt: {
1571               const TargetRegisterClass *RC =
1572                 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1573               unsigned TmpReg = createResultReg(RC);
1574               if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1575                 return false;
1576               SrcReg = TmpReg;
1577               break;
1578             }
1579             case CCValAssign::SExt: {
1580               const TargetRegisterClass *RC =
1581                 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1582               unsigned TmpReg = createResultReg(RC);
1583               if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1584                 return false;
1585               SrcReg = TmpReg;
1586               break;
1587             }
1588           }
1589         }
1590
1591         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1592                 TII.get(TargetOpcode::COPY), RetRegs[i])
1593           .addReg(SrcReg);
1594       }
1595     }
1596   }
1597
1598   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1599                                     TII.get(PPC::BLR));
1600
1601   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1602     MIB.addReg(RetRegs[i], RegState::Implicit);
1603
1604   return true;
1605 }
1606
1607 // Attempt to emit an integer extend of SrcReg into DestReg.  Both
1608 // signed and zero extensions are supported.  Return false if we
1609 // can't handle it.
1610 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1611                                 unsigned DestReg, bool IsZExt) {
1612   if (DestVT != MVT::i32 && DestVT != MVT::i64)
1613     return false;
1614   if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1615     return false;
1616
1617   // Signed extensions use EXTSB, EXTSH, EXTSW.
1618   if (!IsZExt) {
1619     unsigned Opc;
1620     if (SrcVT == MVT::i8)
1621       Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1622     else if (SrcVT == MVT::i16)
1623       Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1624     else {
1625       assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1626       Opc = PPC::EXTSW_32_64;
1627     }
1628     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1629       .addReg(SrcReg);
1630
1631   // Unsigned 32-bit extensions use RLWINM.
1632   } else if (DestVT == MVT::i32) {
1633     unsigned MB;
1634     if (SrcVT == MVT::i8)
1635       MB = 24;
1636     else {
1637       assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1638       MB = 16;
1639     }
1640     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLWINM),
1641             DestReg)
1642       .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1643
1644   // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1645   } else {
1646     unsigned MB;
1647     if (SrcVT == MVT::i8)
1648       MB = 56;
1649     else if (SrcVT == MVT::i16)
1650       MB = 48;
1651     else
1652       MB = 32;
1653     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1654             TII.get(PPC::RLDICL_32_64), DestReg)
1655       .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1656   }
1657
1658   return true;
1659 }
1660
1661 // Attempt to fast-select an indirect branch instruction.
1662 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1663   unsigned AddrReg = getRegForValue(I->getOperand(0));
1664   if (AddrReg == 0)
1665     return false;
1666
1667   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::MTCTR8))
1668     .addReg(AddrReg);
1669   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCTR8));
1670
1671   const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1672   for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1673     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1674
1675   return true;
1676 }
1677
1678 // Attempt to fast-select an integer truncate instruction.
1679 bool PPCFastISel::SelectTrunc(const Instruction *I) {
1680   Value *Src  = I->getOperand(0);
1681   EVT SrcVT  = TLI.getValueType(Src->getType(), true);
1682   EVT DestVT = TLI.getValueType(I->getType(), true);
1683
1684   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16)
1685     return false;
1686
1687   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
1688     return false;
1689
1690   unsigned SrcReg = getRegForValue(Src);
1691   if (!SrcReg)
1692     return false;
1693
1694   // The only interesting case is when we need to switch register classes.
1695   if (SrcVT == MVT::i64) {
1696     unsigned ResultReg = createResultReg(&PPC::GPRCRegClass);
1697     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1698             TII.get(TargetOpcode::COPY),
1699             ResultReg).addReg(SrcReg, 0, PPC::sub_32);
1700     SrcReg = ResultReg;
1701   }
1702
1703   UpdateValueMap(I, SrcReg);
1704   return true;
1705 }
1706
1707 // Attempt to fast-select an integer extend instruction.
1708 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1709   Type *DestTy = I->getType();
1710   Value *Src = I->getOperand(0);
1711   Type *SrcTy = Src->getType();
1712
1713   bool IsZExt = isa<ZExtInst>(I);
1714   unsigned SrcReg = getRegForValue(Src);
1715   if (!SrcReg) return false;
1716
1717   EVT SrcEVT, DestEVT;
1718   SrcEVT = TLI.getValueType(SrcTy, true);
1719   DestEVT = TLI.getValueType(DestTy, true);
1720   if (!SrcEVT.isSimple())
1721     return false;
1722   if (!DestEVT.isSimple())
1723     return false;
1724
1725   MVT SrcVT = SrcEVT.getSimpleVT();
1726   MVT DestVT = DestEVT.getSimpleVT();
1727
1728   // If we know the register class needed for the result of this
1729   // instruction, use it.  Otherwise pick the register class of the
1730   // correct size that does not contain X0/R0, since we don't know
1731   // whether downstream uses permit that assignment.
1732   unsigned AssignedReg = FuncInfo.ValueMap[I];
1733   const TargetRegisterClass *RC =
1734     (AssignedReg ? MRI.getRegClass(AssignedReg) :
1735      (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1736       &PPC::GPRC_and_GPRC_NOR0RegClass));
1737   unsigned ResultReg = createResultReg(RC);
1738
1739   if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1740     return false;
1741
1742   UpdateValueMap(I, ResultReg);
1743   return true;
1744 }
1745
1746 // Attempt to fast-select an instruction that wasn't handled by
1747 // the table-generated machinery.
1748 bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
1749
1750   switch (I->getOpcode()) {
1751     case Instruction::Load:
1752       return SelectLoad(I);
1753     case Instruction::Store:
1754       return SelectStore(I);
1755     case Instruction::Br:
1756       return SelectBranch(I);
1757     case Instruction::IndirectBr:
1758       return SelectIndirectBr(I);
1759     case Instruction::FPExt:
1760       return SelectFPExt(I);
1761     case Instruction::FPTrunc:
1762       return SelectFPTrunc(I);
1763     case Instruction::SIToFP:
1764       return SelectIToFP(I, /*IsSigned*/ true);
1765     case Instruction::UIToFP:
1766       return SelectIToFP(I, /*IsSigned*/ false);
1767     case Instruction::FPToSI:
1768       return SelectFPToI(I, /*IsSigned*/ true);
1769     case Instruction::FPToUI:
1770       return SelectFPToI(I, /*IsSigned*/ false);
1771     case Instruction::Add:
1772       return SelectBinaryIntOp(I, ISD::ADD);
1773     case Instruction::Or:
1774       return SelectBinaryIntOp(I, ISD::OR);
1775     case Instruction::Sub:
1776       return SelectBinaryIntOp(I, ISD::SUB);
1777     case Instruction::Call:
1778       if (dyn_cast<IntrinsicInst>(I))
1779         return false;
1780       return SelectCall(I);
1781     case Instruction::Ret:
1782       return SelectRet(I);
1783     case Instruction::Trunc:
1784       return SelectTrunc(I);
1785     case Instruction::ZExt:
1786     case Instruction::SExt:
1787       return SelectIntExt(I);
1788     // Here add other flavors of Instruction::XXX that automated
1789     // cases don't catch.  For example, switches are terminators
1790     // that aren't yet handled.
1791     default:
1792       break;
1793   }
1794   return false;
1795 }
1796
1797 // Materialize a floating-point constant into a register, and return
1798 // the register number (or zero if we failed to handle it).
1799 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1800   // No plans to handle long double here.
1801   if (VT != MVT::f32 && VT != MVT::f64)
1802     return 0;
1803
1804   // All FP constants are loaded from the constant pool.
1805   unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
1806   assert(Align > 0 && "Unexpectedly missing alignment information!");
1807   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1808   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1809   CodeModel::Model CModel = TM.getCodeModel();
1810
1811   MachineMemOperand *MMO =
1812     FuncInfo.MF->getMachineMemOperand(
1813       MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1814       (VT == MVT::f32) ? 4 : 8, Align);
1815
1816   unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1817   unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1818
1819   // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1820   if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1821     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocCPT),
1822             TmpReg)
1823       .addConstantPoolIndex(Idx).addReg(PPC::X2);
1824     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1825       .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1826   } else {
1827     // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1828     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1829             TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1830     // But for large code model, we must generate a LDtocL followed
1831     // by the LF[SD].
1832     if (CModel == CodeModel::Large) {
1833       unsigned TmpReg2 = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1834       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1835               TmpReg2).addConstantPoolIndex(Idx).addReg(TmpReg);
1836       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1837         .addImm(0).addReg(TmpReg2);
1838     } else 
1839       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1840         .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1841         .addReg(TmpReg)
1842         .addMemOperand(MMO);
1843   }
1844
1845   return DestReg;
1846 }
1847
1848 // Materialize the address of a global value into a register, and return
1849 // the register number (or zero if we failed to handle it).
1850 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1851   assert(VT == MVT::i64 && "Non-address!");
1852   const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1853   unsigned DestReg = createResultReg(RC);
1854
1855   // Global values may be plain old object addresses, TLS object
1856   // addresses, constant pool entries, or jump tables.  How we generate
1857   // code for these may depend on small, medium, or large code model.
1858   CodeModel::Model CModel = TM.getCodeModel();
1859
1860   // FIXME: Jump tables are not yet required because fast-isel doesn't
1861   // handle switches; if that changes, we need them as well.  For now,
1862   // what follows assumes everything's a generic (or TLS) global address.
1863   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1864   if (!GVar) {
1865     // If GV is an alias, use the aliasee for determining thread-locality.
1866     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1867       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1868   }
1869
1870   // FIXME: We don't yet handle the complexity of TLS.
1871   bool IsTLS = GVar && GVar->isThreadLocal();
1872   if (IsTLS)
1873     return 0;
1874
1875   // For small code model, generate a simple TOC load.
1876   if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1877     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtoc),
1878             DestReg)
1879         .addGlobalAddress(GV)
1880         .addReg(PPC::X2);
1881   else {
1882     // If the address is an externally defined symbol, a symbol with
1883     // common or externally available linkage, a function address, or a
1884     // jump table address (not yet needed), or if we are generating code
1885     // for large code model, we generate:
1886     //       LDtocL(GV, ADDIStocHA(%X2, GV))
1887     // Otherwise we generate:
1888     //       ADDItocL(ADDIStocHA(%X2, GV), GV)
1889     // Either way, start with the ADDIStocHA:
1890     unsigned HighPartReg = createResultReg(RC);
1891     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1892             HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1893
1894     // !GVar implies a function address.  An external variable is one
1895     // without an initializer.
1896     // If/when switches are implemented, jump tables should be handled
1897     // on the "if" path here.
1898     if (CModel == CodeModel::Large || !GVar || !GVar->hasInitializer() ||
1899         GVar->hasCommonLinkage() || GVar->hasAvailableExternallyLinkage())
1900       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1901               DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1902     else
1903       // Otherwise generate the ADDItocL.
1904       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDItocL),
1905               DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1906   }
1907
1908   return DestReg;
1909 }
1910
1911 // Materialize a 32-bit integer constant into a register, and return
1912 // the register number (or zero if we failed to handle it).
1913 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1914                                              const TargetRegisterClass *RC) {
1915   unsigned Lo = Imm & 0xFFFF;
1916   unsigned Hi = (Imm >> 16) & 0xFFFF;
1917
1918   unsigned ResultReg = createResultReg(RC);
1919   bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1920
1921   if (isInt<16>(Imm))
1922     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1923             TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1924       .addImm(Imm);
1925   else if (Lo) {
1926     // Both Lo and Hi have nonzero bits.
1927     unsigned TmpReg = createResultReg(RC);
1928     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1929             TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1930       .addImm(Hi);
1931     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1932             TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1933       .addReg(TmpReg).addImm(Lo);
1934   } else
1935     // Just Hi bits.
1936     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1937             TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1938       .addImm(Hi);
1939   
1940   return ResultReg;
1941 }
1942
1943 // Materialize a 64-bit integer constant into a register, and return
1944 // the register number (or zero if we failed to handle it).
1945 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1946                                              const TargetRegisterClass *RC) {
1947   unsigned Remainder = 0;
1948   unsigned Shift = 0;
1949
1950   // If the value doesn't fit in 32 bits, see if we can shift it
1951   // so that it fits in 32 bits.
1952   if (!isInt<32>(Imm)) {
1953     Shift = countTrailingZeros<uint64_t>(Imm);
1954     int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1955
1956     if (isInt<32>(ImmSh))
1957       Imm = ImmSh;
1958     else {
1959       Remainder = Imm;
1960       Shift = 32;
1961       Imm >>= 32;
1962     }
1963   }
1964
1965   // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1966   // (if not shifted).
1967   unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1968   if (!Shift)
1969     return TmpReg1;
1970
1971   // If upper 32 bits were not zero, we've built them and need to shift
1972   // them into place.
1973   unsigned TmpReg2;
1974   if (Imm) {
1975     TmpReg2 = createResultReg(RC);
1976     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLDICR),
1977             TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1978   } else
1979     TmpReg2 = TmpReg1;
1980
1981   unsigned TmpReg3, Hi, Lo;
1982   if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1983     TmpReg3 = createResultReg(RC);
1984     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORIS8),
1985             TmpReg3).addReg(TmpReg2).addImm(Hi);
1986   } else
1987     TmpReg3 = TmpReg2;
1988
1989   if ((Lo = Remainder & 0xFFFF)) {
1990     unsigned ResultReg = createResultReg(RC);
1991     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORI8),
1992             ResultReg).addReg(TmpReg3).addImm(Lo);
1993     return ResultReg;
1994   }
1995
1996   return TmpReg3;
1997 }
1998
1999
2000 // Materialize an integer constant into a register, and return
2001 // the register number (or zero if we failed to handle it).
2002 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
2003   // If we're using CR bit registers for i1 values, handle that as a special
2004   // case first.
2005   if (VT == MVT::i1 && PPCSubTarget.useCRBits()) {
2006     const ConstantInt *CI = cast<ConstantInt>(C);
2007     unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2008     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2009             TII.get(CI->isZero() ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2010     return ImmReg;
2011   }
2012
2013   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2014       VT != MVT::i8 && VT != MVT::i1) 
2015     return 0;
2016
2017   const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2018                                    &PPC::GPRCRegClass);
2019
2020   // If the constant is in range, use a load-immediate.
2021   const ConstantInt *CI = cast<ConstantInt>(C);
2022   if (isInt<16>(CI->getSExtValue())) {
2023     unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
2024     unsigned ImmReg = createResultReg(RC);
2025     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ImmReg)
2026       .addImm(CI->getSExtValue());
2027     return ImmReg;
2028   }
2029
2030   // Construct the constant piecewise.
2031   int64_t Imm = CI->getZExtValue();
2032
2033   if (VT == MVT::i64)
2034     return PPCMaterialize64BitInt(Imm, RC);
2035   else if (VT == MVT::i32)
2036     return PPCMaterialize32BitInt(Imm, RC);
2037
2038   return 0;
2039 }
2040
2041 // Materialize a constant into a register, and return the register
2042 // number (or zero if we failed to handle it).
2043 unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
2044   EVT CEVT = TLI.getValueType(C->getType(), true);
2045
2046   // Only handle simple types.
2047   if (!CEVT.isSimple()) return 0;
2048   MVT VT = CEVT.getSimpleVT();
2049
2050   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
2051     return PPCMaterializeFP(CFP, VT);
2052   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
2053     return PPCMaterializeGV(GV, VT);
2054   else if (isa<ConstantInt>(C))
2055     return PPCMaterializeInt(C, VT);
2056
2057   return 0;
2058 }
2059
2060 // Materialize the address created by an alloca into a register, and
2061 // return the register number (or zero if we failed to handle it).
2062 unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
2063   // Don't handle dynamic allocas.
2064   if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
2065
2066   MVT VT;
2067   if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
2068
2069   DenseMap<const AllocaInst*, int>::iterator SI =
2070     FuncInfo.StaticAllocaMap.find(AI);
2071
2072   if (SI != FuncInfo.StaticAllocaMap.end()) {
2073     unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
2074     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
2075             ResultReg).addFrameIndex(SI->second).addImm(0);
2076     return ResultReg;
2077   }
2078
2079   return 0;
2080 }
2081
2082 // Fold loads into extends when possible.
2083 // FIXME: We can have multiple redundant extend/trunc instructions
2084 // following a load.  The folding only picks up one.  Extend this
2085 // to check subsequent instructions for the same pattern and remove
2086 // them.  Thus ResultReg should be the def reg for the last redundant
2087 // instruction in a chain, and all intervening instructions can be
2088 // removed from parent.  Change test/CodeGen/PowerPC/fast-isel-fold.ll
2089 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2090 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2091                                       const LoadInst *LI) {
2092   // Verify we have a legal type before going any further.
2093   MVT VT;
2094   if (!isLoadTypeLegal(LI->getType(), VT))
2095     return false;
2096
2097   // Combine load followed by zero- or sign-extend.
2098   bool IsZExt = false;
2099   switch(MI->getOpcode()) {
2100     default:
2101       return false;
2102
2103     case PPC::RLDICL:
2104     case PPC::RLDICL_32_64: {
2105       IsZExt = true;
2106       unsigned MB = MI->getOperand(3).getImm();
2107       if ((VT == MVT::i8 && MB <= 56) ||
2108           (VT == MVT::i16 && MB <= 48) ||
2109           (VT == MVT::i32 && MB <= 32))
2110         break;
2111       return false;
2112     }
2113
2114     case PPC::RLWINM:
2115     case PPC::RLWINM8: {
2116       IsZExt = true;
2117       unsigned MB = MI->getOperand(3).getImm();
2118       if ((VT == MVT::i8 && MB <= 24) ||
2119           (VT == MVT::i16 && MB <= 16))
2120         break;
2121       return false;
2122     }
2123
2124     case PPC::EXTSB:
2125     case PPC::EXTSB8:
2126     case PPC::EXTSB8_32_64:
2127       /* There is no sign-extending load-byte instruction. */
2128       return false;
2129
2130     case PPC::EXTSH:
2131     case PPC::EXTSH8:
2132     case PPC::EXTSH8_32_64: {
2133       if (VT != MVT::i16 && VT != MVT::i8)
2134         return false;
2135       break;
2136     }
2137
2138     case PPC::EXTSW:
2139     case PPC::EXTSW_32_64: {
2140       if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2141         return false;
2142       break;
2143     }
2144   }
2145
2146   // See if we can handle this address.
2147   Address Addr;
2148   if (!PPCComputeAddress(LI->getOperand(0), Addr))
2149     return false;
2150
2151   unsigned ResultReg = MI->getOperand(0).getReg();
2152
2153   if (!PPCEmitLoad(VT, ResultReg, Addr, 0, IsZExt))
2154     return false;
2155
2156   MI->eraseFromParent();
2157   return true;
2158 }
2159
2160 // Attempt to lower call arguments in a faster way than done by
2161 // the selection DAG code.
2162 bool PPCFastISel::FastLowerArguments() {
2163   // Defer to normal argument lowering for now.  It's reasonably
2164   // efficient.  Consider doing something like ARM to handle the
2165   // case where all args fit in registers, no varargs, no float
2166   // or vector args.
2167   return false;
2168 }
2169
2170 // Handle materializing integer constants into a register.  This is not
2171 // automatically generated for PowerPC, so must be explicitly created here.
2172 unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2173   
2174   if (Opc != ISD::Constant)
2175     return 0;
2176
2177   // If we're using CR bit registers for i1 values, handle that as a special
2178   // case first.
2179   if (VT == MVT::i1 && PPCSubTarget.useCRBits()) {
2180     unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2181     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2182             TII.get(Imm == 0 ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2183     return ImmReg;
2184   }
2185
2186   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2187       VT != MVT::i8 && VT != MVT::i1) 
2188     return 0;
2189
2190   const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2191                                    &PPC::GPRCRegClass);
2192   if (VT == MVT::i64)
2193     return PPCMaterialize64BitInt(Imm, RC);
2194   else
2195     return PPCMaterialize32BitInt(Imm, RC);
2196 }
2197
2198 // Override for ADDI and ADDI8 to set the correct register class
2199 // on RHS operand 0.  The automatic infrastructure naively assumes
2200 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2201 // for these cases.  At the moment, none of the other automatically
2202 // generated RI instructions require special treatment.  However, once
2203 // SelectSelect is implemented, "isel" requires similar handling.
2204 //
2205 // Also be conservative about the output register class.  Avoid
2206 // assigning R0 or X0 to the output register for GPRC and G8RC
2207 // register classes, as any such result could be used in ADDI, etc.,
2208 // where those regs have another meaning.
2209 unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
2210                                       const TargetRegisterClass *RC,
2211                                       unsigned Op0, bool Op0IsKill,
2212                                       uint64_t Imm) {
2213   if (MachineInstOpcode == PPC::ADDI)
2214     MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2215   else if (MachineInstOpcode == PPC::ADDI8)
2216     MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2217
2218   const TargetRegisterClass *UseRC =
2219     (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2220      (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2221
2222   return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
2223                                    Op0, Op0IsKill, Imm);
2224 }
2225
2226 // Override for instructions with one register operand to avoid use of
2227 // R0/X0.  The automatic infrastructure isn't aware of the context so
2228 // we must be conservative.
2229 unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
2230                                      const TargetRegisterClass* RC,
2231                                      unsigned Op0, bool Op0IsKill) {
2232   const TargetRegisterClass *UseRC =
2233     (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2234      (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2235
2236   return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2237 }
2238
2239 // Override for instructions with two register operands to avoid use
2240 // of R0/X0.  The automatic infrastructure isn't aware of the context
2241 // so we must be conservative.
2242 unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
2243                                       const TargetRegisterClass* RC,
2244                                       unsigned Op0, bool Op0IsKill,
2245                                       unsigned Op1, bool Op1IsKill) {
2246   const TargetRegisterClass *UseRC =
2247     (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2248      (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2249
2250   return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2251                                    Op1, Op1IsKill);
2252 }
2253
2254 namespace llvm {
2255   // Create the fast instruction selector for PowerPC64 ELF.
2256   FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2257                                 const TargetLibraryInfo *LibInfo) {
2258     const TargetMachine &TM = FuncInfo.MF->getTarget();
2259
2260     // Only available on 64-bit ELF for now.
2261     const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
2262     if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
2263       return new PPCFastISel(FuncInfo, LibInfo);
2264
2265     return 0;
2266   }
2267 }