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