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 "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"
44 typedef struct Address {
57 // Innocuous defaults for our address.
59 : BaseType(RegBase), Offset(0) {
64 class PPCFastISel : public FastISel {
66 const TargetMachine &TM;
67 const TargetInstrInfo &TII;
68 const TargetLowering &TLI;
69 const PPCSubtarget &PPCSubTarget;
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()),
80 *((static_cast<const PPCTargetMachine *>(&TM))->getSubtargetImpl())
82 Context(&FuncInfo.Fn->getContext()) { }
84 // Backend specific FastISel code.
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,
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,
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);
105 // Instruction selection routines.
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 SelectFPExt(const Instruction *I);
113 bool SelectFPTrunc(const Instruction *I);
114 bool SelectIToFP(const Instruction *I, bool IsSigned);
115 bool SelectFPToI(const Instruction *I, bool IsSigned);
116 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
117 bool SelectRet(const Instruction *I);
118 bool SelectIntExt(const Instruction *I);
122 bool isTypeLegal(Type *Ty, MVT &VT);
123 bool isLoadTypeLegal(Type *Ty, MVT &VT);
124 bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
125 bool isZExt, unsigned DestReg);
126 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
127 const TargetRegisterClass *RC, bool IsZExt = true,
128 unsigned FP64LoadOpc = PPC::LFD);
129 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
130 bool PPCComputeAddress(const Value *Obj, Address &Addr);
131 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
133 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
134 unsigned DestReg, bool IsZExt);
135 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
136 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
137 unsigned PPCMaterializeInt(const Constant *C, MVT VT);
138 unsigned PPCMaterialize32BitInt(int64_t Imm,
139 const TargetRegisterClass *RC);
140 unsigned PPCMaterialize64BitInt(int64_t Imm,
141 const TargetRegisterClass *RC);
142 unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
143 unsigned SrcReg, bool IsSigned);
144 unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
146 // Call handling routines.
148 CCAssignFn *usePPC32CCs(unsigned Flag);
151 #include "PPCGenFastISel.inc"
155 } // end anonymous namespace
157 #include "PPCGenCallingConv.inc"
159 // Function whose sole purpose is to kill compiler warnings
160 // stemming from unused functions included from PPCGenCallingConv.inc.
161 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
163 return CC_PPC32_SVR4;
165 return CC_PPC32_SVR4_ByVal;
167 return CC_PPC32_SVR4_VarArg;
172 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
174 // These are not representable with any single compare.
175 case CmpInst::FCMP_FALSE:
176 case CmpInst::FCMP_UEQ:
177 case CmpInst::FCMP_UGT:
178 case CmpInst::FCMP_UGE:
179 case CmpInst::FCMP_ULT:
180 case CmpInst::FCMP_ULE:
181 case CmpInst::FCMP_UNE:
182 case CmpInst::FCMP_TRUE:
184 return Optional<PPC::Predicate>();
186 case CmpInst::FCMP_OEQ:
187 case CmpInst::ICMP_EQ:
190 case CmpInst::FCMP_OGT:
191 case CmpInst::ICMP_UGT:
192 case CmpInst::ICMP_SGT:
195 case CmpInst::FCMP_OGE:
196 case CmpInst::ICMP_UGE:
197 case CmpInst::ICMP_SGE:
200 case CmpInst::FCMP_OLT:
201 case CmpInst::ICMP_ULT:
202 case CmpInst::ICMP_SLT:
205 case CmpInst::FCMP_OLE:
206 case CmpInst::ICMP_ULE:
207 case CmpInst::ICMP_SLE:
210 case CmpInst::FCMP_ONE:
211 case CmpInst::ICMP_NE:
214 case CmpInst::FCMP_ORD:
217 case CmpInst::FCMP_UNO:
222 // Determine whether the type Ty is simple enough to be handled by
223 // fast-isel, and return its equivalent machine type in VT.
224 // FIXME: Copied directly from ARM -- factor into base class?
225 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
226 EVT Evt = TLI.getValueType(Ty, true);
228 // Only handle simple types.
229 if (Evt == MVT::Other || !Evt.isSimple()) return false;
230 VT = Evt.getSimpleVT();
232 // Handle all legal types, i.e. a register that will directly hold this
234 return TLI.isTypeLegal(VT);
237 // Determine whether the type Ty is simple enough to be handled by
238 // fast-isel as a load target, and return its equivalent machine type in VT.
239 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
240 if (isTypeLegal(Ty, VT)) return true;
242 // If this is a type than can be sign or zero-extended to a basic operation
243 // go ahead and accept it now.
244 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
251 // Given a value Obj, create an Address object Addr that represents its
252 // address. Return false if we can't handle it.
253 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
254 const User *U = NULL;
255 unsigned Opcode = Instruction::UserOp1;
256 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
257 // Don't walk into other basic blocks unless the object is an alloca from
258 // another block, otherwise it may not have a virtual register assigned.
259 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
260 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
261 Opcode = I->getOpcode();
264 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
265 Opcode = C->getOpcode();
272 case Instruction::BitCast:
273 // Look through bitcasts.
274 return PPCComputeAddress(U->getOperand(0), Addr);
275 case Instruction::IntToPtr:
276 // Look past no-op inttoptrs.
277 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
278 return PPCComputeAddress(U->getOperand(0), Addr);
280 case Instruction::PtrToInt:
281 // Look past no-op ptrtoints.
282 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
283 return PPCComputeAddress(U->getOperand(0), Addr);
285 case Instruction::GetElementPtr: {
286 Address SavedAddr = Addr;
287 long TmpOffset = Addr.Offset;
289 // Iterate through the GEP folding the constants into offsets where
291 gep_type_iterator GTI = gep_type_begin(U);
292 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
293 II != IE; ++II, ++GTI) {
294 const Value *Op = *II;
295 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
296 const StructLayout *SL = TD.getStructLayout(STy);
297 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
298 TmpOffset += SL->getElementOffset(Idx);
300 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
302 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
303 // Constant-offset addressing.
304 TmpOffset += CI->getSExtValue() * S;
307 if (isa<AddOperator>(Op) &&
308 (!isa<Instruction>(Op) ||
309 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
311 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
312 // An add (in the same block) with a constant operand. Fold the
315 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
316 TmpOffset += CI->getSExtValue() * S;
317 // Iterate on the other operand.
318 Op = cast<AddOperator>(Op)->getOperand(0);
322 goto unsupported_gep;
327 // Try to grab the base operand now.
328 Addr.Offset = TmpOffset;
329 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
331 // We failed, restore everything and try the other options.
337 case Instruction::Alloca: {
338 const AllocaInst *AI = cast<AllocaInst>(Obj);
339 DenseMap<const AllocaInst*, int>::iterator SI =
340 FuncInfo.StaticAllocaMap.find(AI);
341 if (SI != FuncInfo.StaticAllocaMap.end()) {
342 Addr.BaseType = Address::FrameIndexBase;
343 Addr.Base.FI = SI->second;
350 // FIXME: References to parameters fall through to the behavior
351 // below. They should be able to reference a frame index since
352 // they are stored to the stack, so we can get "ld rx, offset(r1)"
353 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
354 // just contain the parameter. Try to handle this with a FI.
356 // Try to get this in a register if nothing else has worked.
357 if (Addr.Base.Reg == 0)
358 Addr.Base.Reg = getRegForValue(Obj);
360 // Prevent assignment of base register to X0, which is inappropriate
361 // for loads and stores alike.
362 if (Addr.Base.Reg != 0)
363 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
365 return Addr.Base.Reg != 0;
368 // Fix up some addresses that can't be used directly. For example, if
369 // an offset won't fit in an instruction field, we may need to move it
370 // into an index register.
371 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
372 unsigned &IndexReg) {
374 // Check whether the offset fits in the instruction field.
375 if (!isInt<16>(Addr.Offset))
378 // If this is a stack pointer and the offset needs to be simplified then
379 // put the alloca address into a register, set the base type back to
380 // register and continue. This should almost never happen.
381 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
382 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
383 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDI8),
384 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
385 Addr.Base.Reg = ResultReg;
386 Addr.BaseType = Address::RegBase;
390 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
391 : Type::getInt64Ty(*Context));
392 const ConstantInt *Offset =
393 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
394 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
395 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
399 // Emit a load instruction if possible, returning true if we succeeded,
400 // otherwise false. See commentary below for how the register class of
401 // the load is determined.
402 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
403 const TargetRegisterClass *RC,
404 bool IsZExt, unsigned FP64LoadOpc) {
406 bool UseOffset = true;
408 // If ResultReg is given, it determines the register class of the load.
409 // Otherwise, RC is the register class to use. If the result of the
410 // load isn't anticipated in this block, both may be zero, in which
411 // case we must make a conservative guess. In particular, don't assign
412 // R0 or X0 to the result register, as the result may be used in a load,
413 // store, add-immediate, or isel that won't permit this. (Though
414 // perhaps the spill and reload of live-exit values would handle this?)
415 const TargetRegisterClass *UseRC =
416 (ResultReg ? MRI.getRegClass(ResultReg) :
418 (VT == MVT::f64 ? &PPC::F8RCRegClass :
419 (VT == MVT::f32 ? &PPC::F4RCRegClass :
420 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
421 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
423 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
425 switch (VT.SimpleTy) {
426 default: // e.g., vector types not handled
429 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
433 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
434 (Is32BitInt ? PPC::LHA : PPC::LHA8));
438 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
439 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
440 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
445 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
446 "64-bit load with 32-bit target??");
447 UseOffset = ((Addr.Offset & 3) == 0);
457 // If necessary, materialize the offset into a register and use
458 // the indexed form. Also handle stack pointers with special needs.
459 unsigned IndexReg = 0;
460 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
462 ResultReg = createResultReg(UseRC);
464 // Note: If we still have a frame index here, we know the offset is
465 // in range, as otherwise PPCSimplifyAddress would have converted it
467 if (Addr.BaseType == Address::FrameIndexBase) {
469 MachineMemOperand *MMO =
470 FuncInfo.MF->getMachineMemOperand(
471 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
472 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
473 MFI.getObjectAlignment(Addr.Base.FI));
475 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
476 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
478 // Base reg with offset in range.
479 } else if (UseOffset) {
481 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
482 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
486 // Get the RR opcode corresponding to the RI one. FIXME: It would be
487 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
488 // is hard to get at.
490 default: llvm_unreachable("Unexpected opcode!");
491 case PPC::LBZ: Opc = PPC::LBZX; break;
492 case PPC::LBZ8: Opc = PPC::LBZX8; break;
493 case PPC::LHZ: Opc = PPC::LHZX; break;
494 case PPC::LHZ8: Opc = PPC::LHZX8; break;
495 case PPC::LHA: Opc = PPC::LHAX; break;
496 case PPC::LHA8: Opc = PPC::LHAX8; break;
497 case PPC::LWZ: Opc = PPC::LWZX; break;
498 case PPC::LWZ8: Opc = PPC::LWZX8; break;
499 case PPC::LWA: Opc = PPC::LWAX; break;
500 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
501 case PPC::LD: Opc = PPC::LDX; break;
502 case PPC::LFS: Opc = PPC::LFSX; break;
503 case PPC::LFD: Opc = PPC::LFDX; break;
505 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
506 .addReg(Addr.Base.Reg).addReg(IndexReg);
512 // Attempt to fast-select a load instruction.
513 bool PPCFastISel::SelectLoad(const Instruction *I) {
514 // FIXME: No atomic loads are supported.
515 if (cast<LoadInst>(I)->isAtomic())
518 // Verify we have a legal type before going any further.
520 if (!isLoadTypeLegal(I->getType(), VT))
523 // See if we can handle this address.
525 if (!PPCComputeAddress(I->getOperand(0), Addr))
528 // Look at the currently assigned register for this instruction
529 // to determine the required register class. This is necessary
530 // to constrain RA from using R0/X0 when this is not legal.
531 unsigned AssignedReg = FuncInfo.ValueMap[I];
532 const TargetRegisterClass *RC =
533 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
535 unsigned ResultReg = 0;
536 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
538 UpdateValueMap(I, ResultReg);
542 // Emit a store instruction to store SrcReg at Addr.
543 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
544 assert(SrcReg && "Nothing to store!");
546 bool UseOffset = true;
548 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
549 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
551 switch (VT.SimpleTy) {
552 default: // e.g., vector types not handled
555 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
558 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
561 assert(Is32BitInt && "Not GPRC for i32??");
566 UseOffset = ((Addr.Offset & 3) == 0);
576 // If necessary, materialize the offset into a register and use
577 // the indexed form. Also handle stack pointers with special needs.
578 unsigned IndexReg = 0;
579 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
581 // Note: If we still have a frame index here, we know the offset is
582 // in range, as otherwise PPCSimplifyAddress would have converted it
584 if (Addr.BaseType == Address::FrameIndexBase) {
585 MachineMemOperand *MMO =
586 FuncInfo.MF->getMachineMemOperand(
587 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
588 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
589 MFI.getObjectAlignment(Addr.Base.FI));
591 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc)).addReg(SrcReg)
592 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
594 // Base reg with offset in range.
595 } else if (UseOffset)
596 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
597 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
601 // Get the RR opcode corresponding to the RI one. FIXME: It would be
602 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
603 // is hard to get at.
605 default: llvm_unreachable("Unexpected opcode!");
606 case PPC::STB: Opc = PPC::STBX; break;
607 case PPC::STH : Opc = PPC::STHX; break;
608 case PPC::STW : Opc = PPC::STWX; break;
609 case PPC::STB8: Opc = PPC::STBX8; break;
610 case PPC::STH8: Opc = PPC::STHX8; break;
611 case PPC::STW8: Opc = PPC::STWX8; break;
612 case PPC::STD: Opc = PPC::STDX; break;
613 case PPC::STFS: Opc = PPC::STFSX; break;
614 case PPC::STFD: Opc = PPC::STFDX; break;
616 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
617 .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
623 // Attempt to fast-select a store instruction.
624 bool PPCFastISel::SelectStore(const Instruction *I) {
625 Value *Op0 = I->getOperand(0);
628 // FIXME: No atomics loads are supported.
629 if (cast<StoreInst>(I)->isAtomic())
632 // Verify we have a legal type before going any further.
634 if (!isLoadTypeLegal(Op0->getType(), VT))
637 // Get the value to be stored into a register.
638 SrcReg = getRegForValue(Op0);
642 // See if we can handle this address.
644 if (!PPCComputeAddress(I->getOperand(1), Addr))
647 if (!PPCEmitStore(VT, SrcReg, Addr))
653 // Attempt to fast-select a branch instruction.
654 bool PPCFastISel::SelectBranch(const Instruction *I) {
655 const BranchInst *BI = cast<BranchInst>(I);
656 MachineBasicBlock *BrBB = FuncInfo.MBB;
657 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
658 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
660 // For now, just try the simplest case where it's fed by a compare.
661 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
662 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
666 PPC::Predicate PPCPred = OptPPCPred.getValue();
668 // Take advantage of fall-through opportunities.
669 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
671 PPCPred = PPC::InvertPredicate(PPCPred);
674 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
676 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
680 BuildMI(*BrBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCC))
681 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
682 FastEmitBranch(FBB, DL);
683 FuncInfo.MBB->addSuccessor(TBB);
686 } else if (const ConstantInt *CI =
687 dyn_cast<ConstantInt>(BI->getCondition())) {
688 uint64_t Imm = CI->getZExtValue();
689 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
690 FastEmitBranch(Target, DL);
694 // FIXME: ARM looks for a case where the block containing the compare
695 // has been split from the block containing the branch. If this happens,
696 // there is a vreg available containing the result of the compare. I'm
697 // not sure we can do much, as we've lost the predicate information with
698 // the compare instruction -- we have a 4-bit CR but don't know which bit
703 // Attempt to emit a compare of the two source values. Signed and unsigned
704 // comparisons are supported. Return false if we can't handle it.
705 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
706 bool IsZExt, unsigned DestReg) {
707 Type *Ty = SrcValue1->getType();
708 EVT SrcEVT = TLI.getValueType(Ty, true);
709 if (!SrcEVT.isSimple())
711 MVT SrcVT = SrcEVT.getSimpleVT();
713 // See if operand 2 is an immediate encodeable in the compare.
714 // FIXME: Operands are not in canonical order at -O0, so an immediate
715 // operand in position 1 is a lost opportunity for now. We are
716 // similar to ARM in this regard.
720 // Only 16-bit integer constants can be represented in compares for
721 // PowerPC. Others will be materialized into a register.
722 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
723 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
724 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
725 const APInt &CIVal = ConstInt->getValue();
726 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
727 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
733 bool NeedsExt = false;
734 switch (SrcVT.SimpleTy) {
735 default: return false;
737 CmpOpc = PPC::FCMPUS;
740 CmpOpc = PPC::FCMPUD;
746 // Intentional fall-through.
749 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
751 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
755 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
757 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
761 unsigned SrcReg1 = getRegForValue(SrcValue1);
765 unsigned SrcReg2 = 0;
767 SrcReg2 = getRegForValue(SrcValue2);
773 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
774 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
779 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
780 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
787 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
788 .addReg(SrcReg1).addReg(SrcReg2);
790 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
791 .addReg(SrcReg1).addImm(Imm);
796 // Attempt to fast-select a floating-point extend instruction.
797 bool PPCFastISel::SelectFPExt(const Instruction *I) {
798 Value *Src = I->getOperand(0);
799 EVT SrcVT = TLI.getValueType(Src->getType(), true);
800 EVT DestVT = TLI.getValueType(I->getType(), true);
802 if (SrcVT != MVT::f32 || DestVT != MVT::f64)
805 unsigned SrcReg = getRegForValue(Src);
809 // No code is generated for a FP extend.
810 UpdateValueMap(I, SrcReg);
814 // Attempt to fast-select a floating-point truncate instruction.
815 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
816 Value *Src = I->getOperand(0);
817 EVT SrcVT = TLI.getValueType(Src->getType(), true);
818 EVT DestVT = TLI.getValueType(I->getType(), true);
820 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
823 unsigned SrcReg = getRegForValue(Src);
827 // Round the result to single precision.
828 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
829 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP), DestReg)
832 UpdateValueMap(I, DestReg);
836 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
837 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
838 // those should be used instead of moving via a stack slot when the
839 // subtarget permits.
840 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
841 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
842 // case to 8 bytes which produces tighter code but wastes stack space.
843 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
846 // If necessary, extend 32-bit int to 64-bit.
847 if (SrcVT == MVT::i32) {
848 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
849 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
854 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
856 Addr.BaseType = Address::FrameIndexBase;
857 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
859 // Store the value from the GPR.
860 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
863 // Load the integer value into an FPR. The kind of load used depends
864 // on a number of conditions.
865 unsigned LoadOpc = PPC::LFD;
867 if (SrcVT == MVT::i32) {
870 LoadOpc = PPC::LFIWZX;
871 else if (PPCSubTarget.hasLFIWAX())
872 LoadOpc = PPC::LFIWAX;
875 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
876 unsigned ResultReg = 0;
877 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
883 // Attempt to fast-select an integer-to-floating-point conversion.
884 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
886 Type *DstTy = I->getType();
887 if (!isTypeLegal(DstTy, DstVT))
890 if (DstVT != MVT::f32 && DstVT != MVT::f64)
893 Value *Src = I->getOperand(0);
894 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
895 if (!SrcEVT.isSimple())
898 MVT SrcVT = SrcEVT.getSimpleVT();
900 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
901 SrcVT != MVT::i32 && SrcVT != MVT::i64)
904 unsigned SrcReg = getRegForValue(Src);
908 // We can only lower an unsigned convert if we have the newer
909 // floating-point conversion operations.
910 if (!IsSigned && !PPCSubTarget.hasFPCVT())
913 // FIXME: For now we require the newer floating-point conversion operations
914 // (which are present only on P7 and A2 server models) when converting
915 // to single-precision float. Otherwise we have to generate a lot of
916 // fiddly code to avoid double rounding. If necessary, the fiddly code
917 // can be found in PPCTargetLowering::LowerINT_TO_FP().
918 if (DstVT == MVT::f32 && !PPCSubTarget.hasFPCVT())
921 // Extend the input if necessary.
922 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
923 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
924 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
930 // Move the integer value to an FPR.
931 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
935 // Determine the opcode for the conversion.
936 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
937 unsigned DestReg = createResultReg(RC);
940 if (DstVT == MVT::f32)
941 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
943 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
945 // Generate the convert.
946 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
949 UpdateValueMap(I, DestReg);
953 // Move the floating-point value in SrcReg into an integer destination
954 // register, and return the register (or zero if we can't handle it).
955 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
956 // those should be used instead of moving via a stack slot when the
957 // subtarget permits.
958 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
959 unsigned SrcReg, bool IsSigned) {
960 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
961 // Note that if have STFIWX available, we could use a 4-byte stack
962 // slot for i32, but this being fast-isel we'll just go with the
963 // easiest code gen possible.
965 Addr.BaseType = Address::FrameIndexBase;
966 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
968 // Store the value from the FPR.
969 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
972 // Reload it into a GPR. If we want an i32, modify the address
973 // to have a 4-byte offset so we load from the right place.
977 // Look at the currently assigned register for this instruction
978 // to determine the required register class.
979 unsigned AssignedReg = FuncInfo.ValueMap[I];
980 const TargetRegisterClass *RC =
981 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
983 unsigned ResultReg = 0;
984 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
990 // Attempt to fast-select a floating-point-to-integer conversion.
991 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
993 Type *DstTy = I->getType();
994 if (!isTypeLegal(DstTy, DstVT))
997 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1000 Value *Src = I->getOperand(0);
1001 Type *SrcTy = Src->getType();
1002 if (!isTypeLegal(SrcTy, SrcVT))
1005 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1008 unsigned SrcReg = getRegForValue(Src);
1012 // Convert f32 to f64 if necessary. This is just a meaningless copy
1013 // to get the register class right. COPY_TO_REGCLASS is needed since
1014 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1015 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1016 if (InRC == &PPC::F4RCRegClass) {
1017 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1018 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1019 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1020 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1024 // Determine the opcode for the conversion, which takes place
1025 // entirely within FPRs.
1026 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1029 if (DstVT == MVT::i32)
1033 Opc = PPCSubTarget.hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1035 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1037 // Generate the convert.
1038 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1041 // Now move the integer value from a float register to an integer register.
1042 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1046 UpdateValueMap(I, IntReg);
1050 // Attempt to fast-select a binary integer operation that isn't already
1051 // handled automatically.
1052 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1053 EVT DestVT = TLI.getValueType(I->getType(), true);
1055 // We can get here in the case when we have a binary operation on a non-legal
1056 // type and the target independent selector doesn't know how to handle it.
1057 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1060 // Look at the currently assigned register for this instruction
1061 // to determine the required register class. If there is no register,
1062 // make a conservative choice (don't assign R0).
1063 unsigned AssignedReg = FuncInfo.ValueMap[I];
1064 const TargetRegisterClass *RC =
1065 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1066 &PPC::GPRC_and_GPRC_NOR0RegClass);
1067 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1070 switch (ISDOpcode) {
1071 default: return false;
1073 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1076 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1079 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1083 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1084 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1085 if (SrcReg1 == 0) return false;
1087 // Handle case of small immediate operand.
1088 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1089 const APInt &CIVal = ConstInt->getValue();
1090 int Imm = (int)CIVal.getSExtValue();
1092 if (isInt<16>(Imm)) {
1095 llvm_unreachable("Missing case!");
1098 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1102 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1115 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1124 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1131 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1132 .addReg(SrcReg1).addImm(Imm);
1133 UpdateValueMap(I, ResultReg);
1140 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1141 if (SrcReg2 == 0) return false;
1143 // Reverse operands for subtract-from.
1144 if (ISDOpcode == ISD::SUB)
1145 std::swap(SrcReg1, SrcReg2);
1147 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1148 .addReg(SrcReg1).addReg(SrcReg2);
1149 UpdateValueMap(I, ResultReg);
1153 // Attempt to fast-select a return instruction.
1154 bool PPCFastISel::SelectRet(const Instruction *I) {
1156 if (!FuncInfo.CanLowerReturn)
1159 const ReturnInst *Ret = cast<ReturnInst>(I);
1160 const Function &F = *I->getParent()->getParent();
1162 // Build a list of return value registers.
1163 SmallVector<unsigned, 4> RetRegs;
1164 CallingConv::ID CC = F.getCallingConv();
1166 if (Ret->getNumOperands() > 0) {
1167 SmallVector<ISD::OutputArg, 4> Outs;
1168 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1170 // Analyze operands of the call, assigning locations to each operand.
1171 SmallVector<CCValAssign, 16> ValLocs;
1172 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
1173 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1174 const Value *RV = Ret->getOperand(0);
1176 // FIXME: Only one output register for now.
1177 if (ValLocs.size() > 1)
1180 // Special case for returning a constant integer of any size.
1181 // Materialize the constant as an i64 and copy it to the return
1182 // register. This avoids an unnecessary extend or truncate.
1183 if (isa<ConstantInt>(*RV)) {
1184 const Constant *C = cast<Constant>(RV);
1185 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
1186 unsigned RetReg = ValLocs[0].getLocReg();
1187 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1188 RetReg).addReg(SrcReg);
1189 RetRegs.push_back(RetReg);
1192 unsigned Reg = getRegForValue(RV);
1197 // Copy the result values into the output registers.
1198 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1200 CCValAssign &VA = ValLocs[i];
1201 assert(VA.isRegLoc() && "Can only return in registers!");
1202 RetRegs.push_back(VA.getLocReg());
1203 unsigned SrcReg = Reg + VA.getValNo();
1205 EVT RVEVT = TLI.getValueType(RV->getType());
1206 if (!RVEVT.isSimple())
1208 MVT RVVT = RVEVT.getSimpleVT();
1209 MVT DestVT = VA.getLocVT();
1211 if (RVVT != DestVT && RVVT != MVT::i8 &&
1212 RVVT != MVT::i16 && RVVT != MVT::i32)
1215 if (RVVT != DestVT) {
1216 switch (VA.getLocInfo()) {
1218 llvm_unreachable("Unknown loc info!");
1219 case CCValAssign::Full:
1220 llvm_unreachable("Full value assign but types don't match?");
1221 case CCValAssign::AExt:
1222 case CCValAssign::ZExt: {
1223 const TargetRegisterClass *RC =
1224 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1225 unsigned TmpReg = createResultReg(RC);
1226 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1231 case CCValAssign::SExt: {
1232 const TargetRegisterClass *RC =
1233 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1234 unsigned TmpReg = createResultReg(RC);
1235 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1243 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1244 TII.get(TargetOpcode::COPY), RetRegs[i])
1250 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1253 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1254 MIB.addReg(RetRegs[i], RegState::Implicit);
1259 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1260 // signed and zero extensions are supported. Return false if we
1262 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1263 unsigned DestReg, bool IsZExt) {
1264 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1266 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1269 // Signed extensions use EXTSB, EXTSH, EXTSW.
1272 if (SrcVT == MVT::i8)
1273 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1274 else if (SrcVT == MVT::i16)
1275 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1277 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1278 Opc = PPC::EXTSW_32_64;
1280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1283 // Unsigned 32-bit extensions use RLWINM.
1284 } else if (DestVT == MVT::i32) {
1286 if (SrcVT == MVT::i8)
1289 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1292 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLWINM),
1294 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1296 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1299 if (SrcVT == MVT::i8)
1301 else if (SrcVT == MVT::i16)
1305 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1306 TII.get(PPC::RLDICL_32_64), DestReg)
1307 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1313 // Attempt to fast-select an indirect branch instruction.
1314 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1315 unsigned AddrReg = getRegForValue(I->getOperand(0));
1319 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::MTCTR8))
1321 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCTR8));
1323 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1324 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1325 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1330 // Attempt to fast-select a compare instruction.
1331 bool PPCFastISel::SelectCmp(const Instruction *I) {
1332 const CmpInst *CI = cast<CmpInst>(I);
1333 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
1337 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
1339 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
1343 UpdateValueMap(I, CondReg);
1347 // Attempt to fast-select an integer extend instruction.
1348 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1349 Type *DestTy = I->getType();
1350 Value *Src = I->getOperand(0);
1351 Type *SrcTy = Src->getType();
1353 bool IsZExt = isa<ZExtInst>(I);
1354 unsigned SrcReg = getRegForValue(Src);
1355 if (!SrcReg) return false;
1357 EVT SrcEVT, DestEVT;
1358 SrcEVT = TLI.getValueType(SrcTy, true);
1359 DestEVT = TLI.getValueType(DestTy, true);
1360 if (!SrcEVT.isSimple())
1362 if (!DestEVT.isSimple())
1365 MVT SrcVT = SrcEVT.getSimpleVT();
1366 MVT DestVT = DestEVT.getSimpleVT();
1368 // If we know the register class needed for the result of this
1369 // instruction, use it. Otherwise pick the register class of the
1370 // correct size that does not contain X0/R0, since we don't know
1371 // whether downstream uses permit that assignment.
1372 unsigned AssignedReg = FuncInfo.ValueMap[I];
1373 const TargetRegisterClass *RC =
1374 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1375 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1376 &PPC::GPRC_and_GPRC_NOR0RegClass));
1377 unsigned ResultReg = createResultReg(RC);
1379 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1382 UpdateValueMap(I, ResultReg);
1386 // Attempt to fast-select an instruction that wasn't handled by
1387 // the table-generated machinery.
1388 bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
1390 switch (I->getOpcode()) {
1391 case Instruction::Load:
1392 return SelectLoad(I);
1393 case Instruction::Store:
1394 return SelectStore(I);
1395 case Instruction::Br:
1396 return SelectBranch(I);
1397 case Instruction::IndirectBr:
1398 return SelectIndirectBr(I);
1399 case Instruction::FPExt:
1400 return SelectFPExt(I);
1401 case Instruction::FPTrunc:
1402 return SelectFPTrunc(I);
1403 case Instruction::SIToFP:
1404 return SelectIToFP(I, /*IsSigned*/ true);
1405 case Instruction::UIToFP:
1406 return SelectIToFP(I, /*IsSigned*/ false);
1407 case Instruction::FPToSI:
1408 return SelectFPToI(I, /*IsSigned*/ true);
1409 case Instruction::FPToUI:
1410 return SelectFPToI(I, /*IsSigned*/ false);
1411 case Instruction::Add:
1412 return SelectBinaryIntOp(I, ISD::ADD);
1413 case Instruction::Or:
1414 return SelectBinaryIntOp(I, ISD::OR);
1415 case Instruction::Sub:
1416 return SelectBinaryIntOp(I, ISD::SUB);
1417 case Instruction::Ret:
1418 return SelectRet(I);
1419 case Instruction::ZExt:
1420 case Instruction::SExt:
1421 return SelectIntExt(I);
1422 // Here add other flavors of Instruction::XXX that automated
1423 // cases don't catch. For example, switches are terminators
1424 // that aren't yet handled.
1431 // Materialize a floating-point constant into a register, and return
1432 // the register number (or zero if we failed to handle it).
1433 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1434 // No plans to handle long double here.
1435 if (VT != MVT::f32 && VT != MVT::f64)
1438 // All FP constants are loaded from the constant pool.
1439 unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
1440 assert(Align > 0 && "Unexpectedly missing alignment information!");
1441 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1442 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1443 CodeModel::Model CModel = TM.getCodeModel();
1445 MachineMemOperand *MMO =
1446 FuncInfo.MF->getMachineMemOperand(
1447 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1448 (VT == MVT::f32) ? 4 : 8, Align);
1450 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1451 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1453 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1454 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1455 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocCPT),
1457 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1458 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1459 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1461 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1462 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1463 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1465 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1467 .addMemOperand(MMO);
1473 // Materialize the address of a global value into a register, and return
1474 // the register number (or zero if we failed to handle it).
1475 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1476 assert(VT == MVT::i64 && "Non-address!");
1477 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1478 unsigned DestReg = createResultReg(RC);
1480 // Global values may be plain old object addresses, TLS object
1481 // addresses, constant pool entries, or jump tables. How we generate
1482 // code for these may depend on small, medium, or large code model.
1483 CodeModel::Model CModel = TM.getCodeModel();
1485 // FIXME: Jump tables are not yet required because fast-isel doesn't
1486 // handle switches; if that changes, we need them as well. For now,
1487 // what follows assumes everything's a generic (or TLS) global address.
1488 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1490 // If GV is an alias, use the aliasee for determining thread-locality.
1491 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1492 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1493 assert((GVar || isa<Function>(GV)) && "Unexpected GV subclass!");
1496 // FIXME: We don't yet handle the complexity of TLS.
1497 bool IsTLS = GVar && GVar->isThreadLocal();
1501 // For small code model, generate a simple TOC load.
1502 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1503 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtoc), DestReg)
1504 .addGlobalAddress(GV).addReg(PPC::X2);
1506 // If the address is an externally defined symbol, a symbol with
1507 // common or externally available linkage, a function address, or a
1508 // jump table address (not yet needed), or if we are generating code
1509 // for large code model, we generate:
1510 // LDtocL(GV, ADDIStocHA(%X2, GV))
1511 // Otherwise we generate:
1512 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1513 // Either way, start with the ADDIStocHA:
1514 unsigned HighPartReg = createResultReg(RC);
1515 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1516 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1518 // !GVar implies a function address. An external variable is one
1519 // without an initializer.
1520 // If/when switches are implemented, jump tables should be handled
1521 // on the "if" path here.
1522 if (CModel == CodeModel::Large || !GVar || !GVar->hasInitializer() ||
1523 GVar->hasCommonLinkage() || GVar->hasAvailableExternallyLinkage())
1524 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocL),
1525 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1527 // Otherwise generate the ADDItocL.
1528 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDItocL),
1529 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1535 // Materialize a 32-bit integer constant into a register, and return
1536 // the register number (or zero if we failed to handle it).
1537 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1538 const TargetRegisterClass *RC) {
1539 unsigned Lo = Imm & 0xFFFF;
1540 unsigned Hi = (Imm >> 16) & 0xFFFF;
1542 unsigned ResultReg = createResultReg(RC);
1543 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1546 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1547 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1550 // Both Lo and Hi have nonzero bits.
1551 unsigned TmpReg = createResultReg(RC);
1552 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1553 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1555 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1556 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1557 .addReg(TmpReg).addImm(Lo);
1560 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1561 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1567 // Materialize a 64-bit integer constant into a register, and return
1568 // the register number (or zero if we failed to handle it).
1569 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1570 const TargetRegisterClass *RC) {
1571 unsigned Remainder = 0;
1574 // If the value doesn't fit in 32 bits, see if we can shift it
1575 // so that it fits in 32 bits.
1576 if (!isInt<32>(Imm)) {
1577 Shift = countTrailingZeros<uint64_t>(Imm);
1578 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1580 if (isInt<32>(ImmSh))
1589 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1590 // (if not shifted).
1591 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1595 // If upper 32 bits were not zero, we've built them and need to shift
1599 TmpReg2 = createResultReg(RC);
1600 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLDICR),
1601 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1605 unsigned TmpReg3, Hi, Lo;
1606 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1607 TmpReg3 = createResultReg(RC);
1608 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORIS8),
1609 TmpReg3).addReg(TmpReg2).addImm(Hi);
1613 if ((Lo = Remainder & 0xFFFF)) {
1614 unsigned ResultReg = createResultReg(RC);
1615 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORI8),
1616 ResultReg).addReg(TmpReg3).addImm(Lo);
1624 // Materialize an integer constant into a register, and return
1625 // the register number (or zero if we failed to handle it).
1626 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
1628 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1629 VT != MVT::i8 && VT != MVT::i1)
1632 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
1633 &PPC::GPRCRegClass);
1635 // If the constant is in range, use a load-immediate.
1636 const ConstantInt *CI = cast<ConstantInt>(C);
1637 if (isInt<16>(CI->getSExtValue())) {
1638 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
1639 unsigned ImmReg = createResultReg(RC);
1640 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ImmReg)
1641 .addImm(CI->getSExtValue());
1645 // Construct the constant piecewise.
1646 int64_t Imm = CI->getZExtValue();
1649 return PPCMaterialize64BitInt(Imm, RC);
1650 else if (VT == MVT::i32)
1651 return PPCMaterialize32BitInt(Imm, RC);
1656 // Materialize a constant into a register, and return the register
1657 // number (or zero if we failed to handle it).
1658 unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
1659 EVT CEVT = TLI.getValueType(C->getType(), true);
1661 // Only handle simple types.
1662 if (!CEVT.isSimple()) return 0;
1663 MVT VT = CEVT.getSimpleVT();
1665 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1666 return PPCMaterializeFP(CFP, VT);
1667 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1668 return PPCMaterializeGV(GV, VT);
1669 else if (isa<ConstantInt>(C))
1670 return PPCMaterializeInt(C, VT);
1671 // TBD: Global values.
1676 // Materialize the address created by an alloca into a register, and
1677 // return the register number (or zero if we failed to handle it). TBD.
1678 unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
1682 // Fold loads into extends when possible.
1683 // FIXME: We can have multiple redundant extend/trunc instructions
1684 // following a load. The folding only picks up one. Extend this
1685 // to check subsequent instructions for the same pattern and remove
1686 // them. Thus ResultReg should be the def reg for the last redundant
1687 // instruction in a chain, and all intervening instructions can be
1688 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
1689 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
1690 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
1691 const LoadInst *LI) {
1692 // Verify we have a legal type before going any further.
1694 if (!isLoadTypeLegal(LI->getType(), VT))
1697 // Combine load followed by zero- or sign-extend.
1698 bool IsZExt = false;
1699 switch(MI->getOpcode()) {
1704 case PPC::RLDICL_32_64: {
1706 unsigned MB = MI->getOperand(3).getImm();
1707 if ((VT == MVT::i8 && MB <= 56) ||
1708 (VT == MVT::i16 && MB <= 48) ||
1709 (VT == MVT::i32 && MB <= 32))
1715 case PPC::RLWINM8: {
1717 unsigned MB = MI->getOperand(3).getImm();
1718 if ((VT == MVT::i8 && MB <= 24) ||
1719 (VT == MVT::i16 && MB <= 16))
1726 case PPC::EXTSB8_32_64:
1727 /* There is no sign-extending load-byte instruction. */
1732 case PPC::EXTSH8_32_64: {
1733 if (VT != MVT::i16 && VT != MVT::i8)
1739 case PPC::EXTSW_32_64: {
1740 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
1746 // See if we can handle this address.
1748 if (!PPCComputeAddress(LI->getOperand(0), Addr))
1751 unsigned ResultReg = MI->getOperand(0).getReg();
1753 if (!PPCEmitLoad(VT, ResultReg, Addr, 0, IsZExt))
1756 MI->eraseFromParent();
1760 // Attempt to lower call arguments in a faster way than done by
1761 // the selection DAG code.
1762 bool PPCFastISel::FastLowerArguments() {
1763 // Defer to normal argument lowering for now. It's reasonably
1764 // efficient. Consider doing something like ARM to handle the
1765 // case where all args fit in registers, no varargs, no float
1770 // Handle materializing integer constants into a register. This is not
1771 // automatically generated for PowerPC, so must be explicitly created here.
1772 unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
1774 if (Opc != ISD::Constant)
1777 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1778 VT != MVT::i8 && VT != MVT::i1)
1781 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
1782 &PPC::GPRCRegClass);
1784 return PPCMaterialize64BitInt(Imm, RC);
1786 return PPCMaterialize32BitInt(Imm, RC);
1789 // Override for ADDI and ADDI8 to set the correct register class
1790 // on RHS operand 0. The automatic infrastructure naively assumes
1791 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
1792 // for these cases. At the moment, none of the other automatically
1793 // generated RI instructions require special treatment. However, once
1794 // SelectSelect is implemented, "isel" requires similar handling.
1796 // Also be conservative about the output register class. Avoid
1797 // assigning R0 or X0 to the output register for GPRC and G8RC
1798 // register classes, as any such result could be used in ADDI, etc.,
1799 // where those regs have another meaning.
1800 unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1801 const TargetRegisterClass *RC,
1802 unsigned Op0, bool Op0IsKill,
1804 if (MachineInstOpcode == PPC::ADDI)
1805 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
1806 else if (MachineInstOpcode == PPC::ADDI8)
1807 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
1809 const TargetRegisterClass *UseRC =
1810 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
1811 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
1813 return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
1814 Op0, Op0IsKill, Imm);
1817 // Override for instructions with one register operand to avoid use of
1818 // R0/X0. The automatic infrastructure isn't aware of the context so
1819 // we must be conservative.
1820 unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1821 const TargetRegisterClass* RC,
1822 unsigned Op0, bool Op0IsKill) {
1823 const TargetRegisterClass *UseRC =
1824 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
1825 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
1827 return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
1830 // Override for instructions with two register operands to avoid use
1831 // of R0/X0. The automatic infrastructure isn't aware of the context
1832 // so we must be conservative.
1833 unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1834 const TargetRegisterClass* RC,
1835 unsigned Op0, bool Op0IsKill,
1836 unsigned Op1, bool Op1IsKill) {
1837 const TargetRegisterClass *UseRC =
1838 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
1839 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
1841 return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
1846 // Create the fast instruction selector for PowerPC64 ELF.
1847 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
1848 const TargetLibraryInfo *LibInfo) {
1849 const TargetMachine &TM = FuncInfo.MF->getTarget();
1851 // Only available on 64-bit ELF for now.
1852 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
1853 if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
1854 return new PPCFastISel(FuncInfo, LibInfo);