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 SelectCall(const Instruction *I);
118 bool SelectRet(const Instruction *I);
119 bool SelectIntExt(const Instruction *I);
123 bool isTypeLegal(Type *Ty, MVT &VT);
124 bool isLoadTypeLegal(Type *Ty, MVT &VT);
125 bool PPCEmitCmp(const Value *Src1Value, const Value *Src2Value,
126 bool isZExt, unsigned DestReg);
127 bool PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
128 const TargetRegisterClass *RC, bool IsZExt = true,
129 unsigned FP64LoadOpc = PPC::LFD);
130 bool PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr);
131 bool PPCComputeAddress(const Value *Obj, Address &Addr);
132 void PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
134 bool PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
135 unsigned DestReg, bool IsZExt);
136 unsigned PPCMaterializeFP(const ConstantFP *CFP, MVT VT);
137 unsigned PPCMaterializeGV(const GlobalValue *GV, MVT VT);
138 unsigned PPCMaterializeInt(const Constant *C, MVT VT);
139 unsigned PPCMaterialize32BitInt(int64_t Imm,
140 const TargetRegisterClass *RC);
141 unsigned PPCMaterialize64BitInt(int64_t Imm,
142 const TargetRegisterClass *RC);
143 unsigned PPCMoveToIntReg(const Instruction *I, MVT VT,
144 unsigned SrcReg, bool IsSigned);
145 unsigned PPCMoveToFPReg(MVT VT, unsigned SrcReg, bool IsSigned);
147 // Call handling routines.
149 bool processCallArgs(SmallVectorImpl<Value*> &Args,
150 SmallVectorImpl<unsigned> &ArgRegs,
151 SmallVectorImpl<MVT> &ArgVTs,
152 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
153 SmallVectorImpl<unsigned> &RegArgs,
157 void finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
158 const Instruction *I, CallingConv::ID CC,
159 unsigned &NumBytes, bool IsVarArg);
160 CCAssignFn *usePPC32CCs(unsigned Flag);
163 #include "PPCGenFastISel.inc"
167 } // end anonymous namespace
169 #include "PPCGenCallingConv.inc"
171 // Function whose sole purpose is to kill compiler warnings
172 // stemming from unused functions included from PPCGenCallingConv.inc.
173 CCAssignFn *PPCFastISel::usePPC32CCs(unsigned Flag) {
175 return CC_PPC32_SVR4;
177 return CC_PPC32_SVR4_ByVal;
179 return CC_PPC32_SVR4_VarArg;
184 static Optional<PPC::Predicate> getComparePred(CmpInst::Predicate Pred) {
186 // These are not representable with any single compare.
187 case CmpInst::FCMP_FALSE:
188 case CmpInst::FCMP_UEQ:
189 case CmpInst::FCMP_UGT:
190 case CmpInst::FCMP_UGE:
191 case CmpInst::FCMP_ULT:
192 case CmpInst::FCMP_ULE:
193 case CmpInst::FCMP_UNE:
194 case CmpInst::FCMP_TRUE:
196 return Optional<PPC::Predicate>();
198 case CmpInst::FCMP_OEQ:
199 case CmpInst::ICMP_EQ:
202 case CmpInst::FCMP_OGT:
203 case CmpInst::ICMP_UGT:
204 case CmpInst::ICMP_SGT:
207 case CmpInst::FCMP_OGE:
208 case CmpInst::ICMP_UGE:
209 case CmpInst::ICMP_SGE:
212 case CmpInst::FCMP_OLT:
213 case CmpInst::ICMP_ULT:
214 case CmpInst::ICMP_SLT:
217 case CmpInst::FCMP_OLE:
218 case CmpInst::ICMP_ULE:
219 case CmpInst::ICMP_SLE:
222 case CmpInst::FCMP_ONE:
223 case CmpInst::ICMP_NE:
226 case CmpInst::FCMP_ORD:
229 case CmpInst::FCMP_UNO:
234 // Determine whether the type Ty is simple enough to be handled by
235 // fast-isel, and return its equivalent machine type in VT.
236 // FIXME: Copied directly from ARM -- factor into base class?
237 bool PPCFastISel::isTypeLegal(Type *Ty, MVT &VT) {
238 EVT Evt = TLI.getValueType(Ty, true);
240 // Only handle simple types.
241 if (Evt == MVT::Other || !Evt.isSimple()) return false;
242 VT = Evt.getSimpleVT();
244 // Handle all legal types, i.e. a register that will directly hold this
246 return TLI.isTypeLegal(VT);
249 // Determine whether the type Ty is simple enough to be handled by
250 // fast-isel as a load target, and return its equivalent machine type in VT.
251 bool PPCFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
252 if (isTypeLegal(Ty, VT)) return true;
254 // If this is a type than can be sign or zero-extended to a basic operation
255 // go ahead and accept it now.
256 if (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) {
263 // Given a value Obj, create an Address object Addr that represents its
264 // address. Return false if we can't handle it.
265 bool PPCFastISel::PPCComputeAddress(const Value *Obj, Address &Addr) {
266 const User *U = NULL;
267 unsigned Opcode = Instruction::UserOp1;
268 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
269 // Don't walk into other basic blocks unless the object is an alloca from
270 // another block, otherwise it may not have a virtual register assigned.
271 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
272 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
273 Opcode = I->getOpcode();
276 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
277 Opcode = C->getOpcode();
284 case Instruction::BitCast:
285 // Look through bitcasts.
286 return PPCComputeAddress(U->getOperand(0), Addr);
287 case Instruction::IntToPtr:
288 // Look past no-op inttoptrs.
289 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
290 return PPCComputeAddress(U->getOperand(0), Addr);
292 case Instruction::PtrToInt:
293 // Look past no-op ptrtoints.
294 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
295 return PPCComputeAddress(U->getOperand(0), Addr);
297 case Instruction::GetElementPtr: {
298 Address SavedAddr = Addr;
299 long TmpOffset = Addr.Offset;
301 // Iterate through the GEP folding the constants into offsets where
303 gep_type_iterator GTI = gep_type_begin(U);
304 for (User::const_op_iterator II = U->op_begin() + 1, IE = U->op_end();
305 II != IE; ++II, ++GTI) {
306 const Value *Op = *II;
307 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
308 const StructLayout *SL = TD.getStructLayout(STy);
309 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
310 TmpOffset += SL->getElementOffset(Idx);
312 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
314 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
315 // Constant-offset addressing.
316 TmpOffset += CI->getSExtValue() * S;
319 if (isa<AddOperator>(Op) &&
320 (!isa<Instruction>(Op) ||
321 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
323 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
324 // An add (in the same block) with a constant operand. Fold the
327 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
328 TmpOffset += CI->getSExtValue() * S;
329 // Iterate on the other operand.
330 Op = cast<AddOperator>(Op)->getOperand(0);
334 goto unsupported_gep;
339 // Try to grab the base operand now.
340 Addr.Offset = TmpOffset;
341 if (PPCComputeAddress(U->getOperand(0), Addr)) return true;
343 // We failed, restore everything and try the other options.
349 case Instruction::Alloca: {
350 const AllocaInst *AI = cast<AllocaInst>(Obj);
351 DenseMap<const AllocaInst*, int>::iterator SI =
352 FuncInfo.StaticAllocaMap.find(AI);
353 if (SI != FuncInfo.StaticAllocaMap.end()) {
354 Addr.BaseType = Address::FrameIndexBase;
355 Addr.Base.FI = SI->second;
362 // FIXME: References to parameters fall through to the behavior
363 // below. They should be able to reference a frame index since
364 // they are stored to the stack, so we can get "ld rx, offset(r1)"
365 // instead of "addi ry, r1, offset / ld rx, 0(ry)". Obj will
366 // just contain the parameter. Try to handle this with a FI.
368 // Try to get this in a register if nothing else has worked.
369 if (Addr.Base.Reg == 0)
370 Addr.Base.Reg = getRegForValue(Obj);
372 // Prevent assignment of base register to X0, which is inappropriate
373 // for loads and stores alike.
374 if (Addr.Base.Reg != 0)
375 MRI.setRegClass(Addr.Base.Reg, &PPC::G8RC_and_G8RC_NOX0RegClass);
377 return Addr.Base.Reg != 0;
380 // Fix up some addresses that can't be used directly. For example, if
381 // an offset won't fit in an instruction field, we may need to move it
382 // into an index register.
383 void PPCFastISel::PPCSimplifyAddress(Address &Addr, MVT VT, bool &UseOffset,
384 unsigned &IndexReg) {
386 // Check whether the offset fits in the instruction field.
387 if (!isInt<16>(Addr.Offset))
390 // If this is a stack pointer and the offset needs to be simplified then
391 // put the alloca address into a register, set the base type back to
392 // register and continue. This should almost never happen.
393 if (!UseOffset && Addr.BaseType == Address::FrameIndexBase) {
394 unsigned ResultReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
395 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDI8),
396 ResultReg).addFrameIndex(Addr.Base.FI).addImm(0);
397 Addr.Base.Reg = ResultReg;
398 Addr.BaseType = Address::RegBase;
402 IntegerType *OffsetTy = ((VT == MVT::i32) ? Type::getInt32Ty(*Context)
403 : Type::getInt64Ty(*Context));
404 const ConstantInt *Offset =
405 ConstantInt::getSigned(OffsetTy, (int64_t)(Addr.Offset));
406 IndexReg = PPCMaterializeInt(Offset, MVT::i64);
407 assert(IndexReg && "Unexpected error in PPCMaterializeInt!");
411 // Emit a load instruction if possible, returning true if we succeeded,
412 // otherwise false. See commentary below for how the register class of
413 // the load is determined.
414 bool PPCFastISel::PPCEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
415 const TargetRegisterClass *RC,
416 bool IsZExt, unsigned FP64LoadOpc) {
418 bool UseOffset = true;
420 // If ResultReg is given, it determines the register class of the load.
421 // Otherwise, RC is the register class to use. If the result of the
422 // load isn't anticipated in this block, both may be zero, in which
423 // case we must make a conservative guess. In particular, don't assign
424 // R0 or X0 to the result register, as the result may be used in a load,
425 // store, add-immediate, or isel that won't permit this. (Though
426 // perhaps the spill and reload of live-exit values would handle this?)
427 const TargetRegisterClass *UseRC =
428 (ResultReg ? MRI.getRegClass(ResultReg) :
430 (VT == MVT::f64 ? &PPC::F8RCRegClass :
431 (VT == MVT::f32 ? &PPC::F4RCRegClass :
432 (VT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
433 &PPC::GPRC_and_GPRC_NOR0RegClass)))));
435 bool Is32BitInt = UseRC->hasSuperClassEq(&PPC::GPRCRegClass);
437 switch (VT.SimpleTy) {
438 default: // e.g., vector types not handled
441 Opc = Is32BitInt ? PPC::LBZ : PPC::LBZ8;
445 (Is32BitInt ? PPC::LHZ : PPC::LHZ8) :
446 (Is32BitInt ? PPC::LHA : PPC::LHA8));
450 (Is32BitInt ? PPC::LWZ : PPC::LWZ8) :
451 (Is32BitInt ? PPC::LWA_32 : PPC::LWA));
452 if ((Opc == PPC::LWA || Opc == PPC::LWA_32) && ((Addr.Offset & 3) != 0))
457 assert(UseRC->hasSuperClassEq(&PPC::G8RCRegClass) &&
458 "64-bit load with 32-bit target??");
459 UseOffset = ((Addr.Offset & 3) == 0);
469 // If necessary, materialize the offset into a register and use
470 // the indexed form. Also handle stack pointers with special needs.
471 unsigned IndexReg = 0;
472 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
474 ResultReg = createResultReg(UseRC);
476 // Note: If we still have a frame index here, we know the offset is
477 // in range, as otherwise PPCSimplifyAddress would have converted it
479 if (Addr.BaseType == Address::FrameIndexBase) {
481 MachineMemOperand *MMO =
482 FuncInfo.MF->getMachineMemOperand(
483 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
484 MachineMemOperand::MOLoad, MFI.getObjectSize(Addr.Base.FI),
485 MFI.getObjectAlignment(Addr.Base.FI));
487 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
488 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
490 // Base reg with offset in range.
491 } else if (UseOffset) {
493 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
494 .addImm(Addr.Offset).addReg(Addr.Base.Reg);
498 // Get the RR opcode corresponding to the RI one. FIXME: It would be
499 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
500 // is hard to get at.
502 default: llvm_unreachable("Unexpected opcode!");
503 case PPC::LBZ: Opc = PPC::LBZX; break;
504 case PPC::LBZ8: Opc = PPC::LBZX8; break;
505 case PPC::LHZ: Opc = PPC::LHZX; break;
506 case PPC::LHZ8: Opc = PPC::LHZX8; break;
507 case PPC::LHA: Opc = PPC::LHAX; break;
508 case PPC::LHA8: Opc = PPC::LHAX8; break;
509 case PPC::LWZ: Opc = PPC::LWZX; break;
510 case PPC::LWZ8: Opc = PPC::LWZX8; break;
511 case PPC::LWA: Opc = PPC::LWAX; break;
512 case PPC::LWA_32: Opc = PPC::LWAX_32; break;
513 case PPC::LD: Opc = PPC::LDX; break;
514 case PPC::LFS: Opc = PPC::LFSX; break;
515 case PPC::LFD: Opc = PPC::LFDX; break;
517 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
518 .addReg(Addr.Base.Reg).addReg(IndexReg);
524 // Attempt to fast-select a load instruction.
525 bool PPCFastISel::SelectLoad(const Instruction *I) {
526 // FIXME: No atomic loads are supported.
527 if (cast<LoadInst>(I)->isAtomic())
530 // Verify we have a legal type before going any further.
532 if (!isLoadTypeLegal(I->getType(), VT))
535 // See if we can handle this address.
537 if (!PPCComputeAddress(I->getOperand(0), Addr))
540 // Look at the currently assigned register for this instruction
541 // to determine the required register class. This is necessary
542 // to constrain RA from using R0/X0 when this is not legal.
543 unsigned AssignedReg = FuncInfo.ValueMap[I];
544 const TargetRegisterClass *RC =
545 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
547 unsigned ResultReg = 0;
548 if (!PPCEmitLoad(VT, ResultReg, Addr, RC))
550 UpdateValueMap(I, ResultReg);
554 // Emit a store instruction to store SrcReg at Addr.
555 bool PPCFastISel::PPCEmitStore(MVT VT, unsigned SrcReg, Address &Addr) {
556 assert(SrcReg && "Nothing to store!");
558 bool UseOffset = true;
560 const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
561 bool Is32BitInt = RC->hasSuperClassEq(&PPC::GPRCRegClass);
563 switch (VT.SimpleTy) {
564 default: // e.g., vector types not handled
567 Opc = Is32BitInt ? PPC::STB : PPC::STB8;
570 Opc = Is32BitInt ? PPC::STH : PPC::STH8;
573 assert(Is32BitInt && "Not GPRC for i32??");
578 UseOffset = ((Addr.Offset & 3) == 0);
588 // If necessary, materialize the offset into a register and use
589 // the indexed form. Also handle stack pointers with special needs.
590 unsigned IndexReg = 0;
591 PPCSimplifyAddress(Addr, VT, UseOffset, IndexReg);
593 // Note: If we still have a frame index here, we know the offset is
594 // in range, as otherwise PPCSimplifyAddress would have converted it
596 if (Addr.BaseType == Address::FrameIndexBase) {
597 MachineMemOperand *MMO =
598 FuncInfo.MF->getMachineMemOperand(
599 MachinePointerInfo::getFixedStack(Addr.Base.FI, Addr.Offset),
600 MachineMemOperand::MOStore, MFI.getObjectSize(Addr.Base.FI),
601 MFI.getObjectAlignment(Addr.Base.FI));
603 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc)).addReg(SrcReg)
604 .addImm(Addr.Offset).addFrameIndex(Addr.Base.FI).addMemOperand(MMO);
606 // Base reg with offset in range.
607 } else if (UseOffset)
608 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
609 .addReg(SrcReg).addImm(Addr.Offset).addReg(Addr.Base.Reg);
613 // Get the RR opcode corresponding to the RI one. FIXME: It would be
614 // preferable to use the ImmToIdxMap from PPCRegisterInfo.cpp, but it
615 // is hard to get at.
617 default: llvm_unreachable("Unexpected opcode!");
618 case PPC::STB: Opc = PPC::STBX; break;
619 case PPC::STH : Opc = PPC::STHX; break;
620 case PPC::STW : Opc = PPC::STWX; break;
621 case PPC::STB8: Opc = PPC::STBX8; break;
622 case PPC::STH8: Opc = PPC::STHX8; break;
623 case PPC::STW8: Opc = PPC::STWX8; break;
624 case PPC::STD: Opc = PPC::STDX; break;
625 case PPC::STFS: Opc = PPC::STFSX; break;
626 case PPC::STFD: Opc = PPC::STFDX; break;
628 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
629 .addReg(SrcReg).addReg(Addr.Base.Reg).addReg(IndexReg);
635 // Attempt to fast-select a store instruction.
636 bool PPCFastISel::SelectStore(const Instruction *I) {
637 Value *Op0 = I->getOperand(0);
640 // FIXME: No atomics loads are supported.
641 if (cast<StoreInst>(I)->isAtomic())
644 // Verify we have a legal type before going any further.
646 if (!isLoadTypeLegal(Op0->getType(), VT))
649 // Get the value to be stored into a register.
650 SrcReg = getRegForValue(Op0);
654 // See if we can handle this address.
656 if (!PPCComputeAddress(I->getOperand(1), Addr))
659 if (!PPCEmitStore(VT, SrcReg, Addr))
665 // Attempt to fast-select a branch instruction.
666 bool PPCFastISel::SelectBranch(const Instruction *I) {
667 const BranchInst *BI = cast<BranchInst>(I);
668 MachineBasicBlock *BrBB = FuncInfo.MBB;
669 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
670 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
672 // For now, just try the simplest case where it's fed by a compare.
673 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
674 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
678 PPC::Predicate PPCPred = OptPPCPred.getValue();
680 // Take advantage of fall-through opportunities.
681 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
683 PPCPred = PPC::InvertPredicate(PPCPred);
686 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
688 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
692 BuildMI(*BrBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCC))
693 .addImm(PPCPred).addReg(CondReg).addMBB(TBB);
694 FastEmitBranch(FBB, DL);
695 FuncInfo.MBB->addSuccessor(TBB);
698 } else if (const ConstantInt *CI =
699 dyn_cast<ConstantInt>(BI->getCondition())) {
700 uint64_t Imm = CI->getZExtValue();
701 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
702 FastEmitBranch(Target, DL);
706 // FIXME: ARM looks for a case where the block containing the compare
707 // has been split from the block containing the branch. If this happens,
708 // there is a vreg available containing the result of the compare. I'm
709 // not sure we can do much, as we've lost the predicate information with
710 // the compare instruction -- we have a 4-bit CR but don't know which bit
715 // Attempt to emit a compare of the two source values. Signed and unsigned
716 // comparisons are supported. Return false if we can't handle it.
717 bool PPCFastISel::PPCEmitCmp(const Value *SrcValue1, const Value *SrcValue2,
718 bool IsZExt, unsigned DestReg) {
719 Type *Ty = SrcValue1->getType();
720 EVT SrcEVT = TLI.getValueType(Ty, true);
721 if (!SrcEVT.isSimple())
723 MVT SrcVT = SrcEVT.getSimpleVT();
725 // See if operand 2 is an immediate encodeable in the compare.
726 // FIXME: Operands are not in canonical order at -O0, so an immediate
727 // operand in position 1 is a lost opportunity for now. We are
728 // similar to ARM in this regard.
732 // Only 16-bit integer constants can be represented in compares for
733 // PowerPC. Others will be materialized into a register.
734 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(SrcValue2)) {
735 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
736 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
737 const APInt &CIVal = ConstInt->getValue();
738 Imm = (IsZExt) ? (long)CIVal.getZExtValue() : (long)CIVal.getSExtValue();
739 if ((IsZExt && isUInt<16>(Imm)) || (!IsZExt && isInt<16>(Imm)))
745 bool NeedsExt = false;
746 switch (SrcVT.SimpleTy) {
747 default: return false;
749 CmpOpc = PPC::FCMPUS;
752 CmpOpc = PPC::FCMPUD;
758 // Intentional fall-through.
761 CmpOpc = IsZExt ? PPC::CMPLW : PPC::CMPW;
763 CmpOpc = IsZExt ? PPC::CMPLWI : PPC::CMPWI;
767 CmpOpc = IsZExt ? PPC::CMPLD : PPC::CMPD;
769 CmpOpc = IsZExt ? PPC::CMPLDI : PPC::CMPDI;
773 unsigned SrcReg1 = getRegForValue(SrcValue1);
777 unsigned SrcReg2 = 0;
779 SrcReg2 = getRegForValue(SrcValue2);
785 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
786 if (!PPCEmitIntExt(SrcVT, SrcReg1, MVT::i32, ExtReg, IsZExt))
791 unsigned ExtReg = createResultReg(&PPC::GPRCRegClass);
792 if (!PPCEmitIntExt(SrcVT, SrcReg2, MVT::i32, ExtReg, IsZExt))
799 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
800 .addReg(SrcReg1).addReg(SrcReg2);
802 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc), DestReg)
803 .addReg(SrcReg1).addImm(Imm);
808 // Attempt to fast-select a floating-point extend instruction.
809 bool PPCFastISel::SelectFPExt(const Instruction *I) {
810 Value *Src = I->getOperand(0);
811 EVT SrcVT = TLI.getValueType(Src->getType(), true);
812 EVT DestVT = TLI.getValueType(I->getType(), true);
814 if (SrcVT != MVT::f32 || DestVT != MVT::f64)
817 unsigned SrcReg = getRegForValue(Src);
821 // No code is generated for a FP extend.
822 UpdateValueMap(I, SrcReg);
826 // Attempt to fast-select a floating-point truncate instruction.
827 bool PPCFastISel::SelectFPTrunc(const Instruction *I) {
828 Value *Src = I->getOperand(0);
829 EVT SrcVT = TLI.getValueType(Src->getType(), true);
830 EVT DestVT = TLI.getValueType(I->getType(), true);
832 if (SrcVT != MVT::f64 || DestVT != MVT::f32)
835 unsigned SrcReg = getRegForValue(Src);
839 // Round the result to single precision.
840 unsigned DestReg = createResultReg(&PPC::F4RCRegClass);
841 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP), DestReg)
844 UpdateValueMap(I, DestReg);
848 // Move an i32 or i64 value in a GPR to an f64 value in an FPR.
849 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
850 // those should be used instead of moving via a stack slot when the
851 // subtarget permits.
852 // FIXME: The code here is sloppy for the 4-byte case. Can use a 4-byte
853 // stack slot and 4-byte store/load sequence. Or just sext the 4-byte
854 // case to 8 bytes which produces tighter code but wastes stack space.
855 unsigned PPCFastISel::PPCMoveToFPReg(MVT SrcVT, unsigned SrcReg,
858 // If necessary, extend 32-bit int to 64-bit.
859 if (SrcVT == MVT::i32) {
860 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
861 if (!PPCEmitIntExt(MVT::i32, SrcReg, MVT::i64, TmpReg, !IsSigned))
866 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
868 Addr.BaseType = Address::FrameIndexBase;
869 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
871 // Store the value from the GPR.
872 if (!PPCEmitStore(MVT::i64, SrcReg, Addr))
875 // Load the integer value into an FPR. The kind of load used depends
876 // on a number of conditions.
877 unsigned LoadOpc = PPC::LFD;
879 if (SrcVT == MVT::i32) {
882 LoadOpc = PPC::LFIWZX;
883 else if (PPCSubTarget.hasLFIWAX())
884 LoadOpc = PPC::LFIWAX;
887 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
888 unsigned ResultReg = 0;
889 if (!PPCEmitLoad(MVT::f64, ResultReg, Addr, RC, !IsSigned, LoadOpc))
895 // Attempt to fast-select an integer-to-floating-point conversion.
896 bool PPCFastISel::SelectIToFP(const Instruction *I, bool IsSigned) {
898 Type *DstTy = I->getType();
899 if (!isTypeLegal(DstTy, DstVT))
902 if (DstVT != MVT::f32 && DstVT != MVT::f64)
905 Value *Src = I->getOperand(0);
906 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
907 if (!SrcEVT.isSimple())
910 MVT SrcVT = SrcEVT.getSimpleVT();
912 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 &&
913 SrcVT != MVT::i32 && SrcVT != MVT::i64)
916 unsigned SrcReg = getRegForValue(Src);
920 // We can only lower an unsigned convert if we have the newer
921 // floating-point conversion operations.
922 if (!IsSigned && !PPCSubTarget.hasFPCVT())
925 // FIXME: For now we require the newer floating-point conversion operations
926 // (which are present only on P7 and A2 server models) when converting
927 // to single-precision float. Otherwise we have to generate a lot of
928 // fiddly code to avoid double rounding. If necessary, the fiddly code
929 // can be found in PPCTargetLowering::LowerINT_TO_FP().
930 if (DstVT == MVT::f32 && !PPCSubTarget.hasFPCVT())
933 // Extend the input if necessary.
934 if (SrcVT == MVT::i8 || SrcVT == MVT::i16) {
935 unsigned TmpReg = createResultReg(&PPC::G8RCRegClass);
936 if (!PPCEmitIntExt(SrcVT, SrcReg, MVT::i64, TmpReg, !IsSigned))
942 // Move the integer value to an FPR.
943 unsigned FPReg = PPCMoveToFPReg(SrcVT, SrcReg, IsSigned);
947 // Determine the opcode for the conversion.
948 const TargetRegisterClass *RC = &PPC::F8RCRegClass;
949 unsigned DestReg = createResultReg(RC);
952 if (DstVT == MVT::f32)
953 Opc = IsSigned ? PPC::FCFIDS : PPC::FCFIDUS;
955 Opc = IsSigned ? PPC::FCFID : PPC::FCFIDU;
957 // Generate the convert.
958 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
961 UpdateValueMap(I, DestReg);
965 // Move the floating-point value in SrcReg into an integer destination
966 // register, and return the register (or zero if we can't handle it).
967 // FIXME: When direct register moves are implemented (see PowerISA 2.08),
968 // those should be used instead of moving via a stack slot when the
969 // subtarget permits.
970 unsigned PPCFastISel::PPCMoveToIntReg(const Instruction *I, MVT VT,
971 unsigned SrcReg, bool IsSigned) {
972 // Get a stack slot 8 bytes wide, aligned on an 8-byte boundary.
973 // Note that if have STFIWX available, we could use a 4-byte stack
974 // slot for i32, but this being fast-isel we'll just go with the
975 // easiest code gen possible.
977 Addr.BaseType = Address::FrameIndexBase;
978 Addr.Base.FI = MFI.CreateStackObject(8, 8, false);
980 // Store the value from the FPR.
981 if (!PPCEmitStore(MVT::f64, SrcReg, Addr))
984 // Reload it into a GPR. If we want an i32, modify the address
985 // to have a 4-byte offset so we load from the right place.
989 // Look at the currently assigned register for this instruction
990 // to determine the required register class.
991 unsigned AssignedReg = FuncInfo.ValueMap[I];
992 const TargetRegisterClass *RC =
993 AssignedReg ? MRI.getRegClass(AssignedReg) : 0;
995 unsigned ResultReg = 0;
996 if (!PPCEmitLoad(VT, ResultReg, Addr, RC, !IsSigned))
1002 // Attempt to fast-select a floating-point-to-integer conversion.
1003 bool PPCFastISel::SelectFPToI(const Instruction *I, bool IsSigned) {
1005 Type *DstTy = I->getType();
1006 if (!isTypeLegal(DstTy, DstVT))
1009 if (DstVT != MVT::i32 && DstVT != MVT::i64)
1012 Value *Src = I->getOperand(0);
1013 Type *SrcTy = Src->getType();
1014 if (!isTypeLegal(SrcTy, SrcVT))
1017 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
1020 unsigned SrcReg = getRegForValue(Src);
1024 // Convert f32 to f64 if necessary. This is just a meaningless copy
1025 // to get the register class right. COPY_TO_REGCLASS is needed since
1026 // a COPY from F4RC to F8RC is converted to a F4RC-F4RC copy downstream.
1027 const TargetRegisterClass *InRC = MRI.getRegClass(SrcReg);
1028 if (InRC == &PPC::F4RCRegClass) {
1029 unsigned TmpReg = createResultReg(&PPC::F8RCRegClass);
1030 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1031 TII.get(TargetOpcode::COPY_TO_REGCLASS), TmpReg)
1032 .addReg(SrcReg).addImm(PPC::F8RCRegClassID);
1036 // Determine the opcode for the conversion, which takes place
1037 // entirely within FPRs.
1038 unsigned DestReg = createResultReg(&PPC::F8RCRegClass);
1041 if (DstVT == MVT::i32)
1045 Opc = PPCSubTarget.hasFPCVT() ? PPC::FCTIWUZ : PPC::FCTIDZ;
1047 Opc = IsSigned ? PPC::FCTIDZ : PPC::FCTIDUZ;
1049 // Generate the convert.
1050 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1053 // Now move the integer value from a float register to an integer register.
1054 unsigned IntReg = PPCMoveToIntReg(I, DstVT, DestReg, IsSigned);
1058 UpdateValueMap(I, IntReg);
1062 // Attempt to fast-select a binary integer operation that isn't already
1063 // handled automatically.
1064 bool PPCFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1065 EVT DestVT = TLI.getValueType(I->getType(), true);
1067 // We can get here in the case when we have a binary operation on a non-legal
1068 // type and the target independent selector doesn't know how to handle it.
1069 if (DestVT != MVT::i16 && DestVT != MVT::i8)
1072 // Look at the currently assigned register for this instruction
1073 // to determine the required register class. If there is no register,
1074 // make a conservative choice (don't assign R0).
1075 unsigned AssignedReg = FuncInfo.ValueMap[I];
1076 const TargetRegisterClass *RC =
1077 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1078 &PPC::GPRC_and_GPRC_NOR0RegClass);
1079 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1082 switch (ISDOpcode) {
1083 default: return false;
1085 Opc = IsGPRC ? PPC::ADD4 : PPC::ADD8;
1088 Opc = IsGPRC ? PPC::OR : PPC::OR8;
1091 Opc = IsGPRC ? PPC::SUBF : PPC::SUBF8;
1095 unsigned ResultReg = createResultReg(RC ? RC : &PPC::G8RCRegClass);
1096 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1097 if (SrcReg1 == 0) return false;
1099 // Handle case of small immediate operand.
1100 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(1))) {
1101 const APInt &CIVal = ConstInt->getValue();
1102 int Imm = (int)CIVal.getSExtValue();
1104 if (isInt<16>(Imm)) {
1107 llvm_unreachable("Missing case!");
1110 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1114 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1127 MRI.setRegClass(SrcReg1, &PPC::GPRC_and_GPRC_NOR0RegClass);
1136 MRI.setRegClass(SrcReg1, &PPC::G8RC_and_G8RC_NOX0RegClass);
1143 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1144 .addReg(SrcReg1).addImm(Imm);
1145 UpdateValueMap(I, ResultReg);
1152 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1153 if (SrcReg2 == 0) return false;
1155 // Reverse operands for subtract-from.
1156 if (ISDOpcode == ISD::SUB)
1157 std::swap(SrcReg1, SrcReg2);
1159 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1160 .addReg(SrcReg1).addReg(SrcReg2);
1161 UpdateValueMap(I, ResultReg);
1165 // Handle arguments to a call that we're attempting to fast-select.
1166 // Return false if the arguments are too complex for us at the moment.
1167 bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args,
1168 SmallVectorImpl<unsigned> &ArgRegs,
1169 SmallVectorImpl<MVT> &ArgVTs,
1170 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1171 SmallVectorImpl<unsigned> &RegArgs,
1175 SmallVector<CCValAssign, 16> ArgLocs;
1176 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, ArgLocs, *Context);
1177 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_PPC64_ELF_FIS);
1179 // Bail out if we can't handle any of the arguments.
1180 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1181 CCValAssign &VA = ArgLocs[I];
1182 MVT ArgVT = ArgVTs[VA.getValNo()];
1184 // Skip vector arguments for now, as well as long double and
1185 // uint128_t, and anything that isn't passed in a register.
1186 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64 ||
1187 !VA.isRegLoc() || VA.needsCustom())
1190 // Skip bit-converted arguments for now.
1191 if (VA.getLocInfo() == CCValAssign::BCvt)
1195 // Get a count of how many bytes are to be pushed onto the stack.
1196 NumBytes = CCInfo.getNextStackOffset();
1198 // Issue CALLSEQ_START.
1199 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1200 TII.get(TII.getCallFrameSetupOpcode()))
1203 // Prepare to assign register arguments. Every argument uses up a
1204 // GPR protocol register even if it's passed in a floating-point
1206 unsigned NextGPR = PPC::X3;
1207 unsigned NextFPR = PPC::F1;
1209 // Process arguments.
1210 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1211 CCValAssign &VA = ArgLocs[I];
1212 unsigned Arg = ArgRegs[VA.getValNo()];
1213 MVT ArgVT = ArgVTs[VA.getValNo()];
1215 // Handle argument promotion and bitcasts.
1216 switch (VA.getLocInfo()) {
1218 llvm_unreachable("Unknown loc info!");
1219 case CCValAssign::Full:
1221 case CCValAssign::SExt: {
1222 MVT DestVT = VA.getLocVT();
1223 const TargetRegisterClass *RC =
1224 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1225 unsigned TmpReg = createResultReg(RC);
1226 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/false))
1227 llvm_unreachable("Failed to emit a sext!");
1232 case CCValAssign::AExt:
1233 case CCValAssign::ZExt: {
1234 MVT DestVT = VA.getLocVT();
1235 const TargetRegisterClass *RC =
1236 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1237 unsigned TmpReg = createResultReg(RC);
1238 if (!PPCEmitIntExt(ArgVT, Arg, DestVT, TmpReg, /*IsZExt*/true))
1239 llvm_unreachable("Failed to emit a zext!");
1244 case CCValAssign::BCvt: {
1245 // FIXME: Not yet handled.
1246 llvm_unreachable("Should have bailed before getting here!");
1251 // Copy this argument to the appropriate register.
1253 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) {
1259 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1260 ArgReg).addReg(Arg);
1261 RegArgs.push_back(ArgReg);
1267 // For a call that we've determined we can fast-select, finish the
1268 // call sequence and generate a copy to obtain the return value (if any).
1269 void PPCFastISel::finishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1270 const Instruction *I, CallingConv::ID CC,
1271 unsigned &NumBytes, bool IsVarArg) {
1272 // Issue CallSEQ_END.
1273 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1274 TII.get(TII.getCallFrameDestroyOpcode()))
1275 .addImm(NumBytes).addImm(0);
1277 // Next, generate a copy to obtain the return value.
1278 // FIXME: No multi-register return values yet, though I don't foresee
1279 // any real difficulties there.
1280 if (RetVT != MVT::isVoid) {
1281 SmallVector<CCValAssign, 16> RVLocs;
1282 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1283 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1284 CCValAssign &VA = RVLocs[0];
1285 assert(RVLocs.size() == 1 && "No support for multi-reg return values!");
1286 assert(VA.isRegLoc() && "Can only return in registers!");
1288 MVT DestVT = VA.getValVT();
1289 MVT CopyVT = DestVT;
1291 // Ints smaller than a register still arrive in a full 64-bit
1292 // register, so make sure we recognize this.
1293 if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32)
1296 unsigned SourcePhysReg = VA.getLocReg();
1299 if (RetVT == CopyVT) {
1300 const TargetRegisterClass *CpyRC = TLI.getRegClassFor(CopyVT);
1301 ResultReg = createResultReg(CpyRC);
1303 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1304 TII.get(TargetOpcode::COPY), ResultReg)
1305 .addReg(SourcePhysReg);
1307 // If necessary, round the floating result to single precision.
1308 } else if (CopyVT == MVT::f64) {
1309 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1310 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::FRSP),
1311 ResultReg).addReg(SourcePhysReg);
1313 // If only the low half of a general register is needed, generate
1314 // a GPRC copy instead of a G8RC copy. (EXTRACT_SUBREG can't be
1315 // used along the fast-isel path (not lowered), and downstream logic
1316 // also doesn't like a direct subreg copy on a physical reg.)
1317 } else if (RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32) {
1318 ResultReg = createResultReg(&PPC::GPRCRegClass);
1319 // Convert physical register from G8RC to GPRC.
1320 SourcePhysReg -= PPC::X0 - PPC::R0;
1321 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1322 TII.get(TargetOpcode::COPY), ResultReg)
1323 .addReg(SourcePhysReg);
1326 UsedRegs.push_back(SourcePhysReg);
1327 UpdateValueMap(I, ResultReg);
1331 // Attempt to fast-select a call instruction.
1332 bool PPCFastISel::SelectCall(const Instruction *I) {
1333 const CallInst *CI = cast<CallInst>(I);
1334 const Value *Callee = CI->getCalledValue();
1336 // Can't handle inline asm.
1337 if (isa<InlineAsm>(Callee))
1340 // Allow SelectionDAG isel to handle tail calls.
1341 if (CI->isTailCall())
1344 // Obtain calling convention.
1345 ImmutableCallSite CS(CI);
1346 CallingConv::ID CC = CS.getCallingConv();
1348 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1349 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1350 bool IsVarArg = FTy->isVarArg();
1352 // Not ready for varargs yet.
1356 // Handle simple calls for now, with legal return types and
1357 // those that can be extended.
1358 Type *RetTy = I->getType();
1360 if (RetTy->isVoidTy())
1361 RetVT = MVT::isVoid;
1362 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
1366 // FIXME: No multi-register return values yet.
1367 if (RetVT != MVT::isVoid && RetVT != MVT::i8 && RetVT != MVT::i16 &&
1368 RetVT != MVT::i32 && RetVT != MVT::i64 && RetVT != MVT::f32 &&
1369 RetVT != MVT::f64) {
1370 SmallVector<CCValAssign, 16> RVLocs;
1371 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
1372 CCInfo.AnalyzeCallResult(RetVT, RetCC_PPC64_ELF_FIS);
1373 if (RVLocs.size() > 1)
1377 // Bail early if more than 8 arguments, as we only currently
1378 // handle arguments passed in registers.
1379 unsigned NumArgs = CS.arg_size();
1383 // Set up the argument vectors.
1384 SmallVector<Value*, 8> Args;
1385 SmallVector<unsigned, 8> ArgRegs;
1386 SmallVector<MVT, 8> ArgVTs;
1387 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1389 Args.reserve(NumArgs);
1390 ArgRegs.reserve(NumArgs);
1391 ArgVTs.reserve(NumArgs);
1392 ArgFlags.reserve(NumArgs);
1394 for (ImmutableCallSite::arg_iterator II = CS.arg_begin(), IE = CS.arg_end();
1396 // FIXME: ARM does something for intrinsic calls here, check into that.
1398 unsigned AttrIdx = II - CS.arg_begin() + 1;
1400 // Only handle easy calls for now. It would be reasonably easy
1401 // to handle <= 8-byte structures passed ByVal in registers, but we
1402 // have to ensure they are right-justified in the register.
1403 if (CS.paramHasAttr(AttrIdx, Attribute::InReg) ||
1404 CS.paramHasAttr(AttrIdx, Attribute::StructRet) ||
1405 CS.paramHasAttr(AttrIdx, Attribute::Nest) ||
1406 CS.paramHasAttr(AttrIdx, Attribute::ByVal))
1409 ISD::ArgFlagsTy Flags;
1410 if (CS.paramHasAttr(AttrIdx, Attribute::SExt))
1412 if (CS.paramHasAttr(AttrIdx, Attribute::ZExt))
1415 Type *ArgTy = (*II)->getType();
1417 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8)
1420 if (ArgVT.isVector())
1423 unsigned Arg = getRegForValue(*II);
1427 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1428 Flags.setOrigAlign(OriginalAlignment);
1430 Args.push_back(*II);
1431 ArgRegs.push_back(Arg);
1432 ArgVTs.push_back(ArgVT);
1433 ArgFlags.push_back(Flags);
1436 // Process the arguments.
1437 SmallVector<unsigned, 8> RegArgs;
1440 if (!processCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
1441 RegArgs, CC, NumBytes, IsVarArg))
1444 // FIXME: No handling for function pointers yet. This requires
1445 // implementing the function descriptor (OPD) setup.
1446 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1450 // Build direct call with NOP for TOC restore.
1451 // FIXME: We can and should optimize away the NOP for local calls.
1452 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1453 TII.get(PPC::BL8_NOP));
1455 MIB.addGlobalAddress(GV);
1457 // Add implicit physical register uses to the call.
1458 for (unsigned II = 0, IE = RegArgs.size(); II != IE; ++II)
1459 MIB.addReg(RegArgs[II], RegState::Implicit);
1461 // Add a register mask with the call-preserved registers. Proper
1462 // defs for return values will be added by setPhysRegsDeadExcept().
1463 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1465 // Finish off the call including any return values.
1466 SmallVector<unsigned, 4> UsedRegs;
1467 finishCall(RetVT, UsedRegs, I, CC, NumBytes, IsVarArg);
1469 // Set all unused physregs defs as dead.
1470 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1475 // Attempt to fast-select a return instruction.
1476 bool PPCFastISel::SelectRet(const Instruction *I) {
1478 if (!FuncInfo.CanLowerReturn)
1481 const ReturnInst *Ret = cast<ReturnInst>(I);
1482 const Function &F = *I->getParent()->getParent();
1484 // Build a list of return value registers.
1485 SmallVector<unsigned, 4> RetRegs;
1486 CallingConv::ID CC = F.getCallingConv();
1488 if (Ret->getNumOperands() > 0) {
1489 SmallVector<ISD::OutputArg, 4> Outs;
1490 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1492 // Analyze operands of the call, assigning locations to each operand.
1493 SmallVector<CCValAssign, 16> ValLocs;
1494 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, *Context);
1495 CCInfo.AnalyzeReturn(Outs, RetCC_PPC64_ELF_FIS);
1496 const Value *RV = Ret->getOperand(0);
1498 // FIXME: Only one output register for now.
1499 if (ValLocs.size() > 1)
1502 // Special case for returning a constant integer of any size.
1503 // Materialize the constant as an i64 and copy it to the return
1504 // register. This avoids an unnecessary extend or truncate.
1505 if (isa<ConstantInt>(*RV)) {
1506 const Constant *C = cast<Constant>(RV);
1507 unsigned SrcReg = PPCMaterializeInt(C, MVT::i64);
1508 unsigned RetReg = ValLocs[0].getLocReg();
1509 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1510 RetReg).addReg(SrcReg);
1511 RetRegs.push_back(RetReg);
1514 unsigned Reg = getRegForValue(RV);
1519 // Copy the result values into the output registers.
1520 for (unsigned i = 0; i < ValLocs.size(); ++i) {
1522 CCValAssign &VA = ValLocs[i];
1523 assert(VA.isRegLoc() && "Can only return in registers!");
1524 RetRegs.push_back(VA.getLocReg());
1525 unsigned SrcReg = Reg + VA.getValNo();
1527 EVT RVEVT = TLI.getValueType(RV->getType());
1528 if (!RVEVT.isSimple())
1530 MVT RVVT = RVEVT.getSimpleVT();
1531 MVT DestVT = VA.getLocVT();
1533 if (RVVT != DestVT && RVVT != MVT::i8 &&
1534 RVVT != MVT::i16 && RVVT != MVT::i32)
1537 if (RVVT != DestVT) {
1538 switch (VA.getLocInfo()) {
1540 llvm_unreachable("Unknown loc info!");
1541 case CCValAssign::Full:
1542 llvm_unreachable("Full value assign but types don't match?");
1543 case CCValAssign::AExt:
1544 case CCValAssign::ZExt: {
1545 const TargetRegisterClass *RC =
1546 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1547 unsigned TmpReg = createResultReg(RC);
1548 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, true))
1553 case CCValAssign::SExt: {
1554 const TargetRegisterClass *RC =
1555 (DestVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
1556 unsigned TmpReg = createResultReg(RC);
1557 if (!PPCEmitIntExt(RVVT, SrcReg, DestVT, TmpReg, false))
1565 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1566 TII.get(TargetOpcode::COPY), RetRegs[i])
1572 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1575 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1576 MIB.addReg(RetRegs[i], RegState::Implicit);
1581 // Attempt to emit an integer extend of SrcReg into DestReg. Both
1582 // signed and zero extensions are supported. Return false if we
1584 bool PPCFastISel::PPCEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1585 unsigned DestReg, bool IsZExt) {
1586 if (DestVT != MVT::i32 && DestVT != MVT::i64)
1588 if (SrcVT != MVT::i8 && SrcVT != MVT::i16 && SrcVT != MVT::i32)
1591 // Signed extensions use EXTSB, EXTSH, EXTSW.
1594 if (SrcVT == MVT::i8)
1595 Opc = (DestVT == MVT::i32) ? PPC::EXTSB : PPC::EXTSB8_32_64;
1596 else if (SrcVT == MVT::i16)
1597 Opc = (DestVT == MVT::i32) ? PPC::EXTSH : PPC::EXTSH8_32_64;
1599 assert(DestVT == MVT::i64 && "Signed extend from i32 to i32??");
1600 Opc = PPC::EXTSW_32_64;
1602 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1605 // Unsigned 32-bit extensions use RLWINM.
1606 } else if (DestVT == MVT::i32) {
1608 if (SrcVT == MVT::i8)
1611 assert(SrcVT == MVT::i16 && "Unsigned extend from i32 to i32??");
1614 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLWINM),
1616 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB).addImm(/*ME=*/31);
1618 // Unsigned 64-bit extensions use RLDICL (with a 32-bit source).
1621 if (SrcVT == MVT::i8)
1623 else if (SrcVT == MVT::i16)
1627 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1628 TII.get(PPC::RLDICL_32_64), DestReg)
1629 .addReg(SrcReg).addImm(/*SH=*/0).addImm(MB);
1635 // Attempt to fast-select an indirect branch instruction.
1636 bool PPCFastISel::SelectIndirectBr(const Instruction *I) {
1637 unsigned AddrReg = getRegForValue(I->getOperand(0));
1641 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::MTCTR8))
1643 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::BCTR8));
1645 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1646 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1647 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1652 // Attempt to fast-select a compare instruction.
1653 bool PPCFastISel::SelectCmp(const Instruction *I) {
1654 const CmpInst *CI = cast<CmpInst>(I);
1655 Optional<PPC::Predicate> OptPPCPred = getComparePred(CI->getPredicate());
1659 unsigned CondReg = createResultReg(&PPC::CRRCRegClass);
1661 if (!PPCEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned(),
1665 UpdateValueMap(I, CondReg);
1669 // Attempt to fast-select an integer extend instruction.
1670 bool PPCFastISel::SelectIntExt(const Instruction *I) {
1671 Type *DestTy = I->getType();
1672 Value *Src = I->getOperand(0);
1673 Type *SrcTy = Src->getType();
1675 bool IsZExt = isa<ZExtInst>(I);
1676 unsigned SrcReg = getRegForValue(Src);
1677 if (!SrcReg) return false;
1679 EVT SrcEVT, DestEVT;
1680 SrcEVT = TLI.getValueType(SrcTy, true);
1681 DestEVT = TLI.getValueType(DestTy, true);
1682 if (!SrcEVT.isSimple())
1684 if (!DestEVT.isSimple())
1687 MVT SrcVT = SrcEVT.getSimpleVT();
1688 MVT DestVT = DestEVT.getSimpleVT();
1690 // If we know the register class needed for the result of this
1691 // instruction, use it. Otherwise pick the register class of the
1692 // correct size that does not contain X0/R0, since we don't know
1693 // whether downstream uses permit that assignment.
1694 unsigned AssignedReg = FuncInfo.ValueMap[I];
1695 const TargetRegisterClass *RC =
1696 (AssignedReg ? MRI.getRegClass(AssignedReg) :
1697 (DestVT == MVT::i64 ? &PPC::G8RC_and_G8RC_NOX0RegClass :
1698 &PPC::GPRC_and_GPRC_NOR0RegClass));
1699 unsigned ResultReg = createResultReg(RC);
1701 if (!PPCEmitIntExt(SrcVT, SrcReg, DestVT, ResultReg, IsZExt))
1704 UpdateValueMap(I, ResultReg);
1708 // Attempt to fast-select an instruction that wasn't handled by
1709 // the table-generated machinery.
1710 bool PPCFastISel::TargetSelectInstruction(const Instruction *I) {
1712 switch (I->getOpcode()) {
1713 case Instruction::Load:
1714 return SelectLoad(I);
1715 case Instruction::Store:
1716 return SelectStore(I);
1717 case Instruction::Br:
1718 return SelectBranch(I);
1719 case Instruction::IndirectBr:
1720 return SelectIndirectBr(I);
1721 case Instruction::FPExt:
1722 return SelectFPExt(I);
1723 case Instruction::FPTrunc:
1724 return SelectFPTrunc(I);
1725 case Instruction::SIToFP:
1726 return SelectIToFP(I, /*IsSigned*/ true);
1727 case Instruction::UIToFP:
1728 return SelectIToFP(I, /*IsSigned*/ false);
1729 case Instruction::FPToSI:
1730 return SelectFPToI(I, /*IsSigned*/ true);
1731 case Instruction::FPToUI:
1732 return SelectFPToI(I, /*IsSigned*/ false);
1733 case Instruction::Add:
1734 return SelectBinaryIntOp(I, ISD::ADD);
1735 case Instruction::Or:
1736 return SelectBinaryIntOp(I, ISD::OR);
1737 case Instruction::Sub:
1738 return SelectBinaryIntOp(I, ISD::SUB);
1739 case Instruction::Call:
1740 if (dyn_cast<IntrinsicInst>(I))
1742 return SelectCall(I);
1743 case Instruction::Ret:
1744 return SelectRet(I);
1745 case Instruction::ZExt:
1746 case Instruction::SExt:
1747 return SelectIntExt(I);
1748 // Here add other flavors of Instruction::XXX that automated
1749 // cases don't catch. For example, switches are terminators
1750 // that aren't yet handled.
1757 // Materialize a floating-point constant into a register, and return
1758 // the register number (or zero if we failed to handle it).
1759 unsigned PPCFastISel::PPCMaterializeFP(const ConstantFP *CFP, MVT VT) {
1760 // No plans to handle long double here.
1761 if (VT != MVT::f32 && VT != MVT::f64)
1764 // All FP constants are loaded from the constant pool.
1765 unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
1766 assert(Align > 0 && "Unexpectedly missing alignment information!");
1767 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
1768 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
1769 CodeModel::Model CModel = TM.getCodeModel();
1771 MachineMemOperand *MMO =
1772 FuncInfo.MF->getMachineMemOperand(
1773 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
1774 (VT == MVT::f32) ? 4 : 8, Align);
1776 unsigned Opc = (VT == MVT::f32) ? PPC::LFS : PPC::LFD;
1777 unsigned TmpReg = createResultReg(&PPC::G8RC_and_G8RC_NOX0RegClass);
1779 // For small code model, generate a LF[SD](0, LDtocCPT(Idx, X2)).
1780 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault) {
1781 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocCPT),
1783 .addConstantPoolIndex(Idx).addReg(PPC::X2);
1784 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1785 .addImm(0).addReg(TmpReg).addMemOperand(MMO);
1787 // Otherwise we generate LF[SD](Idx[lo], ADDIStocHA(X2, Idx)).
1788 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1789 TmpReg).addReg(PPC::X2).addConstantPoolIndex(Idx);
1790 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
1791 .addConstantPoolIndex(Idx, 0, PPCII::MO_TOC_LO)
1793 .addMemOperand(MMO);
1799 // Materialize the address of a global value into a register, and return
1800 // the register number (or zero if we failed to handle it).
1801 unsigned PPCFastISel::PPCMaterializeGV(const GlobalValue *GV, MVT VT) {
1802 assert(VT == MVT::i64 && "Non-address!");
1803 const TargetRegisterClass *RC = &PPC::G8RC_and_G8RC_NOX0RegClass;
1804 unsigned DestReg = createResultReg(RC);
1806 // Global values may be plain old object addresses, TLS object
1807 // addresses, constant pool entries, or jump tables. How we generate
1808 // code for these may depend on small, medium, or large code model.
1809 CodeModel::Model CModel = TM.getCodeModel();
1811 // FIXME: Jump tables are not yet required because fast-isel doesn't
1812 // handle switches; if that changes, we need them as well. For now,
1813 // what follows assumes everything's a generic (or TLS) global address.
1814 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1816 // If GV is an alias, use the aliasee for determining thread-locality.
1817 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1818 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1821 // FIXME: We don't yet handle the complexity of TLS.
1822 bool IsTLS = GVar && GVar->isThreadLocal();
1826 // For small code model, generate a simple TOC load.
1827 if (CModel == CodeModel::Small || CModel == CodeModel::JITDefault)
1828 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtoc), DestReg)
1829 .addGlobalAddress(GV).addReg(PPC::X2);
1831 // If the address is an externally defined symbol, a symbol with
1832 // common or externally available linkage, a function address, or a
1833 // jump table address (not yet needed), or if we are generating code
1834 // for large code model, we generate:
1835 // LDtocL(GV, ADDIStocHA(%X2, GV))
1836 // Otherwise we generate:
1837 // ADDItocL(ADDIStocHA(%X2, GV), GV)
1838 // Either way, start with the ADDIStocHA:
1839 unsigned HighPartReg = createResultReg(RC);
1840 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDIStocHA),
1841 HighPartReg).addReg(PPC::X2).addGlobalAddress(GV);
1843 // !GVar implies a function address. An external variable is one
1844 // without an initializer.
1845 // If/when switches are implemented, jump tables should be handled
1846 // on the "if" path here.
1847 if (CModel == CodeModel::Large || !GVar || !GVar->hasInitializer() ||
1848 GVar->hasCommonLinkage() || GVar->hasAvailableExternallyLinkage())
1849 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::LDtocL),
1850 DestReg).addGlobalAddress(GV).addReg(HighPartReg);
1852 // Otherwise generate the ADDItocL.
1853 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ADDItocL),
1854 DestReg).addReg(HighPartReg).addGlobalAddress(GV);
1860 // Materialize a 32-bit integer constant into a register, and return
1861 // the register number (or zero if we failed to handle it).
1862 unsigned PPCFastISel::PPCMaterialize32BitInt(int64_t Imm,
1863 const TargetRegisterClass *RC) {
1864 unsigned Lo = Imm & 0xFFFF;
1865 unsigned Hi = (Imm >> 16) & 0xFFFF;
1867 unsigned ResultReg = createResultReg(RC);
1868 bool IsGPRC = RC->hasSuperClassEq(&PPC::GPRCRegClass);
1871 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1872 TII.get(IsGPRC ? PPC::LI : PPC::LI8), ResultReg)
1875 // Both Lo and Hi have nonzero bits.
1876 unsigned TmpReg = createResultReg(RC);
1877 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1878 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), TmpReg)
1880 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1881 TII.get(IsGPRC ? PPC::ORI : PPC::ORI8), ResultReg)
1882 .addReg(TmpReg).addImm(Lo);
1885 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1886 TII.get(IsGPRC ? PPC::LIS : PPC::LIS8), ResultReg)
1892 // Materialize a 64-bit integer constant into a register, and return
1893 // the register number (or zero if we failed to handle it).
1894 unsigned PPCFastISel::PPCMaterialize64BitInt(int64_t Imm,
1895 const TargetRegisterClass *RC) {
1896 unsigned Remainder = 0;
1899 // If the value doesn't fit in 32 bits, see if we can shift it
1900 // so that it fits in 32 bits.
1901 if (!isInt<32>(Imm)) {
1902 Shift = countTrailingZeros<uint64_t>(Imm);
1903 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
1905 if (isInt<32>(ImmSh))
1914 // Handle the high-order 32 bits (if shifted) or the whole 32 bits
1915 // (if not shifted).
1916 unsigned TmpReg1 = PPCMaterialize32BitInt(Imm, RC);
1920 // If upper 32 bits were not zero, we've built them and need to shift
1924 TmpReg2 = createResultReg(RC);
1925 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::RLDICR),
1926 TmpReg2).addReg(TmpReg1).addImm(Shift).addImm(63 - Shift);
1930 unsigned TmpReg3, Hi, Lo;
1931 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1932 TmpReg3 = createResultReg(RC);
1933 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORIS8),
1934 TmpReg3).addReg(TmpReg2).addImm(Hi);
1938 if ((Lo = Remainder & 0xFFFF)) {
1939 unsigned ResultReg = createResultReg(RC);
1940 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(PPC::ORI8),
1941 ResultReg).addReg(TmpReg3).addImm(Lo);
1949 // Materialize an integer constant into a register, and return
1950 // the register number (or zero if we failed to handle it).
1951 unsigned PPCFastISel::PPCMaterializeInt(const Constant *C, MVT VT) {
1953 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
1954 VT != MVT::i8 && VT != MVT::i1)
1957 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
1958 &PPC::GPRCRegClass);
1960 // If the constant is in range, use a load-immediate.
1961 const ConstantInt *CI = cast<ConstantInt>(C);
1962 if (isInt<16>(CI->getSExtValue())) {
1963 unsigned Opc = (VT == MVT::i64) ? PPC::LI8 : PPC::LI;
1964 unsigned ImmReg = createResultReg(RC);
1965 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ImmReg)
1966 .addImm(CI->getSExtValue());
1970 // Construct the constant piecewise.
1971 int64_t Imm = CI->getZExtValue();
1974 return PPCMaterialize64BitInt(Imm, RC);
1975 else if (VT == MVT::i32)
1976 return PPCMaterialize32BitInt(Imm, RC);
1981 // Materialize a constant into a register, and return the register
1982 // number (or zero if we failed to handle it).
1983 unsigned PPCFastISel::TargetMaterializeConstant(const Constant *C) {
1984 EVT CEVT = TLI.getValueType(C->getType(), true);
1986 // Only handle simple types.
1987 if (!CEVT.isSimple()) return 0;
1988 MVT VT = CEVT.getSimpleVT();
1990 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1991 return PPCMaterializeFP(CFP, VT);
1992 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1993 return PPCMaterializeGV(GV, VT);
1994 else if (isa<ConstantInt>(C))
1995 return PPCMaterializeInt(C, VT);
1996 // TBD: Global values.
2001 // Materialize the address created by an alloca into a register, and
2002 // return the register number (or zero if we failed to handle it). TBD.
2003 unsigned PPCFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
2007 // Fold loads into extends when possible.
2008 // FIXME: We can have multiple redundant extend/trunc instructions
2009 // following a load. The folding only picks up one. Extend this
2010 // to check subsequent instructions for the same pattern and remove
2011 // them. Thus ResultReg should be the def reg for the last redundant
2012 // instruction in a chain, and all intervening instructions can be
2013 // removed from parent. Change test/CodeGen/PowerPC/fast-isel-fold.ll
2014 // to add ELF64-NOT: rldicl to the appropriate tests when this works.
2015 bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2016 const LoadInst *LI) {
2017 // Verify we have a legal type before going any further.
2019 if (!isLoadTypeLegal(LI->getType(), VT))
2022 // Combine load followed by zero- or sign-extend.
2023 bool IsZExt = false;
2024 switch(MI->getOpcode()) {
2029 case PPC::RLDICL_32_64: {
2031 unsigned MB = MI->getOperand(3).getImm();
2032 if ((VT == MVT::i8 && MB <= 56) ||
2033 (VT == MVT::i16 && MB <= 48) ||
2034 (VT == MVT::i32 && MB <= 32))
2040 case PPC::RLWINM8: {
2042 unsigned MB = MI->getOperand(3).getImm();
2043 if ((VT == MVT::i8 && MB <= 24) ||
2044 (VT == MVT::i16 && MB <= 16))
2051 case PPC::EXTSB8_32_64:
2052 /* There is no sign-extending load-byte instruction. */
2057 case PPC::EXTSH8_32_64: {
2058 if (VT != MVT::i16 && VT != MVT::i8)
2064 case PPC::EXTSW_32_64: {
2065 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8)
2071 // See if we can handle this address.
2073 if (!PPCComputeAddress(LI->getOperand(0), Addr))
2076 unsigned ResultReg = MI->getOperand(0).getReg();
2078 if (!PPCEmitLoad(VT, ResultReg, Addr, 0, IsZExt))
2081 MI->eraseFromParent();
2085 // Attempt to lower call arguments in a faster way than done by
2086 // the selection DAG code.
2087 bool PPCFastISel::FastLowerArguments() {
2088 // Defer to normal argument lowering for now. It's reasonably
2089 // efficient. Consider doing something like ARM to handle the
2090 // case where all args fit in registers, no varargs, no float
2095 // Handle materializing integer constants into a register. This is not
2096 // automatically generated for PowerPC, so must be explicitly created here.
2097 unsigned PPCFastISel::FastEmit_i(MVT Ty, MVT VT, unsigned Opc, uint64_t Imm) {
2099 if (Opc != ISD::Constant)
2102 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16 &&
2103 VT != MVT::i8 && VT != MVT::i1)
2106 const TargetRegisterClass *RC = ((VT == MVT::i64) ? &PPC::G8RCRegClass :
2107 &PPC::GPRCRegClass);
2109 return PPCMaterialize64BitInt(Imm, RC);
2111 return PPCMaterialize32BitInt(Imm, RC);
2114 // Override for ADDI and ADDI8 to set the correct register class
2115 // on RHS operand 0. The automatic infrastructure naively assumes
2116 // GPRC for i32 and G8RC for i64; the concept of "no R0" is lost
2117 // for these cases. At the moment, none of the other automatically
2118 // generated RI instructions require special treatment. However, once
2119 // SelectSelect is implemented, "isel" requires similar handling.
2121 // Also be conservative about the output register class. Avoid
2122 // assigning R0 or X0 to the output register for GPRC and G8RC
2123 // register classes, as any such result could be used in ADDI, etc.,
2124 // where those regs have another meaning.
2125 unsigned PPCFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
2126 const TargetRegisterClass *RC,
2127 unsigned Op0, bool Op0IsKill,
2129 if (MachineInstOpcode == PPC::ADDI)
2130 MRI.setRegClass(Op0, &PPC::GPRC_and_GPRC_NOR0RegClass);
2131 else if (MachineInstOpcode == PPC::ADDI8)
2132 MRI.setRegClass(Op0, &PPC::G8RC_and_G8RC_NOX0RegClass);
2134 const TargetRegisterClass *UseRC =
2135 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2136 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2138 return FastISel::FastEmitInst_ri(MachineInstOpcode, UseRC,
2139 Op0, Op0IsKill, Imm);
2142 // Override for instructions with one register operand to avoid use of
2143 // R0/X0. The automatic infrastructure isn't aware of the context so
2144 // we must be conservative.
2145 unsigned PPCFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
2146 const TargetRegisterClass* RC,
2147 unsigned Op0, bool Op0IsKill) {
2148 const TargetRegisterClass *UseRC =
2149 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2150 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2152 return FastISel::FastEmitInst_r(MachineInstOpcode, UseRC, Op0, Op0IsKill);
2155 // Override for instructions with two register operands to avoid use
2156 // of R0/X0. The automatic infrastructure isn't aware of the context
2157 // so we must be conservative.
2158 unsigned PPCFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
2159 const TargetRegisterClass* RC,
2160 unsigned Op0, bool Op0IsKill,
2161 unsigned Op1, bool Op1IsKill) {
2162 const TargetRegisterClass *UseRC =
2163 (RC == &PPC::GPRCRegClass ? &PPC::GPRC_and_GPRC_NOR0RegClass :
2164 (RC == &PPC::G8RCRegClass ? &PPC::G8RC_and_G8RC_NOX0RegClass : RC));
2166 return FastISel::FastEmitInst_rr(MachineInstOpcode, UseRC, Op0, Op0IsKill,
2171 // Create the fast instruction selector for PowerPC64 ELF.
2172 FastISel *PPC::createFastISel(FunctionLoweringInfo &FuncInfo,
2173 const TargetLibraryInfo *LibInfo) {
2174 const TargetMachine &TM = FuncInfo.MF->getTarget();
2176 // Only available on 64-bit ELF for now.
2177 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
2178 if (Subtarget->isPPC64() && Subtarget->isSVR4ABI())
2179 return new PPCFastISel(FuncInfo, LibInfo);