1 //===-- PPCFastISel.cpp - PowerPC FastISel implementation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "ppcfastisel"
18 #include "MCTargetDesc/PPCPredicates.h"
19 #include "PPCISelLowering.h"
20 #include "PPCSubtarget.h"
21 #include "PPCTargetMachine.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/FastISel.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/GetElementPtrTypeIterator.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
40 //===----------------------------------------------------------------------===//
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.
58 //===----------------------------------------------------------------------===//
63 typedef struct Address {
76 // Innocuous defaults for our address.
78 : BaseType(RegBase), Offset(0) {
83 class PPCFastISel final : public FastISel {
85 const TargetMachine &TM;
86 const TargetInstrInfo &TII;
87 const TargetLowering &TLI;
88 const PPCSubtarget &PPCSubTarget;
92 explicit PPCFastISel(FunctionLoweringInfo &FuncInfo,
93 const TargetLibraryInfo *LibInfo)
94 : FastISel(FuncInfo, LibInfo),
95 TM(FuncInfo.MF->getTarget()),
96 TII(*TM.getInstrInfo()),
97 TLI(*TM.getTargetLowering()),
99 *((static_cast<const PPCTargetMachine *>(&TM))->getSubtargetImpl())
101 Context(&FuncInfo.Fn->getContext()) { }
103 // Backend specific FastISel code.
105 virtual bool TargetSelectInstruction(const Instruction *I);
106 virtual unsigned TargetMaterializeConstant(const Constant *C);
107 virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
108 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
110 virtual bool FastLowerArguments();
111 virtual unsigned FastEmit_i(MVT Ty, MVT RetTy, unsigned Opc, uint64_t Imm);
112 virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
113 const TargetRegisterClass *RC,
114 unsigned Op0, bool Op0IsKill,
116 virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
117 const TargetRegisterClass *RC,
118 unsigned Op0, bool Op0IsKill);
119 virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
120 const TargetRegisterClass *RC,
121 unsigned Op0, bool Op0IsKill,
122 unsigned Op1, bool Op1IsKill);
124 // Instruction selection routines.
126 bool SelectLoad(const Instruction *I);
127 bool SelectStore(const Instruction *I);
128 bool SelectBranch(const Instruction *I);
129 bool SelectIndirectBr(const Instruction *I);
130 bool SelectFPExt(const Instruction *I);
131 bool SelectFPTrunc(const Instruction *I);
132 bool SelectIToFP(const Instruction *I, bool IsSigned);
133 bool SelectFPToI(const Instruction *I, bool IsSigned);
134 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
135 bool SelectCall(const Instruction *I);
136 bool SelectRet(const Instruction *I);
137 bool SelectTrunc(const Instruction *I);
138 bool SelectIntExt(const Instruction *I);
142 bool isTypeLegal(Type *Ty, MVT &VT);
143 bool isLoadTypeLegal(Type *Ty, MVT &VT);
144 bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
145 bool isZExt, unsigned DestReg);
146 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
147 const TargetRegisterClass *RC, bool IsZExt = true,
148 unsigned FP64LoadOpc = PPC::LFD);
149 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
150 bool PPCComputeAddress(const Value *Obj, Address &Addr);
151 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
153 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
154 unsigned DestReg, bool IsZExt);
155 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
156 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
157 unsigned PPCMaterializeInt(const Constant *C, MVT VT);
158 unsigned PPCMaterialize32BitInt(int64_t Imm,
159 const TargetRegisterClass *RC);
160 unsigned PPCMaterialize64BitInt(int64_t Imm,
161 const TargetRegisterClass *RC);
162 unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
163 unsigned SrcReg, bool IsSigned);
164 unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
166 // Call handling routines.
168 bool processCallArgs(SmallVectorImpl<Value*> &Args,
169 SmallVectorImpl<unsigned> &ArgRegs,
170 SmallVectorImpl<MVT> &ArgVTs,
171 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
172 SmallVectorImpl<unsigned> &RegArgs,
176 void finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
177 const Instruction *I, CallingConv::ID CC,
178 unsigned &NumBytes, bool IsVarArg);
179 CCAssignFn *usePPC32CCs(unsigned Flag);
182 #include "PPCGenFastISel.inc"
186 } // end anonymous namespace
188 #include "PPCGenCallingConv.inc"
190 // Function whose sole purpose is to kill compiler warnings
191 // stemming from unused functions included from PPCGenCallingConv.inc.
192 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
194 return CC_PPC32_SVR4;
196 return CC_PPC32_SVR4_ByVal;
198 return CC_PPC32_SVR4_VarArg;
203 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
205 // These are not representable with any single compare.
206 case CmpInst::FCMP_FALSE:
207 case CmpInst::FCMP_UEQ:
208 case CmpInst::FCMP_UGT:
209 case CmpInst::FCMP_UGE:
210 case CmpInst::FCMP_ULT:
211 case CmpInst::FCMP_ULE:
212 case CmpInst::FCMP_UNE:
213 case CmpInst::FCMP_TRUE:
215 return Optional<PPC::Predicate>();
217 case CmpInst::FCMP_OEQ:
218 case CmpInst::ICMP_EQ:
221 case CmpInst::FCMP_OGT:
222 case CmpInst::ICMP_UGT:
223 case CmpInst::ICMP_SGT:
226 case CmpInst::FCMP_OGE:
227 case CmpInst::ICMP_UGE:
228 case CmpInst::ICMP_SGE:
231 case CmpInst::FCMP_OLT:
232 case CmpInst::ICMP_ULT:
233 case CmpInst::ICMP_SLT:
236 case CmpInst::FCMP_OLE:
237 case CmpInst::ICMP_ULE:
238 case CmpInst::ICMP_SLE:
241 case CmpInst::FCMP_ONE:
242 case CmpInst::ICMP_NE:
245 case CmpInst::FCMP_ORD:
248 case CmpInst::FCMP_UNO:
253 // Determine whether the type Ty is simple enough to be handled by
254 // fast-isel, and return its equivalent machine type in VT.
255 // FIXME: Copied directly from ARM -- factor into base class?
256 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
257 EVT Evt = TLI.getValueType(Ty, true);
259 // Only handle simple types.
260 if (Evt == MVT::Other || !Evt.isSimple()) return false;
261 VT = Evt.getSimpleVT();
263 // Handle all legal types, i.e. a register that will directly hold this
265 return TLI.isTypeLegal(VT);
268 // Determine whether the type Ty is simple enough to be handled by
269 // fast-isel as a load target, and return its equivalent machine type in VT.
270 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
271 if (isTypeLegal(Ty, VT)) return true;
273 // If this is a type than can be sign or zero-extended to a basic operation
274 // go ahead and accept it now.
275 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
282 // Given a value Obj, create an Address object Addr that represents its
283 // address. Return false if we can't handle it.
284 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
285 const User *U = NULL;
286 unsigned Opcode = Instruction::UserOp1;
287 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
288 // Don't walk into other basic blocks unless the object is an alloca from
289 // another block, otherwise it may not have a virtual register assigned.
290 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
291 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
292 Opcode = I->getOpcode();
295 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
296 Opcode = C->getOpcode();
303 case Instruction::BitCast:
304 // Look through bitcasts.
305 return PPCComputeAddress(U->getOperand(0), Addr);
306 case Instruction::IntToPtr:
307 // Look past no-op inttoptrs.
308 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
309 return PPCComputeAddress(U->getOperand(0), Addr);
311 case Instruction::PtrToInt:
312 // Look past no-op ptrtoints.
313 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
314 return PPCComputeAddress(U->getOperand(0), Addr);
316 case Instruction::GetElementPtr: {
317 Address SavedAddr = Addr;
318 long TmpOffset = Addr.Offset;
320 // Iterate through the GEP folding the constants into offsets where
322 gep_type_iterator GTI = gep_type_begin(U);
323 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
324 II != IE; ++II, ++GTI) {
325 const Value *Op = *II;
326 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
327 const StructLayout *SL = DL.getStructLayout(STy);
328 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
329 TmpOffset += SL->getElementOffset(Idx);
331 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
333 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
334 // Constant-offset addressing.
335 TmpOffset += CI->getSExtValue() * S;
338 if (canFoldAddIntoGEP(U, Op)) {
339 // A compatible add with a constant operand. Fold the constant.
341 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
342 TmpOffset += CI->getSExtValue() * S;
343 // Iterate on the other operand.
344 Op = cast<AddOperator>(Op)->getOperand(0);
348 goto unsupported_gep;
353 // Try to grab the base operand now.
354 Addr.Offset = TmpOffset;
355 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
357 // We failed, restore everything and try the other options.
363 case Instruction::Alloca: {
364 const AllocaInst *AI = cast<AllocaInst>(Obj);
365 DenseMap<const AllocaInst*, int>::iterator SI =
366 FuncInfo.StaticAllocaMap.find(AI);
367 if (SI != FuncInfo.StaticAllocaMap.end()) {
368 Addr.BaseType = Address::FrameIndexBase;
369 Addr.Base.FI = SI->second;
376 // FIXME: References to parameters fall through to the behavior
377 // below. They should be able to reference a frame index since
378 // they are stored to the stack, so we can get "ld rx, offset(r1)"
379 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
380 // just contain the parameter. Try to handle this with a FI.
382 // Try to get this in a register if nothing else has worked.
383 if (Addr.Base.Reg == 0)
384 Addr.Base.Reg = getRegForValue(Obj);
386 // Prevent assignment of base register to X0, which is inappropriate
387 // for loads and stores alike.
388 if (Addr.Base.Reg != 0)
389 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
391 return Addr.Base.Reg != 0;
394 // Fix up some addresses that can't be used directly. For example, if
395 // an offset won't fit in an instruction field, we may need to move it
396 // into an index register.
397 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
398 unsigned &IndexReg) {
400 // Check whether the offset fits in the instruction field.
401 if (!isInt<16>(Addr.Offset))
404 // If this is a stack pointer and the offset needs to be simplified then
405 // put the alloca address into a register, set the base type back to
406 // register and continue. This should almost never happen.
407 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
408 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
409 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
410 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
411 Addr.Base.Reg = ResultReg;
412 Addr.BaseType = Address::RegBase;
416 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
417 : Type::getInt64Ty(*Context));
418 const ConstantInt *Offset =
419 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
420 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
421 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
425 // Emit a load instruction if possible, returning true if we succeeded,
426 // otherwise false. See commentary below for how the register class of
427 // the load is determined.
428 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
429 const TargetRegisterClass *RC,
430 bool IsZExt, unsigned FP64LoadOpc) {
432 bool UseOffset = true;
434 // If ResultReg is given, it determines the register class of the load.
435 // Otherwise, RC is the register class to use. If the result of the
436 // load isn't anticipated in this block, both may be zero, in which
437 // case we must make a conservative guess. In particular, don't assign
438 // R0 or X0 to the result register, as the result may be used in a load,
439 // store, add-immediate, or isel that won't permit this. (Though
440 // perhaps the spill and reload of live-exit values would handle this?)
441 const TargetRegisterClass *UseRC =
442 (ResultReg ? MRI.getRegClass(ResultReg) :
444 (VT == MVT::f64 ? &PPC::F8RCRegClass :
445 (VT == MVT::f32 ? &PPC::F4RCRegClass :
446 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
447 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
449 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
451 switch (VT.SimpleTy) {
452 default: // e.g., vector types not handled
455 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
459 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
460 (Is32BitInt ? PPC::LHA : PPC::LHA8));
464 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
465 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
466 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
471 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
472 "64-bit load with 32-bit target??");
473 UseOffset = ((Addr.Offset & 3) == 0);
483 // If necessary, materialize the offset into a register and use
484 // the indexed form. Also handle stack pointers with special needs.
485 unsigned IndexReg = 0;
486 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
488 ResultReg = createResultReg(UseRC);
490 // Note: If we still have a frame index here, we know the offset is
491 // in range, as otherwise PPCSimplifyAddress would have converted it
493 if (Addr.BaseType == Address::FrameIndexBase) {
495 MachineMemOperand *MMO =
496 FuncInfo.MF->getMachineMemOperand(
497 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
498 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
499 MFI.getObjectAlignment(Addr.Base.FI));
501 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
502 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
504 // Base reg with offset in range.
505 } else if (UseOffset) {
507 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
508 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
512 // Get the RR opcode corresponding to the RI one. FIXME: It would be
513 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
514 // is hard to get at.
516 default: llvm_unreachable("Unexpected opcode!");
517 case PPC::LBZ: Opc = PPC::LBZX; break;
518 case PPC::LBZ8: Opc = PPC::LBZX8; break;
519 case PPC::LHZ: Opc = PPC::LHZX; break;
520 case PPC::LHZ8: Opc = PPC::LHZX8; break;
521 case PPC::LHA: Opc = PPC::LHAX; break;
522 case PPC::LHA8: Opc = PPC::LHAX8; break;
523 case PPC::LWZ: Opc = PPC::LWZX; break;
524 case PPC::LWZ8: Opc = PPC::LWZX8; break;
525 case PPC::LWA: Opc = PPC::LWAX; break;
526 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
527 case PPC::LD: Opc = PPC::LDX; break;
528 case PPC::LFS: Opc = PPC::LFSX; break;
529 case PPC::LFD: Opc = PPC::LFDX; break;
531 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
532 .addReg(Addr.Base.Reg).addReg(IndexReg);
538 // Attempt to fast-select a load instruction.
539 bool PPCFastISel::SelectLoad(const Instruction *I) {
540 // FIXME: No atomic loads are supported.
541 if (cast<LoadInst>(I)->isAtomic())
544 // Verify we have a legal type before going any further.
546 if (!isLoadTypeLegal(I->getType(), VT))
549 // See if we can handle this address.
551 if (!PPCComputeAddress(I->getOperand(0), Addr))
554 // Look at the currently assigned register for this instruction
555 // to determine the required register class. This is necessary
556 // to constrain RA from using R0/X0 when this is not legal.
557 unsigned AssignedReg = FuncInfo.ValueMap[I];
558 const TargetRegisterClass *RC =
559 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
561 unsigned ResultReg = 0;
562 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
564 UpdateValueMap(I, ResultReg);
568 // Emit a store instruction to store SrcReg at Addr.
569 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
570 assert(SrcReg && "Nothing to store!");
572 bool UseOffset = true;
574 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
575 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
577 switch (VT.SimpleTy) {
578 default: // e.g., vector types not handled
581 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
584 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
587 assert(Is32BitInt && "Not GPRC for i32??");
592 UseOffset = ((Addr.Offset & 3) == 0);
602 // If necessary, materialize the offset into a register and use
603 // the indexed form. Also handle stack pointers with special needs.
604 unsigned IndexReg = 0;
605 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
607 // Note: If we still have a frame index here, we know the offset is
608 // in range, as otherwise PPCSimplifyAddress would have converted it
610 if (Addr.BaseType == Address::FrameIndexBase) {
611 MachineMemOperand *MMO =
612 FuncInfo.MF->getMachineMemOperand(
613 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
614 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
615 MFI.getObjectAlignment(Addr.Base.FI));
617 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
620 .addFrameIndex(Addr.Base.FI)
623 // Base reg with offset in range.
624 } else if (UseOffset)
625 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
626 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
630 // Get the RR opcode corresponding to the RI one. FIXME: It would be
631 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
632 // is hard to get at.
634 default: llvm_unreachable("Unexpected opcode!");
635 case PPC::STB: Opc = PPC::STBX; break;
636 case PPC::STH : Opc = PPC::STHX; break;
637 case PPC::STW : Opc = PPC::STWX; break;
638 case PPC::STB8: Opc = PPC::STBX8; break;
639 case PPC::STH8: Opc = PPC::STHX8; break;
640 case PPC::STW8: Opc = PPC::STWX8; break;
641 case PPC::STD: Opc = PPC::STDX; break;
642 case PPC::STFS: Opc = PPC::STFSX; break;
643 case PPC::STFD: Opc = PPC::STFDX; break;
645 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
646 .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
652 // Attempt to fast-select a store instruction.
653 bool PPCFastISel::SelectStore(const Instruction *I) {
654 Value *Op0 = I->getOperand(0);
657 // FIXME: No atomics loads are supported.
658 if (cast<StoreInst>(I)->isAtomic())
661 // Verify we have a legal type before going any further.
663 if (!isLoadTypeLegal(Op0->getType(), VT))
666 // Get the value to be stored into a register.
667 SrcReg = getRegForValue(Op0);
671 // See if we can handle this address.
673 if (!PPCComputeAddress(I->getOperand(1), Addr))
676 if (!PPCEmitStore(VT, SrcReg, Addr))
682 // Attempt to fast-select a branch instruction.
683 bool PPCFastISel::SelectBranch(const Instruction *I) {
684 const BranchInst *BI = cast<BranchInst>(I);
685 MachineBasicBlock *BrBB = FuncInfo.MBB;
686 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
687 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
689 // For now, just try the simplest case where it's fed by a compare.
690 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
691 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
695 PPC::Predicate PPCPred = OptPPCPred.getValue();
697 // Take advantage of fall-through opportunities.
698 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
700 PPCPred = PPC::InvertPredicate(PPCPred);
703 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
705 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
709 BuildMI(*BrBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCC))
710 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
711 FastEmitBranch(FBB, DbgLoc);
712 FuncInfo.MBB->addSuccessor(TBB);
715 } else if (const ConstantInt *CI =
716 dyn_cast<ConstantInt>(BI->getCondition())) {
717 uint64_t Imm = CI->getZExtValue();
718 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
719 FastEmitBranch(Target, DbgLoc);
723 // FIXME: ARM looks for a case where the block containing the compare
724 // has been split from the block containing the branch. If this happens,
725 // there is a vreg available containing the result of the compare. I'm
726 // not sure we can do much, as we've lost the predicate information with
727 // the compare instruction -- we have a 4-bit CR but don't know which bit
732 // Attempt to emit a compare of the two source values. Signed and unsigned
733 // comparisons are supported. Return false if we can't handle it.
734 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
735 bool IsZExt, unsigned DestReg) {
736 Type *Ty = SrcValue1->getType();
737 EVT SrcEVT = TLI.getValueType(Ty, true);
738 if (!SrcEVT.isSimple())
740 MVT SrcVT = SrcEVT.getSimpleVT();
742 if (SrcVT == MVT::i1 && PPCSubTarget.useCRBits())
745 // See if operand 2 is an immediate encodeable in the compare.
746 // FIXME: Operands are not in canonical order at -O0, so an immediate
747 // operand in position 1 is a lost opportunity for now. We are
748 // similar to ARM in this regard.
752 // Only 16-bit integer constants can be represented in compares for
753 // PowerPC. Others will be materialized into a register.
754 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
755 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
756 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
757 const APInt &CIVal = ConstInt->getValue();
758 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
759 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
765 bool NeedsExt = false;
766 switch (SrcVT.SimpleTy) {
767 default: return false;
769 CmpOpc = PPC::FCMPUS;
772 CmpOpc = PPC::FCMPUD;
778 // Intentional fall-through.
781 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
783 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
787 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
789 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
793 unsigned SrcReg1 = getRegForValue(SrcValue1);
797 unsigned SrcReg2 = 0;
799 SrcReg2 = getRegForValue(SrcValue2);
805 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
806 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
811 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
812 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
819 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
820 .addReg(SrcReg1).addReg(SrcReg2);
822 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), DestReg)
823 .addReg(SrcReg1).addImm(Imm);
828 // Attempt to fast-select a floating-point extend instruction.
829 bool PPCFastISel::SelectFPExt(const Instruction *I) {
830 Value *Src = I->getOperand(0);
831 EVT SrcVT = TLI.getValueType(Src->getType(), true);
832 EVT DestVT = TLI.getValueType(I->getType(), true);
834 if (SrcVT != MVT::f32 || DestVT != MVT::f64)
837 unsigned SrcReg = getRegForValue(Src);
841 // No code is generated for a FP extend.
842 UpdateValueMap(I, SrcReg);
846 // Attempt to fast-select a floating-point truncate instruction.
847 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
848 Value *Src = I->getOperand(0);
849 EVT SrcVT = TLI.getValueType(Src->getType(), true);
850 EVT DestVT = TLI.getValueType(I->getType(), true);
852 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
855 unsigned SrcReg = getRegForValue(Src);
859 // Round the result to single precision.
860 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
861 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP), DestReg)
864 UpdateValueMap(I, DestReg);
868 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
869 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
870 // those should be used instead of moving via a stack slot when the
871 // subtarget permits.
872 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
873 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
874 // case to 8 bytes which produces tighter code but wastes stack space.
875 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
878 // If necessary, extend 32-bit int to 64-bit.
879 if (SrcVT == MVT::i32) {
880 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
881 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
886 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
888 Addr.BaseType = Address::FrameIndexBase;
889 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
891 // Store the value from the GPR.
892 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
895 // Load the integer value into an FPR. The kind of load used depends
896 // on a number of conditions.
897 unsigned LoadOpc = PPC::LFD;
899 if (SrcVT == MVT::i32) {
901 LoadOpc = PPC::LFIWZX;
903 } else if (PPCSubTarget.hasLFIWAX()) {
904 LoadOpc = PPC::LFIWAX;
909 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
910 unsigned ResultReg = 0;
911 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
917 // Attempt to fast-select an integer-to-floating-point conversion.
918 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
920 Type *DstTy = I->getType();
921 if (!isTypeLegal(DstTy, DstVT))
924 if (DstVT != MVT::f32 && DstVT != MVT::f64)
927 Value *Src = I->getOperand(0);
928 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
929 if (!SrcEVT.isSimple())
932 MVT SrcVT = SrcEVT.getSimpleVT();
934 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
935 SrcVT != MVT::i32 && SrcVT != MVT::i64)
938 unsigned SrcReg = getRegForValue(Src);
942 // We can only lower an unsigned convert if we have the newer
943 // floating-point conversion operations.
944 if (!IsSigned && !PPCSubTarget.hasFPCVT())
947 // FIXME: For now we require the newer floating-point conversion operations
948 // (which are present only on P7 and A2 server models) when converting
949 // to single-precision float. Otherwise we have to generate a lot of
950 // fiddly code to avoid double rounding. If necessary, the fiddly code
951 // can be found in PPCTargetLowering::LowerINT_TO_FP().
952 if (DstVT == MVT::f32 && !PPCSubTarget.hasFPCVT())
955 // Extend the input if necessary.
956 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
957 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
958 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
964 // Move the integer value to an FPR.
965 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
969 // Determine the opcode for the conversion.
970 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
971 unsigned DestReg = createResultReg(RC);
974 if (DstVT == MVT::f32)
975 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
977 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
979 // Generate the convert.
980 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
983 UpdateValueMap(I, DestReg);
987 // Move the floating-point value in SrcReg into an integer destination
988 // register, and return the register (or zero if we can't handle it).
989 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
990 // those should be used instead of moving via a stack slot when the
991 // subtarget permits.
992 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
993 unsigned SrcReg, bool IsSigned) {
994 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
995 // Note that if have STFIWX available, we could use a 4-byte stack
996 // slot for i32, but this being fast-isel we'll just go with the
997 // easiest code gen possible.
999 Addr.BaseType = Address::FrameIndexBase;
1000 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
1002 // Store the value from the FPR.
1003 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
1006 // Reload it into a GPR. If we want an i32, modify the address
1007 // to have a 4-byte offset so we load from the right place.
1011 // Look at the currently assigned register for this instruction
1012 // to determine the required register class.
1013 unsigned AssignedReg = FuncInfo.ValueMap[I];
1014 const TargetRegisterClass *RC =
1015 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
1017 unsigned ResultReg = 0;
1018 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1024 // Attempt to fast-select a floating-point-to-integer conversion.
1025 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1027 Type *DstTy = I->getType();
1028 if (!isTypeLegal(DstTy, DstVT))
1031 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1034 Value *Src = I->getOperand(0);
1035 Type *SrcTy = Src->getType();
1036 if (!isTypeLegal(SrcTy, SrcVT))
1039 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1042 unsigned SrcReg = getRegForValue(Src);
1046 // Convert f32 to f64 if necessary. This is just a meaningless copy
1047 // to get the register class right. COPY_TO_REGCLASS is needed since
1048 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1049 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1050 if (InRC == &PPC::F4RCRegClass) {
1051 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1052 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1053 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1054 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1058 // Determine the opcode for the conversion, which takes place
1059 // entirely within FPRs.
1060 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1063 if (DstVT == MVT::i32)
1067 Opc = PPCSubTarget.hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1069 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1071 // Generate the convert.
1072 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1075 // Now move the integer value from a float register to an integer register.
1076 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1080 UpdateValueMap(I, IntReg);
1084 // Attempt to fast-select a binary integer operation that isn't already
1085 // handled automatically.
1086 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1087 EVT DestVT = TLI.getValueType(I->getType(), true);
1089 // We can get here in the case when we have a binary operation on a non-legal
1090 // type and the target independent selector doesn't know how to handle it.
1091 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1094 // Look at the currently assigned register for this instruction
1095 // to determine the required register class. If there is no register,
1096 // make a conservative choice (don't assign R0).
1097 unsigned AssignedReg = FuncInfo.ValueMap[I];
1098 const TargetRegisterClass *RC =
1099 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1100 &PPC::GPRC_and_GPRC_NOR0RegClass);
1101 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1104 switch (ISDOpcode) {
1105 default: return false;
1107 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1110 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1113 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1117 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1118 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1119 if (SrcReg1 == 0) return false;
1121 // Handle case of small immediate operand.
1122 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1123 const APInt &CIVal = ConstInt->getValue();
1124 int Imm = (int)CIVal.getSExtValue();
1126 if (isInt<16>(Imm)) {
1129 llvm_unreachable("Missing case!");
1132 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1136 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1149 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1158 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1165 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1169 UpdateValueMap(I, ResultReg);
1176 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1177 if (SrcReg2 == 0) return false;
1179 // Reverse operands for subtract-from.
1180 if (ISDOpcode == ISD::SUB)
1181 std::swap(SrcReg1, SrcReg2);
1183 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1184 .addReg(SrcReg1).addReg(SrcReg2);
1185 UpdateValueMap(I, ResultReg);
1189 // Handle arguments to a call that we're attempting to fast-select.
1190 // Return false if the arguments are too complex for us at the moment.
1191 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1192 SmallVectorImpl<unsigned> &ArgRegs,
1193 SmallVectorImpl<MVT> &ArgVTs,
1194 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1195 SmallVectorImpl<unsigned> &RegArgs,
1199 SmallVector<CCValAssign, 16> ArgLocs;
1200 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, ArgLocs, *Context);
1201 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1203 // Bail out if we can't handle any of the arguments.
1204 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1205 CCValAssign &VA = ArgLocs[I];
1206 MVT ArgVT = ArgVTs[VA.getValNo()];
1208 // Skip vector arguments for now, as well as long double and
1209 // uint128_t, and anything that isn't passed in a register.
1210 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 || ArgVT == MVT::i1 ||
1211 !VA.isRegLoc() || VA.needsCustom())
1214 // Skip bit-converted arguments for now.
1215 if (VA.getLocInfo() == CCValAssign::BCvt)
1219 // Get a count of how many bytes are to be pushed onto the stack.
1220 NumBytes = CCInfo.getNextStackOffset();
1222 // Issue CALLSEQ_START.
1223 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1224 TII.get(TII.getCallFrameSetupOpcode()))
1227 // Prepare to assign register arguments. Every argument uses up a
1228 // GPR protocol register even if it's passed in a floating-point
1230 unsigned NextGPR = PPC::X3;
1231 unsigned NextFPR = PPC::F1;
1233 // Process arguments.
1234 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1235 CCValAssign &VA = ArgLocs[I];
1236 unsigned Arg = ArgRegs[VA.getValNo()];
1237 MVT ArgVT = ArgVTs[VA.getValNo()];
1239 // Handle argument promotion and bitcasts.
1240 switch (VA.getLocInfo()) {
1242 llvm_unreachable("Unknown loc info!");
1243 case CCValAssign::Full:
1245 case CCValAssign::SExt: {
1246 MVT DestVT = VA.getLocVT();
1247 const TargetRegisterClass *RC =
1248 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1249 unsigned TmpReg = createResultReg(RC);
1250 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1251 llvm_unreachable("Failed to emit a sext!");
1256 case CCValAssign::AExt:
1257 case CCValAssign::ZExt: {
1258 MVT DestVT = VA.getLocVT();
1259 const TargetRegisterClass *RC =
1260 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1261 unsigned TmpReg = createResultReg(RC);
1262 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1263 llvm_unreachable("Failed to emit a zext!");
1268 case CCValAssign::BCvt: {
1269 // FIXME: Not yet handled.
1270 llvm_unreachable("Should have bailed before getting here!");
1275 // Copy this argument to the appropriate register.
1277 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1283 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1284 TII.get(TargetOpcode::COPY), ArgReg).addReg(Arg);
1285 RegArgs.push_back(ArgReg);
1291 // For a call that we've determined we can fast-select, finish the
1292 // call sequence and generate a copy to obtain the return value (if any).
1293 void PPCFastISel::finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1294 const Instruction *I, CallingConv::ID CC,
1295 unsigned &NumBytes, bool IsVarArg) {
1296 // Issue CallSEQ_END.
1297 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1298 TII.get(TII.getCallFrameDestroyOpcode()))
1299 .addImm(NumBytes).addImm(0);
1301 // Next, generate a copy to obtain the return value.
1302 // FIXME: No multi-register return values yet, though I don't foresee
1303 // any real difficulties there.
1304 if (RetVT != MVT::isVoid) {
1305 SmallVector<CCValAssign, 16> RVLocs;
1306 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1307 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1308 CCValAssign &VA = RVLocs[0];
1309 assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1310 assert(VA.isRegLoc() && "Can only return in registers!");
1312 MVT DestVT = VA.getValVT();
1313 MVT CopyVT = DestVT;
1315 // Ints smaller than a register still arrive in a full 64-bit
1316 // register, so make sure we recognize this.
1317 if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1320 unsigned SourcePhysReg = VA.getLocReg();
1321 unsigned ResultReg = 0;
1323 if (RetVT == CopyVT) {
1324 const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1325 ResultReg = createResultReg(CpyRC);
1327 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1328 TII.get(TargetOpcode::COPY), ResultReg)
1329 .addReg(SourcePhysReg);
1331 // If necessary, round the floating result to single precision.
1332 } else if (CopyVT == MVT::f64) {
1333 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1334 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::FRSP),
1335 ResultReg).addReg(SourcePhysReg);
1337 // If only the low half of a general register is needed, generate
1338 // a GPRC copy instead of a G8RC copy. (EXTRACT_SUBREG can't be
1339 // used along the fast-isel path (not lowered), and downstream logic
1340 // also doesn't like a direct subreg copy on a physical reg.)
1341 } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1342 ResultReg = createResultReg(&PPC::GPRCRegClass);
1343 // Convert physical register from G8RC to GPRC.
1344 SourcePhysReg -= PPC::X0 - PPC::R0;
1345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1346 TII.get(TargetOpcode::COPY), ResultReg)
1347 .addReg(SourcePhysReg);
1350 assert(ResultReg && "ResultReg unset!");
1351 UsedRegs.push_back(SourcePhysReg);
1352 UpdateValueMap(I, ResultReg);
1356 // Attempt to fast-select a call instruction.
1357 bool PPCFastISel::SelectCall(const Instruction *I) {
1358 const CallInst *CI = cast<CallInst>(I);
1359 const Value *Callee = CI->getCalledValue();
1361 // Can't handle inline asm.
1362 if (isa<InlineAsm>(Callee))
1365 // Allow SelectionDAG isel to handle tail calls.
1366 if (CI->isTailCall())
1369 // Obtain calling convention.
1370 ImmutableCallSite CS(CI);
1371 CallingConv::ID CC = CS.getCallingConv();
1373 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1374 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1375 bool IsVarArg = FTy->isVarArg();
1377 // Not ready for varargs yet.
1381 // Handle simple calls for now, with legal return types and
1382 // those that can be extended.
1383 Type *RetTy = I->getType();
1385 if (RetTy->isVoidTy())
1386 RetVT = MVT::isVoid;
1387 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1391 // FIXME: No multi-register return values yet.
1392 if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1393 RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1394 RetVT != MVT::f64) {
1395 SmallVector<CCValAssign, 16> RVLocs;
1396 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1397 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1398 if (RVLocs.size() > 1)
1402 // Bail early if more than 8 arguments, as we only currently
1403 // handle arguments passed in registers.
1404 unsigned NumArgs = CS.arg_size();
1408 // Set up the argument vectors.
1409 SmallVector<Value*, 8> Args;
1410 SmallVector<unsigned, 8> ArgRegs;
1411 SmallVector<MVT, 8> ArgVTs;
1412 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1414 Args.reserve(NumArgs);
1415 ArgRegs.reserve(NumArgs);
1416 ArgVTs.reserve(NumArgs);
1417 ArgFlags.reserve(NumArgs);
1419 for (ImmutableCallSite::arg_iterator II = CS.arg_begin(), IE = CS.arg_end();
1421 // FIXME: ARM does something for intrinsic calls here, check into that.
1423 unsigned AttrIdx = II - CS.arg_begin() + 1;
1425 // Only handle easy calls for now. It would be reasonably easy
1426 // to handle <= 8-byte structures passed ByVal in registers, but we
1427 // have to ensure they are right-justified in the register.
1428 if (CS.paramHasAttr(AttrIdx, Attribute::InReg) ||
1429 CS.paramHasAttr(AttrIdx, Attribute::StructRet) ||
1430 CS.paramHasAttr(AttrIdx, Attribute::Nest) ||
1431 CS.paramHasAttr(AttrIdx, Attribute::ByVal))
1434 ISD::ArgFlagsTy Flags;
1435 if (CS.paramHasAttr(AttrIdx, Attribute::SExt))
1437 if (CS.paramHasAttr(AttrIdx, Attribute::ZExt))
1440 Type *ArgTy = (*II)->getType();
1442 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1445 if (ArgVT.isVector())
1448 unsigned Arg = getRegForValue(*II);
1452 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
1453 Flags.setOrigAlign(OriginalAlignment);
1455 Args.push_back(*II);
1456 ArgRegs.push_back(Arg);
1457 ArgVTs.push_back(ArgVT);
1458 ArgFlags.push_back(Flags);
1461 // Process the arguments.
1462 SmallVector<unsigned, 8> RegArgs;
1465 if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1466 RegArgs, CC, NumBytes, IsVarArg))
1469 // FIXME: No handling for function pointers yet. This requires
1470 // implementing the function descriptor (OPD) setup.
1471 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1475 // Build direct call with NOP for TOC restore.
1476 // FIXME: We can and should optimize away the NOP for local calls.
1477 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1478 TII.get(PPC::BL8_NOP));
1480 MIB.addGlobalAddress(GV);
1482 // Add implicit physical register uses to the call.
1483 for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1484 MIB.addReg(RegArgs[II], RegState::Implicit);
1486 // Add a register mask with the call-preserved registers. Proper
1487 // defs for return values will be added by setPhysRegsDeadExcept().
1488 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1490 // Finish off the call including any return values.
1491 SmallVector<unsigned, 4> UsedRegs;
1492 finishCall(RetVT, UsedRegs, I, CC, NumBytes, IsVarArg);
1494 // Set all unused physregs defs as dead.
1495 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1500 // Attempt to fast-select a return instruction.
1501 bool PPCFastISel::SelectRet(const Instruction *I) {
1503 if (!FuncInfo.CanLowerReturn)
1506 const ReturnInst *Ret = cast<ReturnInst>(I);
1507 const Function &F = *I->getParent()->getParent();
1509 // Build a list of return value registers.
1510 SmallVector<unsigned, 4> RetRegs;
1511 CallingConv::ID CC = F.getCallingConv();
1513 if (Ret->getNumOperands() > 0) {
1514 SmallVector<ISD::OutputArg, 4> Outs;
1515 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1517 // Analyze operands of the call, assigning locations to each operand.
1518 SmallVector<CCValAssign, 16> ValLocs;
1519 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
1520 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1521 const Value *RV = Ret->getOperand(0);
1523 // FIXME: Only one output register for now.
1524 if (ValLocs.size() > 1)
1527 // Special case for returning a constant integer of any size.
1528 // Materialize the constant as an i64 and copy it to the return
1529 // register. This avoids an unnecessary extend or truncate.
1530 if (isa<ConstantInt>(*RV)) {
1531 const Constant *C = cast<Constant>(RV);
1532 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
1533 unsigned RetReg = ValLocs[0].getLocReg();
1534 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1535 TII.get(TargetOpcode::COPY), RetReg).addReg(SrcReg);
1536 RetRegs.push_back(RetReg);
1539 unsigned Reg = getRegForValue(RV);
1544 // Copy the result values into the output registers.
1545 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1547 CCValAssign &VA = ValLocs[i];
1548 assert(VA.isRegLoc() && "Can only return in registers!");
1549 RetRegs.push_back(VA.getLocReg());
1550 unsigned SrcReg = Reg + VA.getValNo();
1552 EVT RVEVT = TLI.getValueType(RV->getType());
1553 if (!RVEVT.isSimple())
1555 MVT RVVT = RVEVT.getSimpleVT();
1556 MVT DestVT = VA.getLocVT();
1558 if (RVVT != DestVT && RVVT != MVT::i8 &&
1559 RVVT != MVT::i16 && RVVT != MVT::i32)
1562 if (RVVT != DestVT) {
1563 switch (VA.getLocInfo()) {
1565 llvm_unreachable("Unknown loc info!");
1566 case CCValAssign::Full:
1567 llvm_unreachable("Full value assign but types don't match?");
1568 case CCValAssign::AExt:
1569 case CCValAssign::ZExt: {
1570 const TargetRegisterClass *RC =
1571 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1572 unsigned TmpReg = createResultReg(RC);
1573 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1578 case CCValAssign::SExt: {
1579 const TargetRegisterClass *RC =
1580 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1581 unsigned TmpReg = createResultReg(RC);
1582 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1590 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1591 TII.get(TargetOpcode::COPY), RetRegs[i])
1597 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1600 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1601 MIB.addReg(RetRegs[i], RegState::Implicit);
1606 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1607 // signed and zero extensions are supported. Return false if we
1609 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1610 unsigned DestReg, bool IsZExt) {
1611 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1613 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1616 // Signed extensions use EXTSB, EXTSH, EXTSW.
1619 if (SrcVT == MVT::i8)
1620 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1621 else if (SrcVT == MVT::i16)
1622 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1624 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1625 Opc = PPC::EXTSW_32_64;
1627 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1630 // Unsigned 32-bit extensions use RLWINM.
1631 } else if (DestVT == MVT::i32) {
1633 if (SrcVT == MVT::i8)
1636 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1639 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLWINM),
1641 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1643 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1646 if (SrcVT == MVT::i8)
1648 else if (SrcVT == MVT::i16)
1652 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1653 TII.get(PPC::RLDICL_32_64), DestReg)
1654 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1660 // Attempt to fast-select an indirect branch instruction.
1661 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1662 unsigned AddrReg = getRegForValue(I->getOperand(0));
1666 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::MTCTR8))
1668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::BCTR8));
1670 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1671 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1672 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1677 // Attempt to fast-select an integer truncate instruction.
1678 bool PPCFastISel::SelectTrunc(const Instruction *I) {
1679 Value *Src = I->getOperand(0);
1680 EVT SrcVT = TLI.getValueType(Src->getType(), true);
1681 EVT DestVT = TLI.getValueType(I->getType(), true);
1683 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16)
1686 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
1689 unsigned SrcReg = getRegForValue(Src);
1693 // The only interesting case is when we need to switch register classes.
1694 if (SrcVT == MVT::i64) {
1695 unsigned ResultReg = createResultReg(&PPC::GPRCRegClass);
1696 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1697 TII.get(TargetOpcode::COPY),
1698 ResultReg).addReg(SrcReg, 0, PPC::sub_32);
1702 UpdateValueMap(I, SrcReg);
1706 // Attempt to fast-select an integer extend instruction.
1707 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1708 Type *DestTy = I->getType();
1709 Value *Src = I->getOperand(0);
1710 Type *SrcTy = Src->getType();
1712 bool IsZExt = isa<ZExtInst>(I);
1713 unsigned SrcReg = getRegForValue(Src);
1714 if (!SrcReg) return false;
1716 EVT SrcEVT, DestEVT;
1717 SrcEVT = TLI.getValueType(SrcTy, true);
1718 DestEVT = TLI.getValueType(DestTy, true);
1719 if (!SrcEVT.isSimple())
1721 if (!DestEVT.isSimple())
1724 MVT SrcVT = SrcEVT.getSimpleVT();
1725 MVT DestVT = DestEVT.getSimpleVT();
1727 // If we know the register class needed for the result of this
1728 // instruction, use it. Otherwise pick the register class of the
1729 // correct size that does not contain X0/R0, since we don't know
1730 // whether downstream uses permit that assignment.
1731 unsigned AssignedReg = FuncInfo.ValueMap[I];
1732 const TargetRegisterClass *RC =
1733 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1734 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1735 &PPC::GPRC_and_GPRC_NOR0RegClass));
1736 unsigned ResultReg = createResultReg(RC);
1738 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1741 UpdateValueMap(I, ResultReg);
1745 // Attempt to fast-select an instruction that wasn't handled by
1746 // the table-generated machinery.
1747 bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
1749 switch (I->getOpcode()) {
1750 case Instruction::Load:
1751 return SelectLoad(I);
1752 case Instruction::Store:
1753 return SelectStore(I);
1754 case Instruction::Br:
1755 return SelectBranch(I);
1756 case Instruction::IndirectBr:
1757 return SelectIndirectBr(I);
1758 case Instruction::FPExt:
1759 return SelectFPExt(I);
1760 case Instruction::FPTrunc:
1761 return SelectFPTrunc(I);
1762 case Instruction::SIToFP:
1763 return SelectIToFP(I, /*IsSigned*/ true);
1764 case Instruction::UIToFP:
1765 return SelectIToFP(I, /*IsSigned*/ false);
1766 case Instruction::FPToSI:
1767 return SelectFPToI(I, /*IsSigned*/ true);
1768 case Instruction::FPToUI:
1769 return SelectFPToI(I, /*IsSigned*/ false);
1770 case Instruction::Add:
1771 return SelectBinaryIntOp(I, ISD::ADD);
1772 case Instruction::Or:
1773 return SelectBinaryIntOp(I, ISD::OR);
1774 case Instruction::Sub:
1775 return SelectBinaryIntOp(I, ISD::SUB);
1776 case Instruction::Call:
1777 if (dyn_cast<IntrinsicInst>(I))
1779 return SelectCall(I);
1780 case Instruction::Ret:
1781 return SelectRet(I);
1782 case Instruction::Trunc:
1783 return SelectTrunc(I);
1784 case Instruction::ZExt:
1785 case Instruction::SExt:
1786 return SelectIntExt(I);
1787 // Here add other flavors of Instruction::XXX that automated
1788 // cases don't catch. For example, switches are terminators
1789 // that aren't yet handled.
1796 // Materialize a floating-point constant into a register, and return
1797 // the register number (or zero if we failed to handle it).
1798 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1799 // No plans to handle long double here.
1800 if (VT != MVT::f32 && VT != MVT::f64)
1803 // All FP constants are loaded from the constant pool.
1804 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
1805 assert(Align > 0 && "Unexpectedly missing alignment information!");
1806 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1807 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1808 CodeModel::Model CModel = TM.getCodeModel();
1810 MachineMemOperand *MMO =
1811 FuncInfo.MF->getMachineMemOperand(
1812 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1813 (VT == MVT::f32) ? 4 : 8, Align);
1815 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1816 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1818 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1819 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1820 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocCPT),
1822 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1823 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1824 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1826 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1827 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1828 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1829 // But for large code model, we must generate a LDtocL followed
1831 if (CModel == CodeModel::Large) {
1832 unsigned TmpReg2 = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1833 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1834 TmpReg2).addConstantPoolIndex(Idx).addReg(TmpReg);
1835 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1836 .addImm(0).addReg(TmpReg2);
1838 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
1839 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1841 .addMemOperand(MMO);
1847 // Materialize the address of a global value into a register, and return
1848 // the register number (or zero if we failed to handle it).
1849 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1850 assert(VT == MVT::i64 && "Non-address!");
1851 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1852 unsigned DestReg = createResultReg(RC);
1854 // Global values may be plain old object addresses, TLS object
1855 // addresses, constant pool entries, or jump tables. How we generate
1856 // code for these may depend on small, medium, or large code model.
1857 CodeModel::Model CModel = TM.getCodeModel();
1859 // FIXME: Jump tables are not yet required because fast-isel doesn't
1860 // handle switches; if that changes, we need them as well. For now,
1861 // what follows assumes everything's a generic (or TLS) global address.
1862 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1864 // If GV is an alias, use the aliasee for determining thread-locality.
1865 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1866 GVar = dyn_cast_or_null<GlobalVariable>(GA->getAliasedGlobal());
1869 // FIXME: We don't yet handle the complexity of TLS.
1870 bool IsTLS = GVar && GVar->isThreadLocal();
1874 // For small code model, generate a simple TOC load.
1875 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1876 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtoc),
1878 .addGlobalAddress(GV)
1881 // If the address is an externally defined symbol, a symbol with
1882 // common or externally available linkage, a function address, or a
1883 // jump table address (not yet needed), or if we are generating code
1884 // for large code model, we generate:
1885 // LDtocL(GV, ADDIStocHA(%X2, GV))
1886 // Otherwise we generate:
1887 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1888 // Either way, start with the ADDIStocHA:
1889 unsigned HighPartReg = createResultReg(RC);
1890 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDIStocHA),
1891 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1893 // !GVar implies a function address. An external variable is one
1894 // without an initializer.
1895 // If/when switches are implemented, jump tables should be handled
1896 // on the "if" path here.
1897 if (CModel == CodeModel::Large || !GVar || !GVar->hasInitializer() ||
1898 GVar->hasCommonLinkage() || GVar->hasAvailableExternallyLinkage())
1899 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::LDtocL),
1900 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1902 // Otherwise generate the ADDItocL.
1903 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDItocL),
1904 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1910 // Materialize a 32-bit integer constant into a register, and return
1911 // the register number (or zero if we failed to handle it).
1912 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1913 const TargetRegisterClass *RC) {
1914 unsigned Lo = Imm & 0xFFFF;
1915 unsigned Hi = (Imm >> 16) & 0xFFFF;
1917 unsigned ResultReg = createResultReg(RC);
1918 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1921 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1922 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1925 // Both Lo and Hi have nonzero bits.
1926 unsigned TmpReg = createResultReg(RC);
1927 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1928 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1930 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1931 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1932 .addReg(TmpReg).addImm(Lo);
1935 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1936 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1942 // Materialize a 64-bit integer constant into a register, and return
1943 // the register number (or zero if we failed to handle it).
1944 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1945 const TargetRegisterClass *RC) {
1946 unsigned Remainder = 0;
1949 // If the value doesn't fit in 32 bits, see if we can shift it
1950 // so that it fits in 32 bits.
1951 if (!isInt<32>(Imm)) {
1952 Shift = countTrailingZeros<uint64_t>(Imm);
1953 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1955 if (isInt<32>(ImmSh))
1964 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1965 // (if not shifted).
1966 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1970 // If upper 32 bits were not zero, we've built them and need to shift
1974 TmpReg2 = createResultReg(RC);
1975 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::RLDICR),
1976 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1980 unsigned TmpReg3, Hi, Lo;
1981 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1982 TmpReg3 = createResultReg(RC);
1983 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORIS8),
1984 TmpReg3).addReg(TmpReg2).addImm(Hi);
1988 if ((Lo = Remainder & 0xFFFF)) {
1989 unsigned ResultReg = createResultReg(RC);
1990 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ORI8),
1991 ResultReg).addReg(TmpReg3).addImm(Lo);
1999 // Materialize an integer constant into a register, and return
2000 // the register number (or zero if we failed to handle it).
2001 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
2002 // If we're using CR bit registers for i1 values, handle that as a special
2004 if (VT == MVT::i1 && PPCSubTarget.useCRBits()) {
2005 const ConstantInt *CI = cast<ConstantInt>(C);
2006 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2007 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2008 TII.get(CI->isZero() ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2012 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2013 VT != MVT::i8 && VT != MVT::i1)
2016 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2017 &PPC::GPRCRegClass);
2019 // If the constant is in range, use a load-immediate.
2020 const ConstantInt *CI = cast<ConstantInt>(C);
2021 if (isInt<16>(CI->getSExtValue())) {
2022 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
2023 unsigned ImmReg = createResultReg(RC);
2024 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ImmReg)
2025 .addImm(CI->getSExtValue());
2029 // Construct the constant piecewise.
2030 int64_t Imm = CI->getZExtValue();
2033 return PPCMaterialize64BitInt(Imm, RC);
2034 else if (VT == MVT::i32)
2035 return PPCMaterialize32BitInt(Imm, RC);
2040 // Materialize a constant into a register, and return the register
2041 // number (or zero if we failed to handle it).
2042 unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
2043 EVT CEVT = TLI.getValueType(C->getType(), true);
2045 // Only handle simple types.
2046 if (!CEVT.isSimple()) return 0;
2047 MVT VT = CEVT.getSimpleVT();
2049 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
2050 return PPCMaterializeFP(CFP, VT);
2051 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
2052 return PPCMaterializeGV(GV, VT);
2053 else if (isa<ConstantInt>(C))
2054 return PPCMaterializeInt(C, VT);
2059 // Materialize the address created by an alloca into a register, and
2060 // return the register number (or zero if we failed to handle it).
2061 unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
2062 // Don't handle dynamic allocas.
2063 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
2066 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
2068 DenseMap<const AllocaInst*, int>::iterator SI =
2069 FuncInfo.StaticAllocaMap.find(AI);
2071 if (SI != FuncInfo.StaticAllocaMap.end()) {
2072 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
2073 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(PPC::ADDI8),
2074 ResultReg).addFrameIndex(SI->second).addImm(0);
2081 // Fold loads into extends when possible.
2082 // FIXME: We can have multiple redundant extend/trunc instructions
2083 // following a load. The folding only picks up one. Extend this
2084 // to check subsequent instructions for the same pattern and remove
2085 // them. Thus ResultReg should be the def reg for the last redundant
2086 // instruction in a chain, and all intervening instructions can be
2087 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
2088 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2089 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2090 const LoadInst *LI) {
2091 // Verify we have a legal type before going any further.
2093 if (!isLoadTypeLegal(LI->getType(), VT))
2096 // Combine load followed by zero- or sign-extend.
2097 bool IsZExt = false;
2098 switch(MI->getOpcode()) {
2103 case PPC::RLDICL_32_64: {
2105 unsigned MB = MI->getOperand(3).getImm();
2106 if ((VT == MVT::i8 && MB <= 56) ||
2107 (VT == MVT::i16 && MB <= 48) ||
2108 (VT == MVT::i32 && MB <= 32))
2114 case PPC::RLWINM8: {
2116 unsigned MB = MI->getOperand(3).getImm();
2117 if ((VT == MVT::i8 && MB <= 24) ||
2118 (VT == MVT::i16 && MB <= 16))
2125 case PPC::EXTSB8_32_64:
2126 /* There is no sign-extending load-byte instruction. */
2131 case PPC::EXTSH8_32_64: {
2132 if (VT != MVT::i16 && VT != MVT::i8)
2138 case PPC::EXTSW_32_64: {
2139 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2145 // See if we can handle this address.
2147 if (!PPCComputeAddress(LI->getOperand(0), Addr))
2150 unsigned ResultReg = MI->getOperand(0).getReg();
2152 if (!PPCEmitLoad(VT, ResultReg, Addr, 0, IsZExt))
2155 MI->eraseFromParent();
2159 // Attempt to lower call arguments in a faster way than done by
2160 // the selection DAG code.
2161 bool PPCFastISel::FastLowerArguments() {
2162 // Defer to normal argument lowering for now. It's reasonably
2163 // efficient. Consider doing something like ARM to handle the
2164 // case where all args fit in registers, no varargs, no float
2169 // Handle materializing integer constants into a register. This is not
2170 // automatically generated for PowerPC, so must be explicitly created here.
2171 unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2173 if (Opc != ISD::Constant)
2176 // If we're using CR bit registers for i1 values, handle that as a special
2178 if (VT == MVT::i1 && PPCSubTarget.useCRBits()) {
2179 unsigned ImmReg = createResultReg(&PPC::CRBITRCRegClass);
2180 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2181 TII.get(Imm == 0 ? PPC::CRUNSET : PPC::CRSET), ImmReg);
2185 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2186 VT != MVT::i8 && VT != MVT::i1)
2189 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2190 &PPC::GPRCRegClass);
2192 return PPCMaterialize64BitInt(Imm, RC);
2194 return PPCMaterialize32BitInt(Imm, RC);
2197 // Override for ADDI and ADDI8 to set the correct register class
2198 // on RHS operand 0. The automatic infrastructure naively assumes
2199 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2200 // for these cases. At the moment, none of the other automatically
2201 // generated RI instructions require special treatment. However, once
2202 // SelectSelect is implemented, "isel" requires similar handling.
2204 // Also be conservative about the output register class. Avoid
2205 // assigning R0 or X0 to the output register for GPRC and G8RC
2206 // register classes, as any such result could be used in ADDI, etc.,
2207 // where those regs have another meaning.
2208 unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
2209 const TargetRegisterClass *RC,
2210 unsigned Op0, bool Op0IsKill,
2212 if (MachineInstOpcode == PPC::ADDI)
2213 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2214 else if (MachineInstOpcode == PPC::ADDI8)
2215 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2217 const TargetRegisterClass *UseRC =
2218 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2219 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2221 return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
2222 Op0, Op0IsKill, Imm);
2225 // Override for instructions with one register operand to avoid use of
2226 // R0/X0. The automatic infrastructure isn't aware of the context so
2227 // we must be conservative.
2228 unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
2229 const TargetRegisterClass* RC,
2230 unsigned Op0, bool Op0IsKill) {
2231 const TargetRegisterClass *UseRC =
2232 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2233 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2235 return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2238 // Override for instructions with two register operands to avoid use
2239 // of R0/X0. The automatic infrastructure isn't aware of the context
2240 // so we must be conservative.
2241 unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
2242 const TargetRegisterClass* RC,
2243 unsigned Op0, bool Op0IsKill,
2244 unsigned Op1, bool Op1IsKill) {
2245 const TargetRegisterClass *UseRC =
2246 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2247 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2249 return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2254 // Create the fast instruction selector for PowerPC64 ELF.
2255 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2256 const TargetLibraryInfo *LibInfo) {
2257 const TargetMachine &TM = FuncInfo.MF->getTarget();
2259 // Only available on 64-bit ELF for now.
2260 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
2261 if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
2262 return new PPCFastISel(FuncInfo, LibInfo);