1 //===-- ARMFastISel.cpp - ARM 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 ARM-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // ARMGenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMISelLowering.h"
21 #include "ARMMachineFunctionInfo.h"
22 #include "ARMSubtarget.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/GetElementPtrTypeIterator.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Operator.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
52 // All possible address modes, plus some.
53 typedef struct Address {
66 // Innocuous defaults for our address.
68 : BaseType(RegBase), Offset(0) {
73 class ARMFastISel final : public FastISel {
75 /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
76 /// make the right decision when generating code for different targets.
77 const ARMSubtarget *Subtarget;
79 const TargetMachine &TM;
80 const TargetInstrInfo &TII;
81 const TargetLowering &TLI;
84 // Convenience variables to avoid some queries.
89 explicit ARMFastISel(FunctionLoweringInfo &funcInfo,
90 const TargetLibraryInfo *libInfo)
91 : FastISel(funcInfo, libInfo),
93 &static_cast<const ARMSubtarget &>(funcInfo.MF->getSubtarget())),
94 M(const_cast<Module &>(*funcInfo.Fn->getParent())),
95 TM(funcInfo.MF->getTarget()), TII(*Subtarget->getInstrInfo()),
96 TLI(*Subtarget->getTargetLowering()) {
97 AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
98 isThumb2 = AFI->isThumbFunction();
99 Context = &funcInfo.Fn->getContext();
102 // Code from FastISel.cpp.
104 unsigned fastEmitInst_r(unsigned MachineInstOpcode,
105 const TargetRegisterClass *RC,
106 unsigned Op0, bool Op0IsKill);
107 unsigned fastEmitInst_rr(unsigned MachineInstOpcode,
108 const TargetRegisterClass *RC,
109 unsigned Op0, bool Op0IsKill,
110 unsigned Op1, bool Op1IsKill);
111 unsigned fastEmitInst_ri(unsigned MachineInstOpcode,
112 const TargetRegisterClass *RC,
113 unsigned Op0, bool Op0IsKill,
115 unsigned fastEmitInst_i(unsigned MachineInstOpcode,
116 const TargetRegisterClass *RC,
119 // Backend specific FastISel code.
121 bool fastSelectInstruction(const Instruction *I) override;
122 unsigned fastMaterializeConstant(const Constant *C) override;
123 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
124 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
125 const LoadInst *LI) override;
126 bool fastLowerArguments() override;
128 #include "ARMGenFastISel.inc"
130 // Instruction selection routines.
132 bool SelectLoad(const Instruction *I);
133 bool SelectStore(const Instruction *I);
134 bool SelectBranch(const Instruction *I);
135 bool SelectIndirectBr(const Instruction *I);
136 bool SelectCmp(const Instruction *I);
137 bool SelectFPExt(const Instruction *I);
138 bool SelectFPTrunc(const Instruction *I);
139 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
140 bool SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode);
141 bool SelectIToFP(const Instruction *I, bool isSigned);
142 bool SelectFPToI(const Instruction *I, bool isSigned);
143 bool SelectDiv(const Instruction *I, bool isSigned);
144 bool SelectRem(const Instruction *I, bool isSigned);
145 bool SelectCall(const Instruction *I, const char *IntrMemName);
146 bool SelectIntrinsicCall(const IntrinsicInst &I);
147 bool SelectSelect(const Instruction *I);
148 bool SelectRet(const Instruction *I);
149 bool SelectTrunc(const Instruction *I);
150 bool SelectIntExt(const Instruction *I);
151 bool SelectShift(const Instruction *I, ARM_AM::ShiftOpc ShiftTy);
155 bool isPositionIndependent() const;
156 bool isTypeLegal(Type *Ty, MVT &VT);
157 bool isLoadTypeLegal(Type *Ty, MVT &VT);
158 bool ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
160 bool ARMEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
161 unsigned Alignment = 0, bool isZExt = true,
162 bool allocReg = true);
163 bool ARMEmitStore(MVT VT, unsigned SrcReg, Address &Addr,
164 unsigned Alignment = 0);
165 bool ARMComputeAddress(const Value *Obj, Address &Addr);
166 void ARMSimplifyAddress(Address &Addr, MVT VT, bool useAM3);
167 bool ARMIsMemCpySmall(uint64_t Len);
168 bool ARMTryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
170 unsigned ARMEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
171 unsigned ARMMaterializeFP(const ConstantFP *CFP, MVT VT);
172 unsigned ARMMaterializeInt(const Constant *C, MVT VT);
173 unsigned ARMMaterializeGV(const GlobalValue *GV, MVT VT);
174 unsigned ARMMoveToFPReg(MVT VT, unsigned SrcReg);
175 unsigned ARMMoveToIntReg(MVT VT, unsigned SrcReg);
176 unsigned ARMSelectCallOp(bool UseReg);
177 unsigned ARMLowerPICELF(const GlobalValue *GV, unsigned Align, MVT VT);
179 const TargetLowering *getTargetLowering() { return &TLI; }
181 // Call handling routines.
183 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC,
186 bool ProcessCallArgs(SmallVectorImpl<Value*> &Args,
187 SmallVectorImpl<unsigned> &ArgRegs,
188 SmallVectorImpl<MVT> &ArgVTs,
189 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
190 SmallVectorImpl<unsigned> &RegArgs,
194 unsigned getLibcallReg(const Twine &Name);
195 bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
196 const Instruction *I, CallingConv::ID CC,
197 unsigned &NumBytes, bool isVarArg);
198 bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
200 // OptionalDef handling routines.
202 bool isARMNEONPred(const MachineInstr *MI);
203 bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
204 const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
205 void AddLoadStoreOperands(MVT VT, Address &Addr,
206 const MachineInstrBuilder &MIB,
207 MachineMemOperand::Flags Flags, bool useAM3);
210 } // end anonymous namespace
212 #include "ARMGenCallingConv.inc"
214 // DefinesOptionalPredicate - This is different from DefinesPredicate in that
215 // we don't care about implicit defs here, just places we'll need to add a
216 // default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
217 bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
218 if (!MI->hasOptionalDef())
221 // Look to see if our OptionalDef is defining CPSR or CCR.
222 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
223 const MachineOperand &MO = MI->getOperand(i);
224 if (!MO.isReg() || !MO.isDef()) continue;
225 if (MO.getReg() == ARM::CPSR)
231 bool ARMFastISel::isARMNEONPred(const MachineInstr *MI) {
232 const MCInstrDesc &MCID = MI->getDesc();
234 // If we're a thumb2 or not NEON function we'll be handled via isPredicable.
235 if ((MCID.TSFlags & ARMII::DomainMask) != ARMII::DomainNEON ||
236 AFI->isThumb2Function())
237 return MI->isPredicable();
239 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i)
240 if (MCID.OpInfo[i].isPredicate())
246 // If the machine is predicable go ahead and add the predicate operands, if
247 // it needs default CC operands add those.
248 // TODO: If we want to support thumb1 then we'll need to deal with optional
249 // CPSR defs that need to be added before the remaining operands. See s_cc_out
250 // for descriptions why.
251 const MachineInstrBuilder &
252 ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
253 MachineInstr *MI = &*MIB;
255 // Do we use a predicate? or...
256 // Are we NEON in ARM mode and have a predicate operand? If so, I know
257 // we're not predicable but add it anyways.
258 if (isARMNEONPred(MI))
261 // Do we optionally set a predicate? Preds is size > 0 iff the predicate
262 // defines CPSR. All other OptionalDefines in ARM are the CCR register.
264 if (DefinesOptionalPredicate(MI, &CPSR)) {
273 unsigned ARMFastISel::fastEmitInst_r(unsigned MachineInstOpcode,
274 const TargetRegisterClass *RC,
275 unsigned Op0, bool Op0IsKill) {
276 unsigned ResultReg = createResultReg(RC);
277 const MCInstrDesc &II = TII.get(MachineInstOpcode);
279 // Make sure the input operand is sufficiently constrained to be legal
280 // for this instruction.
281 Op0 = constrainOperandRegClass(II, Op0, 1);
282 if (II.getNumDefs() >= 1) {
283 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II,
284 ResultReg).addReg(Op0, Op0IsKill * RegState::Kill));
286 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
287 .addReg(Op0, Op0IsKill * RegState::Kill));
288 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
289 TII.get(TargetOpcode::COPY), ResultReg)
290 .addReg(II.ImplicitDefs[0]));
295 unsigned ARMFastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
296 const TargetRegisterClass *RC,
297 unsigned Op0, bool Op0IsKill,
298 unsigned Op1, bool Op1IsKill) {
299 unsigned ResultReg = createResultReg(RC);
300 const MCInstrDesc &II = TII.get(MachineInstOpcode);
302 // Make sure the input operands are sufficiently constrained to be legal
303 // for this instruction.
304 Op0 = constrainOperandRegClass(II, Op0, 1);
305 Op1 = constrainOperandRegClass(II, Op1, 2);
307 if (II.getNumDefs() >= 1) {
309 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
310 .addReg(Op0, Op0IsKill * RegState::Kill)
311 .addReg(Op1, Op1IsKill * RegState::Kill));
313 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
314 .addReg(Op0, Op0IsKill * RegState::Kill)
315 .addReg(Op1, Op1IsKill * RegState::Kill));
316 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
317 TII.get(TargetOpcode::COPY), ResultReg)
318 .addReg(II.ImplicitDefs[0]));
323 unsigned ARMFastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
324 const TargetRegisterClass *RC,
325 unsigned Op0, bool Op0IsKill,
327 unsigned ResultReg = createResultReg(RC);
328 const MCInstrDesc &II = TII.get(MachineInstOpcode);
330 // Make sure the input operand is sufficiently constrained to be legal
331 // for this instruction.
332 Op0 = constrainOperandRegClass(II, Op0, 1);
333 if (II.getNumDefs() >= 1) {
335 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
336 .addReg(Op0, Op0IsKill * RegState::Kill)
339 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
340 .addReg(Op0, Op0IsKill * RegState::Kill)
342 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
343 TII.get(TargetOpcode::COPY), ResultReg)
344 .addReg(II.ImplicitDefs[0]));
349 unsigned ARMFastISel::fastEmitInst_i(unsigned MachineInstOpcode,
350 const TargetRegisterClass *RC,
352 unsigned ResultReg = createResultReg(RC);
353 const MCInstrDesc &II = TII.get(MachineInstOpcode);
355 if (II.getNumDefs() >= 1) {
356 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II,
357 ResultReg).addImm(Imm));
359 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
361 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
362 TII.get(TargetOpcode::COPY), ResultReg)
363 .addReg(II.ImplicitDefs[0]));
368 // TODO: Don't worry about 64-bit now, but when this is fixed remove the
369 // checks from the various callers.
370 unsigned ARMFastISel::ARMMoveToFPReg(MVT VT, unsigned SrcReg) {
371 if (VT == MVT::f64) return 0;
373 unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
374 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
375 TII.get(ARM::VMOVSR), MoveReg)
380 unsigned ARMFastISel::ARMMoveToIntReg(MVT VT, unsigned SrcReg) {
381 if (VT == MVT::i64) return 0;
383 unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
384 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
385 TII.get(ARM::VMOVRS), MoveReg)
390 // For double width floating point we need to materialize two constants
391 // (the high and the low) into integer registers then use a move to get
392 // the combined constant into an FP reg.
393 unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, MVT VT) {
394 const APFloat Val = CFP->getValueAPF();
395 bool is64bit = VT == MVT::f64;
397 // This checks to see if we can use VFP3 instructions to materialize
398 // a constant, otherwise we have to go through the constant pool.
399 if (TLI.isFPImmLegal(Val, VT)) {
403 Imm = ARM_AM::getFP64Imm(Val);
406 Imm = ARM_AM::getFP32Imm(Val);
409 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
410 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
411 TII.get(Opc), DestReg).addImm(Imm));
415 // Require VFP2 for loading fp constants.
416 if (!Subtarget->hasVFP2()) return false;
418 // MachineConstantPool wants an explicit alignment.
419 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
421 // TODO: Figure out if this is correct.
422 Align = DL.getTypeAllocSize(CFP->getType());
424 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
425 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
426 unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
428 // The extra reg is for addrmode5.
430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
431 .addConstantPoolIndex(Idx)
436 unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, MVT VT) {
438 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8 && VT != MVT::i1)
441 // If we can do this in a single instruction without a constant pool entry
443 const ConstantInt *CI = cast<ConstantInt>(C);
444 if (Subtarget->hasV6T2Ops() && isUInt<16>(CI->getZExtValue())) {
445 unsigned Opc = isThumb2 ? ARM::t2MOVi16 : ARM::MOVi16;
446 const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass :
448 unsigned ImmReg = createResultReg(RC);
449 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
450 TII.get(Opc), ImmReg)
451 .addImm(CI->getZExtValue()));
455 // Use MVN to emit negative constants.
456 if (VT == MVT::i32 && Subtarget->hasV6T2Ops() && CI->isNegative()) {
457 unsigned Imm = (unsigned)~(CI->getSExtValue());
458 bool UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
459 (ARM_AM::getSOImmVal(Imm) != -1);
461 unsigned Opc = isThumb2 ? ARM::t2MVNi : ARM::MVNi;
462 const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass :
464 unsigned ImmReg = createResultReg(RC);
465 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
466 TII.get(Opc), ImmReg)
472 unsigned ResultReg = 0;
473 if (Subtarget->useMovt(*FuncInfo.MF))
474 ResultReg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
479 // Load from constant pool. For now 32-bit only.
483 // MachineConstantPool wants an explicit alignment.
484 unsigned Align = DL.getPrefTypeAlignment(C->getType());
486 // TODO: Figure out if this is correct.
487 Align = DL.getTypeAllocSize(C->getType());
489 unsigned Idx = MCP.getConstantPoolIndex(C, Align);
490 ResultReg = createResultReg(TLI.getRegClassFor(VT));
492 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
493 TII.get(ARM::t2LDRpci), ResultReg)
494 .addConstantPoolIndex(Idx));
496 // The extra immediate is for addrmode2.
497 ResultReg = constrainOperandRegClass(TII.get(ARM::LDRcp), ResultReg, 0);
498 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
499 TII.get(ARM::LDRcp), ResultReg)
500 .addConstantPoolIndex(Idx)
506 bool ARMFastISel::isPositionIndependent() const {
507 return TLI.isPositionIndependent();
510 unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, MVT VT) {
511 // For now 32-bit only.
512 if (VT != MVT::i32 || GV->isThreadLocal()) return 0;
514 // ROPI/RWPI not currently supported.
515 if (Subtarget->isROPI() || Subtarget->isRWPI())
518 bool IsIndirect = Subtarget->isGVIndirectSymbol(GV);
519 const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass
521 unsigned DestReg = createResultReg(RC);
523 // FastISel TLS support on non-MachO is broken, punt to SelectionDAG.
524 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
525 bool IsThreadLocal = GVar && GVar->isThreadLocal();
526 if (!Subtarget->isTargetMachO() && IsThreadLocal) return 0;
528 bool IsPositionIndependent = isPositionIndependent();
529 // Use movw+movt when possible, it avoids constant pool entries.
530 // Non-darwin targets only support static movt relocations in FastISel.
531 if (Subtarget->useMovt(*FuncInfo.MF) &&
532 (Subtarget->isTargetMachO() || !IsPositionIndependent)) {
534 unsigned char TF = 0;
535 if (Subtarget->isTargetMachO())
536 TF = ARMII::MO_NONLAZY;
538 if (IsPositionIndependent)
539 Opc = isThumb2 ? ARM::t2MOV_ga_pcrel : ARM::MOV_ga_pcrel;
541 Opc = isThumb2 ? ARM::t2MOVi32imm : ARM::MOVi32imm;
542 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
543 TII.get(Opc), DestReg).addGlobalAddress(GV, 0, TF));
545 // MachineConstantPool wants an explicit alignment.
546 unsigned Align = DL.getPrefTypeAlignment(GV->getType());
548 // TODO: Figure out if this is correct.
549 Align = DL.getTypeAllocSize(GV->getType());
552 if (Subtarget->isTargetELF() && IsPositionIndependent)
553 return ARMLowerPICELF(GV, Align, VT);
556 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
557 unsigned Id = AFI->createPICLabelUId();
558 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(GV, Id,
561 unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
564 MachineInstrBuilder MIB;
566 unsigned Opc = IsPositionIndependent ? ARM::t2LDRpci_pic : ARM::t2LDRpci;
567 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
568 DestReg).addConstantPoolIndex(Idx);
569 if (IsPositionIndependent)
571 AddOptionalDefs(MIB);
573 // The extra immediate is for addrmode2.
574 DestReg = constrainOperandRegClass(TII.get(ARM::LDRcp), DestReg, 0);
575 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
576 TII.get(ARM::LDRcp), DestReg)
577 .addConstantPoolIndex(Idx)
579 AddOptionalDefs(MIB);
581 if (IsPositionIndependent) {
582 unsigned Opc = IsIndirect ? ARM::PICLDR : ARM::PICADD;
583 unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
585 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
586 DbgLoc, TII.get(Opc), NewDestReg)
589 AddOptionalDefs(MIB);
596 MachineInstrBuilder MIB;
597 unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
599 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
600 TII.get(ARM::t2LDRi12), NewDestReg)
604 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
605 TII.get(ARM::LDRi12), NewDestReg)
608 DestReg = NewDestReg;
609 AddOptionalDefs(MIB);
615 unsigned ARMFastISel::fastMaterializeConstant(const Constant *C) {
616 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
618 // Only handle simple types.
619 if (!CEVT.isSimple()) return 0;
620 MVT VT = CEVT.getSimpleVT();
622 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
623 return ARMMaterializeFP(CFP, VT);
624 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
625 return ARMMaterializeGV(GV, VT);
626 else if (isa<ConstantInt>(C))
627 return ARMMaterializeInt(C, VT);
632 // TODO: unsigned ARMFastISel::TargetMaterializeFloatZero(const ConstantFP *CF);
634 unsigned ARMFastISel::fastMaterializeAlloca(const AllocaInst *AI) {
635 // Don't handle dynamic allocas.
636 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
639 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
641 DenseMap<const AllocaInst*, int>::iterator SI =
642 FuncInfo.StaticAllocaMap.find(AI);
644 // This will get lowered later into the correct offsets and registers
645 // via rewriteXFrameIndex.
646 if (SI != FuncInfo.StaticAllocaMap.end()) {
647 unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
648 const TargetRegisterClass* RC = TLI.getRegClassFor(VT);
649 unsigned ResultReg = createResultReg(RC);
650 ResultReg = constrainOperandRegClass(TII.get(Opc), ResultReg, 0);
652 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
653 TII.get(Opc), ResultReg)
654 .addFrameIndex(SI->second)
662 bool ARMFastISel::isTypeLegal(Type *Ty, MVT &VT) {
663 EVT evt = TLI.getValueType(DL, Ty, true);
665 // Only handle simple types.
666 if (evt == MVT::Other || !evt.isSimple()) return false;
667 VT = evt.getSimpleVT();
669 // Handle all legal types, i.e. a register that will directly hold this
671 return TLI.isTypeLegal(VT);
674 bool ARMFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
675 if (isTypeLegal(Ty, VT)) return true;
677 // If this is a type than can be sign or zero-extended to a basic operation
678 // go ahead and accept it now.
679 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
685 // Computes the address to get to an object.
686 bool ARMFastISel::ARMComputeAddress(const Value *Obj, Address &Addr) {
687 // Some boilerplate from the X86 FastISel.
688 const User *U = nullptr;
689 unsigned Opcode = Instruction::UserOp1;
690 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
691 // Don't walk into other basic blocks unless the object is an alloca from
692 // another block, otherwise it may not have a virtual register assigned.
693 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
694 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
695 Opcode = I->getOpcode();
698 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
699 Opcode = C->getOpcode();
703 if (PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
704 if (Ty->getAddressSpace() > 255)
705 // Fast instruction selection doesn't support the special
712 case Instruction::BitCast:
713 // Look through bitcasts.
714 return ARMComputeAddress(U->getOperand(0), Addr);
715 case Instruction::IntToPtr:
716 // Look past no-op inttoptrs.
717 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
718 TLI.getPointerTy(DL))
719 return ARMComputeAddress(U->getOperand(0), Addr);
721 case Instruction::PtrToInt:
722 // Look past no-op ptrtoints.
723 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
724 return ARMComputeAddress(U->getOperand(0), Addr);
726 case Instruction::GetElementPtr: {
727 Address SavedAddr = Addr;
728 int TmpOffset = Addr.Offset;
730 // Iterate through the GEP folding the constants into offsets where
732 gep_type_iterator GTI = gep_type_begin(U);
733 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
734 i != e; ++i, ++GTI) {
735 const Value *Op = *i;
736 if (StructType *STy = GTI.getStructTypeOrNull()) {
737 const StructLayout *SL = DL.getStructLayout(STy);
738 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
739 TmpOffset += SL->getElementOffset(Idx);
741 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
743 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
744 // Constant-offset addressing.
745 TmpOffset += CI->getSExtValue() * S;
748 if (canFoldAddIntoGEP(U, Op)) {
749 // A compatible add with a constant operand. Fold the constant.
751 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
752 TmpOffset += CI->getSExtValue() * S;
753 // Iterate on the other operand.
754 Op = cast<AddOperator>(Op)->getOperand(0);
758 goto unsupported_gep;
763 // Try to grab the base operand now.
764 Addr.Offset = TmpOffset;
765 if (ARMComputeAddress(U->getOperand(0), Addr)) return true;
767 // We failed, restore everything and try the other options.
773 case Instruction::Alloca: {
774 const AllocaInst *AI = cast<AllocaInst>(Obj);
775 DenseMap<const AllocaInst*, int>::iterator SI =
776 FuncInfo.StaticAllocaMap.find(AI);
777 if (SI != FuncInfo.StaticAllocaMap.end()) {
778 Addr.BaseType = Address::FrameIndexBase;
779 Addr.Base.FI = SI->second;
786 // Try to get this in a register if nothing else has worked.
787 if (Addr.Base.Reg == 0) Addr.Base.Reg = getRegForValue(Obj);
788 return Addr.Base.Reg != 0;
791 void ARMFastISel::ARMSimplifyAddress(Address &Addr, MVT VT, bool useAM3) {
792 bool needsLowering = false;
793 switch (VT.SimpleTy) {
794 default: llvm_unreachable("Unhandled load/store type!");
800 // Integer loads/stores handle 12-bit offsets.
801 needsLowering = ((Addr.Offset & 0xfff) != Addr.Offset);
802 // Handle negative offsets.
803 if (needsLowering && isThumb2)
804 needsLowering = !(Subtarget->hasV6T2Ops() && Addr.Offset < 0 &&
807 // ARM halfword load/stores and signed byte loads use +/-imm8 offsets.
808 needsLowering = (Addr.Offset > 255 || Addr.Offset < -255);
813 // Floating point operands handle 8-bit offsets.
814 needsLowering = ((Addr.Offset & 0xff) != Addr.Offset);
818 // If this is a stack pointer and the offset needs to be simplified then
819 // put the alloca address into a register, set the base type back to
820 // register and continue. This should almost never happen.
821 if (needsLowering && Addr.BaseType == Address::FrameIndexBase) {
822 const TargetRegisterClass *RC = isThumb2 ? &ARM::tGPRRegClass
824 unsigned ResultReg = createResultReg(RC);
825 unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
826 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
827 TII.get(Opc), ResultReg)
828 .addFrameIndex(Addr.Base.FI)
830 Addr.Base.Reg = ResultReg;
831 Addr.BaseType = Address::RegBase;
834 // Since the offset is too large for the load/store instruction
835 // get the reg+offset into a register.
837 Addr.Base.Reg = fastEmit_ri_(MVT::i32, ISD::ADD, Addr.Base.Reg,
838 /*Op0IsKill*/false, Addr.Offset, MVT::i32);
843 void ARMFastISel::AddLoadStoreOperands(MVT VT, Address &Addr,
844 const MachineInstrBuilder &MIB,
845 MachineMemOperand::Flags Flags,
847 // addrmode5 output depends on the selection dag addressing dividing the
848 // offset by 4 that it then later multiplies. Do this here as well.
849 if (VT.SimpleTy == MVT::f32 || VT.SimpleTy == MVT::f64)
852 // Frame base works a bit differently. Handle it separately.
853 if (Addr.BaseType == Address::FrameIndexBase) {
854 int FI = Addr.Base.FI;
855 int Offset = Addr.Offset;
856 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
857 MachinePointerInfo::getFixedStack(*FuncInfo.MF, FI, Offset), Flags,
858 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
859 // Now add the rest of the operands.
860 MIB.addFrameIndex(FI);
862 // ARM halfword load/stores and signed byte loads need an additional
865 int Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
869 MIB.addImm(Addr.Offset);
871 MIB.addMemOperand(MMO);
873 // Now add the rest of the operands.
874 MIB.addReg(Addr.Base.Reg);
876 // ARM halfword load/stores and signed byte loads need an additional
879 int Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
883 MIB.addImm(Addr.Offset);
886 AddOptionalDefs(MIB);
889 bool ARMFastISel::ARMEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
890 unsigned Alignment, bool isZExt, bool allocReg) {
893 bool needVMOV = false;
894 const TargetRegisterClass *RC;
895 switch (VT.SimpleTy) {
896 // This is mostly going to be Neon/vector support.
897 default: return false;
901 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
902 Opc = isZExt ? ARM::t2LDRBi8 : ARM::t2LDRSBi8;
904 Opc = isZExt ? ARM::t2LDRBi12 : ARM::t2LDRSBi12;
913 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
916 if (Alignment && Alignment < 2 && !Subtarget->allowsUnalignedMem())
920 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
921 Opc = isZExt ? ARM::t2LDRHi8 : ARM::t2LDRSHi8;
923 Opc = isZExt ? ARM::t2LDRHi12 : ARM::t2LDRSHi12;
925 Opc = isZExt ? ARM::LDRH : ARM::LDRSH;
928 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
931 if (Alignment && Alignment < 4 && !Subtarget->allowsUnalignedMem())
935 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
942 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
945 if (!Subtarget->hasVFP2()) return false;
946 // Unaligned loads need special handling. Floats require word-alignment.
947 if (Alignment && Alignment < 4) {
950 Opc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
951 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
954 RC = TLI.getRegClassFor(VT);
958 if (!Subtarget->hasVFP2()) return false;
959 // FIXME: Unaligned loads need special handling. Doublewords require
961 if (Alignment && Alignment < 4)
965 RC = TLI.getRegClassFor(VT);
968 // Simplify this down to something we can handle.
969 ARMSimplifyAddress(Addr, VT, useAM3);
971 // Create the base instruction, then add the operands.
973 ResultReg = createResultReg(RC);
974 assert (ResultReg > 255 && "Expected an allocated virtual register.");
975 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
976 TII.get(Opc), ResultReg);
977 AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOLoad, useAM3);
979 // If we had an unaligned load of a float we've converted it to an regular
980 // load. Now we must move from the GRP to the FP register.
982 unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::f32));
983 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
984 TII.get(ARM::VMOVSR), MoveReg)
991 bool ARMFastISel::SelectLoad(const Instruction *I) {
992 // Atomic loads need special handling.
993 if (cast<LoadInst>(I)->isAtomic())
996 const Value *SV = I->getOperand(0);
997 if (TLI.supportSwiftError()) {
998 // Swifterror values can come from either a function parameter with
999 // swifterror attribute or an alloca with swifterror attribute.
1000 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1001 if (Arg->hasSwiftErrorAttr())
1005 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1006 if (Alloca->isSwiftError())
1011 // Verify we have a legal type before going any further.
1013 if (!isLoadTypeLegal(I->getType(), VT))
1016 // See if we can handle this address.
1018 if (!ARMComputeAddress(I->getOperand(0), Addr)) return false;
1021 if (!ARMEmitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
1023 updateValueMap(I, ResultReg);
1027 bool ARMFastISel::ARMEmitStore(MVT VT, unsigned SrcReg, Address &Addr,
1028 unsigned Alignment) {
1030 bool useAM3 = false;
1031 switch (VT.SimpleTy) {
1032 // This is mostly going to be Neon/vector support.
1033 default: return false;
1035 unsigned Res = createResultReg(isThumb2 ? &ARM::tGPRRegClass
1036 : &ARM::GPRRegClass);
1037 unsigned Opc = isThumb2 ? ARM::t2ANDri : ARM::ANDri;
1038 SrcReg = constrainOperandRegClass(TII.get(Opc), SrcReg, 1);
1039 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1041 .addReg(SrcReg).addImm(1));
1047 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1048 StrOpc = ARM::t2STRBi8;
1050 StrOpc = ARM::t2STRBi12;
1052 StrOpc = ARM::STRBi12;
1056 if (Alignment && Alignment < 2 && !Subtarget->allowsUnalignedMem())
1060 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1061 StrOpc = ARM::t2STRHi8;
1063 StrOpc = ARM::t2STRHi12;
1070 if (Alignment && Alignment < 4 && !Subtarget->allowsUnalignedMem())
1074 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1075 StrOpc = ARM::t2STRi8;
1077 StrOpc = ARM::t2STRi12;
1079 StrOpc = ARM::STRi12;
1083 if (!Subtarget->hasVFP2()) return false;
1084 // Unaligned stores need special handling. Floats require word-alignment.
1085 if (Alignment && Alignment < 4) {
1086 unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::i32));
1087 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1088 TII.get(ARM::VMOVRS), MoveReg)
1092 StrOpc = isThumb2 ? ARM::t2STRi12 : ARM::STRi12;
1094 StrOpc = ARM::VSTRS;
1098 if (!Subtarget->hasVFP2()) return false;
1099 // FIXME: Unaligned stores need special handling. Doublewords require
1101 if (Alignment && Alignment < 4)
1104 StrOpc = ARM::VSTRD;
1107 // Simplify this down to something we can handle.
1108 ARMSimplifyAddress(Addr, VT, useAM3);
1110 // Create the base instruction, then add the operands.
1111 SrcReg = constrainOperandRegClass(TII.get(StrOpc), SrcReg, 0);
1112 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1115 AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOStore, useAM3);
1119 bool ARMFastISel::SelectStore(const Instruction *I) {
1120 Value *Op0 = I->getOperand(0);
1121 unsigned SrcReg = 0;
1123 // Atomic stores need special handling.
1124 if (cast<StoreInst>(I)->isAtomic())
1127 const Value *PtrV = I->getOperand(1);
1128 if (TLI.supportSwiftError()) {
1129 // Swifterror values can come from either a function parameter with
1130 // swifterror attribute or an alloca with swifterror attribute.
1131 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1132 if (Arg->hasSwiftErrorAttr())
1136 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1137 if (Alloca->isSwiftError())
1142 // Verify we have a legal type before going any further.
1144 if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
1147 // Get the value to be stored into a register.
1148 SrcReg = getRegForValue(Op0);
1149 if (SrcReg == 0) return false;
1151 // See if we can handle this address.
1153 if (!ARMComputeAddress(I->getOperand(1), Addr))
1156 if (!ARMEmitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
1161 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
1163 // Needs two compares...
1164 case CmpInst::FCMP_ONE:
1165 case CmpInst::FCMP_UEQ:
1167 // AL is our "false" for now. The other two need more compares.
1169 case CmpInst::ICMP_EQ:
1170 case CmpInst::FCMP_OEQ:
1172 case CmpInst::ICMP_SGT:
1173 case CmpInst::FCMP_OGT:
1175 case CmpInst::ICMP_SGE:
1176 case CmpInst::FCMP_OGE:
1178 case CmpInst::ICMP_UGT:
1179 case CmpInst::FCMP_UGT:
1181 case CmpInst::FCMP_OLT:
1183 case CmpInst::ICMP_ULE:
1184 case CmpInst::FCMP_OLE:
1186 case CmpInst::FCMP_ORD:
1188 case CmpInst::FCMP_UNO:
1190 case CmpInst::FCMP_UGE:
1192 case CmpInst::ICMP_SLT:
1193 case CmpInst::FCMP_ULT:
1195 case CmpInst::ICMP_SLE:
1196 case CmpInst::FCMP_ULE:
1198 case CmpInst::FCMP_UNE:
1199 case CmpInst::ICMP_NE:
1201 case CmpInst::ICMP_UGE:
1203 case CmpInst::ICMP_ULT:
1208 bool ARMFastISel::SelectBranch(const Instruction *I) {
1209 const BranchInst *BI = cast<BranchInst>(I);
1210 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1211 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1213 // Simple branch support.
1215 // If we can, avoid recomputing the compare - redoing it could lead to wonky
1217 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1218 if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
1220 // Get the compare predicate.
1221 // Try to take advantage of fallthrough opportunities.
1222 CmpInst::Predicate Predicate = CI->getPredicate();
1223 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1224 std::swap(TBB, FBB);
1225 Predicate = CmpInst::getInversePredicate(Predicate);
1228 ARMCC::CondCodes ARMPred = getComparePred(Predicate);
1230 // We may not handle every CC for now.
1231 if (ARMPred == ARMCC::AL) return false;
1233 // Emit the compare.
1234 if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1237 unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BrOpc))
1239 .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
1240 finishCondBranch(BI->getParent(), TBB, FBB);
1243 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1245 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1246 (isLoadTypeLegal(TI->getOperand(0)->getType(), SourceVT))) {
1247 unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1248 unsigned OpReg = getRegForValue(TI->getOperand(0));
1249 OpReg = constrainOperandRegClass(TII.get(TstOpc), OpReg, 0);
1250 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1252 .addReg(OpReg).addImm(1));
1254 unsigned CCMode = ARMCC::NE;
1255 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1256 std::swap(TBB, FBB);
1260 unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1261 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BrOpc))
1262 .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1264 finishCondBranch(BI->getParent(), TBB, FBB);
1267 } else if (const ConstantInt *CI =
1268 dyn_cast<ConstantInt>(BI->getCondition())) {
1269 uint64_t Imm = CI->getZExtValue();
1270 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1271 fastEmitBranch(Target, DbgLoc);
1275 unsigned CmpReg = getRegForValue(BI->getCondition());
1276 if (CmpReg == 0) return false;
1278 // We've been divorced from our compare! Our block was split, and
1279 // now our compare lives in a predecessor block. We musn't
1280 // re-compare here, as the children of the compare aren't guaranteed
1281 // live across the block boundary (we *could* check for this).
1282 // Regardless, the compare has been done in the predecessor block,
1283 // and it left a value for us in a virtual register. Ergo, we test
1284 // the one-bit value left in the virtual register.
1285 unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1286 CmpReg = constrainOperandRegClass(TII.get(TstOpc), CmpReg, 0);
1288 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TstOpc))
1292 unsigned CCMode = ARMCC::NE;
1293 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1294 std::swap(TBB, FBB);
1298 unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1299 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BrOpc))
1300 .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1301 finishCondBranch(BI->getParent(), TBB, FBB);
1305 bool ARMFastISel::SelectIndirectBr(const Instruction *I) {
1306 unsigned AddrReg = getRegForValue(I->getOperand(0));
1307 if (AddrReg == 0) return false;
1309 unsigned Opc = isThumb2 ? ARM::tBRIND : ARM::BX;
1310 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1311 TII.get(Opc)).addReg(AddrReg));
1313 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1314 for (const BasicBlock *SuccBB : IB->successors())
1315 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[SuccBB]);
1320 bool ARMFastISel::ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
1322 Type *Ty = Src1Value->getType();
1323 EVT SrcEVT = TLI.getValueType(DL, Ty, true);
1324 if (!SrcEVT.isSimple()) return false;
1325 MVT SrcVT = SrcEVT.getSimpleVT();
1327 bool isFloat = (Ty->isFloatTy() || Ty->isDoubleTy());
1328 if (isFloat && !Subtarget->hasVFP2())
1331 // Check to see if the 2nd operand is a constant that we can encode directly
1334 bool UseImm = false;
1335 bool isNegativeImm = false;
1336 // FIXME: At -O0 we don't have anything that canonicalizes operand order.
1337 // Thus, Src1Value may be a ConstantInt, but we're missing it.
1338 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
1339 if (SrcVT == MVT::i32 || SrcVT == MVT::i16 || SrcVT == MVT::i8 ||
1341 const APInt &CIVal = ConstInt->getValue();
1342 Imm = (isZExt) ? (int)CIVal.getZExtValue() : (int)CIVal.getSExtValue();
1343 // For INT_MIN/LONG_MIN (i.e., 0x80000000) we need to use a cmp, rather
1344 // then a cmn, because there is no way to represent 2147483648 as a
1345 // signed 32-bit int.
1346 if (Imm < 0 && Imm != (int)0x80000000) {
1347 isNegativeImm = true;
1350 UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1351 (ARM_AM::getSOImmVal(Imm) != -1);
1353 } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
1354 if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
1355 if (ConstFP->isZero() && !ConstFP->isNegative())
1361 bool needsExt = false;
1362 switch (SrcVT.SimpleTy) {
1363 default: return false;
1364 // TODO: Verify compares.
1367 CmpOpc = UseImm ? ARM::VCMPEZS : ARM::VCMPES;
1371 CmpOpc = UseImm ? ARM::VCMPEZD : ARM::VCMPED;
1377 // Intentional fall-through.
1381 CmpOpc = ARM::t2CMPrr;
1383 CmpOpc = isNegativeImm ? ARM::t2CMNri : ARM::t2CMPri;
1386 CmpOpc = ARM::CMPrr;
1388 CmpOpc = isNegativeImm ? ARM::CMNri : ARM::CMPri;
1393 unsigned SrcReg1 = getRegForValue(Src1Value);
1394 if (SrcReg1 == 0) return false;
1396 unsigned SrcReg2 = 0;
1398 SrcReg2 = getRegForValue(Src2Value);
1399 if (SrcReg2 == 0) return false;
1402 // We have i1, i8, or i16, we need to either zero extend or sign extend.
1404 SrcReg1 = ARMEmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
1405 if (SrcReg1 == 0) return false;
1407 SrcReg2 = ARMEmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
1408 if (SrcReg2 == 0) return false;
1412 const MCInstrDesc &II = TII.get(CmpOpc);
1413 SrcReg1 = constrainOperandRegClass(II, SrcReg1, 0);
1415 SrcReg2 = constrainOperandRegClass(II, SrcReg2, 1);
1416 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1417 .addReg(SrcReg1).addReg(SrcReg2));
1419 MachineInstrBuilder MIB;
1420 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1423 // Only add immediate for icmp as the immediate for fcmp is an implicit 0.0.
1426 AddOptionalDefs(MIB);
1429 // For floating point we need to move the result to a comparison register
1430 // that we can then use for branches.
1431 if (Ty->isFloatTy() || Ty->isDoubleTy())
1432 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1433 TII.get(ARM::FMSTAT)));
1437 bool ARMFastISel::SelectCmp(const Instruction *I) {
1438 const CmpInst *CI = cast<CmpInst>(I);
1440 // Get the compare predicate.
1441 ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1443 // We may not handle every CC for now.
1444 if (ARMPred == ARMCC::AL) return false;
1446 // Emit the compare.
1447 if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1450 // Now set a register based on the comparison. Explicitly set the predicates
1452 unsigned MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1453 const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass
1454 : &ARM::GPRRegClass;
1455 unsigned DestReg = createResultReg(RC);
1456 Constant *Zero = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1457 unsigned ZeroReg = fastMaterializeConstant(Zero);
1458 // ARMEmitCmp emits a FMSTAT when necessary, so it's always safe to use CPSR.
1459 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovCCOpc), DestReg)
1460 .addReg(ZeroReg).addImm(1)
1461 .addImm(ARMPred).addReg(ARM::CPSR);
1463 updateValueMap(I, DestReg);
1467 bool ARMFastISel::SelectFPExt(const Instruction *I) {
1468 // Make sure we have VFP and that we're extending float to double.
1469 if (!Subtarget->hasVFP2()) return false;
1471 Value *V = I->getOperand(0);
1472 if (!I->getType()->isDoubleTy() ||
1473 !V->getType()->isFloatTy()) return false;
1475 unsigned Op = getRegForValue(V);
1476 if (Op == 0) return false;
1478 unsigned Result = createResultReg(&ARM::DPRRegClass);
1479 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1480 TII.get(ARM::VCVTDS), Result)
1482 updateValueMap(I, Result);
1486 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1487 // Make sure we have VFP and that we're truncating double to float.
1488 if (!Subtarget->hasVFP2()) return false;
1490 Value *V = I->getOperand(0);
1491 if (!(I->getType()->isFloatTy() &&
1492 V->getType()->isDoubleTy())) return false;
1494 unsigned Op = getRegForValue(V);
1495 if (Op == 0) return false;
1497 unsigned Result = createResultReg(&ARM::SPRRegClass);
1498 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1499 TII.get(ARM::VCVTSD), Result)
1501 updateValueMap(I, Result);
1505 bool ARMFastISel::SelectIToFP(const Instruction *I, bool isSigned) {
1506 // Make sure we have VFP.
1507 if (!Subtarget->hasVFP2()) return false;
1510 Type *Ty = I->getType();
1511 if (!isTypeLegal(Ty, DstVT))
1514 Value *Src = I->getOperand(0);
1515 EVT SrcEVT = TLI.getValueType(DL, Src->getType(), true);
1516 if (!SrcEVT.isSimple())
1518 MVT SrcVT = SrcEVT.getSimpleVT();
1519 if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
1522 unsigned SrcReg = getRegForValue(Src);
1523 if (SrcReg == 0) return false;
1525 // Handle sign-extension.
1526 if (SrcVT == MVT::i16 || SrcVT == MVT::i8) {
1527 SrcReg = ARMEmitIntExt(SrcVT, SrcReg, MVT::i32,
1528 /*isZExt*/!isSigned);
1529 if (SrcReg == 0) return false;
1532 // The conversion routine works on fp-reg to fp-reg and the operand above
1533 // was an integer, move it to the fp registers if possible.
1534 unsigned FP = ARMMoveToFPReg(MVT::f32, SrcReg);
1535 if (FP == 0) return false;
1538 if (Ty->isFloatTy()) Opc = isSigned ? ARM::VSITOS : ARM::VUITOS;
1539 else if (Ty->isDoubleTy()) Opc = isSigned ? ARM::VSITOD : ARM::VUITOD;
1542 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1543 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1544 TII.get(Opc), ResultReg).addReg(FP));
1545 updateValueMap(I, ResultReg);
1549 bool ARMFastISel::SelectFPToI(const Instruction *I, bool isSigned) {
1550 // Make sure we have VFP.
1551 if (!Subtarget->hasVFP2()) return false;
1554 Type *RetTy = I->getType();
1555 if (!isTypeLegal(RetTy, DstVT))
1558 unsigned Op = getRegForValue(I->getOperand(0));
1559 if (Op == 0) return false;
1562 Type *OpTy = I->getOperand(0)->getType();
1563 if (OpTy->isFloatTy()) Opc = isSigned ? ARM::VTOSIZS : ARM::VTOUIZS;
1564 else if (OpTy->isDoubleTy()) Opc = isSigned ? ARM::VTOSIZD : ARM::VTOUIZD;
1567 // f64->s32/u32 or f32->s32/u32 both need an intermediate f32 reg.
1568 unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1569 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1570 TII.get(Opc), ResultReg).addReg(Op));
1572 // This result needs to be in an integer register, but the conversion only
1573 // takes place in fp-regs.
1574 unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1575 if (IntReg == 0) return false;
1577 updateValueMap(I, IntReg);
1581 bool ARMFastISel::SelectSelect(const Instruction *I) {
1583 if (!isTypeLegal(I->getType(), VT))
1586 // Things need to be register sized for register moves.
1587 if (VT != MVT::i32) return false;
1589 unsigned CondReg = getRegForValue(I->getOperand(0));
1590 if (CondReg == 0) return false;
1591 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1592 if (Op1Reg == 0) return false;
1594 // Check to see if we can use an immediate in the conditional move.
1596 bool UseImm = false;
1597 bool isNegativeImm = false;
1598 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(2))) {
1599 assert (VT == MVT::i32 && "Expecting an i32.");
1600 Imm = (int)ConstInt->getValue().getZExtValue();
1602 isNegativeImm = true;
1605 UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1606 (ARM_AM::getSOImmVal(Imm) != -1);
1609 unsigned Op2Reg = 0;
1611 Op2Reg = getRegForValue(I->getOperand(2));
1612 if (Op2Reg == 0) return false;
1615 unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1616 CondReg = constrainOperandRegClass(TII.get(TstOpc), CondReg, 0);
1618 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TstOpc))
1623 const TargetRegisterClass *RC;
1625 RC = isThumb2 ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
1626 MovCCOpc = isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr;
1628 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass;
1630 MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1632 MovCCOpc = isThumb2 ? ARM::t2MVNCCi : ARM::MVNCCi;
1634 unsigned ResultReg = createResultReg(RC);
1636 Op2Reg = constrainOperandRegClass(TII.get(MovCCOpc), Op2Reg, 1);
1637 Op1Reg = constrainOperandRegClass(TII.get(MovCCOpc), Op1Reg, 2);
1638 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovCCOpc),
1645 Op1Reg = constrainOperandRegClass(TII.get(MovCCOpc), Op1Reg, 1);
1646 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovCCOpc),
1653 updateValueMap(I, ResultReg);
1657 bool ARMFastISel::SelectDiv(const Instruction *I, bool isSigned) {
1659 Type *Ty = I->getType();
1660 if (!isTypeLegal(Ty, VT))
1663 // If we have integer div support we should have selected this automagically.
1664 // In case we have a real miss go ahead and return false and we'll pick
1666 if (Subtarget->hasDivide()) return false;
1668 // Otherwise emit a libcall.
1669 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1671 LC = isSigned ? RTLIB::SDIV_I8 : RTLIB::UDIV_I8;
1672 else if (VT == MVT::i16)
1673 LC = isSigned ? RTLIB::SDIV_I16 : RTLIB::UDIV_I16;
1674 else if (VT == MVT::i32)
1675 LC = isSigned ? RTLIB::SDIV_I32 : RTLIB::UDIV_I32;
1676 else if (VT == MVT::i64)
1677 LC = isSigned ? RTLIB::SDIV_I64 : RTLIB::UDIV_I64;
1678 else if (VT == MVT::i128)
1679 LC = isSigned ? RTLIB::SDIV_I128 : RTLIB::UDIV_I128;
1680 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1682 return ARMEmitLibcall(I, LC);
1685 bool ARMFastISel::SelectRem(const Instruction *I, bool isSigned) {
1687 Type *Ty = I->getType();
1688 if (!isTypeLegal(Ty, VT))
1691 // Many ABIs do not provide a libcall for standalone remainder, so we need to
1692 // use divrem (see the RTABI 4.3.1). Since FastISel can't handle non-double
1693 // multi-reg returns, we'll have to bail out.
1694 if (!TLI.hasStandaloneRem(VT)) {
1698 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1700 LC = isSigned ? RTLIB::SREM_I8 : RTLIB::UREM_I8;
1701 else if (VT == MVT::i16)
1702 LC = isSigned ? RTLIB::SREM_I16 : RTLIB::UREM_I16;
1703 else if (VT == MVT::i32)
1704 LC = isSigned ? RTLIB::SREM_I32 : RTLIB::UREM_I32;
1705 else if (VT == MVT::i64)
1706 LC = isSigned ? RTLIB::SREM_I64 : RTLIB::UREM_I64;
1707 else if (VT == MVT::i128)
1708 LC = isSigned ? RTLIB::SREM_I128 : RTLIB::UREM_I128;
1709 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1711 return ARMEmitLibcall(I, LC);
1714 bool ARMFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1715 EVT DestVT = TLI.getValueType(DL, I->getType(), true);
1717 // We can get here in the case when we have a binary operation on a non-legal
1718 // type and the target independent selector doesn't know how to handle it.
1719 if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
1723 switch (ISDOpcode) {
1724 default: return false;
1726 Opc = isThumb2 ? ARM::t2ADDrr : ARM::ADDrr;
1729 Opc = isThumb2 ? ARM::t2ORRrr : ARM::ORRrr;
1732 Opc = isThumb2 ? ARM::t2SUBrr : ARM::SUBrr;
1736 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1737 if (SrcReg1 == 0) return false;
1739 // TODO: Often the 2nd operand is an immediate, which can be encoded directly
1740 // in the instruction, rather then materializing the value in a register.
1741 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1742 if (SrcReg2 == 0) return false;
1744 unsigned ResultReg = createResultReg(&ARM::GPRnopcRegClass);
1745 SrcReg1 = constrainOperandRegClass(TII.get(Opc), SrcReg1, 1);
1746 SrcReg2 = constrainOperandRegClass(TII.get(Opc), SrcReg2, 2);
1747 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1748 TII.get(Opc), ResultReg)
1749 .addReg(SrcReg1).addReg(SrcReg2));
1750 updateValueMap(I, ResultReg);
1754 bool ARMFastISel::SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode) {
1755 EVT FPVT = TLI.getValueType(DL, I->getType(), true);
1756 if (!FPVT.isSimple()) return false;
1757 MVT VT = FPVT.getSimpleVT();
1759 // FIXME: Support vector types where possible.
1763 // We can get here in the case when we want to use NEON for our fp
1764 // operations, but can't figure out how to. Just use the vfp instructions
1766 // FIXME: It'd be nice to use NEON instructions.
1767 Type *Ty = I->getType();
1768 bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1769 if (isFloat && !Subtarget->hasVFP2())
1773 bool is64bit = VT == MVT::f64 || VT == MVT::i64;
1774 switch (ISDOpcode) {
1775 default: return false;
1777 Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1780 Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1783 Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1786 unsigned Op1 = getRegForValue(I->getOperand(0));
1787 if (Op1 == 0) return false;
1789 unsigned Op2 = getRegForValue(I->getOperand(1));
1790 if (Op2 == 0) return false;
1792 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT.SimpleTy));
1793 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1794 TII.get(Opc), ResultReg)
1795 .addReg(Op1).addReg(Op2));
1796 updateValueMap(I, ResultReg);
1800 // Call Handling Code
1802 // This is largely taken directly from CCAssignFnForNode
1803 // TODO: We may not support all of this.
1804 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC,
1809 llvm_unreachable("Unsupported calling convention");
1810 case CallingConv::Fast:
1811 if (Subtarget->hasVFP2() && !isVarArg) {
1812 if (!Subtarget->isAAPCS_ABI())
1813 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1814 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1815 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1818 case CallingConv::C:
1819 case CallingConv::CXX_FAST_TLS:
1820 // Use target triple & subtarget features to do actual dispatch.
1821 if (Subtarget->isAAPCS_ABI()) {
1822 if (Subtarget->hasVFP2() &&
1823 TM.Options.FloatABIType == FloatABI::Hard && !isVarArg)
1824 return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1826 return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1828 return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1830 case CallingConv::ARM_AAPCS_VFP:
1831 case CallingConv::Swift:
1833 return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1834 // Fall through to soft float variant, variadic functions don't
1835 // use hard floating point ABI.
1837 case CallingConv::ARM_AAPCS:
1838 return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1839 case CallingConv::ARM_APCS:
1840 return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1841 case CallingConv::GHC:
1843 llvm_unreachable("Can't return in GHC call convention");
1845 return CC_ARM_APCS_GHC;
1849 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1850 SmallVectorImpl<unsigned> &ArgRegs,
1851 SmallVectorImpl<MVT> &ArgVTs,
1852 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1853 SmallVectorImpl<unsigned> &RegArgs,
1857 SmallVector<CCValAssign, 16> ArgLocs;
1858 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, ArgLocs, *Context);
1859 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags,
1860 CCAssignFnForCall(CC, false, isVarArg));
1862 // Check that we can handle all of the arguments. If we can't, then bail out
1863 // now before we add code to the MBB.
1864 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1865 CCValAssign &VA = ArgLocs[i];
1866 MVT ArgVT = ArgVTs[VA.getValNo()];
1868 // We don't handle NEON/vector parameters yet.
1869 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1872 // Now copy/store arg to correct locations.
1873 if (VA.isRegLoc() && !VA.needsCustom()) {
1875 } else if (VA.needsCustom()) {
1876 // TODO: We need custom lowering for vector (v2f64) args.
1877 if (VA.getLocVT() != MVT::f64 ||
1878 // TODO: Only handle register args for now.
1879 !VA.isRegLoc() || !ArgLocs[++i].isRegLoc())
1882 switch (ArgVT.SimpleTy) {
1891 if (!Subtarget->hasVFP2())
1895 if (!Subtarget->hasVFP2())
1902 // At the point, we are able to handle the call's arguments in fast isel.
1904 // Get a count of how many bytes are to be pushed on the stack.
1905 NumBytes = CCInfo.getNextStackOffset();
1907 // Issue CALLSEQ_START
1908 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1909 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1910 TII.get(AdjStackDown))
1913 // Process the args.
1914 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1915 CCValAssign &VA = ArgLocs[i];
1916 const Value *ArgVal = Args[VA.getValNo()];
1917 unsigned Arg = ArgRegs[VA.getValNo()];
1918 MVT ArgVT = ArgVTs[VA.getValNo()];
1920 assert((!ArgVT.isVector() && ArgVT.getSizeInBits() <= 64) &&
1921 "We don't handle NEON/vector parameters yet.");
1923 // Handle arg promotion, etc.
1924 switch (VA.getLocInfo()) {
1925 case CCValAssign::Full: break;
1926 case CCValAssign::SExt: {
1927 MVT DestVT = VA.getLocVT();
1928 Arg = ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/false);
1929 assert (Arg != 0 && "Failed to emit a sext");
1933 case CCValAssign::AExt:
1934 // Intentional fall-through. Handle AExt and ZExt.
1935 case CCValAssign::ZExt: {
1936 MVT DestVT = VA.getLocVT();
1937 Arg = ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/true);
1938 assert (Arg != 0 && "Failed to emit a zext");
1942 case CCValAssign::BCvt: {
1943 unsigned BC = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, Arg,
1944 /*TODO: Kill=*/false);
1945 assert(BC != 0 && "Failed to emit a bitcast!");
1947 ArgVT = VA.getLocVT();
1950 default: llvm_unreachable("Unknown arg promotion!");
1953 // Now copy/store arg to correct locations.
1954 if (VA.isRegLoc() && !VA.needsCustom()) {
1955 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1956 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
1957 RegArgs.push_back(VA.getLocReg());
1958 } else if (VA.needsCustom()) {
1959 // TODO: We need custom lowering for vector (v2f64) args.
1960 assert(VA.getLocVT() == MVT::f64 &&
1961 "Custom lowering for v2f64 args not available");
1963 CCValAssign &NextVA = ArgLocs[++i];
1965 assert(VA.isRegLoc() && NextVA.isRegLoc() &&
1966 "We only handle register args!");
1968 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1969 TII.get(ARM::VMOVRRD), VA.getLocReg())
1970 .addReg(NextVA.getLocReg(), RegState::Define)
1972 RegArgs.push_back(VA.getLocReg());
1973 RegArgs.push_back(NextVA.getLocReg());
1975 assert(VA.isMemLoc());
1976 // Need to store on the stack.
1978 // Don't emit stores for undef values.
1979 if (isa<UndefValue>(ArgVal))
1983 Addr.BaseType = Address::RegBase;
1984 Addr.Base.Reg = ARM::SP;
1985 Addr.Offset = VA.getLocMemOffset();
1987 bool EmitRet = ARMEmitStore(ArgVT, Arg, Addr); (void)EmitRet;
1988 assert(EmitRet && "Could not emit a store for argument!");
1995 bool ARMFastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1996 const Instruction *I, CallingConv::ID CC,
1997 unsigned &NumBytes, bool isVarArg) {
1998 // Issue CALLSEQ_END
1999 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2000 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2001 TII.get(AdjStackUp))
2002 .addImm(NumBytes).addImm(0));
2004 // Now the return value.
2005 if (RetVT != MVT::isVoid) {
2006 SmallVector<CCValAssign, 16> RVLocs;
2007 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, RVLocs, *Context);
2008 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, isVarArg));
2010 // Copy all of the result registers out of their specified physreg.
2011 if (RVLocs.size() == 2 && RetVT == MVT::f64) {
2012 // For this move we copy into two registers and then move into the
2013 // double fp reg we want.
2014 MVT DestVT = RVLocs[0].getValVT();
2015 const TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
2016 unsigned ResultReg = createResultReg(DstRC);
2017 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2018 TII.get(ARM::VMOVDRR), ResultReg)
2019 .addReg(RVLocs[0].getLocReg())
2020 .addReg(RVLocs[1].getLocReg()));
2022 UsedRegs.push_back(RVLocs[0].getLocReg());
2023 UsedRegs.push_back(RVLocs[1].getLocReg());
2025 // Finally update the result.
2026 updateValueMap(I, ResultReg);
2028 assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
2029 MVT CopyVT = RVLocs[0].getValVT();
2031 // Special handling for extended integers.
2032 if (RetVT == MVT::i1 || RetVT == MVT::i8 || RetVT == MVT::i16)
2035 const TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
2037 unsigned ResultReg = createResultReg(DstRC);
2038 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2039 TII.get(TargetOpcode::COPY),
2040 ResultReg).addReg(RVLocs[0].getLocReg());
2041 UsedRegs.push_back(RVLocs[0].getLocReg());
2043 // Finally update the result.
2044 updateValueMap(I, ResultReg);
2051 bool ARMFastISel::SelectRet(const Instruction *I) {
2052 const ReturnInst *Ret = cast<ReturnInst>(I);
2053 const Function &F = *I->getParent()->getParent();
2055 if (!FuncInfo.CanLowerReturn)
2058 if (TLI.supportSwiftError() &&
2059 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
2062 if (TLI.supportSplitCSR(FuncInfo.MF))
2065 // Build a list of return value registers.
2066 SmallVector<unsigned, 4> RetRegs;
2068 CallingConv::ID CC = F.getCallingConv();
2069 if (Ret->getNumOperands() > 0) {
2070 SmallVector<ISD::OutputArg, 4> Outs;
2071 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
2073 // Analyze operands of the call, assigning locations to each operand.
2074 SmallVector<CCValAssign, 16> ValLocs;
2075 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
2076 CCInfo.AnalyzeReturn(Outs, CCAssignFnForCall(CC, true /* is Ret */,
2079 const Value *RV = Ret->getOperand(0);
2080 unsigned Reg = getRegForValue(RV);
2084 // Only handle a single return value for now.
2085 if (ValLocs.size() != 1)
2088 CCValAssign &VA = ValLocs[0];
2090 // Don't bother handling odd stuff for now.
2091 if (VA.getLocInfo() != CCValAssign::Full)
2093 // Only handle register returns for now.
2097 unsigned SrcReg = Reg + VA.getValNo();
2098 EVT RVEVT = TLI.getValueType(DL, RV->getType());
2099 if (!RVEVT.isSimple()) return false;
2100 MVT RVVT = RVEVT.getSimpleVT();
2101 MVT DestVT = VA.getValVT();
2102 // Special handling for extended integers.
2103 if (RVVT != DestVT) {
2104 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
2107 assert(DestVT == MVT::i32 && "ARM should always ext to i32");
2109 // Perform extension if flagged as either zext or sext. Otherwise, do
2111 if (Outs[0].Flags.isZExt() || Outs[0].Flags.isSExt()) {
2112 SrcReg = ARMEmitIntExt(RVVT, SrcReg, DestVT, Outs[0].Flags.isZExt());
2113 if (SrcReg == 0) return false;
2118 unsigned DstReg = VA.getLocReg();
2119 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
2120 // Avoid a cross-class copy. This is very unlikely.
2121 if (!SrcRC->contains(DstReg))
2123 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2124 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
2126 // Add register to return instruction.
2127 RetRegs.push_back(VA.getLocReg());
2130 unsigned RetOpc = isThumb2 ? ARM::tBX_RET : ARM::BX_RET;
2131 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2133 AddOptionalDefs(MIB);
2134 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
2135 MIB.addReg(RetRegs[i], RegState::Implicit);
2139 unsigned ARMFastISel::ARMSelectCallOp(bool UseReg) {
2141 return isThumb2 ? ARM::tBLXr : ARM::BLX;
2143 return isThumb2 ? ARM::tBL : ARM::BL;
2146 unsigned ARMFastISel::getLibcallReg(const Twine &Name) {
2147 // Manually compute the global's type to avoid building it when unnecessary.
2148 Type *GVTy = Type::getInt32PtrTy(*Context, /*AS=*/0);
2149 EVT LCREVT = TLI.getValueType(DL, GVTy);
2150 if (!LCREVT.isSimple()) return 0;
2152 GlobalValue *GV = new GlobalVariable(M, Type::getInt32Ty(*Context), false,
2153 GlobalValue::ExternalLinkage, nullptr,
2155 assert(GV->getType() == GVTy && "We miscomputed the type for the global!");
2156 return ARMMaterializeGV(GV, LCREVT.getSimpleVT());
2159 // A quick function that will emit a call for a named libcall in F with the
2160 // vector of passed arguments for the Instruction in I. We can assume that we
2161 // can emit a call for any libcall we can produce. This is an abridged version
2162 // of the full call infrastructure since we won't need to worry about things
2163 // like computed function pointers or strange arguments at call sites.
2164 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
2166 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
2167 CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
2169 // Handle *simple* calls for now.
2170 Type *RetTy = I->getType();
2172 if (RetTy->isVoidTy())
2173 RetVT = MVT::isVoid;
2174 else if (!isTypeLegal(RetTy, RetVT))
2177 // Can't handle non-double multi-reg retvals.
2178 if (RetVT != MVT::isVoid && RetVT != MVT::i32) {
2179 SmallVector<CCValAssign, 16> RVLocs;
2180 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2181 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, false));
2182 if (RVLocs.size() >= 2 && RetVT != MVT::f64)
2186 // Set up the argument vectors.
2187 SmallVector<Value*, 8> Args;
2188 SmallVector<unsigned, 8> ArgRegs;
2189 SmallVector<MVT, 8> ArgVTs;
2190 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2191 Args.reserve(I->getNumOperands());
2192 ArgRegs.reserve(I->getNumOperands());
2193 ArgVTs.reserve(I->getNumOperands());
2194 ArgFlags.reserve(I->getNumOperands());
2195 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2196 Value *Op = I->getOperand(i);
2197 unsigned Arg = getRegForValue(Op);
2198 if (Arg == 0) return false;
2200 Type *ArgTy = Op->getType();
2202 if (!isTypeLegal(ArgTy, ArgVT)) return false;
2204 ISD::ArgFlagsTy Flags;
2205 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2206 Flags.setOrigAlign(OriginalAlignment);
2209 ArgRegs.push_back(Arg);
2210 ArgVTs.push_back(ArgVT);
2211 ArgFlags.push_back(Flags);
2214 // Handle the arguments now that we've gotten them.
2215 SmallVector<unsigned, 4> RegArgs;
2217 if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
2218 RegArgs, CC, NumBytes, false))
2221 unsigned CalleeReg = 0;
2222 if (Subtarget->genLongCalls()) {
2223 CalleeReg = getLibcallReg(TLI.getLibcallName(Call));
2224 if (CalleeReg == 0) return false;
2228 unsigned CallOpc = ARMSelectCallOp(Subtarget->genLongCalls());
2229 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2230 DbgLoc, TII.get(CallOpc));
2231 // BL / BLX don't take a predicate, but tBL / tBLX do.
2233 AddDefaultPred(MIB);
2234 if (Subtarget->genLongCalls())
2235 MIB.addReg(CalleeReg);
2237 MIB.addExternalSymbol(TLI.getLibcallName(Call));
2239 // Add implicit physical register uses to the call.
2240 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2241 MIB.addReg(RegArgs[i], RegState::Implicit);
2243 // Add a register mask with the call-preserved registers.
2244 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2245 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
2247 // Finish off the call including any return values.
2248 SmallVector<unsigned, 4> UsedRegs;
2249 if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes, false)) return false;
2251 // Set all unused physreg defs as dead.
2252 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2257 bool ARMFastISel::SelectCall(const Instruction *I,
2258 const char *IntrMemName = nullptr) {
2259 const CallInst *CI = cast<CallInst>(I);
2260 const Value *Callee = CI->getCalledValue();
2262 // Can't handle inline asm.
2263 if (isa<InlineAsm>(Callee)) return false;
2265 // Allow SelectionDAG isel to handle tail calls.
2266 if (CI->isTailCall()) return false;
2268 // Check the calling convention.
2269 ImmutableCallSite CS(CI);
2270 CallingConv::ID CC = CS.getCallingConv();
2272 // TODO: Avoid some calling conventions?
2274 FunctionType *FTy = CS.getFunctionType();
2275 bool isVarArg = FTy->isVarArg();
2277 // Handle *simple* calls for now.
2278 Type *RetTy = I->getType();
2280 if (RetTy->isVoidTy())
2281 RetVT = MVT::isVoid;
2282 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
2283 RetVT != MVT::i8 && RetVT != MVT::i1)
2286 // Can't handle non-double multi-reg retvals.
2287 if (RetVT != MVT::isVoid && RetVT != MVT::i1 && RetVT != MVT::i8 &&
2288 RetVT != MVT::i16 && RetVT != MVT::i32) {
2289 SmallVector<CCValAssign, 16> RVLocs;
2290 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, RVLocs, *Context);
2291 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, isVarArg));
2292 if (RVLocs.size() >= 2 && RetVT != MVT::f64)
2296 // Set up the argument vectors.
2297 SmallVector<Value*, 8> Args;
2298 SmallVector<unsigned, 8> ArgRegs;
2299 SmallVector<MVT, 8> ArgVTs;
2300 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2301 unsigned arg_size = CS.arg_size();
2302 Args.reserve(arg_size);
2303 ArgRegs.reserve(arg_size);
2304 ArgVTs.reserve(arg_size);
2305 ArgFlags.reserve(arg_size);
2306 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2308 // If we're lowering a memory intrinsic instead of a regular call, skip the
2309 // last two arguments, which shouldn't be passed to the underlying function.
2310 if (IntrMemName && e-i <= 2)
2313 ISD::ArgFlagsTy Flags;
2314 unsigned AttrInd = i - CS.arg_begin() + 1;
2315 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2317 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2320 // FIXME: Only handle *easy* calls for now.
2321 if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
2322 CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
2323 CS.paramHasAttr(AttrInd, Attribute::SwiftSelf) ||
2324 CS.paramHasAttr(AttrInd, Attribute::SwiftError) ||
2325 CS.paramHasAttr(AttrInd, Attribute::Nest) ||
2326 CS.paramHasAttr(AttrInd, Attribute::ByVal))
2329 Type *ArgTy = (*i)->getType();
2331 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8 &&
2335 unsigned Arg = getRegForValue(*i);
2339 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2340 Flags.setOrigAlign(OriginalAlignment);
2343 ArgRegs.push_back(Arg);
2344 ArgVTs.push_back(ArgVT);
2345 ArgFlags.push_back(Flags);
2348 // Handle the arguments now that we've gotten them.
2349 SmallVector<unsigned, 4> RegArgs;
2351 if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
2352 RegArgs, CC, NumBytes, isVarArg))
2355 bool UseReg = false;
2356 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
2357 if (!GV || Subtarget->genLongCalls()) UseReg = true;
2359 unsigned CalleeReg = 0;
2362 CalleeReg = getLibcallReg(IntrMemName);
2364 CalleeReg = getRegForValue(Callee);
2366 if (CalleeReg == 0) return false;
2370 unsigned CallOpc = ARMSelectCallOp(UseReg);
2371 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2372 DbgLoc, TII.get(CallOpc));
2374 // ARM calls don't take a predicate, but tBL / tBLX do.
2376 AddDefaultPred(MIB);
2378 MIB.addReg(CalleeReg);
2379 else if (!IntrMemName)
2380 MIB.addGlobalAddress(GV, 0, 0);
2382 MIB.addExternalSymbol(IntrMemName, 0);
2384 // Add implicit physical register uses to the call.
2385 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2386 MIB.addReg(RegArgs[i], RegState::Implicit);
2388 // Add a register mask with the call-preserved registers.
2389 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2390 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
2392 // Finish off the call including any return values.
2393 SmallVector<unsigned, 4> UsedRegs;
2394 if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes, isVarArg))
2397 // Set all unused physreg defs as dead.
2398 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2403 bool ARMFastISel::ARMIsMemCpySmall(uint64_t Len) {
2407 bool ARMFastISel::ARMTryEmitSmallMemCpy(Address Dest, Address Src,
2408 uint64_t Len, unsigned Alignment) {
2409 // Make sure we don't bloat code by inlining very large memcpy's.
2410 if (!ARMIsMemCpySmall(Len))
2415 if (!Alignment || Alignment >= 4) {
2421 assert (Len == 1 && "Expected a length of 1!");
2425 // Bound based on alignment.
2426 if (Len >= 2 && Alignment == 2)
2435 RV = ARMEmitLoad(VT, ResultReg, Src);
2436 assert (RV == true && "Should be able to handle this load.");
2437 RV = ARMEmitStore(VT, ResultReg, Dest);
2438 assert (RV == true && "Should be able to handle this store.");
2441 unsigned Size = VT.getSizeInBits()/8;
2443 Dest.Offset += Size;
2450 bool ARMFastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
2451 // FIXME: Handle more intrinsics.
2452 switch (I.getIntrinsicID()) {
2453 default: return false;
2454 case Intrinsic::frameaddress: {
2455 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
2456 MFI.setFrameAddressIsTaken(true);
2458 unsigned LdrOpc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
2459 const TargetRegisterClass *RC = isThumb2 ? &ARM::tGPRRegClass
2460 : &ARM::GPRRegClass;
2462 const ARMBaseRegisterInfo *RegInfo =
2463 static_cast<const ARMBaseRegisterInfo *>(Subtarget->getRegisterInfo());
2464 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
2465 unsigned SrcReg = FramePtr;
2467 // Recursively load frame address
2473 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
2475 DestReg = createResultReg(RC);
2476 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2477 TII.get(LdrOpc), DestReg)
2478 .addReg(SrcReg).addImm(0));
2481 updateValueMap(&I, SrcReg);
2484 case Intrinsic::memcpy:
2485 case Intrinsic::memmove: {
2486 const MemTransferInst &MTI = cast<MemTransferInst>(I);
2487 // Don't handle volatile.
2488 if (MTI.isVolatile())
2491 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
2492 // we would emit dead code because we don't currently handle memmoves.
2493 bool isMemCpy = (I.getIntrinsicID() == Intrinsic::memcpy);
2494 if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
2495 // Small memcpy's are common enough that we want to do them without a call
2497 uint64_t Len = cast<ConstantInt>(MTI.getLength())->getZExtValue();
2498 if (ARMIsMemCpySmall(Len)) {
2500 if (!ARMComputeAddress(MTI.getRawDest(), Dest) ||
2501 !ARMComputeAddress(MTI.getRawSource(), Src))
2503 unsigned Alignment = MTI.getAlignment();
2504 if (ARMTryEmitSmallMemCpy(Dest, Src, Len, Alignment))
2509 if (!MTI.getLength()->getType()->isIntegerTy(32))
2512 if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 255)
2515 const char *IntrMemName = isa<MemCpyInst>(I) ? "memcpy" : "memmove";
2516 return SelectCall(&I, IntrMemName);
2518 case Intrinsic::memset: {
2519 const MemSetInst &MSI = cast<MemSetInst>(I);
2520 // Don't handle volatile.
2521 if (MSI.isVolatile())
2524 if (!MSI.getLength()->getType()->isIntegerTy(32))
2527 if (MSI.getDestAddressSpace() > 255)
2530 return SelectCall(&I, "memset");
2532 case Intrinsic::trap: {
2533 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(
2534 Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP));
2540 bool ARMFastISel::SelectTrunc(const Instruction *I) {
2541 // The high bits for a type smaller than the register size are assumed to be
2543 Value *Op = I->getOperand(0);
2546 SrcVT = TLI.getValueType(DL, Op->getType(), true);
2547 DestVT = TLI.getValueType(DL, I->getType(), true);
2549 if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
2551 if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
2554 unsigned SrcReg = getRegForValue(Op);
2555 if (!SrcReg) return false;
2557 // Because the high bits are undefined, a truncate doesn't generate
2559 updateValueMap(I, SrcReg);
2563 unsigned ARMFastISel::ARMEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
2565 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
2567 if (SrcVT != MVT::i16 && SrcVT != MVT::i8 && SrcVT != MVT::i1)
2570 // Table of which combinations can be emitted as a single instruction,
2571 // and which will require two.
2572 static const uint8_t isSingleInstrTbl[3][2][2][2] = {
2574 // !hasV6Ops hasV6Ops !hasV6Ops hasV6Ops
2575 // ext: s z s z s z s z
2576 /* 1 */ { { { 0, 1 }, { 0, 1 } }, { { 0, 0 }, { 0, 1 } } },
2577 /* 8 */ { { { 0, 1 }, { 1, 1 } }, { { 0, 0 }, { 1, 1 } } },
2578 /* 16 */ { { { 0, 0 }, { 1, 1 } }, { { 0, 0 }, { 1, 1 } } }
2581 // Target registers for:
2582 // - For ARM can never be PC.
2583 // - For 16-bit Thumb are restricted to lower 8 registers.
2584 // - For 32-bit Thumb are restricted to non-SP and non-PC.
2585 static const TargetRegisterClass *RCTbl[2][2] = {
2586 // Instructions: Two Single
2587 /* ARM */ { &ARM::GPRnopcRegClass, &ARM::GPRnopcRegClass },
2588 /* Thumb */ { &ARM::tGPRRegClass, &ARM::rGPRRegClass }
2591 // Table governing the instruction(s) to be emitted.
2592 static const struct InstructionTable {
2594 uint32_t hasS : 1; // Some instructions have an S bit, always set it to 0.
2595 uint32_t Shift : 7; // For shift operand addressing mode, used by MOVsi.
2596 uint32_t Imm : 8; // All instructions have either a shift or a mask.
2597 } IT[2][2][3][2] = {
2598 { // Two instructions (first is left shift, second is in this table).
2599 { // ARM Opc S Shift Imm
2600 /* 1 bit sext */ { { ARM::MOVsi , 1, ARM_AM::asr , 31 },
2601 /* 1 bit zext */ { ARM::MOVsi , 1, ARM_AM::lsr , 31 } },
2602 /* 8 bit sext */ { { ARM::MOVsi , 1, ARM_AM::asr , 24 },
2603 /* 8 bit zext */ { ARM::MOVsi , 1, ARM_AM::lsr , 24 } },
2604 /* 16 bit sext */ { { ARM::MOVsi , 1, ARM_AM::asr , 16 },
2605 /* 16 bit zext */ { ARM::MOVsi , 1, ARM_AM::lsr , 16 } }
2607 { // Thumb Opc S Shift Imm
2608 /* 1 bit sext */ { { ARM::tASRri , 0, ARM_AM::no_shift, 31 },
2609 /* 1 bit zext */ { ARM::tLSRri , 0, ARM_AM::no_shift, 31 } },
2610 /* 8 bit sext */ { { ARM::tASRri , 0, ARM_AM::no_shift, 24 },
2611 /* 8 bit zext */ { ARM::tLSRri , 0, ARM_AM::no_shift, 24 } },
2612 /* 16 bit sext */ { { ARM::tASRri , 0, ARM_AM::no_shift, 16 },
2613 /* 16 bit zext */ { ARM::tLSRri , 0, ARM_AM::no_shift, 16 } }
2616 { // Single instruction.
2617 { // ARM Opc S Shift Imm
2618 /* 1 bit sext */ { { ARM::KILL , 0, ARM_AM::no_shift, 0 },
2619 /* 1 bit zext */ { ARM::ANDri , 1, ARM_AM::no_shift, 1 } },
2620 /* 8 bit sext */ { { ARM::SXTB , 0, ARM_AM::no_shift, 0 },
2621 /* 8 bit zext */ { ARM::ANDri , 1, ARM_AM::no_shift, 255 } },
2622 /* 16 bit sext */ { { ARM::SXTH , 0, ARM_AM::no_shift, 0 },
2623 /* 16 bit zext */ { ARM::UXTH , 0, ARM_AM::no_shift, 0 } }
2625 { // Thumb Opc S Shift Imm
2626 /* 1 bit sext */ { { ARM::KILL , 0, ARM_AM::no_shift, 0 },
2627 /* 1 bit zext */ { ARM::t2ANDri, 1, ARM_AM::no_shift, 1 } },
2628 /* 8 bit sext */ { { ARM::t2SXTB , 0, ARM_AM::no_shift, 0 },
2629 /* 8 bit zext */ { ARM::t2ANDri, 1, ARM_AM::no_shift, 255 } },
2630 /* 16 bit sext */ { { ARM::t2SXTH , 0, ARM_AM::no_shift, 0 },
2631 /* 16 bit zext */ { ARM::t2UXTH , 0, ARM_AM::no_shift, 0 } }
2636 unsigned SrcBits = SrcVT.getSizeInBits();
2637 unsigned DestBits = DestVT.getSizeInBits();
2639 assert((SrcBits < DestBits) && "can only extend to larger types");
2640 assert((DestBits == 32 || DestBits == 16 || DestBits == 8) &&
2641 "other sizes unimplemented");
2642 assert((SrcBits == 16 || SrcBits == 8 || SrcBits == 1) &&
2643 "other sizes unimplemented");
2645 bool hasV6Ops = Subtarget->hasV6Ops();
2646 unsigned Bitness = SrcBits / 8; // {1,8,16}=>{0,1,2}
2647 assert((Bitness < 3) && "sanity-check table bounds");
2649 bool isSingleInstr = isSingleInstrTbl[Bitness][isThumb2][hasV6Ops][isZExt];
2650 const TargetRegisterClass *RC = RCTbl[isThumb2][isSingleInstr];
2651 const InstructionTable *ITP = &IT[isSingleInstr][isThumb2][Bitness][isZExt];
2652 unsigned Opc = ITP->Opc;
2653 assert(ARM::KILL != Opc && "Invalid table entry");
2654 unsigned hasS = ITP->hasS;
2655 ARM_AM::ShiftOpc Shift = (ARM_AM::ShiftOpc) ITP->Shift;
2656 assert(((Shift == ARM_AM::no_shift) == (Opc != ARM::MOVsi)) &&
2657 "only MOVsi has shift operand addressing mode");
2658 unsigned Imm = ITP->Imm;
2660 // 16-bit Thumb instructions always set CPSR (unless they're in an IT block).
2661 bool setsCPSR = &ARM::tGPRRegClass == RC;
2662 unsigned LSLOpc = isThumb2 ? ARM::tLSLri : ARM::MOVsi;
2664 // MOVsi encodes shift and immediate in shift operand addressing mode.
2665 // The following condition has the same value when emitting two
2666 // instruction sequences: both are shifts.
2667 bool ImmIsSO = (Shift != ARM_AM::no_shift);
2669 // Either one or two instructions are emitted.
2670 // They're always of the form:
2672 // CPSR is set only by 16-bit Thumb instructions.
2673 // Predicate, if any, is AL.
2674 // S bit, if available, is always 0.
2675 // When two are emitted the first's result will feed as the second's input,
2676 // that value is then dead.
2677 unsigned NumInstrsEmitted = isSingleInstr ? 1 : 2;
2678 for (unsigned Instr = 0; Instr != NumInstrsEmitted; ++Instr) {
2679 ResultReg = createResultReg(RC);
2680 bool isLsl = (0 == Instr) && !isSingleInstr;
2681 unsigned Opcode = isLsl ? LSLOpc : Opc;
2682 ARM_AM::ShiftOpc ShiftAM = isLsl ? ARM_AM::lsl : Shift;
2683 unsigned ImmEnc = ImmIsSO ? ARM_AM::getSORegOpc(ShiftAM, Imm) : Imm;
2684 bool isKill = 1 == Instr;
2685 MachineInstrBuilder MIB = BuildMI(
2686 *FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opcode), ResultReg);
2688 MIB.addReg(ARM::CPSR, RegState::Define);
2689 SrcReg = constrainOperandRegClass(TII.get(Opcode), SrcReg, 1 + setsCPSR);
2690 AddDefaultPred(MIB.addReg(SrcReg, isKill * RegState::Kill).addImm(ImmEnc));
2693 // Second instruction consumes the first's result.
2700 bool ARMFastISel::SelectIntExt(const Instruction *I) {
2701 // On ARM, in general, integer casts don't involve legal types; this code
2702 // handles promotable integers.
2703 Type *DestTy = I->getType();
2704 Value *Src = I->getOperand(0);
2705 Type *SrcTy = Src->getType();
2707 bool isZExt = isa<ZExtInst>(I);
2708 unsigned SrcReg = getRegForValue(Src);
2709 if (!SrcReg) return false;
2711 EVT SrcEVT, DestEVT;
2712 SrcEVT = TLI.getValueType(DL, SrcTy, true);
2713 DestEVT = TLI.getValueType(DL, DestTy, true);
2714 if (!SrcEVT.isSimple()) return false;
2715 if (!DestEVT.isSimple()) return false;
2717 MVT SrcVT = SrcEVT.getSimpleVT();
2718 MVT DestVT = DestEVT.getSimpleVT();
2719 unsigned ResultReg = ARMEmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2720 if (ResultReg == 0) return false;
2721 updateValueMap(I, ResultReg);
2725 bool ARMFastISel::SelectShift(const Instruction *I,
2726 ARM_AM::ShiftOpc ShiftTy) {
2727 // We handle thumb2 mode by target independent selector
2728 // or SelectionDAG ISel.
2732 // Only handle i32 now.
2733 EVT DestVT = TLI.getValueType(DL, I->getType(), true);
2734 if (DestVT != MVT::i32)
2737 unsigned Opc = ARM::MOVsr;
2739 Value *Src2Value = I->getOperand(1);
2740 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Src2Value)) {
2741 ShiftImm = CI->getZExtValue();
2743 // Fall back to selection DAG isel if the shift amount
2744 // is zero or greater than the width of the value type.
2745 if (ShiftImm == 0 || ShiftImm >=32)
2751 Value *Src1Value = I->getOperand(0);
2752 unsigned Reg1 = getRegForValue(Src1Value);
2753 if (Reg1 == 0) return false;
2756 if (Opc == ARM::MOVsr) {
2757 Reg2 = getRegForValue(Src2Value);
2758 if (Reg2 == 0) return false;
2761 unsigned ResultReg = createResultReg(&ARM::GPRnopcRegClass);
2762 if(ResultReg == 0) return false;
2764 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2765 TII.get(Opc), ResultReg)
2768 if (Opc == ARM::MOVsi)
2769 MIB.addImm(ARM_AM::getSORegOpc(ShiftTy, ShiftImm));
2770 else if (Opc == ARM::MOVsr) {
2772 MIB.addImm(ARM_AM::getSORegOpc(ShiftTy, 0));
2775 AddOptionalDefs(MIB);
2776 updateValueMap(I, ResultReg);
2780 // TODO: SoftFP support.
2781 bool ARMFastISel::fastSelectInstruction(const Instruction *I) {
2783 switch (I->getOpcode()) {
2784 case Instruction::Load:
2785 return SelectLoad(I);
2786 case Instruction::Store:
2787 return SelectStore(I);
2788 case Instruction::Br:
2789 return SelectBranch(I);
2790 case Instruction::IndirectBr:
2791 return SelectIndirectBr(I);
2792 case Instruction::ICmp:
2793 case Instruction::FCmp:
2794 return SelectCmp(I);
2795 case Instruction::FPExt:
2796 return SelectFPExt(I);
2797 case Instruction::FPTrunc:
2798 return SelectFPTrunc(I);
2799 case Instruction::SIToFP:
2800 return SelectIToFP(I, /*isSigned*/ true);
2801 case Instruction::UIToFP:
2802 return SelectIToFP(I, /*isSigned*/ false);
2803 case Instruction::FPToSI:
2804 return SelectFPToI(I, /*isSigned*/ true);
2805 case Instruction::FPToUI:
2806 return SelectFPToI(I, /*isSigned*/ false);
2807 case Instruction::Add:
2808 return SelectBinaryIntOp(I, ISD::ADD);
2809 case Instruction::Or:
2810 return SelectBinaryIntOp(I, ISD::OR);
2811 case Instruction::Sub:
2812 return SelectBinaryIntOp(I, ISD::SUB);
2813 case Instruction::FAdd:
2814 return SelectBinaryFPOp(I, ISD::FADD);
2815 case Instruction::FSub:
2816 return SelectBinaryFPOp(I, ISD::FSUB);
2817 case Instruction::FMul:
2818 return SelectBinaryFPOp(I, ISD::FMUL);
2819 case Instruction::SDiv:
2820 return SelectDiv(I, /*isSigned*/ true);
2821 case Instruction::UDiv:
2822 return SelectDiv(I, /*isSigned*/ false);
2823 case Instruction::SRem:
2824 return SelectRem(I, /*isSigned*/ true);
2825 case Instruction::URem:
2826 return SelectRem(I, /*isSigned*/ false);
2827 case Instruction::Call:
2828 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2829 return SelectIntrinsicCall(*II);
2830 return SelectCall(I);
2831 case Instruction::Select:
2832 return SelectSelect(I);
2833 case Instruction::Ret:
2834 return SelectRet(I);
2835 case Instruction::Trunc:
2836 return SelectTrunc(I);
2837 case Instruction::ZExt:
2838 case Instruction::SExt:
2839 return SelectIntExt(I);
2840 case Instruction::Shl:
2841 return SelectShift(I, ARM_AM::lsl);
2842 case Instruction::LShr:
2843 return SelectShift(I, ARM_AM::lsr);
2844 case Instruction::AShr:
2845 return SelectShift(I, ARM_AM::asr);
2852 // This table describes sign- and zero-extend instructions which can be
2853 // folded into a preceding load. All of these extends have an immediate
2854 // (sometimes a mask and sometimes a shift) that's applied after
2856 const struct FoldableLoadExtendsStruct {
2857 uint16_t Opc[2]; // ARM, Thumb.
2858 uint8_t ExpectedImm;
2860 uint8_t ExpectedVT : 7;
2861 } FoldableLoadExtends[] = {
2862 { { ARM::SXTH, ARM::t2SXTH }, 0, 0, MVT::i16 },
2863 { { ARM::UXTH, ARM::t2UXTH }, 0, 1, MVT::i16 },
2864 { { ARM::ANDri, ARM::t2ANDri }, 255, 1, MVT::i8 },
2865 { { ARM::SXTB, ARM::t2SXTB }, 0, 0, MVT::i8 },
2866 { { ARM::UXTB, ARM::t2UXTB }, 0, 1, MVT::i8 }
2870 /// \brief The specified machine instr operand is a vreg, and that
2871 /// vreg is being provided by the specified load instruction. If possible,
2872 /// try to fold the load as an operand to the instruction, returning true if
2874 bool ARMFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2875 const LoadInst *LI) {
2876 // Verify we have a legal type before going any further.
2878 if (!isLoadTypeLegal(LI->getType(), VT))
2881 // Combine load followed by zero- or sign-extend.
2882 // ldrb r1, [r0] ldrb r1, [r0]
2884 // mov r3, r2 mov r3, r1
2885 if (MI->getNumOperands() < 3 || !MI->getOperand(2).isImm())
2887 const uint64_t Imm = MI->getOperand(2).getImm();
2891 for (unsigned i = 0, e = array_lengthof(FoldableLoadExtends);
2893 if (FoldableLoadExtends[i].Opc[isThumb2] == MI->getOpcode() &&
2894 (uint64_t)FoldableLoadExtends[i].ExpectedImm == Imm &&
2895 MVT((MVT::SimpleValueType)FoldableLoadExtends[i].ExpectedVT) == VT) {
2897 isZExt = FoldableLoadExtends[i].isZExt;
2900 if (!Found) return false;
2902 // See if we can handle this address.
2904 if (!ARMComputeAddress(LI->getOperand(0), Addr)) return false;
2906 unsigned ResultReg = MI->getOperand(0).getReg();
2907 if (!ARMEmitLoad(VT, ResultReg, Addr, LI->getAlignment(), isZExt, false))
2909 MI->eraseFromParent();
2913 unsigned ARMFastISel::ARMLowerPICELF(const GlobalValue *GV,
2914 unsigned Align, MVT VT) {
2915 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
2917 LLVMContext *Context = &MF->getFunction()->getContext();
2918 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2919 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2920 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2921 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2922 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2923 /*AddCurrentAddress=*/UseGOT_PREL);
2925 unsigned ConstAlign =
2926 MF->getDataLayout().getPrefTypeAlignment(Type::getInt32PtrTy(*Context));
2927 unsigned Idx = MF->getConstantPool()->getConstantPoolIndex(CPV, ConstAlign);
2929 unsigned TempReg = MF->getRegInfo().createVirtualRegister(&ARM::rGPRRegClass);
2930 unsigned Opc = isThumb2 ? ARM::t2LDRpci : ARM::LDRcp;
2931 MachineInstrBuilder MIB =
2932 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), TempReg)
2933 .addConstantPoolIndex(Idx);
2934 if (Opc == ARM::LDRcp)
2936 AddDefaultPred(MIB);
2938 // Fix the address by adding pc.
2939 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
2940 Opc = Subtarget->isThumb() ? ARM::tPICADD : UseGOT_PREL ? ARM::PICLDR
2942 DestReg = constrainOperandRegClass(TII.get(Opc), DestReg, 0);
2943 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
2945 .addImm(ARMPCLabelIndex);
2946 if (!Subtarget->isThumb())
2947 AddDefaultPred(MIB);
2949 if (UseGOT_PREL && Subtarget->isThumb()) {
2950 unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
2951 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2952 TII.get(ARM::t2LDRi12), NewDestReg)
2955 DestReg = NewDestReg;
2956 AddOptionalDefs(MIB);
2961 bool ARMFastISel::fastLowerArguments() {
2962 if (!FuncInfo.CanLowerReturn)
2965 const Function *F = FuncInfo.Fn;
2969 CallingConv::ID CC = F->getCallingConv();
2973 case CallingConv::Fast:
2974 case CallingConv::C:
2975 case CallingConv::ARM_AAPCS_VFP:
2976 case CallingConv::ARM_AAPCS:
2977 case CallingConv::ARM_APCS:
2978 case CallingConv::Swift:
2982 // Only handle simple cases. i.e. Up to 4 i8/i16/i32 scalar arguments
2983 // which are passed in r0 - r3.
2985 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2986 I != E; ++I, ++Idx) {
2990 if (F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2991 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2992 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
2993 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
2994 F->getAttributes().hasAttribute(Idx, Attribute::ByVal))
2997 Type *ArgTy = I->getType();
2998 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3001 EVT ArgVT = TLI.getValueType(DL, ArgTy);
3002 if (!ArgVT.isSimple()) return false;
3003 switch (ArgVT.getSimpleVT().SimpleTy) {
3014 static const MCPhysReg GPRArgRegs[] = {
3015 ARM::R0, ARM::R1, ARM::R2, ARM::R3
3018 const TargetRegisterClass *RC = &ARM::rGPRRegClass;
3020 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
3021 I != E; ++I, ++Idx) {
3022 unsigned SrcReg = GPRArgRegs[Idx];
3023 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3024 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3025 // Without this, EmitLiveInCopies may eliminate the livein if its only
3026 // use is a bitcast (which isn't turned into an instruction).
3027 unsigned ResultReg = createResultReg(RC);
3028 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3029 TII.get(TargetOpcode::COPY),
3030 ResultReg).addReg(DstReg, getKillRegState(true));
3031 updateValueMap(&*I, ResultReg);
3038 FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo,
3039 const TargetLibraryInfo *libInfo) {
3040 if (funcInfo.MF->getSubtarget<ARMSubtarget>().useFastISel())
3041 return new ARMFastISel(funcInfo, libInfo);