[PowerPC] Handle selection of compare instructions in fast-isel.
[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 "PPCISelLowering.h"
19 #include "PPCSubtarget.h"
20 #include "PPCTargetMachine.h"
21 #include "MCTargetDesc/PPCPredicates.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/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39
40 using namespace llvm;
41
42 namespace {
43
44 typedef struct Address {
45   enum {
46     RegBase,
47     FrameIndexBase
48   } BaseType;
49
50   union {
51     unsigned Reg;
52     int FI;
53   } Base;
54
55   long Offset;
56
57   // Innocuous defaults for our address.
58   Address()
59    : BaseType(RegBase), Offset(0) {
60      Base.Reg = 0;
61    }
62 } Address;
63
64 class PPCFastISel : public FastISel {
65
66   const TargetMachine &TM;
67   const TargetInstrInfo &TII;
68   const TargetLowering &TLI;
69   const PPCSubtarget &PPCSubTarget;
70   LLVMContext *Context;
71
72   public:
73     explicit PPCFastISel(FunctionLoweringInfo &FuncInfo,
74                          const TargetLibraryInfo *LibInfo)
75     : FastISel(FuncInfo, LibInfo),
76       TM(FuncInfo.MF->getTarget()),
77       TII(*TM.getInstrInfo()),
78       TLI(*TM.getTargetLowering()),
79       PPCSubTarget(
80        *((static_cast<const PPCTargetMachine *>(&TM))->getSubtargetImpl())
81       ),
82       Context(&FuncInfo.Fn->getContext()) { }
83
84   // Backend specific FastISel code.
85   private:
86     virtual bool TargetSelectInstruction(const Instruction *I);
87     virtual unsigned TargetMaterializeConstant(const Constant *C);
88     virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
89     virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
90                                      const LoadInst *LI);
91     virtual bool FastLowerArguments();
92     virtual unsigned FastEmit_i(MVT Ty, MVT RetTy, unsigned Opc, uint64_t Imm);
93     virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
94                                      const TargetRegisterClass *RC,
95                                      unsigned Op0, bool Op0IsKill,
96                                      uint64_t Imm);
97     virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
98                                     const TargetRegisterClass *RC,
99                                     unsigned Op0, bool Op0IsKill);
100     virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
101                                      const TargetRegisterClass *RC,
102                                      unsigned Op0, bool Op0IsKill,
103                                      unsigned Op1, bool Op1IsKill);
104
105   // Instruction selection routines.
106   private:
107     bool SelectLoad(const Instruction *I);
108     bool SelectStore(const Instruction *I);
109     bool SelectBranch(const Instruction *I);
110     bool SelectIndirectBr(const Instruction *I);
111     bool SelectCmp(const Instruction *I);
112     bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
113     bool SelectRet(const Instruction *I);
114     bool SelectIntExt(const Instruction *I);
115
116   // Utility routines.
117   private:
118     bool isTypeLegal(Type *Ty, MVT &VT);
119     bool isLoadTypeLegal(Type *Ty, MVT &VT);
120     bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
121                     bool isZExt, unsigned DestReg);
122     bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
123                      const TargetRegisterClass *RC, bool IsZExt = true,
124                      unsigned FP64LoadOpc = PPC::LFD);
125     bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
126     bool PPCComputeAddress(const Value *Obj, Address &Addr);
127     void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
128                             unsigned &IndexReg);
129     bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
130                            unsigned DestReg, bool IsZExt);
131     unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
132     unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
133     unsigned PPCMaterializeInt(const Constant *C, MVT VT);
134     unsigned PPCMaterialize32BitInt(int64_t Imm,
135                                     const TargetRegisterClass *RC);
136     unsigned PPCMaterialize64BitInt(int64_t Imm,
137                                     const TargetRegisterClass *RC);
138
139   // Call handling routines.
140   private:
141     CCAssignFn *usePPC32CCs(unsigned Flag);
142
143   private:
144   #include "PPCGenFastISel.inc"
145
146 };
147
148 } // end anonymous namespace
149
150 #include "PPCGenCallingConv.inc"
151
152 // Function whose sole purpose is to kill compiler warnings 
153 // stemming from unused functions included from PPCGenCallingConv.inc.
154 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
155   if (Flag == 1)
156     return CC_PPC32_SVR4;
157   else if (Flag == 2)
158     return CC_PPC32_SVR4_ByVal;
159   else if (Flag == 3)
160     return CC_PPC32_SVR4_VarArg;
161   else
162     return RetCC_PPC;
163 }
164
165 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
166   switch (Pred) {
167     // These are not representable with any single compare.
168     case CmpInst::FCMP_FALSE:
169     case CmpInst::FCMP_UEQ:
170     case CmpInst::FCMP_UGT:
171     case CmpInst::FCMP_UGE:
172     case CmpInst::FCMP_ULT:
173     case CmpInst::FCMP_ULE:
174     case CmpInst::FCMP_UNE:
175     case CmpInst::FCMP_TRUE:
176     default:
177       return Optional<PPC::Predicate>();
178
179     case CmpInst::FCMP_OEQ:
180     case CmpInst::ICMP_EQ:
181       return PPC::PRED_EQ;
182
183     case CmpInst::FCMP_OGT:
184     case CmpInst::ICMP_UGT:
185     case CmpInst::ICMP_SGT:
186       return PPC::PRED_GT;
187
188     case CmpInst::FCMP_OGE:
189     case CmpInst::ICMP_UGE:
190     case CmpInst::ICMP_SGE:
191       return PPC::PRED_GE;
192
193     case CmpInst::FCMP_OLT:
194     case CmpInst::ICMP_ULT:
195     case CmpInst::ICMP_SLT:
196       return PPC::PRED_LT;
197
198     case CmpInst::FCMP_OLE:
199     case CmpInst::ICMP_ULE:
200     case CmpInst::ICMP_SLE:
201       return PPC::PRED_LE;
202
203     case CmpInst::FCMP_ONE:
204     case CmpInst::ICMP_NE:
205       return PPC::PRED_NE;
206
207     case CmpInst::FCMP_ORD:
208       return PPC::PRED_NU;
209
210     case CmpInst::FCMP_UNO:
211       return PPC::PRED_UN;
212   }
213 }
214
215 // Determine whether the type Ty is simple enough to be handled by
216 // fast-isel, and return its equivalent machine type in VT.
217 // FIXME: Copied directly from ARM -- factor into base class?
218 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
219   EVT Evt = TLI.getValueType(Ty, true);
220
221   // Only handle simple types.
222   if (Evt == MVT::Other || !Evt.isSimple()) return false;
223   VT = Evt.getSimpleVT();
224
225   // Handle all legal types, i.e. a register that will directly hold this
226   // value.
227   return TLI.isTypeLegal(VT);
228 }
229
230 // Determine whether the type Ty is simple enough to be handled by
231 // fast-isel as a load target, and return its equivalent machine type in VT.
232 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
233   if (isTypeLegal(Ty, VT)) return true;
234
235   // If this is a type than can be sign or zero-extended to a basic operation
236   // go ahead and accept it now.
237   if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
238     return true;
239   }
240
241   return false;
242 }
243
244 // Given a value Obj, create an Address object Addr that represents its
245 // address.  Return false if we can't handle it.
246 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
247   const User *U = NULL;
248   unsigned Opcode = Instruction::UserOp1;
249   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
250     // Don't walk into other basic blocks unless the object is an alloca from
251     // another block, otherwise it may not have a virtual register assigned.
252     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
253         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
254       Opcode = I->getOpcode();
255       U = I;
256     }
257   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
258     Opcode = C->getOpcode();
259     U = C;
260   }
261
262   switch (Opcode) {
263     default:
264       break;
265     case Instruction::BitCast:
266       // Look through bitcasts.
267       return PPCComputeAddress(U->getOperand(0), Addr);
268     case Instruction::IntToPtr:
269       // Look past no-op inttoptrs.
270       if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
271         return PPCComputeAddress(U->getOperand(0), Addr);
272       break;
273     case Instruction::PtrToInt:
274       // Look past no-op ptrtoints.
275       if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
276         return PPCComputeAddress(U->getOperand(0), Addr);
277       break;
278     case Instruction::GetElementPtr: {
279       Address SavedAddr = Addr;
280       long TmpOffset = Addr.Offset;
281
282       // Iterate through the GEP folding the constants into offsets where
283       // we can.
284       gep_type_iterator GTI = gep_type_begin(U);
285       for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
286            II != IE; ++II, ++GTI) {
287         const Value *Op = *II;
288         if (StructType *STy = dyn_cast<StructType>(*GTI)) {
289           const StructLayout *SL = TD.getStructLayout(STy);
290           unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
291           TmpOffset += SL->getElementOffset(Idx);
292         } else {
293           uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
294           for (;;) {
295             if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
296               // Constant-offset addressing.
297               TmpOffset += CI->getSExtValue() * S;
298               break;
299             }
300             if (isa<AddOperator>(Op) &&
301                 (!isa<Instruction>(Op) ||
302                  FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
303                  == FuncInfo.MBB) &&
304                 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
305               // An add (in the same block) with a constant operand. Fold the
306               // constant.
307               ConstantInt *CI =
308               cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
309               TmpOffset += CI->getSExtValue() * S;
310               // Iterate on the other operand.
311               Op = cast<AddOperator>(Op)->getOperand(0);
312               continue;
313             }
314             // Unsupported
315             goto unsupported_gep;
316           }
317         }
318       }
319
320       // Try to grab the base operand now.
321       Addr.Offset = TmpOffset;
322       if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
323
324       // We failed, restore everything and try the other options.
325       Addr = SavedAddr;
326
327       unsupported_gep:
328       break;
329     }
330     case Instruction::Alloca: {
331       const AllocaInst *AI = cast<AllocaInst>(Obj);
332       DenseMap<const AllocaInst*, int>::iterator SI =
333         FuncInfo.StaticAllocaMap.find(AI);
334       if (SI != FuncInfo.StaticAllocaMap.end()) {
335         Addr.BaseType = Address::FrameIndexBase;
336         Addr.Base.FI = SI->second;
337         return true;
338       }
339       break;
340     }
341   }
342
343   // FIXME: References to parameters fall through to the behavior
344   // below.  They should be able to reference a frame index since
345   // they are stored to the stack, so we can get "ld rx, offset(r1)"
346   // instead of "addi ry, r1, offset / ld rx, 0(ry)".  Obj will
347   // just contain the parameter.  Try to handle this with a FI.
348
349   // Try to get this in a register if nothing else has worked.
350   if (Addr.Base.Reg == 0)
351     Addr.Base.Reg = getRegForValue(Obj);
352
353   // Prevent assignment of base register to X0, which is inappropriate
354   // for loads and stores alike.
355   if (Addr.Base.Reg != 0)
356     MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
357
358   return Addr.Base.Reg != 0;
359 }
360
361 // Fix up some addresses that can't be used directly.  For example, if
362 // an offset won't fit in an instruction field, we may need to move it
363 // into an index register.
364 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
365                                      unsigned &IndexReg) {
366
367   // Check whether the offset fits in the instruction field.
368   if (!isInt<16>(Addr.Offset))
369     UseOffset = false;
370
371   // If this is a stack pointer and the offset needs to be simplified then
372   // put the alloca address into a register, set the base type back to
373   // register and continue. This should almost never happen.
374   if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
375     unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
376     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDI8),
377             ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
378     Addr.Base.Reg = ResultReg;
379     Addr.BaseType = Address::RegBase;
380   }
381
382   if (!UseOffset) {
383     IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
384                              : Type::getInt64Ty(*Context));
385     const ConstantInt *Offset =
386       ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
387     IndexReg = PPCMaterializeInt(Offset, MVT::i64);
388     assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
389   }
390 }
391
392 // Emit a load instruction if possible, returning true if we succeeded,
393 // otherwise false.  See commentary below for how the register class of
394 // the load is determined. 
395 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
396                               const TargetRegisterClass *RC,
397                               bool IsZExt, unsigned FP64LoadOpc) {
398   unsigned Opc;
399   bool UseOffset = true;
400
401   // If ResultReg is given, it determines the register class of the load.
402   // Otherwise, RC is the register class to use.  If the result of the
403   // load isn't anticipated in this block, both may be zero, in which
404   // case we must make a conservative guess.  In particular, don't assign
405   // R0 or X0 to the result register, as the result may be used in a load,
406   // store, add-immediate, or isel that won't permit this.  (Though
407   // perhaps the spill and reload of live-exit values would handle this?)
408   const TargetRegisterClass *UseRC =
409     (ResultReg ? MRI.getRegClass(ResultReg) :
410      (RC ? RC :
411       (VT == MVT::f64 ? &PPC::F8RCRegClass :
412        (VT == MVT::f32 ? &PPC::F4RCRegClass :
413         (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
414          &PPC::GPRC_and_GPRC_NOR0RegClass)))));
415
416   bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
417
418   switch (VT.SimpleTy) {
419     default: // e.g., vector types not handled
420       return false;
421     case MVT::i8:
422       Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
423       break;
424     case MVT::i16:
425       Opc = (IsZExt ?
426              (Is32BitInt ? PPC::LHZ : PPC::LHZ8) : 
427              (Is32BitInt ? PPC::LHA : PPC::LHA8));
428       break;
429     case MVT::i32:
430       Opc = (IsZExt ? 
431              (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
432              (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
433       if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
434         UseOffset = false;
435       break;
436     case MVT::i64:
437       Opc = PPC::LD;
438       assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) && 
439              "64-bit load with 32-bit target??");
440       UseOffset = ((Addr.Offset & 3) == 0);
441       break;
442     case MVT::f32:
443       Opc = PPC::LFS;
444       break;
445     case MVT::f64:
446       Opc = FP64LoadOpc;
447       break;
448   }
449
450   // If necessary, materialize the offset into a register and use
451   // the indexed form.  Also handle stack pointers with special needs.
452   unsigned IndexReg = 0;
453   PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
454   if (ResultReg == 0)
455     ResultReg = createResultReg(UseRC);
456
457   // Note: If we still have a frame index here, we know the offset is
458   // in range, as otherwise PPCSimplifyAddress would have converted it
459   // into a RegBase.
460   if (Addr.BaseType == Address::FrameIndexBase) {
461
462     MachineMemOperand *MMO =
463       FuncInfo.MF->getMachineMemOperand(
464         MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
465         MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
466         MFI.getObjectAlignment(Addr.Base.FI));
467
468     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
469       .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
470
471   // Base reg with offset in range.
472   } else if (UseOffset) {
473
474     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
475       .addImm(Addr.Offset).addReg(Addr.Base.Reg);
476
477   // Indexed form.
478   } else {
479     // Get the RR opcode corresponding to the RI one.  FIXME: It would be
480     // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
481     // is hard to get at.
482     switch (Opc) {
483       default:        llvm_unreachable("Unexpected opcode!");
484       case PPC::LBZ:    Opc = PPC::LBZX;    break;
485       case PPC::LBZ8:   Opc = PPC::LBZX8;   break;
486       case PPC::LHZ:    Opc = PPC::LHZX;    break;
487       case PPC::LHZ8:   Opc = PPC::LHZX8;   break;
488       case PPC::LHA:    Opc = PPC::LHAX;    break;
489       case PPC::LHA8:   Opc = PPC::LHAX8;   break;
490       case PPC::LWZ:    Opc = PPC::LWZX;    break;
491       case PPC::LWZ8:   Opc = PPC::LWZX8;   break;
492       case PPC::LWA:    Opc = PPC::LWAX;    break;
493       case PPC::LWA_32: Opc = PPC::LWAX_32; break;
494       case PPC::LD:     Opc = PPC::LDX;     break;
495       case PPC::LFS:    Opc = PPC::LFSX;    break;
496       case PPC::LFD:    Opc = PPC::LFDX;    break;
497     }
498     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
499       .addReg(Addr.Base.Reg).addReg(IndexReg);
500   }
501
502   return true;
503 }
504
505 // Attempt to fast-select a load instruction.
506 bool PPCFastISel::SelectLoad(const Instruction *I) {
507   // FIXME: No atomic loads are supported.
508   if (cast<LoadInst>(I)->isAtomic())
509     return false;
510
511   // Verify we have a legal type before going any further.
512   MVT VT;
513   if (!isLoadTypeLegal(I->getType(), VT))
514     return false;
515
516   // See if we can handle this address.
517   Address Addr;
518   if (!PPCComputeAddress(I->getOperand(0), Addr))
519     return false;
520
521   // Look at the currently assigned register for this instruction
522   // to determine the required register class.  This is necessary
523   // to constrain RA from using R0/X0 when this is not legal.
524   unsigned AssignedReg = FuncInfo.ValueMap[I];
525   const TargetRegisterClass *RC =
526     AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
527
528   unsigned ResultReg = 0;
529   if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
530     return false;
531   UpdateValueMap(I, ResultReg);
532   return true;
533 }
534
535 // Emit a store instruction to store SrcReg at Addr.
536 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
537   assert(SrcReg && "Nothing to store!");
538   unsigned Opc;
539   bool UseOffset = true;
540
541   const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
542   bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
543
544   switch (VT.SimpleTy) {
545     default: // e.g., vector types not handled
546       return false;
547     case MVT::i8:
548       Opc = Is32BitInt ? PPC::STB : PPC::STB8;
549       break;
550     case MVT::i16:
551       Opc = Is32BitInt ? PPC::STH : PPC::STH8;
552       break;
553     case MVT::i32:
554       assert(Is32BitInt && "Not GPRC for i32??");
555       Opc = PPC::STW;
556       break;
557     case MVT::i64:
558       Opc = PPC::STD;
559       UseOffset = ((Addr.Offset & 3) == 0);
560       break;
561     case MVT::f32:
562       Opc = PPC::STFS;
563       break;
564     case MVT::f64:
565       Opc = PPC::STFD;
566       break;
567   }
568
569   // If necessary, materialize the offset into a register and use
570   // the indexed form.  Also handle stack pointers with special needs.
571   unsigned IndexReg = 0;
572   PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
573
574   // Note: If we still have a frame index here, we know the offset is
575   // in range, as otherwise PPCSimplifyAddress would have converted it
576   // into a RegBase.
577   if (Addr.BaseType == Address::FrameIndexBase) {
578     MachineMemOperand *MMO =
579       FuncInfo.MF->getMachineMemOperand(
580         MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
581         MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
582         MFI.getObjectAlignment(Addr.Base.FI));
583
584     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc)).addReg(SrcReg)
585       .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
586
587   // Base reg with offset in range.
588   } else if (UseOffset)
589     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
590       .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
591
592   // Indexed form.
593   else {
594     // Get the RR opcode corresponding to the RI one.  FIXME: It would be
595     // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
596     // is hard to get at.
597     switch (Opc) {
598       default:        llvm_unreachable("Unexpected opcode!");
599       case PPC::STB:  Opc = PPC::STBX;  break;
600       case PPC::STH : Opc = PPC::STHX;  break;
601       case PPC::STW : Opc = PPC::STWX;  break;
602       case PPC::STB8: Opc = PPC::STBX8; break;
603       case PPC::STH8: Opc = PPC::STHX8; break;
604       case PPC::STW8: Opc = PPC::STWX8; break;
605       case PPC::STD:  Opc = PPC::STDX;  break;
606       case PPC::STFS: Opc = PPC::STFSX; break;
607       case PPC::STFD: Opc = PPC::STFDX; break;
608     }
609     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
610       .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
611   }
612
613   return true;
614 }
615
616 // Attempt to fast-select a store instruction.
617 bool PPCFastISel::SelectStore(const Instruction *I) {
618   Value *Op0 = I->getOperand(0);
619   unsigned SrcReg = 0;
620
621   // FIXME: No atomics loads are supported.
622   if (cast<StoreInst>(I)->isAtomic())
623     return false;
624
625   // Verify we have a legal type before going any further.
626   MVT VT;
627   if (!isLoadTypeLegal(Op0->getType(), VT))
628     return false;
629
630   // Get the value to be stored into a register.
631   SrcReg = getRegForValue(Op0);
632   if (SrcReg == 0)
633     return false;
634
635   // See if we can handle this address.
636   Address Addr;
637   if (!PPCComputeAddress(I->getOperand(1), Addr))
638     return false;
639
640   if (!PPCEmitStore(VT, SrcReg, Addr))
641     return false;
642
643   return true;
644 }
645
646 // Attempt to fast-select a branch instruction.
647 bool PPCFastISel::SelectBranch(const Instruction *I) {
648   const BranchInst *BI = cast<BranchInst>(I);
649   MachineBasicBlock *BrBB = FuncInfo.MBB;
650   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
651   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
652
653   // For now, just try the simplest case where it's fed by a compare.
654   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
655     Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
656     if (!OptPPCPred)
657       return false;
658
659     PPC::Predicate PPCPred = OptPPCPred.getValue();
660
661     // Take advantage of fall-through opportunities.
662     if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
663       std::swap(TBB, FBB);
664       PPCPred = PPC::InvertPredicate(PPCPred);
665     }
666
667     unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
668
669     if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
670                     CondReg))
671       return false;
672
673     BuildMI(*BrBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCC))
674       .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
675     FastEmitBranch(FBB, DL);
676     FuncInfo.MBB->addSuccessor(TBB);
677     return true;
678
679   } else if (const ConstantInt *CI =
680              dyn_cast<ConstantInt>(BI->getCondition())) {
681     uint64_t Imm = CI->getZExtValue();
682     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
683     FastEmitBranch(Target, DL);
684     return true;
685   }
686
687   // FIXME: ARM looks for a case where the block containing the compare
688   // has been split from the block containing the branch.  If this happens,
689   // there is a vreg available containing the result of the compare.  I'm
690   // not sure we can do much, as we've lost the predicate information with
691   // the compare instruction -- we have a 4-bit CR but don't know which bit
692   // to test here.
693   return false;
694 }
695
696 // Attempt to emit a compare of the two source values.  Signed and unsigned
697 // comparisons are supported.  Return false if we can't handle it.
698 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
699                              bool IsZExt, unsigned DestReg) {
700   Type *Ty = SrcValue1->getType();
701   EVT SrcEVT = TLI.getValueType(Ty, true);
702   if (!SrcEVT.isSimple())
703     return false;
704   MVT SrcVT = SrcEVT.getSimpleVT();
705
706   // See if operand 2 is an immediate encodeable in the compare.
707   // FIXME: Operands are not in canonical order at -O0, so an immediate
708   // operand in position 1 is a lost opportunity for now.  We are
709   // similar to ARM in this regard.
710   long Imm = 0;
711   bool UseImm = false;
712
713   // Only 16-bit integer constants can be represented in compares for 
714   // PowerPC.  Others will be materialized into a register.
715   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
716     if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
717         SrcVT == MVT::i8 || SrcVT == MVT::i1) {
718       const APInt &CIVal = ConstInt->getValue();
719       Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
720       if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
721         UseImm = true;
722     }
723   }
724
725   unsigned CmpOpc;
726   bool NeedsExt = false;
727   switch (SrcVT.SimpleTy) {
728     default: return false;
729     case MVT::f32:
730       CmpOpc = PPC::FCMPUS;
731       break;
732     case MVT::f64:
733       CmpOpc = PPC::FCMPUD;
734       break;
735     case MVT::i1:
736     case MVT::i8:
737     case MVT::i16:
738       NeedsExt = true;
739       // Intentional fall-through.
740     case MVT::i32:
741       if (!UseImm)
742         CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
743       else
744         CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
745       break;
746     case MVT::i64:
747       if (!UseImm)
748         CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
749       else
750         CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
751       break;
752   }
753
754   unsigned SrcReg1 = getRegForValue(SrcValue1);
755   if (SrcReg1 == 0)
756     return false;
757
758   unsigned SrcReg2 = 0;
759   if (!UseImm) {
760     SrcReg2 = getRegForValue(SrcValue2);
761     if (SrcReg2 == 0)
762       return false;
763   }
764
765   if (NeedsExt) {
766     unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
767     if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
768       return false;
769     SrcReg1 = ExtReg;
770
771     if (!UseImm) {
772       unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
773       if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
774         return false;
775       SrcReg2 = ExtReg;
776     }
777   }
778
779   if (!UseImm)
780     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
781       .addReg(SrcReg1).addReg(SrcReg2);
782   else
783     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
784       .addReg(SrcReg1).addImm(Imm);
785
786   return true;
787 }
788
789 // Attempt to fast-select a binary integer operation that isn't already
790 // handled automatically.
791 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
792   EVT DestVT  = TLI.getValueType(I->getType(), true);
793
794   // We can get here in the case when we have a binary operation on a non-legal
795   // type and the target independent selector doesn't know how to handle it.
796   if (DestVT != MVT::i16 && DestVT != MVT::i8)
797     return false;
798
799   // Look at the currently assigned register for this instruction
800   // to determine the required register class.  If there is no register,
801   // make a conservative choice (don't assign R0).
802   unsigned AssignedReg = FuncInfo.ValueMap[I];
803   const TargetRegisterClass *RC =
804     (AssignedReg ? MRI.getRegClass(AssignedReg) :
805      &PPC::GPRC_and_GPRC_NOR0RegClass);
806   bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
807
808   unsigned Opc;
809   switch (ISDOpcode) {
810     default: return false;
811     case ISD::ADD:
812       Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
813       break;
814     case ISD::OR:
815       Opc = IsGPRC ? PPC::OR : PPC::OR8;
816       break;
817     case ISD::SUB:
818       Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
819       break;
820   }
821
822   unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
823   unsigned SrcReg1 = getRegForValue(I->getOperand(0));
824   if (SrcReg1 == 0) return false;
825
826   // Handle case of small immediate operand.
827   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
828     const APInt &CIVal = ConstInt->getValue();
829     int Imm = (int)CIVal.getSExtValue();
830     bool UseImm = true;
831     if (isInt<16>(Imm)) {
832       switch (Opc) {
833         default:
834           llvm_unreachable("Missing case!");
835         case PPC::ADD4:
836           Opc = PPC::ADDI;
837           MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
838           break;
839         case PPC::ADD8:
840           Opc = PPC::ADDI8;
841           MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
842           break;
843         case PPC::OR:
844           Opc = PPC::ORI;
845           break;
846         case PPC::OR8:
847           Opc = PPC::ORI8;
848           break;
849         case PPC::SUBF:
850           if (Imm == -32768)
851             UseImm = false;
852           else {
853             Opc = PPC::ADDI;
854             MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
855             Imm = -Imm;
856           }
857           break;
858         case PPC::SUBF8:
859           if (Imm == -32768)
860             UseImm = false;
861           else {
862             Opc = PPC::ADDI8;
863             MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
864             Imm = -Imm;
865           }
866           break;
867       }
868
869       if (UseImm) {
870         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
871           .addReg(SrcReg1).addImm(Imm);
872         UpdateValueMap(I, ResultReg);
873         return true;
874       }
875     }
876   }
877
878   // Reg-reg case.
879   unsigned SrcReg2 = getRegForValue(I->getOperand(1));
880   if (SrcReg2 == 0) return false;
881
882   // Reverse operands for subtract-from.
883   if (ISDOpcode == ISD::SUB)
884     std::swap(SrcReg1, SrcReg2);
885
886   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
887     .addReg(SrcReg1).addReg(SrcReg2);
888   UpdateValueMap(I, ResultReg);
889   return true;
890 }
891
892 // Attempt to fast-select a return instruction.
893 bool PPCFastISel::SelectRet(const Instruction *I) {
894
895   if (!FuncInfo.CanLowerReturn)
896     return false;
897
898   const ReturnInst *Ret = cast<ReturnInst>(I);
899   const Function &F = *I->getParent()->getParent();
900
901   // Build a list of return value registers.
902   SmallVector<unsigned, 4> RetRegs;
903   CallingConv::ID CC = F.getCallingConv();
904
905   if (Ret->getNumOperands() > 0) {
906     SmallVector<ISD::OutputArg, 4> Outs;
907     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
908
909     // Analyze operands of the call, assigning locations to each operand.
910     SmallVector<CCValAssign, 16> ValLocs;
911     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
912     CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
913     const Value *RV = Ret->getOperand(0);
914     
915     // FIXME: Only one output register for now.
916     if (ValLocs.size() > 1)
917       return false;
918
919     // Special case for returning a constant integer of any size.
920     // Materialize the constant as an i64 and copy it to the return
921     // register.  This avoids an unnecessary extend or truncate.
922     if (isa<ConstantInt>(*RV)) {
923       const Constant *C = cast<Constant>(RV);
924       unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
925       unsigned RetReg = ValLocs[0].getLocReg();
926       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
927               RetReg).addReg(SrcReg);
928       RetRegs.push_back(RetReg);
929
930     } else {
931       unsigned Reg = getRegForValue(RV);
932
933       if (Reg == 0)
934         return false;
935
936       // Copy the result values into the output registers.
937       for (unsigned i = 0; i < ValLocs.size(); ++i) {
938
939         CCValAssign &VA = ValLocs[i];
940         assert(VA.isRegLoc() && "Can only return in registers!");
941         RetRegs.push_back(VA.getLocReg());
942         unsigned SrcReg = Reg + VA.getValNo();
943
944         EVT RVEVT = TLI.getValueType(RV->getType());
945         if (!RVEVT.isSimple())
946           return false;
947         MVT RVVT = RVEVT.getSimpleVT();
948         MVT DestVT = VA.getLocVT();
949
950         if (RVVT != DestVT && RVVT != MVT::i8 &&
951             RVVT != MVT::i16 && RVVT != MVT::i32)
952           return false;
953       
954         if (RVVT != DestVT) {
955           switch (VA.getLocInfo()) {
956             default:
957               llvm_unreachable("Unknown loc info!");
958             case CCValAssign::Full:
959               llvm_unreachable("Full value assign but types don't match?");
960             case CCValAssign::AExt:
961             case CCValAssign::ZExt: {
962               const TargetRegisterClass *RC =
963                 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
964               unsigned TmpReg = createResultReg(RC);
965               if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
966                 return false;
967               SrcReg = TmpReg;
968               break;
969             }
970             case CCValAssign::SExt: {
971               const TargetRegisterClass *RC =
972                 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
973               unsigned TmpReg = createResultReg(RC);
974               if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
975                 return false;
976               SrcReg = TmpReg;
977               break;
978             }
979           }
980         }
981
982         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
983                 TII.get(TargetOpcode::COPY), RetRegs[i])
984           .addReg(SrcReg);
985       }
986     }
987   }
988
989   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
990                                     TII.get(PPC::BLR));
991
992   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
993     MIB.addReg(RetRegs[i], RegState::Implicit);
994
995   return true;
996 }
997
998 // Attempt to emit an integer extend of SrcReg into DestReg.  Both
999 // signed and zero extensions are supported.  Return false if we
1000 // can't handle it.
1001 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1002                                 unsigned DestReg, bool IsZExt) {
1003   if (DestVT != MVT::i32 && DestVT != MVT::i64)
1004     return false;
1005   if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1006     return false;
1007
1008   // Signed extensions use EXTSB, EXTSH, EXTSW.
1009   if (!IsZExt) {
1010     unsigned Opc;
1011     if (SrcVT == MVT::i8)
1012       Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1013     else if (SrcVT == MVT::i16)
1014       Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1015     else {
1016       assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1017       Opc = PPC::EXTSW_32_64;
1018     }
1019     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1020       .addReg(SrcReg);
1021
1022   // Unsigned 32-bit extensions use RLWINM.
1023   } else if (DestVT == MVT::i32) {
1024     unsigned MB;
1025     if (SrcVT == MVT::i8)
1026       MB = 24;
1027     else {
1028       assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1029       MB = 16;
1030     }
1031     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLWINM),
1032             DestReg)
1033       .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1034
1035   // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1036   } else {
1037     unsigned MB;
1038     if (SrcVT == MVT::i8)
1039       MB = 56;
1040     else if (SrcVT == MVT::i16)
1041       MB = 48;
1042     else
1043       MB = 32;
1044     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1045             TII.get(PPC::RLDICL_32_64), DestReg)
1046       .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1047   }
1048
1049   return true;
1050 }
1051
1052 // Attempt to fast-select an indirect branch instruction.
1053 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1054   unsigned AddrReg = getRegForValue(I->getOperand(0));
1055   if (AddrReg == 0)
1056     return false;
1057
1058   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::MTCTR8))
1059     .addReg(AddrReg);
1060   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCTR8));
1061
1062   const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1063   for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1064     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1065
1066   return true;
1067 }
1068
1069 // Attempt to fast-select a compare instruction.
1070 bool PPCFastISel::SelectCmp(const Instruction *I) {
1071   const CmpInst *CI = cast<CmpInst>(I);
1072   Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
1073   if (!OptPPCPred)
1074     return false;
1075
1076   unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
1077
1078   if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
1079                   CondReg))
1080     return false;
1081
1082   UpdateValueMap(I, CondReg);
1083   return true;
1084 }
1085
1086 // Attempt to fast-select an integer extend instruction.
1087 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1088   Type *DestTy = I->getType();
1089   Value *Src = I->getOperand(0);
1090   Type *SrcTy = Src->getType();
1091
1092   bool IsZExt = isa<ZExtInst>(I);
1093   unsigned SrcReg = getRegForValue(Src);
1094   if (!SrcReg) return false;
1095
1096   EVT SrcEVT, DestEVT;
1097   SrcEVT = TLI.getValueType(SrcTy, true);
1098   DestEVT = TLI.getValueType(DestTy, true);
1099   if (!SrcEVT.isSimple())
1100     return false;
1101   if (!DestEVT.isSimple())
1102     return false;
1103
1104   MVT SrcVT = SrcEVT.getSimpleVT();
1105   MVT DestVT = DestEVT.getSimpleVT();
1106
1107   // If we know the register class needed for the result of this
1108   // instruction, use it.  Otherwise pick the register class of the
1109   // correct size that does not contain X0/R0, since we don't know
1110   // whether downstream uses permit that assignment.
1111   unsigned AssignedReg = FuncInfo.ValueMap[I];
1112   const TargetRegisterClass *RC =
1113     (AssignedReg ? MRI.getRegClass(AssignedReg) :
1114      (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1115       &PPC::GPRC_and_GPRC_NOR0RegClass));
1116   unsigned ResultReg = createResultReg(RC);
1117
1118   if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1119     return false;
1120
1121   UpdateValueMap(I, ResultReg);
1122   return true;
1123 }
1124
1125 // Attempt to fast-select an instruction that wasn't handled by
1126 // the table-generated machinery.
1127 bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
1128
1129   switch (I->getOpcode()) {
1130     case Instruction::Load:
1131       return SelectLoad(I);
1132     case Instruction::Store:
1133       return SelectStore(I);
1134     case Instruction::Br:
1135       return SelectBranch(I);
1136     case Instruction::IndirectBr:
1137       return SelectIndirectBr(I);
1138     case Instruction::Add:
1139       return SelectBinaryIntOp(I, ISD::ADD);
1140     case Instruction::Or:
1141       return SelectBinaryIntOp(I, ISD::OR);
1142     case Instruction::Sub:
1143       return SelectBinaryIntOp(I, ISD::SUB);
1144     case Instruction::Ret:
1145       return SelectRet(I);
1146     case Instruction::ZExt:
1147     case Instruction::SExt:
1148       return SelectIntExt(I);
1149     // Here add other flavors of Instruction::XXX that automated
1150     // cases don't catch.  For example, switches are terminators
1151     // that aren't yet handled.
1152     default:
1153       break;
1154   }
1155   return false;
1156 }
1157
1158 // Materialize a floating-point constant into a register, and return
1159 // the register number (or zero if we failed to handle it).
1160 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1161   // No plans to handle long double here.
1162   if (VT != MVT::f32 && VT != MVT::f64)
1163     return 0;
1164
1165   // All FP constants are loaded from the constant pool.
1166   unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
1167   assert(Align > 0 && "Unexpectedly missing alignment information!");
1168   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1169   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1170   CodeModel::Model CModel = TM.getCodeModel();
1171
1172   MachineMemOperand *MMO =
1173     FuncInfo.MF->getMachineMemOperand(
1174       MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1175       (VT == MVT::f32) ? 4 : 8, Align);
1176
1177   unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1178   unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1179
1180   // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1181   if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1182     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocCPT),
1183             TmpReg)
1184       .addConstantPoolIndex(Idx).addReg(PPC::X2);
1185     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1186       .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1187   } else {
1188     // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1189     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1190             TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1191     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1192       .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1193       .addReg(TmpReg)
1194       .addMemOperand(MMO);
1195   }
1196
1197   return DestReg;
1198 }
1199
1200 // Materialize the address of a global value into a register, and return
1201 // the register number (or zero if we failed to handle it).
1202 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1203   assert(VT == MVT::i64 && "Non-address!");
1204   const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1205   unsigned DestReg = createResultReg(RC);
1206
1207   // Global values may be plain old object addresses, TLS object
1208   // addresses, constant pool entries, or jump tables.  How we generate
1209   // code for these may depend on small, medium, or large code model.
1210   CodeModel::Model CModel = TM.getCodeModel();
1211
1212   // FIXME: Jump tables are not yet required because fast-isel doesn't
1213   // handle switches; if that changes, we need them as well.  For now,
1214   // what follows assumes everything's a generic (or TLS) global address.
1215   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1216   if (!GVar) {
1217     // If GV is an alias, use the aliasee for determining thread-locality.
1218     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1219       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1220     assert((GVar || isa<Function>(GV)) && "Unexpected GV subclass!");
1221   }
1222
1223   // FIXME: We don't yet handle the complexity of TLS.
1224   bool IsTLS = GVar && GVar->isThreadLocal();
1225   if (IsTLS)
1226     return 0;
1227
1228   // For small code model, generate a simple TOC load.
1229   if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1230     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtoc), DestReg)
1231       .addGlobalAddress(GV).addReg(PPC::X2);
1232   else {
1233     // If the address is an externally defined symbol, a symbol with
1234     // common or externally available linkage, a function address, or a
1235     // jump table address (not yet needed), or if we are generating code
1236     // for large code model, we generate:
1237     //       LDtocL(GV, ADDIStocHA(%X2, GV))
1238     // Otherwise we generate:
1239     //       ADDItocL(ADDIStocHA(%X2, GV), GV)
1240     // Either way, start with the ADDIStocHA:
1241     unsigned HighPartReg = createResultReg(RC);
1242     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1243             HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1244
1245     // !GVar implies a function address.  An external variable is one
1246     // without an initializer.
1247     // If/when switches are implemented, jump tables should be handled
1248     // on the "if" path here.
1249     if (CModel == CodeModel::Large || !GVar || !GVar->hasInitializer() ||
1250         GVar->hasCommonLinkage() || GVar->hasAvailableExternallyLinkage())
1251       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocL),
1252               DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1253     else
1254       // Otherwise generate the ADDItocL.
1255       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDItocL),
1256               DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1257   }
1258
1259   return DestReg;
1260 }
1261
1262 // Materialize a 32-bit integer constant into a register, and return
1263 // the register number (or zero if we failed to handle it).
1264 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1265                                              const TargetRegisterClass *RC) {
1266   unsigned Lo = Imm & 0xFFFF;
1267   unsigned Hi = (Imm >> 16) & 0xFFFF;
1268
1269   unsigned ResultReg = createResultReg(RC);
1270   bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1271
1272   if (isInt<16>(Imm))
1273     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1274             TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1275       .addImm(Imm);
1276   else if (Lo) {
1277     // Both Lo and Hi have nonzero bits.
1278     unsigned TmpReg = createResultReg(RC);
1279     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1280             TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1281       .addImm(Hi);
1282     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1283             TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1284       .addReg(TmpReg).addImm(Lo);
1285   } else
1286     // Just Hi bits.
1287     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1288             TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1289       .addImm(Hi);
1290   
1291   return ResultReg;
1292 }
1293
1294 // Materialize a 64-bit integer constant into a register, and return
1295 // the register number (or zero if we failed to handle it).
1296 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1297                                              const TargetRegisterClass *RC) {
1298   unsigned Remainder = 0;
1299   unsigned Shift = 0;
1300
1301   // If the value doesn't fit in 32 bits, see if we can shift it
1302   // so that it fits in 32 bits.
1303   if (!isInt<32>(Imm)) {
1304     Shift = countTrailingZeros<uint64_t>(Imm);
1305     int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1306
1307     if (isInt<32>(ImmSh))
1308       Imm = ImmSh;
1309     else {
1310       Remainder = Imm;
1311       Shift = 32;
1312       Imm >>= 32;
1313     }
1314   }
1315
1316   // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1317   // (if not shifted).
1318   unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1319   if (!Shift)
1320     return TmpReg1;
1321
1322   // If upper 32 bits were not zero, we've built them and need to shift
1323   // them into place.
1324   unsigned TmpReg2;
1325   if (Imm) {
1326     TmpReg2 = createResultReg(RC);
1327     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLDICR),
1328             TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1329   } else
1330     TmpReg2 = TmpReg1;
1331
1332   unsigned TmpReg3, Hi, Lo;
1333   if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1334     TmpReg3 = createResultReg(RC);
1335     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORIS8),
1336             TmpReg3).addReg(TmpReg2).addImm(Hi);
1337   } else
1338     TmpReg3 = TmpReg2;
1339
1340   if ((Lo = Remainder & 0xFFFF)) {
1341     unsigned ResultReg = createResultReg(RC);
1342     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORI8),
1343             ResultReg).addReg(TmpReg3).addImm(Lo);
1344     return ResultReg;
1345   }
1346
1347   return TmpReg3;
1348 }
1349
1350
1351 // Materialize an integer constant into a register, and return
1352 // the register number (or zero if we failed to handle it).
1353 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
1354
1355   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1356       VT != MVT::i8 && VT != MVT::i1) 
1357     return 0;
1358
1359   const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
1360                                    &PPC::GPRCRegClass);
1361
1362   // If the constant is in range, use a load-immediate.
1363   const ConstantInt *CI = cast<ConstantInt>(C);
1364   if (isInt<16>(CI->getSExtValue())) {
1365     unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
1366     unsigned ImmReg = createResultReg(RC);
1367     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ImmReg)
1368       .addImm(CI->getSExtValue());
1369     return ImmReg;
1370   }
1371
1372   // Construct the constant piecewise.
1373   int64_t Imm = CI->getZExtValue();
1374
1375   if (VT == MVT::i64)
1376     return PPCMaterialize64BitInt(Imm, RC);
1377   else if (VT == MVT::i32)
1378     return PPCMaterialize32BitInt(Imm, RC);
1379
1380   return 0;
1381 }
1382
1383 // Materialize a constant into a register, and return the register
1384 // number (or zero if we failed to handle it).
1385 unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
1386   EVT CEVT = TLI.getValueType(C->getType(), true);
1387
1388   // Only handle simple types.
1389   if (!CEVT.isSimple()) return 0;
1390   MVT VT = CEVT.getSimpleVT();
1391
1392   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1393     return PPCMaterializeFP(CFP, VT);
1394   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1395     return PPCMaterializeGV(GV, VT);
1396   else if (isa<ConstantInt>(C))
1397     return PPCMaterializeInt(C, VT);
1398   // TBD: Global values.
1399
1400   return 0;
1401 }
1402
1403 // Materialize the address created by an alloca into a register, and
1404 // return the register number (or zero if we failed to handle it).  TBD.
1405 unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
1406   return AI && 0;
1407 }
1408
1409 // Fold loads into extends when possible.
1410 // FIXME: We can have multiple redundant extend/trunc instructions
1411 // following a load.  The folding only picks up one.  Extend this
1412 // to check subsequent instructions for the same pattern and remove
1413 // them.  Thus ResultReg should be the def reg for the last redundant
1414 // instruction in a chain, and all intervening instructions can be
1415 // removed from parent.  Change test/CodeGen/PowerPC/fast-isel-fold.ll
1416 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
1417 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
1418                                       const LoadInst *LI) {
1419   // Verify we have a legal type before going any further.
1420   MVT VT;
1421   if (!isLoadTypeLegal(LI->getType(), VT))
1422     return false;
1423
1424   // Combine load followed by zero- or sign-extend.
1425   bool IsZExt = false;
1426   switch(MI->getOpcode()) {
1427     default:
1428       return false;
1429
1430     case PPC::RLDICL:
1431     case PPC::RLDICL_32_64: {
1432       IsZExt = true;
1433       unsigned MB = MI->getOperand(3).getImm();
1434       if ((VT == MVT::i8 && MB <= 56) ||
1435           (VT == MVT::i16 && MB <= 48) ||
1436           (VT == MVT::i32 && MB <= 32))
1437         break;
1438       return false;
1439     }
1440
1441     case PPC::RLWINM:
1442     case PPC::RLWINM8: {
1443       IsZExt = true;
1444       unsigned MB = MI->getOperand(3).getImm();
1445       if ((VT == MVT::i8 && MB <= 24) ||
1446           (VT == MVT::i16 && MB <= 16))
1447         break;
1448       return false;
1449     }
1450
1451     case PPC::EXTSB:
1452     case PPC::EXTSB8:
1453     case PPC::EXTSB8_32_64:
1454       /* There is no sign-extending load-byte instruction. */
1455       return false;
1456
1457     case PPC::EXTSH:
1458     case PPC::EXTSH8:
1459     case PPC::EXTSH8_32_64: {
1460       if (VT != MVT::i16 && VT != MVT::i8)
1461         return false;
1462       break;
1463     }
1464
1465     case PPC::EXTSW:
1466     case PPC::EXTSW_32_64: {
1467       if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
1468         return false;
1469       break;
1470     }
1471   }
1472
1473   // See if we can handle this address.
1474   Address Addr;
1475   if (!PPCComputeAddress(LI->getOperand(0), Addr))
1476     return false;
1477
1478   unsigned ResultReg = MI->getOperand(0).getReg();
1479
1480   if (!PPCEmitLoad(VT, ResultReg, Addr, 0, IsZExt))
1481     return false;
1482
1483   MI->eraseFromParent();
1484   return true;
1485 }
1486
1487 // Attempt to lower call arguments in a faster way than done by
1488 // the selection DAG code.
1489 bool PPCFastISel::FastLowerArguments() {
1490   // Defer to normal argument lowering for now.  It's reasonably
1491   // efficient.  Consider doing something like ARM to handle the
1492   // case where all args fit in registers, no varargs, no float
1493   // or vector args.
1494   return false;
1495 }
1496
1497 // Handle materializing integer constants into a register.  This is not
1498 // automatically generated for PowerPC, so must be explicitly created here.
1499 unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
1500   
1501   if (Opc != ISD::Constant)
1502     return 0;
1503
1504   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1505       VT != MVT::i8 && VT != MVT::i1) 
1506     return 0;
1507
1508   const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
1509                                    &PPC::GPRCRegClass);
1510   if (VT == MVT::i64)
1511     return PPCMaterialize64BitInt(Imm, RC);
1512   else
1513     return PPCMaterialize32BitInt(Imm, RC);
1514 }
1515
1516 // Override for ADDI and ADDI8 to set the correct register class
1517 // on RHS operand 0.  The automatic infrastructure naively assumes
1518 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
1519 // for these cases.  At the moment, none of the other automatically
1520 // generated RI instructions require special treatment.  However, once
1521 // SelectSelect is implemented, "isel" requires similar handling.
1522 //
1523 // Also be conservative about the output register class.  Avoid
1524 // assigning R0 or X0 to the output register for GPRC and G8RC
1525 // register classes, as any such result could be used in ADDI, etc.,
1526 // where those regs have another meaning.
1527 unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1528                                       const TargetRegisterClass *RC,
1529                                       unsigned Op0, bool Op0IsKill,
1530                                       uint64_t Imm) {
1531   if (MachineInstOpcode == PPC::ADDI)
1532     MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
1533   else if (MachineInstOpcode == PPC::ADDI8)
1534     MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
1535
1536   const TargetRegisterClass *UseRC =
1537     (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
1538      (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
1539
1540   return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
1541                                    Op0, Op0IsKill, Imm);
1542 }
1543
1544 // Override for instructions with one register operand to avoid use of
1545 // R0/X0.  The automatic infrastructure isn't aware of the context so
1546 // we must be conservative.
1547 unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1548                                      const TargetRegisterClass* RC,
1549                                      unsigned Op0, bool Op0IsKill) {
1550   const TargetRegisterClass *UseRC =
1551     (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
1552      (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
1553
1554   return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
1555 }
1556
1557 // Override for instructions with two register operands to avoid use
1558 // of R0/X0.  The automatic infrastructure isn't aware of the context
1559 // so we must be conservative.
1560 unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1561                                       const TargetRegisterClass* RC,
1562                                       unsigned Op0, bool Op0IsKill,
1563                                       unsigned Op1, bool Op1IsKill) {
1564   const TargetRegisterClass *UseRC =
1565     (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
1566      (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
1567
1568   return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
1569                                    Op1, Op1IsKill);
1570 }
1571
1572 namespace llvm {
1573   // Create the fast instruction selector for PowerPC64 ELF.
1574   FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
1575                                 const TargetLibraryInfo *LibInfo) {
1576     const TargetMachine &TM = FuncInfo.MF->getTarget();
1577
1578     // Only available on 64-bit ELF for now.
1579     const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
1580     if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
1581       return new PPCFastISel(FuncInfo, LibInfo);
1582
1583     return 0;
1584   }
1585 }