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 "ARMBaseInstrInfo.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "MCTargetDesc/ARMAddressingModes.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/CodeGen/Analysis.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/CallingConv.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/Support/CallSite.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/GetElementPtrTypeIterator.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetLowering.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
52 extern cl::opt<bool> EnableARMLongCalls;
56 // All possible address modes, plus some.
57 typedef struct Address {
70 // Innocuous defaults for our address.
72 : BaseType(RegBase), Offset(0) {
77 class ARMFastISel : public FastISel {
79 /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
80 /// make the right decision when generating code for different targets.
81 const ARMSubtarget *Subtarget;
82 const TargetMachine &TM;
83 const TargetInstrInfo &TII;
84 const TargetLowering &TLI;
87 // Convenience variables to avoid some queries.
92 explicit ARMFastISel(FunctionLoweringInfo &funcInfo,
93 const TargetLibraryInfo *libInfo)
94 : FastISel(funcInfo, libInfo),
95 TM(funcInfo.MF->getTarget()),
96 TII(*TM.getInstrInfo()),
97 TLI(*TM.getTargetLowering()) {
98 Subtarget = &TM.getSubtarget<ARMSubtarget>();
99 AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
100 isThumb2 = AFI->isThumbFunction();
101 Context = &funcInfo.Fn->getContext();
104 // Code from FastISel.cpp.
106 unsigned FastEmitInst_(unsigned MachineInstOpcode,
107 const TargetRegisterClass *RC);
108 unsigned FastEmitInst_r(unsigned MachineInstOpcode,
109 const TargetRegisterClass *RC,
110 unsigned Op0, bool Op0IsKill);
111 unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
112 const TargetRegisterClass *RC,
113 unsigned Op0, bool Op0IsKill,
114 unsigned Op1, bool Op1IsKill);
115 unsigned FastEmitInst_rrr(unsigned MachineInstOpcode,
116 const TargetRegisterClass *RC,
117 unsigned Op0, bool Op0IsKill,
118 unsigned Op1, bool Op1IsKill,
119 unsigned Op2, bool Op2IsKill);
120 unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
121 const TargetRegisterClass *RC,
122 unsigned Op0, bool Op0IsKill,
124 unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
125 const TargetRegisterClass *RC,
126 unsigned Op0, bool Op0IsKill,
127 const ConstantFP *FPImm);
128 unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
129 const TargetRegisterClass *RC,
130 unsigned Op0, bool Op0IsKill,
131 unsigned Op1, bool Op1IsKill,
133 unsigned FastEmitInst_i(unsigned MachineInstOpcode,
134 const TargetRegisterClass *RC,
136 unsigned FastEmitInst_ii(unsigned MachineInstOpcode,
137 const TargetRegisterClass *RC,
138 uint64_t Imm1, uint64_t Imm2);
140 unsigned FastEmitInst_extractsubreg(MVT RetVT,
141 unsigned Op0, bool Op0IsKill,
144 // Backend specific FastISel code.
146 virtual bool TargetSelectInstruction(const Instruction *I);
147 virtual unsigned TargetMaterializeConstant(const Constant *C);
148 virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
149 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
151 virtual bool FastLowerArguments();
153 #include "ARMGenFastISel.inc"
155 // Instruction selection routines.
157 bool SelectLoad(const Instruction *I);
158 bool SelectStore(const Instruction *I);
159 bool SelectBranch(const Instruction *I);
160 bool SelectIndirectBr(const Instruction *I);
161 bool SelectCmp(const Instruction *I);
162 bool SelectFPExt(const Instruction *I);
163 bool SelectFPTrunc(const Instruction *I);
164 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
165 bool SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode);
166 bool SelectIToFP(const Instruction *I, bool isSigned);
167 bool SelectFPToI(const Instruction *I, bool isSigned);
168 bool SelectDiv(const Instruction *I, bool isSigned);
169 bool SelectRem(const Instruction *I, bool isSigned);
170 bool SelectCall(const Instruction *I, const char *IntrMemName);
171 bool SelectIntrinsicCall(const IntrinsicInst &I);
172 bool SelectSelect(const Instruction *I);
173 bool SelectRet(const Instruction *I);
174 bool SelectTrunc(const Instruction *I);
175 bool SelectIntExt(const Instruction *I);
176 bool SelectShift(const Instruction *I, ARM_AM::ShiftOpc ShiftTy);
180 bool isTypeLegal(Type *Ty, MVT &VT);
181 bool isLoadTypeLegal(Type *Ty, MVT &VT);
182 bool ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
184 bool ARMEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
185 unsigned Alignment = 0, bool isZExt = true,
186 bool allocReg = true);
187 bool ARMEmitStore(MVT VT, unsigned SrcReg, Address &Addr,
188 unsigned Alignment = 0);
189 bool ARMComputeAddress(const Value *Obj, Address &Addr);
190 void ARMSimplifyAddress(Address &Addr, MVT VT, bool useAM3);
191 bool ARMIsMemCpySmall(uint64_t Len);
192 bool ARMTryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
194 unsigned ARMEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
195 unsigned ARMMaterializeFP(const ConstantFP *CFP, MVT VT);
196 unsigned ARMMaterializeInt(const Constant *C, MVT VT);
197 unsigned ARMMaterializeGV(const GlobalValue *GV, MVT VT);
198 unsigned ARMMoveToFPReg(MVT VT, unsigned SrcReg);
199 unsigned ARMMoveToIntReg(MVT VT, unsigned SrcReg);
200 unsigned ARMSelectCallOp(bool UseReg);
201 unsigned ARMLowerPICELF(const GlobalValue *GV, unsigned Align, MVT VT);
203 // Call handling routines.
205 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC,
208 bool ProcessCallArgs(SmallVectorImpl<Value*> &Args,
209 SmallVectorImpl<unsigned> &ArgRegs,
210 SmallVectorImpl<MVT> &ArgVTs,
211 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
212 SmallVectorImpl<unsigned> &RegArgs,
216 unsigned getLibcallReg(const Twine &Name);
217 bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
218 const Instruction *I, CallingConv::ID CC,
219 unsigned &NumBytes, bool isVarArg);
220 bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
222 // OptionalDef handling routines.
224 bool isARMNEONPred(const MachineInstr *MI);
225 bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
226 const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
227 void AddLoadStoreOperands(MVT VT, Address &Addr,
228 const MachineInstrBuilder &MIB,
229 unsigned Flags, bool useAM3);
232 } // end anonymous namespace
234 #include "ARMGenCallingConv.inc"
236 // DefinesOptionalPredicate - This is different from DefinesPredicate in that
237 // we don't care about implicit defs here, just places we'll need to add a
238 // default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
239 bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
240 if (!MI->hasOptionalDef())
243 // Look to see if our OptionalDef is defining CPSR or CCR.
244 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
245 const MachineOperand &MO = MI->getOperand(i);
246 if (!MO.isReg() || !MO.isDef()) continue;
247 if (MO.getReg() == ARM::CPSR)
253 bool ARMFastISel::isARMNEONPred(const MachineInstr *MI) {
254 const MCInstrDesc &MCID = MI->getDesc();
256 // If we're a thumb2 or not NEON function we were handled via isPredicable.
257 if ((MCID.TSFlags & ARMII::DomainMask) != ARMII::DomainNEON ||
258 AFI->isThumb2Function())
261 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i)
262 if (MCID.OpInfo[i].isPredicate())
268 // If the machine is predicable go ahead and add the predicate operands, if
269 // it needs default CC operands add those.
270 // TODO: If we want to support thumb1 then we'll need to deal with optional
271 // CPSR defs that need to be added before the remaining operands. See s_cc_out
272 // for descriptions why.
273 const MachineInstrBuilder &
274 ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
275 MachineInstr *MI = &*MIB;
277 // Do we use a predicate? or...
278 // Are we NEON in ARM mode and have a predicate operand? If so, I know
279 // we're not predicable but add it anyways.
280 if (TII.isPredicable(MI) || isARMNEONPred(MI))
283 // Do we optionally set a predicate? Preds is size > 0 iff the predicate
284 // defines CPSR. All other OptionalDefines in ARM are the CCR register.
286 if (DefinesOptionalPredicate(MI, &CPSR)) {
295 unsigned ARMFastISel::FastEmitInst_(unsigned MachineInstOpcode,
296 const TargetRegisterClass* RC) {
297 unsigned ResultReg = createResultReg(RC);
298 const MCInstrDesc &II = TII.get(MachineInstOpcode);
300 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg));
304 unsigned ARMFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
305 const TargetRegisterClass *RC,
306 unsigned Op0, bool Op0IsKill) {
307 unsigned ResultReg = createResultReg(RC);
308 const MCInstrDesc &II = TII.get(MachineInstOpcode);
310 if (II.getNumDefs() >= 1) {
311 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
312 .addReg(Op0, Op0IsKill * RegState::Kill));
314 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
315 .addReg(Op0, Op0IsKill * RegState::Kill));
316 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
317 TII.get(TargetOpcode::COPY), ResultReg)
318 .addReg(II.ImplicitDefs[0]));
323 unsigned ARMFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
324 const TargetRegisterClass *RC,
325 unsigned Op0, bool Op0IsKill,
326 unsigned Op1, bool Op1IsKill) {
327 unsigned ResultReg = createResultReg(RC);
328 const MCInstrDesc &II = TII.get(MachineInstOpcode);
330 if (II.getNumDefs() >= 1) {
331 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
332 .addReg(Op0, Op0IsKill * RegState::Kill)
333 .addReg(Op1, Op1IsKill * RegState::Kill));
335 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
336 .addReg(Op0, Op0IsKill * RegState::Kill)
337 .addReg(Op1, Op1IsKill * RegState::Kill));
338 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
339 TII.get(TargetOpcode::COPY), ResultReg)
340 .addReg(II.ImplicitDefs[0]));
345 unsigned ARMFastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
346 const TargetRegisterClass *RC,
347 unsigned Op0, bool Op0IsKill,
348 unsigned Op1, bool Op1IsKill,
349 unsigned Op2, bool Op2IsKill) {
350 unsigned ResultReg = createResultReg(RC);
351 const MCInstrDesc &II = TII.get(MachineInstOpcode);
353 if (II.getNumDefs() >= 1) {
354 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
355 .addReg(Op0, Op0IsKill * RegState::Kill)
356 .addReg(Op1, Op1IsKill * RegState::Kill)
357 .addReg(Op2, Op2IsKill * RegState::Kill));
359 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
360 .addReg(Op0, Op0IsKill * RegState::Kill)
361 .addReg(Op1, Op1IsKill * RegState::Kill)
362 .addReg(Op2, Op2IsKill * RegState::Kill));
363 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
364 TII.get(TargetOpcode::COPY), ResultReg)
365 .addReg(II.ImplicitDefs[0]));
370 unsigned ARMFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
371 const TargetRegisterClass *RC,
372 unsigned Op0, bool Op0IsKill,
374 unsigned ResultReg = createResultReg(RC);
375 const MCInstrDesc &II = TII.get(MachineInstOpcode);
377 if (II.getNumDefs() >= 1) {
378 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
379 .addReg(Op0, Op0IsKill * RegState::Kill)
382 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
383 .addReg(Op0, Op0IsKill * RegState::Kill)
385 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
386 TII.get(TargetOpcode::COPY), ResultReg)
387 .addReg(II.ImplicitDefs[0]));
392 unsigned ARMFastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
393 const TargetRegisterClass *RC,
394 unsigned Op0, bool Op0IsKill,
395 const ConstantFP *FPImm) {
396 unsigned ResultReg = createResultReg(RC);
397 const MCInstrDesc &II = TII.get(MachineInstOpcode);
399 if (II.getNumDefs() >= 1) {
400 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
401 .addReg(Op0, Op0IsKill * RegState::Kill)
404 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
405 .addReg(Op0, Op0IsKill * RegState::Kill)
407 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
408 TII.get(TargetOpcode::COPY), ResultReg)
409 .addReg(II.ImplicitDefs[0]));
414 unsigned ARMFastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
415 const TargetRegisterClass *RC,
416 unsigned Op0, bool Op0IsKill,
417 unsigned Op1, bool Op1IsKill,
419 unsigned ResultReg = createResultReg(RC);
420 const MCInstrDesc &II = TII.get(MachineInstOpcode);
422 if (II.getNumDefs() >= 1) {
423 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
424 .addReg(Op0, Op0IsKill * RegState::Kill)
425 .addReg(Op1, Op1IsKill * RegState::Kill)
428 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
429 .addReg(Op0, Op0IsKill * RegState::Kill)
430 .addReg(Op1, Op1IsKill * RegState::Kill)
432 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
433 TII.get(TargetOpcode::COPY), ResultReg)
434 .addReg(II.ImplicitDefs[0]));
439 unsigned ARMFastISel::FastEmitInst_i(unsigned MachineInstOpcode,
440 const TargetRegisterClass *RC,
442 unsigned ResultReg = createResultReg(RC);
443 const MCInstrDesc &II = TII.get(MachineInstOpcode);
445 if (II.getNumDefs() >= 1) {
446 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
449 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
451 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
452 TII.get(TargetOpcode::COPY), ResultReg)
453 .addReg(II.ImplicitDefs[0]));
458 unsigned ARMFastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
459 const TargetRegisterClass *RC,
460 uint64_t Imm1, uint64_t Imm2) {
461 unsigned ResultReg = createResultReg(RC);
462 const MCInstrDesc &II = TII.get(MachineInstOpcode);
464 if (II.getNumDefs() >= 1) {
465 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
466 .addImm(Imm1).addImm(Imm2));
468 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
469 .addImm(Imm1).addImm(Imm2));
470 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
471 TII.get(TargetOpcode::COPY),
473 .addReg(II.ImplicitDefs[0]));
478 unsigned ARMFastISel::FastEmitInst_extractsubreg(MVT RetVT,
479 unsigned Op0, bool Op0IsKill,
481 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
482 assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
483 "Cannot yet extract from physregs");
485 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
486 DL, TII.get(TargetOpcode::COPY), ResultReg)
487 .addReg(Op0, getKillRegState(Op0IsKill), Idx));
491 // TODO: Don't worry about 64-bit now, but when this is fixed remove the
492 // checks from the various callers.
493 unsigned ARMFastISel::ARMMoveToFPReg(MVT VT, unsigned SrcReg) {
494 if (VT == MVT::f64) return 0;
496 unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
497 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
498 TII.get(ARM::VMOVSR), MoveReg)
503 unsigned ARMFastISel::ARMMoveToIntReg(MVT VT, unsigned SrcReg) {
504 if (VT == MVT::i64) return 0;
506 unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
507 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
508 TII.get(ARM::VMOVRS), MoveReg)
513 // For double width floating point we need to materialize two constants
514 // (the high and the low) into integer registers then use a move to get
515 // the combined constant into an FP reg.
516 unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, MVT VT) {
517 const APFloat Val = CFP->getValueAPF();
518 bool is64bit = VT == MVT::f64;
520 // This checks to see if we can use VFP3 instructions to materialize
521 // a constant, otherwise we have to go through the constant pool.
522 if (TLI.isFPImmLegal(Val, VT)) {
526 Imm = ARM_AM::getFP64Imm(Val);
529 Imm = ARM_AM::getFP32Imm(Val);
532 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
533 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
539 // Require VFP2 for loading fp constants.
540 if (!Subtarget->hasVFP2()) return false;
542 // MachineConstantPool wants an explicit alignment.
543 unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
545 // TODO: Figure out if this is correct.
546 Align = TD.getTypeAllocSize(CFP->getType());
548 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
549 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
550 unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
552 // The extra reg is for addrmode5.
553 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
555 .addConstantPoolIndex(Idx)
560 unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, MVT VT) {
562 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8 && VT != MVT::i1)
565 // If we can do this in a single instruction without a constant pool entry
567 const ConstantInt *CI = cast<ConstantInt>(C);
568 if (Subtarget->hasV6T2Ops() && isUInt<16>(CI->getZExtValue())) {
569 unsigned Opc = isThumb2 ? ARM::t2MOVi16 : ARM::MOVi16;
570 const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass :
572 unsigned ImmReg = createResultReg(RC);
573 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
574 TII.get(Opc), ImmReg)
575 .addImm(CI->getZExtValue()));
579 // Use MVN to emit negative constants.
580 if (VT == MVT::i32 && Subtarget->hasV6T2Ops() && CI->isNegative()) {
581 unsigned Imm = (unsigned)~(CI->getSExtValue());
582 bool UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
583 (ARM_AM::getSOImmVal(Imm) != -1);
585 unsigned Opc = isThumb2 ? ARM::t2MVNi : ARM::MVNi;
586 unsigned ImmReg = createResultReg(TLI.getRegClassFor(MVT::i32));
587 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
588 TII.get(Opc), ImmReg)
594 // Load from constant pool. For now 32-bit only.
598 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
600 // MachineConstantPool wants an explicit alignment.
601 unsigned Align = TD.getPrefTypeAlignment(C->getType());
603 // TODO: Figure out if this is correct.
604 Align = TD.getTypeAllocSize(C->getType());
606 unsigned Idx = MCP.getConstantPoolIndex(C, Align);
609 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
610 TII.get(ARM::t2LDRpci), DestReg)
611 .addConstantPoolIndex(Idx));
613 // The extra immediate is for addrmode2.
614 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
615 TII.get(ARM::LDRcp), DestReg)
616 .addConstantPoolIndex(Idx)
622 unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, MVT VT) {
623 // For now 32-bit only.
624 if (VT != MVT::i32) return 0;
626 Reloc::Model RelocM = TM.getRelocationModel();
627 bool IsIndirect = Subtarget->GVIsIndirectSymbol(GV, RelocM);
628 const TargetRegisterClass *RC = isThumb2 ?
629 (const TargetRegisterClass*)&ARM::rGPRRegClass :
630 (const TargetRegisterClass*)&ARM::GPRRegClass;
631 unsigned DestReg = createResultReg(RC);
633 // Use movw+movt when possible, it avoids constant pool entries.
634 // Darwin targets don't support movt with Reloc::Static, see
635 // ARMTargetLowering::LowerGlobalAddressDarwin. Other targets only support
636 // static movt relocations.
637 if (Subtarget->useMovt() &&
638 Subtarget->isTargetDarwin() == (RelocM != Reloc::Static)) {
642 Opc = isThumb2 ? ARM::t2MOV_ga_pcrel : ARM::MOV_ga_pcrel;
644 case Reloc::DynamicNoPIC:
645 Opc = isThumb2 ? ARM::t2MOV_ga_dyn : ARM::MOV_ga_dyn;
648 Opc = isThumb2 ? ARM::t2MOVi32imm : ARM::MOVi32imm;
651 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
652 DestReg).addGlobalAddress(GV));
654 // MachineConstantPool wants an explicit alignment.
655 unsigned Align = TD.getPrefTypeAlignment(GV->getType());
657 // TODO: Figure out if this is correct.
658 Align = TD.getTypeAllocSize(GV->getType());
661 if (Subtarget->isTargetELF() && RelocM == Reloc::PIC_)
662 return ARMLowerPICELF(GV, Align, VT);
665 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 :
666 (Subtarget->isThumb() ? 4 : 8);
667 unsigned Id = AFI->createPICLabelUId();
668 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(GV, Id,
671 unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
674 MachineInstrBuilder MIB;
676 unsigned Opc = (RelocM!=Reloc::PIC_) ? ARM::t2LDRpci : ARM::t2LDRpci_pic;
677 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
678 .addConstantPoolIndex(Idx);
679 if (RelocM == Reloc::PIC_)
681 AddOptionalDefs(MIB);
683 // The extra immediate is for addrmode2.
684 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRcp),
686 .addConstantPoolIndex(Idx)
688 AddOptionalDefs(MIB);
690 if (RelocM == Reloc::PIC_) {
691 unsigned Opc = IsIndirect ? ARM::PICLDR : ARM::PICADD;
692 unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
694 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
695 DL, TII.get(Opc), NewDestReg)
698 AddOptionalDefs(MIB);
705 MachineInstrBuilder MIB;
706 unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
708 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
709 TII.get(ARM::t2LDRi12), NewDestReg)
713 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRi12),
717 DestReg = NewDestReg;
718 AddOptionalDefs(MIB);
724 unsigned ARMFastISel::TargetMaterializeConstant(const Constant *C) {
725 EVT CEVT = TLI.getValueType(C->getType(), true);
727 // Only handle simple types.
728 if (!CEVT.isSimple()) return 0;
729 MVT VT = CEVT.getSimpleVT();
731 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
732 return ARMMaterializeFP(CFP, VT);
733 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
734 return ARMMaterializeGV(GV, VT);
735 else if (isa<ConstantInt>(C))
736 return ARMMaterializeInt(C, VT);
741 // TODO: unsigned ARMFastISel::TargetMaterializeFloatZero(const ConstantFP *CF);
743 unsigned ARMFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
744 // Don't handle dynamic allocas.
745 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
748 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
750 DenseMap<const AllocaInst*, int>::iterator SI =
751 FuncInfo.StaticAllocaMap.find(AI);
753 // This will get lowered later into the correct offsets and registers
754 // via rewriteXFrameIndex.
755 if (SI != FuncInfo.StaticAllocaMap.end()) {
756 const TargetRegisterClass* RC = TLI.getRegClassFor(VT);
757 unsigned ResultReg = createResultReg(RC);
758 unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
759 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
760 TII.get(Opc), ResultReg)
761 .addFrameIndex(SI->second)
769 bool ARMFastISel::isTypeLegal(Type *Ty, MVT &VT) {
770 EVT evt = TLI.getValueType(Ty, true);
772 // Only handle simple types.
773 if (evt == MVT::Other || !evt.isSimple()) return false;
774 VT = evt.getSimpleVT();
776 // Handle all legal types, i.e. a register that will directly hold this
778 return TLI.isTypeLegal(VT);
781 bool ARMFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
782 if (isTypeLegal(Ty, VT)) return true;
784 // If this is a type than can be sign or zero-extended to a basic operation
785 // go ahead and accept it now.
786 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
792 // Computes the address to get to an object.
793 bool ARMFastISel::ARMComputeAddress(const Value *Obj, Address &Addr) {
794 // Some boilerplate from the X86 FastISel.
795 const User *U = NULL;
796 unsigned Opcode = Instruction::UserOp1;
797 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
798 // Don't walk into other basic blocks unless the object is an alloca from
799 // another block, otherwise it may not have a virtual register assigned.
800 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
801 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
802 Opcode = I->getOpcode();
805 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
806 Opcode = C->getOpcode();
810 if (PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
811 if (Ty->getAddressSpace() > 255)
812 // Fast instruction selection doesn't support the special
819 case Instruction::BitCast: {
820 // Look through bitcasts.
821 return ARMComputeAddress(U->getOperand(0), Addr);
823 case Instruction::IntToPtr: {
824 // Look past no-op inttoptrs.
825 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
826 return ARMComputeAddress(U->getOperand(0), Addr);
829 case Instruction::PtrToInt: {
830 // Look past no-op ptrtoints.
831 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
832 return ARMComputeAddress(U->getOperand(0), Addr);
835 case Instruction::GetElementPtr: {
836 Address SavedAddr = Addr;
837 int TmpOffset = Addr.Offset;
839 // Iterate through the GEP folding the constants into offsets where
841 gep_type_iterator GTI = gep_type_begin(U);
842 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
843 i != e; ++i, ++GTI) {
844 const Value *Op = *i;
845 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
846 const StructLayout *SL = TD.getStructLayout(STy);
847 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
848 TmpOffset += SL->getElementOffset(Idx);
850 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
852 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
853 // Constant-offset addressing.
854 TmpOffset += CI->getSExtValue() * S;
857 if (isa<AddOperator>(Op) &&
858 (!isa<Instruction>(Op) ||
859 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
861 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
862 // An add (in the same block) with a constant operand. Fold the
865 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
866 TmpOffset += CI->getSExtValue() * S;
867 // Iterate on the other operand.
868 Op = cast<AddOperator>(Op)->getOperand(0);
872 goto unsupported_gep;
877 // Try to grab the base operand now.
878 Addr.Offset = TmpOffset;
879 if (ARMComputeAddress(U->getOperand(0), Addr)) return true;
881 // We failed, restore everything and try the other options.
887 case Instruction::Alloca: {
888 const AllocaInst *AI = cast<AllocaInst>(Obj);
889 DenseMap<const AllocaInst*, int>::iterator SI =
890 FuncInfo.StaticAllocaMap.find(AI);
891 if (SI != FuncInfo.StaticAllocaMap.end()) {
892 Addr.BaseType = Address::FrameIndexBase;
893 Addr.Base.FI = SI->second;
900 // Try to get this in a register if nothing else has worked.
901 if (Addr.Base.Reg == 0) Addr.Base.Reg = getRegForValue(Obj);
902 return Addr.Base.Reg != 0;
905 void ARMFastISel::ARMSimplifyAddress(Address &Addr, MVT VT, bool useAM3) {
906 bool needsLowering = false;
907 switch (VT.SimpleTy) {
908 default: llvm_unreachable("Unhandled load/store type!");
914 // Integer loads/stores handle 12-bit offsets.
915 needsLowering = ((Addr.Offset & 0xfff) != Addr.Offset);
916 // Handle negative offsets.
917 if (needsLowering && isThumb2)
918 needsLowering = !(Subtarget->hasV6T2Ops() && Addr.Offset < 0 &&
921 // ARM halfword load/stores and signed byte loads use +/-imm8 offsets.
922 needsLowering = (Addr.Offset > 255 || Addr.Offset < -255);
927 // Floating point operands handle 8-bit offsets.
928 needsLowering = ((Addr.Offset & 0xff) != Addr.Offset);
932 // If this is a stack pointer and the offset needs to be simplified then
933 // put the alloca address into a register, set the base type back to
934 // register and continue. This should almost never happen.
935 if (needsLowering && Addr.BaseType == Address::FrameIndexBase) {
936 const TargetRegisterClass *RC = isThumb2 ?
937 (const TargetRegisterClass*)&ARM::tGPRRegClass :
938 (const TargetRegisterClass*)&ARM::GPRRegClass;
939 unsigned ResultReg = createResultReg(RC);
940 unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
941 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
942 TII.get(Opc), ResultReg)
943 .addFrameIndex(Addr.Base.FI)
945 Addr.Base.Reg = ResultReg;
946 Addr.BaseType = Address::RegBase;
949 // Since the offset is too large for the load/store instruction
950 // get the reg+offset into a register.
952 Addr.Base.Reg = FastEmit_ri_(MVT::i32, ISD::ADD, Addr.Base.Reg,
953 /*Op0IsKill*/false, Addr.Offset, MVT::i32);
958 void ARMFastISel::AddLoadStoreOperands(MVT VT, Address &Addr,
959 const MachineInstrBuilder &MIB,
960 unsigned Flags, bool useAM3) {
961 // addrmode5 output depends on the selection dag addressing dividing the
962 // offset by 4 that it then later multiplies. Do this here as well.
963 if (VT.SimpleTy == MVT::f32 || VT.SimpleTy == MVT::f64)
966 // Frame base works a bit differently. Handle it separately.
967 if (Addr.BaseType == Address::FrameIndexBase) {
968 int FI = Addr.Base.FI;
969 int Offset = Addr.Offset;
970 MachineMemOperand *MMO =
971 FuncInfo.MF->getMachineMemOperand(
972 MachinePointerInfo::getFixedStack(FI, Offset),
974 MFI.getObjectSize(FI),
975 MFI.getObjectAlignment(FI));
976 // Now add the rest of the operands.
977 MIB.addFrameIndex(FI);
979 // ARM halfword load/stores and signed byte loads need an additional
982 signed Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
986 MIB.addImm(Addr.Offset);
988 MIB.addMemOperand(MMO);
990 // Now add the rest of the operands.
991 MIB.addReg(Addr.Base.Reg);
993 // ARM halfword load/stores and signed byte loads need an additional
996 signed Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
1000 MIB.addImm(Addr.Offset);
1003 AddOptionalDefs(MIB);
1006 bool ARMFastISel::ARMEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
1007 unsigned Alignment, bool isZExt, bool allocReg) {
1009 bool useAM3 = false;
1010 bool needVMOV = false;
1011 const TargetRegisterClass *RC;
1012 switch (VT.SimpleTy) {
1013 // This is mostly going to be Neon/vector support.
1014 default: return false;
1018 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1019 Opc = isZExt ? ARM::t2LDRBi8 : ARM::t2LDRSBi8;
1021 Opc = isZExt ? ARM::t2LDRBi12 : ARM::t2LDRSBi12;
1030 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
1033 if (Alignment && Alignment < 2 && !Subtarget->allowsUnalignedMem())
1037 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1038 Opc = isZExt ? ARM::t2LDRHi8 : ARM::t2LDRSHi8;
1040 Opc = isZExt ? ARM::t2LDRHi12 : ARM::t2LDRSHi12;
1042 Opc = isZExt ? ARM::LDRH : ARM::LDRSH;
1045 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
1048 if (Alignment && Alignment < 4 && !Subtarget->allowsUnalignedMem())
1052 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1055 Opc = ARM::t2LDRi12;
1059 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
1062 if (!Subtarget->hasVFP2()) return false;
1063 // Unaligned loads need special handling. Floats require word-alignment.
1064 if (Alignment && Alignment < 4) {
1067 Opc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
1068 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
1071 RC = TLI.getRegClassFor(VT);
1075 if (!Subtarget->hasVFP2()) return false;
1076 // FIXME: Unaligned loads need special handling. Doublewords require
1078 if (Alignment && Alignment < 4)
1082 RC = TLI.getRegClassFor(VT);
1085 // Simplify this down to something we can handle.
1086 ARMSimplifyAddress(Addr, VT, useAM3);
1088 // Create the base instruction, then add the operands.
1090 ResultReg = createResultReg(RC);
1091 assert (ResultReg > 255 && "Expected an allocated virtual register.");
1092 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1093 TII.get(Opc), ResultReg);
1094 AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOLoad, useAM3);
1096 // If we had an unaligned load of a float we've converted it to an regular
1097 // load. Now we must move from the GRP to the FP register.
1099 unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1100 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1101 TII.get(ARM::VMOVSR), MoveReg)
1102 .addReg(ResultReg));
1103 ResultReg = MoveReg;
1108 bool ARMFastISel::SelectLoad(const Instruction *I) {
1109 // Atomic loads need special handling.
1110 if (cast<LoadInst>(I)->isAtomic())
1113 // Verify we have a legal type before going any further.
1115 if (!isLoadTypeLegal(I->getType(), VT))
1118 // See if we can handle this address.
1120 if (!ARMComputeAddress(I->getOperand(0), Addr)) return false;
1123 if (!ARMEmitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
1125 UpdateValueMap(I, ResultReg);
1129 bool ARMFastISel::ARMEmitStore(MVT VT, unsigned SrcReg, Address &Addr,
1130 unsigned Alignment) {
1132 bool useAM3 = false;
1133 switch (VT.SimpleTy) {
1134 // This is mostly going to be Neon/vector support.
1135 default: return false;
1137 unsigned Res = createResultReg(isThumb2 ?
1138 (const TargetRegisterClass*)&ARM::tGPRRegClass :
1139 (const TargetRegisterClass*)&ARM::GPRRegClass);
1140 unsigned Opc = isThumb2 ? ARM::t2ANDri : ARM::ANDri;
1141 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1143 .addReg(SrcReg).addImm(1));
1145 } // Fallthrough here.
1148 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1149 StrOpc = ARM::t2STRBi8;
1151 StrOpc = ARM::t2STRBi12;
1153 StrOpc = ARM::STRBi12;
1157 if (Alignment && Alignment < 2 && !Subtarget->allowsUnalignedMem())
1161 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1162 StrOpc = ARM::t2STRHi8;
1164 StrOpc = ARM::t2STRHi12;
1171 if (Alignment && Alignment < 4 && !Subtarget->allowsUnalignedMem())
1175 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1176 StrOpc = ARM::t2STRi8;
1178 StrOpc = ARM::t2STRi12;
1180 StrOpc = ARM::STRi12;
1184 if (!Subtarget->hasVFP2()) return false;
1185 // Unaligned stores need special handling. Floats require word-alignment.
1186 if (Alignment && Alignment < 4) {
1187 unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::i32));
1188 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1189 TII.get(ARM::VMOVRS), MoveReg)
1193 StrOpc = isThumb2 ? ARM::t2STRi12 : ARM::STRi12;
1195 StrOpc = ARM::VSTRS;
1199 if (!Subtarget->hasVFP2()) return false;
1200 // FIXME: Unaligned stores need special handling. Doublewords require
1202 if (Alignment && Alignment < 4)
1205 StrOpc = ARM::VSTRD;
1208 // Simplify this down to something we can handle.
1209 ARMSimplifyAddress(Addr, VT, useAM3);
1211 // Create the base instruction, then add the operands.
1212 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1215 AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOStore, useAM3);
1219 bool ARMFastISel::SelectStore(const Instruction *I) {
1220 Value *Op0 = I->getOperand(0);
1221 unsigned SrcReg = 0;
1223 // Atomic stores need special handling.
1224 if (cast<StoreInst>(I)->isAtomic())
1227 // Verify we have a legal type before going any further.
1229 if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
1232 // Get the value to be stored into a register.
1233 SrcReg = getRegForValue(Op0);
1234 if (SrcReg == 0) return false;
1236 // See if we can handle this address.
1238 if (!ARMComputeAddress(I->getOperand(1), Addr))
1241 if (!ARMEmitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
1246 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
1248 // Needs two compares...
1249 case CmpInst::FCMP_ONE:
1250 case CmpInst::FCMP_UEQ:
1252 // AL is our "false" for now. The other two need more compares.
1254 case CmpInst::ICMP_EQ:
1255 case CmpInst::FCMP_OEQ:
1257 case CmpInst::ICMP_SGT:
1258 case CmpInst::FCMP_OGT:
1260 case CmpInst::ICMP_SGE:
1261 case CmpInst::FCMP_OGE:
1263 case CmpInst::ICMP_UGT:
1264 case CmpInst::FCMP_UGT:
1266 case CmpInst::FCMP_OLT:
1268 case CmpInst::ICMP_ULE:
1269 case CmpInst::FCMP_OLE:
1271 case CmpInst::FCMP_ORD:
1273 case CmpInst::FCMP_UNO:
1275 case CmpInst::FCMP_UGE:
1277 case CmpInst::ICMP_SLT:
1278 case CmpInst::FCMP_ULT:
1280 case CmpInst::ICMP_SLE:
1281 case CmpInst::FCMP_ULE:
1283 case CmpInst::FCMP_UNE:
1284 case CmpInst::ICMP_NE:
1286 case CmpInst::ICMP_UGE:
1288 case CmpInst::ICMP_ULT:
1293 bool ARMFastISel::SelectBranch(const Instruction *I) {
1294 const BranchInst *BI = cast<BranchInst>(I);
1295 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1296 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1298 // Simple branch support.
1300 // If we can, avoid recomputing the compare - redoing it could lead to wonky
1302 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1303 if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
1305 // Get the compare predicate.
1306 // Try to take advantage of fallthrough opportunities.
1307 CmpInst::Predicate Predicate = CI->getPredicate();
1308 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1309 std::swap(TBB, FBB);
1310 Predicate = CmpInst::getInversePredicate(Predicate);
1313 ARMCC::CondCodes ARMPred = getComparePred(Predicate);
1315 // We may not handle every CC for now.
1316 if (ARMPred == ARMCC::AL) return false;
1318 // Emit the compare.
1319 if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1322 unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1323 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1324 .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
1325 FastEmitBranch(FBB, DL);
1326 FuncInfo.MBB->addSuccessor(TBB);
1329 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1331 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1332 (isLoadTypeLegal(TI->getOperand(0)->getType(), SourceVT))) {
1333 unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1334 unsigned OpReg = getRegForValue(TI->getOperand(0));
1335 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1337 .addReg(OpReg).addImm(1));
1339 unsigned CCMode = ARMCC::NE;
1340 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1341 std::swap(TBB, FBB);
1345 unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1346 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1347 .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1349 FastEmitBranch(FBB, DL);
1350 FuncInfo.MBB->addSuccessor(TBB);
1353 } else if (const ConstantInt *CI =
1354 dyn_cast<ConstantInt>(BI->getCondition())) {
1355 uint64_t Imm = CI->getZExtValue();
1356 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1357 FastEmitBranch(Target, DL);
1361 unsigned CmpReg = getRegForValue(BI->getCondition());
1362 if (CmpReg == 0) return false;
1364 // We've been divorced from our compare! Our block was split, and
1365 // now our compare lives in a predecessor block. We musn't
1366 // re-compare here, as the children of the compare aren't guaranteed
1367 // live across the block boundary (we *could* check for this).
1368 // Regardless, the compare has been done in the predecessor block,
1369 // and it left a value for us in a virtual register. Ergo, we test
1370 // the one-bit value left in the virtual register.
1371 unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1372 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TstOpc))
1373 .addReg(CmpReg).addImm(1));
1375 unsigned CCMode = ARMCC::NE;
1376 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1377 std::swap(TBB, FBB);
1381 unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1382 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1383 .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1384 FastEmitBranch(FBB, DL);
1385 FuncInfo.MBB->addSuccessor(TBB);
1389 bool ARMFastISel::SelectIndirectBr(const Instruction *I) {
1390 unsigned AddrReg = getRegForValue(I->getOperand(0));
1391 if (AddrReg == 0) return false;
1393 unsigned Opc = isThumb2 ? ARM::tBRIND : ARM::BX;
1394 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
1397 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1398 for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1399 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1404 bool ARMFastISel::ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
1406 Type *Ty = Src1Value->getType();
1407 EVT SrcEVT = TLI.getValueType(Ty, true);
1408 if (!SrcEVT.isSimple()) return false;
1409 MVT SrcVT = SrcEVT.getSimpleVT();
1411 bool isFloat = (Ty->isFloatTy() || Ty->isDoubleTy());
1412 if (isFloat && !Subtarget->hasVFP2())
1415 // Check to see if the 2nd operand is a constant that we can encode directly
1418 bool UseImm = false;
1419 bool isNegativeImm = false;
1420 // FIXME: At -O0 we don't have anything that canonicalizes operand order.
1421 // Thus, Src1Value may be a ConstantInt, but we're missing it.
1422 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
1423 if (SrcVT == MVT::i32 || SrcVT == MVT::i16 || SrcVT == MVT::i8 ||
1425 const APInt &CIVal = ConstInt->getValue();
1426 Imm = (isZExt) ? (int)CIVal.getZExtValue() : (int)CIVal.getSExtValue();
1427 // For INT_MIN/LONG_MIN (i.e., 0x80000000) we need to use a cmp, rather
1428 // then a cmn, because there is no way to represent 2147483648 as a
1429 // signed 32-bit int.
1430 if (Imm < 0 && Imm != (int)0x80000000) {
1431 isNegativeImm = true;
1434 UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1435 (ARM_AM::getSOImmVal(Imm) != -1);
1437 } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
1438 if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
1439 if (ConstFP->isZero() && !ConstFP->isNegative())
1445 bool needsExt = false;
1446 switch (SrcVT.SimpleTy) {
1447 default: return false;
1448 // TODO: Verify compares.
1451 CmpOpc = UseImm ? ARM::VCMPEZS : ARM::VCMPES;
1455 CmpOpc = UseImm ? ARM::VCMPEZD : ARM::VCMPED;
1461 // Intentional fall-through.
1465 CmpOpc = ARM::t2CMPrr;
1467 CmpOpc = isNegativeImm ? ARM::t2CMNri : ARM::t2CMPri;
1470 CmpOpc = ARM::CMPrr;
1472 CmpOpc = isNegativeImm ? ARM::CMNri : ARM::CMPri;
1477 unsigned SrcReg1 = getRegForValue(Src1Value);
1478 if (SrcReg1 == 0) return false;
1480 unsigned SrcReg2 = 0;
1482 SrcReg2 = getRegForValue(Src2Value);
1483 if (SrcReg2 == 0) return false;
1486 // We have i1, i8, or i16, we need to either zero extend or sign extend.
1488 SrcReg1 = ARMEmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
1489 if (SrcReg1 == 0) return false;
1491 SrcReg2 = ARMEmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
1492 if (SrcReg2 == 0) return false;
1497 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1499 .addReg(SrcReg1).addReg(SrcReg2));
1501 MachineInstrBuilder MIB;
1502 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1505 // Only add immediate for icmp as the immediate for fcmp is an implicit 0.0.
1508 AddOptionalDefs(MIB);
1511 // For floating point we need to move the result to a comparison register
1512 // that we can then use for branches.
1513 if (Ty->isFloatTy() || Ty->isDoubleTy())
1514 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1515 TII.get(ARM::FMSTAT)));
1519 bool ARMFastISel::SelectCmp(const Instruction *I) {
1520 const CmpInst *CI = cast<CmpInst>(I);
1522 // Get the compare predicate.
1523 ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1525 // We may not handle every CC for now.
1526 if (ARMPred == ARMCC::AL) return false;
1528 // Emit the compare.
1529 if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1532 // Now set a register based on the comparison. Explicitly set the predicates
1534 unsigned MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1535 const TargetRegisterClass *RC = isThumb2 ?
1536 (const TargetRegisterClass*)&ARM::rGPRRegClass :
1537 (const TargetRegisterClass*)&ARM::GPRRegClass;
1538 unsigned DestReg = createResultReg(RC);
1539 Constant *Zero = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1540 unsigned ZeroReg = TargetMaterializeConstant(Zero);
1541 // ARMEmitCmp emits a FMSTAT when necessary, so it's always safe to use CPSR.
1542 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
1543 .addReg(ZeroReg).addImm(1)
1544 .addImm(ARMPred).addReg(ARM::CPSR);
1546 UpdateValueMap(I, DestReg);
1550 bool ARMFastISel::SelectFPExt(const Instruction *I) {
1551 // Make sure we have VFP and that we're extending float to double.
1552 if (!Subtarget->hasVFP2()) return false;
1554 Value *V = I->getOperand(0);
1555 if (!I->getType()->isDoubleTy() ||
1556 !V->getType()->isFloatTy()) return false;
1558 unsigned Op = getRegForValue(V);
1559 if (Op == 0) return false;
1561 unsigned Result = createResultReg(&ARM::DPRRegClass);
1562 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1563 TII.get(ARM::VCVTDS), Result)
1565 UpdateValueMap(I, Result);
1569 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1570 // Make sure we have VFP and that we're truncating double to float.
1571 if (!Subtarget->hasVFP2()) return false;
1573 Value *V = I->getOperand(0);
1574 if (!(I->getType()->isFloatTy() &&
1575 V->getType()->isDoubleTy())) return false;
1577 unsigned Op = getRegForValue(V);
1578 if (Op == 0) return false;
1580 unsigned Result = createResultReg(&ARM::SPRRegClass);
1581 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1582 TII.get(ARM::VCVTSD), Result)
1584 UpdateValueMap(I, Result);
1588 bool ARMFastISel::SelectIToFP(const Instruction *I, bool isSigned) {
1589 // Make sure we have VFP.
1590 if (!Subtarget->hasVFP2()) return false;
1593 Type *Ty = I->getType();
1594 if (!isTypeLegal(Ty, DstVT))
1597 Value *Src = I->getOperand(0);
1598 EVT SrcEVT = TLI.getValueType(Src->getType(), true);
1599 if (!SrcEVT.isSimple())
1601 MVT SrcVT = SrcEVT.getSimpleVT();
1602 if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
1605 unsigned SrcReg = getRegForValue(Src);
1606 if (SrcReg == 0) return false;
1608 // Handle sign-extension.
1609 if (SrcVT == MVT::i16 || SrcVT == MVT::i8) {
1610 SrcReg = ARMEmitIntExt(SrcVT, SrcReg, MVT::i32,
1611 /*isZExt*/!isSigned);
1612 if (SrcReg == 0) return false;
1615 // The conversion routine works on fp-reg to fp-reg and the operand above
1616 // was an integer, move it to the fp registers if possible.
1617 unsigned FP = ARMMoveToFPReg(MVT::f32, SrcReg);
1618 if (FP == 0) return false;
1621 if (Ty->isFloatTy()) Opc = isSigned ? ARM::VSITOS : ARM::VUITOS;
1622 else if (Ty->isDoubleTy()) Opc = isSigned ? ARM::VSITOD : ARM::VUITOD;
1625 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1626 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1629 UpdateValueMap(I, ResultReg);
1633 bool ARMFastISel::SelectFPToI(const Instruction *I, bool isSigned) {
1634 // Make sure we have VFP.
1635 if (!Subtarget->hasVFP2()) return false;
1638 Type *RetTy = I->getType();
1639 if (!isTypeLegal(RetTy, DstVT))
1642 unsigned Op = getRegForValue(I->getOperand(0));
1643 if (Op == 0) return false;
1646 Type *OpTy = I->getOperand(0)->getType();
1647 if (OpTy->isFloatTy()) Opc = isSigned ? ARM::VTOSIZS : ARM::VTOUIZS;
1648 else if (OpTy->isDoubleTy()) Opc = isSigned ? ARM::VTOSIZD : ARM::VTOUIZD;
1651 // f64->s32/u32 or f32->s32/u32 both need an intermediate f32 reg.
1652 unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1653 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1657 // This result needs to be in an integer register, but the conversion only
1658 // takes place in fp-regs.
1659 unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1660 if (IntReg == 0) return false;
1662 UpdateValueMap(I, IntReg);
1666 bool ARMFastISel::SelectSelect(const Instruction *I) {
1668 if (!isTypeLegal(I->getType(), VT))
1671 // Things need to be register sized for register moves.
1672 if (VT != MVT::i32) return false;
1674 unsigned CondReg = getRegForValue(I->getOperand(0));
1675 if (CondReg == 0) return false;
1676 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1677 if (Op1Reg == 0) return false;
1679 // Check to see if we can use an immediate in the conditional move.
1681 bool UseImm = false;
1682 bool isNegativeImm = false;
1683 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(2))) {
1684 assert (VT == MVT::i32 && "Expecting an i32.");
1685 Imm = (int)ConstInt->getValue().getZExtValue();
1687 isNegativeImm = true;
1690 UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1691 (ARM_AM::getSOImmVal(Imm) != -1);
1694 unsigned Op2Reg = 0;
1696 Op2Reg = getRegForValue(I->getOperand(2));
1697 if (Op2Reg == 0) return false;
1700 unsigned CmpOpc = isThumb2 ? ARM::t2CMPri : ARM::CMPri;
1701 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1702 .addReg(CondReg).addImm(0));
1705 const TargetRegisterClass *RC;
1707 RC = isThumb2 ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
1708 MovCCOpc = isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr;
1710 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass;
1712 MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1714 MovCCOpc = isThumb2 ? ARM::t2MVNCCi : ARM::MVNCCi;
1716 unsigned ResultReg = createResultReg(RC);
1718 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1719 .addReg(Op2Reg).addReg(Op1Reg).addImm(ARMCC::NE).addReg(ARM::CPSR);
1721 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1722 .addReg(Op1Reg).addImm(Imm).addImm(ARMCC::EQ).addReg(ARM::CPSR);
1723 UpdateValueMap(I, ResultReg);
1727 bool ARMFastISel::SelectDiv(const Instruction *I, bool isSigned) {
1729 Type *Ty = I->getType();
1730 if (!isTypeLegal(Ty, VT))
1733 // If we have integer div support we should have selected this automagically.
1734 // In case we have a real miss go ahead and return false and we'll pick
1736 if (Subtarget->hasDivide()) return false;
1738 // Otherwise emit a libcall.
1739 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1741 LC = isSigned ? RTLIB::SDIV_I8 : RTLIB::UDIV_I8;
1742 else if (VT == MVT::i16)
1743 LC = isSigned ? RTLIB::SDIV_I16 : RTLIB::UDIV_I16;
1744 else if (VT == MVT::i32)
1745 LC = isSigned ? RTLIB::SDIV_I32 : RTLIB::UDIV_I32;
1746 else if (VT == MVT::i64)
1747 LC = isSigned ? RTLIB::SDIV_I64 : RTLIB::UDIV_I64;
1748 else if (VT == MVT::i128)
1749 LC = isSigned ? RTLIB::SDIV_I128 : RTLIB::UDIV_I128;
1750 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1752 return ARMEmitLibcall(I, LC);
1755 bool ARMFastISel::SelectRem(const Instruction *I, bool isSigned) {
1757 Type *Ty = I->getType();
1758 if (!isTypeLegal(Ty, VT))
1761 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1763 LC = isSigned ? RTLIB::SREM_I8 : RTLIB::UREM_I8;
1764 else if (VT == MVT::i16)
1765 LC = isSigned ? RTLIB::SREM_I16 : RTLIB::UREM_I16;
1766 else if (VT == MVT::i32)
1767 LC = isSigned ? RTLIB::SREM_I32 : RTLIB::UREM_I32;
1768 else if (VT == MVT::i64)
1769 LC = isSigned ? RTLIB::SREM_I64 : RTLIB::UREM_I64;
1770 else if (VT == MVT::i128)
1771 LC = isSigned ? RTLIB::SREM_I128 : RTLIB::UREM_I128;
1772 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1774 return ARMEmitLibcall(I, LC);
1777 bool ARMFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1778 EVT DestVT = TLI.getValueType(I->getType(), true);
1780 // We can get here in the case when we have a binary operation on a non-legal
1781 // type and the target independent selector doesn't know how to handle it.
1782 if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
1786 switch (ISDOpcode) {
1787 default: return false;
1789 Opc = isThumb2 ? ARM::t2ADDrr : ARM::ADDrr;
1792 Opc = isThumb2 ? ARM::t2ORRrr : ARM::ORRrr;
1795 Opc = isThumb2 ? ARM::t2SUBrr : ARM::SUBrr;
1799 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1800 if (SrcReg1 == 0) return false;
1802 // TODO: Often the 2nd operand is an immediate, which can be encoded directly
1803 // in the instruction, rather then materializing the value in a register.
1804 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1805 if (SrcReg2 == 0) return false;
1807 unsigned ResultReg = createResultReg(&ARM::GPRnopcRegClass);
1808 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1809 TII.get(Opc), ResultReg)
1810 .addReg(SrcReg1).addReg(SrcReg2));
1811 UpdateValueMap(I, ResultReg);
1815 bool ARMFastISel::SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode) {
1816 EVT FPVT = TLI.getValueType(I->getType(), true);
1817 if (!FPVT.isSimple()) return false;
1818 MVT VT = FPVT.getSimpleVT();
1820 // We can get here in the case when we want to use NEON for our fp
1821 // operations, but can't figure out how to. Just use the vfp instructions
1823 // FIXME: It'd be nice to use NEON instructions.
1824 Type *Ty = I->getType();
1825 bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1826 if (isFloat && !Subtarget->hasVFP2())
1830 bool is64bit = VT == MVT::f64 || VT == MVT::i64;
1831 switch (ISDOpcode) {
1832 default: return false;
1834 Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1837 Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1840 Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1843 unsigned Op1 = getRegForValue(I->getOperand(0));
1844 if (Op1 == 0) return false;
1846 unsigned Op2 = getRegForValue(I->getOperand(1));
1847 if (Op2 == 0) return false;
1849 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT.SimpleTy));
1850 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1851 TII.get(Opc), ResultReg)
1852 .addReg(Op1).addReg(Op2));
1853 UpdateValueMap(I, ResultReg);
1857 // Call Handling Code
1859 // This is largely taken directly from CCAssignFnForNode
1860 // TODO: We may not support all of this.
1861 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC,
1866 llvm_unreachable("Unsupported calling convention");
1867 case CallingConv::Fast:
1868 if (Subtarget->hasVFP2() && !isVarArg) {
1869 if (!Subtarget->isAAPCS_ABI())
1870 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1871 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1872 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1875 case CallingConv::C:
1876 // Use target triple & subtarget features to do actual dispatch.
1877 if (Subtarget->isAAPCS_ABI()) {
1878 if (Subtarget->hasVFP2() &&
1879 TM.Options.FloatABIType == FloatABI::Hard && !isVarArg)
1880 return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1882 return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1884 return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1885 case CallingConv::ARM_AAPCS_VFP:
1887 return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1888 // Fall through to soft float variant, variadic functions don't
1889 // use hard floating point ABI.
1890 case CallingConv::ARM_AAPCS:
1891 return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1892 case CallingConv::ARM_APCS:
1893 return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1894 case CallingConv::GHC:
1896 llvm_unreachable("Can't return in GHC call convention");
1898 return CC_ARM_APCS_GHC;
1902 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1903 SmallVectorImpl<unsigned> &ArgRegs,
1904 SmallVectorImpl<MVT> &ArgVTs,
1905 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1906 SmallVectorImpl<unsigned> &RegArgs,
1910 SmallVector<CCValAssign, 16> ArgLocs;
1911 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs, *Context);
1912 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags,
1913 CCAssignFnForCall(CC, false, isVarArg));
1915 // Check that we can handle all of the arguments. If we can't, then bail out
1916 // now before we add code to the MBB.
1917 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1918 CCValAssign &VA = ArgLocs[i];
1919 MVT ArgVT = ArgVTs[VA.getValNo()];
1921 // We don't handle NEON/vector parameters yet.
1922 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1925 // Now copy/store arg to correct locations.
1926 if (VA.isRegLoc() && !VA.needsCustom()) {
1928 } else if (VA.needsCustom()) {
1929 // TODO: We need custom lowering for vector (v2f64) args.
1930 if (VA.getLocVT() != MVT::f64 ||
1931 // TODO: Only handle register args for now.
1932 !VA.isRegLoc() || !ArgLocs[++i].isRegLoc())
1935 switch (static_cast<EVT>(ArgVT).getSimpleVT().SimpleTy) {
1944 if (!Subtarget->hasVFP2())
1948 if (!Subtarget->hasVFP2())
1955 // At the point, we are able to handle the call's arguments in fast isel.
1957 // Get a count of how many bytes are to be pushed on the stack.
1958 NumBytes = CCInfo.getNextStackOffset();
1960 // Issue CALLSEQ_START
1961 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1962 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1963 TII.get(AdjStackDown))
1966 // Process the args.
1967 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1968 CCValAssign &VA = ArgLocs[i];
1969 unsigned Arg = ArgRegs[VA.getValNo()];
1970 MVT ArgVT = ArgVTs[VA.getValNo()];
1972 assert((!ArgVT.isVector() && ArgVT.getSizeInBits() <= 64) &&
1973 "We don't handle NEON/vector parameters yet.");
1975 // Handle arg promotion, etc.
1976 switch (VA.getLocInfo()) {
1977 case CCValAssign::Full: break;
1978 case CCValAssign::SExt: {
1979 MVT DestVT = VA.getLocVT();
1980 Arg = ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/false);
1981 assert (Arg != 0 && "Failed to emit a sext");
1985 case CCValAssign::AExt:
1986 // Intentional fall-through. Handle AExt and ZExt.
1987 case CCValAssign::ZExt: {
1988 MVT DestVT = VA.getLocVT();
1989 Arg = ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/true);
1990 assert (Arg != 0 && "Failed to emit a zext");
1994 case CCValAssign::BCvt: {
1995 unsigned BC = FastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, Arg,
1996 /*TODO: Kill=*/false);
1997 assert(BC != 0 && "Failed to emit a bitcast!");
1999 ArgVT = VA.getLocVT();
2002 default: llvm_unreachable("Unknown arg promotion!");
2005 // Now copy/store arg to correct locations.
2006 if (VA.isRegLoc() && !VA.needsCustom()) {
2007 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2010 RegArgs.push_back(VA.getLocReg());
2011 } else if (VA.needsCustom()) {
2012 // TODO: We need custom lowering for vector (v2f64) args.
2013 assert(VA.getLocVT() == MVT::f64 &&
2014 "Custom lowering for v2f64 args not available");
2016 CCValAssign &NextVA = ArgLocs[++i];
2018 assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2019 "We only handle register args!");
2021 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2022 TII.get(ARM::VMOVRRD), VA.getLocReg())
2023 .addReg(NextVA.getLocReg(), RegState::Define)
2025 RegArgs.push_back(VA.getLocReg());
2026 RegArgs.push_back(NextVA.getLocReg());
2028 assert(VA.isMemLoc());
2029 // Need to store on the stack.
2031 Addr.BaseType = Address::RegBase;
2032 Addr.Base.Reg = ARM::SP;
2033 Addr.Offset = VA.getLocMemOffset();
2035 bool EmitRet = ARMEmitStore(ArgVT, Arg, Addr); (void)EmitRet;
2036 assert(EmitRet && "Could not emit a store for argument!");
2043 bool ARMFastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
2044 const Instruction *I, CallingConv::ID CC,
2045 unsigned &NumBytes, bool isVarArg) {
2046 // Issue CALLSEQ_END
2047 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2048 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2049 TII.get(AdjStackUp))
2050 .addImm(NumBytes).addImm(0));
2052 // Now the return value.
2053 if (RetVT != MVT::isVoid) {
2054 SmallVector<CCValAssign, 16> RVLocs;
2055 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
2056 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, isVarArg));
2058 // Copy all of the result registers out of their specified physreg.
2059 if (RVLocs.size() == 2 && RetVT == MVT::f64) {
2060 // For this move we copy into two registers and then move into the
2061 // double fp reg we want.
2062 MVT DestVT = RVLocs[0].getValVT();
2063 const TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
2064 unsigned ResultReg = createResultReg(DstRC);
2065 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2066 TII.get(ARM::VMOVDRR), ResultReg)
2067 .addReg(RVLocs[0].getLocReg())
2068 .addReg(RVLocs[1].getLocReg()));
2070 UsedRegs.push_back(RVLocs[0].getLocReg());
2071 UsedRegs.push_back(RVLocs[1].getLocReg());
2073 // Finally update the result.
2074 UpdateValueMap(I, ResultReg);
2076 assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
2077 MVT CopyVT = RVLocs[0].getValVT();
2079 // Special handling for extended integers.
2080 if (RetVT == MVT::i1 || RetVT == MVT::i8 || RetVT == MVT::i16)
2083 const TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
2085 unsigned ResultReg = createResultReg(DstRC);
2086 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2087 ResultReg).addReg(RVLocs[0].getLocReg());
2088 UsedRegs.push_back(RVLocs[0].getLocReg());
2090 // Finally update the result.
2091 UpdateValueMap(I, ResultReg);
2098 bool ARMFastISel::SelectRet(const Instruction *I) {
2099 const ReturnInst *Ret = cast<ReturnInst>(I);
2100 const Function &F = *I->getParent()->getParent();
2102 if (!FuncInfo.CanLowerReturn)
2105 // Build a list of return value registers.
2106 SmallVector<unsigned, 4> RetRegs;
2108 CallingConv::ID CC = F.getCallingConv();
2109 if (Ret->getNumOperands() > 0) {
2110 SmallVector<ISD::OutputArg, 4> Outs;
2111 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
2113 // Analyze operands of the call, assigning locations to each operand.
2114 SmallVector<CCValAssign, 16> ValLocs;
2115 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,I->getContext());
2116 CCInfo.AnalyzeReturn(Outs, CCAssignFnForCall(CC, true /* is Ret */,
2119 const Value *RV = Ret->getOperand(0);
2120 unsigned Reg = getRegForValue(RV);
2124 // Only handle a single return value for now.
2125 if (ValLocs.size() != 1)
2128 CCValAssign &VA = ValLocs[0];
2130 // Don't bother handling odd stuff for now.
2131 if (VA.getLocInfo() != CCValAssign::Full)
2133 // Only handle register returns for now.
2137 unsigned SrcReg = Reg + VA.getValNo();
2138 EVT RVEVT = TLI.getValueType(RV->getType());
2139 if (!RVEVT.isSimple()) return false;
2140 MVT RVVT = RVEVT.getSimpleVT();
2141 MVT DestVT = VA.getValVT();
2142 // Special handling for extended integers.
2143 if (RVVT != DestVT) {
2144 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
2147 assert(DestVT == MVT::i32 && "ARM should always ext to i32");
2149 // Perform extension if flagged as either zext or sext. Otherwise, do
2151 if (Outs[0].Flags.isZExt() || Outs[0].Flags.isSExt()) {
2152 SrcReg = ARMEmitIntExt(RVVT, SrcReg, DestVT, Outs[0].Flags.isZExt());
2153 if (SrcReg == 0) return false;
2158 unsigned DstReg = VA.getLocReg();
2159 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
2160 // Avoid a cross-class copy. This is very unlikely.
2161 if (!SrcRC->contains(DstReg))
2163 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2164 DstReg).addReg(SrcReg);
2166 // Add register to return instruction.
2167 RetRegs.push_back(VA.getLocReg());
2170 unsigned RetOpc = isThumb2 ? ARM::tBX_RET : ARM::BX_RET;
2171 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2173 AddOptionalDefs(MIB);
2174 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
2175 MIB.addReg(RetRegs[i], RegState::Implicit);
2179 unsigned ARMFastISel::ARMSelectCallOp(bool UseReg) {
2181 return isThumb2 ? ARM::tBLXr : ARM::BLX;
2183 return isThumb2 ? ARM::tBL : ARM::BL;
2186 unsigned ARMFastISel::getLibcallReg(const Twine &Name) {
2187 GlobalValue *GV = new GlobalVariable(Type::getInt32Ty(*Context), false,
2188 GlobalValue::ExternalLinkage, 0, Name);
2189 EVT LCREVT = TLI.getValueType(GV->getType());
2190 if (!LCREVT.isSimple()) return 0;
2191 return ARMMaterializeGV(GV, LCREVT.getSimpleVT());
2194 // A quick function that will emit a call for a named libcall in F with the
2195 // vector of passed arguments for the Instruction in I. We can assume that we
2196 // can emit a call for any libcall we can produce. This is an abridged version
2197 // of the full call infrastructure since we won't need to worry about things
2198 // like computed function pointers or strange arguments at call sites.
2199 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
2201 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
2202 CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
2204 // Handle *simple* calls for now.
2205 Type *RetTy = I->getType();
2207 if (RetTy->isVoidTy())
2208 RetVT = MVT::isVoid;
2209 else if (!isTypeLegal(RetTy, RetVT))
2212 // Can't handle non-double multi-reg retvals.
2213 if (RetVT != MVT::isVoid && RetVT != MVT::i32) {
2214 SmallVector<CCValAssign, 16> RVLocs;
2215 CCState CCInfo(CC, false, *FuncInfo.MF, TM, RVLocs, *Context);
2216 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, false));
2217 if (RVLocs.size() >= 2 && RetVT != MVT::f64)
2221 // Set up the argument vectors.
2222 SmallVector<Value*, 8> Args;
2223 SmallVector<unsigned, 8> ArgRegs;
2224 SmallVector<MVT, 8> ArgVTs;
2225 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2226 Args.reserve(I->getNumOperands());
2227 ArgRegs.reserve(I->getNumOperands());
2228 ArgVTs.reserve(I->getNumOperands());
2229 ArgFlags.reserve(I->getNumOperands());
2230 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2231 Value *Op = I->getOperand(i);
2232 unsigned Arg = getRegForValue(Op);
2233 if (Arg == 0) return false;
2235 Type *ArgTy = Op->getType();
2237 if (!isTypeLegal(ArgTy, ArgVT)) return false;
2239 ISD::ArgFlagsTy Flags;
2240 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
2241 Flags.setOrigAlign(OriginalAlignment);
2244 ArgRegs.push_back(Arg);
2245 ArgVTs.push_back(ArgVT);
2246 ArgFlags.push_back(Flags);
2249 // Handle the arguments now that we've gotten them.
2250 SmallVector<unsigned, 4> RegArgs;
2252 if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
2253 RegArgs, CC, NumBytes, false))
2256 unsigned CalleeReg = 0;
2257 if (EnableARMLongCalls) {
2258 CalleeReg = getLibcallReg(TLI.getLibcallName(Call));
2259 if (CalleeReg == 0) return false;
2263 unsigned CallOpc = ARMSelectCallOp(EnableARMLongCalls);
2264 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2265 DL, TII.get(CallOpc));
2266 // BL / BLX don't take a predicate, but tBL / tBLX do.
2268 AddDefaultPred(MIB);
2269 if (EnableARMLongCalls)
2270 MIB.addReg(CalleeReg);
2272 MIB.addExternalSymbol(TLI.getLibcallName(Call));
2274 // Add implicit physical register uses to the call.
2275 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2276 MIB.addReg(RegArgs[i], RegState::Implicit);
2278 // Add a register mask with the call-preserved registers.
2279 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2280 MIB.addRegMask(TRI.getCallPreservedMask(CC));
2282 // Finish off the call including any return values.
2283 SmallVector<unsigned, 4> UsedRegs;
2284 if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes, false)) return false;
2286 // Set all unused physreg defs as dead.
2287 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2292 bool ARMFastISel::SelectCall(const Instruction *I,
2293 const char *IntrMemName = 0) {
2294 const CallInst *CI = cast<CallInst>(I);
2295 const Value *Callee = CI->getCalledValue();
2297 // Can't handle inline asm.
2298 if (isa<InlineAsm>(Callee)) return false;
2300 // Allow SelectionDAG isel to handle tail calls.
2301 if (CI->isTailCall()) return false;
2303 // Check the calling convention.
2304 ImmutableCallSite CS(CI);
2305 CallingConv::ID CC = CS.getCallingConv();
2307 // TODO: Avoid some calling conventions?
2309 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2310 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2311 bool isVarArg = FTy->isVarArg();
2313 // Handle *simple* calls for now.
2314 Type *RetTy = I->getType();
2316 if (RetTy->isVoidTy())
2317 RetVT = MVT::isVoid;
2318 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
2319 RetVT != MVT::i8 && RetVT != MVT::i1)
2322 // Can't handle non-double multi-reg retvals.
2323 if (RetVT != MVT::isVoid && RetVT != MVT::i1 && RetVT != MVT::i8 &&
2324 RetVT != MVT::i16 && RetVT != MVT::i32) {
2325 SmallVector<CCValAssign, 16> RVLocs;
2326 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
2327 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, isVarArg));
2328 if (RVLocs.size() >= 2 && RetVT != MVT::f64)
2332 // Set up the argument vectors.
2333 SmallVector<Value*, 8> Args;
2334 SmallVector<unsigned, 8> ArgRegs;
2335 SmallVector<MVT, 8> ArgVTs;
2336 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2337 unsigned arg_size = CS.arg_size();
2338 Args.reserve(arg_size);
2339 ArgRegs.reserve(arg_size);
2340 ArgVTs.reserve(arg_size);
2341 ArgFlags.reserve(arg_size);
2342 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2344 // If we're lowering a memory intrinsic instead of a regular call, skip the
2345 // last two arguments, which shouldn't be passed to the underlying function.
2346 if (IntrMemName && e-i <= 2)
2349 ISD::ArgFlagsTy Flags;
2350 unsigned AttrInd = i - CS.arg_begin() + 1;
2351 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2353 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2356 // FIXME: Only handle *easy* calls for now.
2357 if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
2358 CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
2359 CS.paramHasAttr(AttrInd, Attribute::Nest) ||
2360 CS.paramHasAttr(AttrInd, Attribute::ByVal))
2363 Type *ArgTy = (*i)->getType();
2365 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8 &&
2369 unsigned Arg = getRegForValue(*i);
2373 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
2374 Flags.setOrigAlign(OriginalAlignment);
2377 ArgRegs.push_back(Arg);
2378 ArgVTs.push_back(ArgVT);
2379 ArgFlags.push_back(Flags);
2382 // Handle the arguments now that we've gotten them.
2383 SmallVector<unsigned, 4> RegArgs;
2385 if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
2386 RegArgs, CC, NumBytes, isVarArg))
2389 bool UseReg = false;
2390 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
2391 if (!GV || EnableARMLongCalls) UseReg = true;
2393 unsigned CalleeReg = 0;
2396 CalleeReg = getLibcallReg(IntrMemName);
2398 CalleeReg = getRegForValue(Callee);
2400 if (CalleeReg == 0) return false;
2404 unsigned CallOpc = ARMSelectCallOp(UseReg);
2405 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2406 DL, TII.get(CallOpc));
2408 // ARM calls don't take a predicate, but tBL / tBLX do.
2410 AddDefaultPred(MIB);
2412 MIB.addReg(CalleeReg);
2413 else if (!IntrMemName)
2414 MIB.addGlobalAddress(GV, 0, 0);
2416 MIB.addExternalSymbol(IntrMemName, 0);
2418 // Add implicit physical register uses to the call.
2419 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2420 MIB.addReg(RegArgs[i], RegState::Implicit);
2422 // Add a register mask with the call-preserved registers.
2423 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2424 MIB.addRegMask(TRI.getCallPreservedMask(CC));
2426 // Finish off the call including any return values.
2427 SmallVector<unsigned, 4> UsedRegs;
2428 if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes, isVarArg))
2431 // Set all unused physreg defs as dead.
2432 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2437 bool ARMFastISel::ARMIsMemCpySmall(uint64_t Len) {
2441 bool ARMFastISel::ARMTryEmitSmallMemCpy(Address Dest, Address Src,
2442 uint64_t Len, unsigned Alignment) {
2443 // Make sure we don't bloat code by inlining very large memcpy's.
2444 if (!ARMIsMemCpySmall(Len))
2449 if (!Alignment || Alignment >= 4) {
2455 assert (Len == 1 && "Expected a length of 1!");
2459 // Bound based on alignment.
2460 if (Len >= 2 && Alignment == 2)
2469 RV = ARMEmitLoad(VT, ResultReg, Src);
2470 assert (RV == true && "Should be able to handle this load.");
2471 RV = ARMEmitStore(VT, ResultReg, Dest);
2472 assert (RV == true && "Should be able to handle this store.");
2475 unsigned Size = VT.getSizeInBits()/8;
2477 Dest.Offset += Size;
2484 bool ARMFastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
2485 // FIXME: Handle more intrinsics.
2486 switch (I.getIntrinsicID()) {
2487 default: return false;
2488 case Intrinsic::frameaddress: {
2489 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2490 MFI->setFrameAddressIsTaken(true);
2493 const TargetRegisterClass *RC;
2495 LdrOpc = ARM::t2LDRi12;
2496 RC = (const TargetRegisterClass*)&ARM::tGPRRegClass;
2498 LdrOpc = ARM::LDRi12;
2499 RC = (const TargetRegisterClass*)&ARM::GPRRegClass;
2502 const ARMBaseRegisterInfo *RegInfo =
2503 static_cast<const ARMBaseRegisterInfo*>(TM.getRegisterInfo());
2504 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
2505 unsigned SrcReg = FramePtr;
2507 // Recursively load frame address
2513 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
2515 DestReg = createResultReg(RC);
2516 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2517 TII.get(LdrOpc), DestReg)
2518 .addReg(SrcReg).addImm(0));
2521 UpdateValueMap(&I, SrcReg);
2524 case Intrinsic::memcpy:
2525 case Intrinsic::memmove: {
2526 const MemTransferInst &MTI = cast<MemTransferInst>(I);
2527 // Don't handle volatile.
2528 if (MTI.isVolatile())
2531 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
2532 // we would emit dead code because we don't currently handle memmoves.
2533 bool isMemCpy = (I.getIntrinsicID() == Intrinsic::memcpy);
2534 if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
2535 // Small memcpy's are common enough that we want to do them without a call
2537 uint64_t Len = cast<ConstantInt>(MTI.getLength())->getZExtValue();
2538 if (ARMIsMemCpySmall(Len)) {
2540 if (!ARMComputeAddress(MTI.getRawDest(), Dest) ||
2541 !ARMComputeAddress(MTI.getRawSource(), Src))
2543 unsigned Alignment = MTI.getAlignment();
2544 if (ARMTryEmitSmallMemCpy(Dest, Src, Len, Alignment))
2549 if (!MTI.getLength()->getType()->isIntegerTy(32))
2552 if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 255)
2555 const char *IntrMemName = isa<MemCpyInst>(I) ? "memcpy" : "memmove";
2556 return SelectCall(&I, IntrMemName);
2558 case Intrinsic::memset: {
2559 const MemSetInst &MSI = cast<MemSetInst>(I);
2560 // Don't handle volatile.
2561 if (MSI.isVolatile())
2564 if (!MSI.getLength()->getType()->isIntegerTy(32))
2567 if (MSI.getDestAddressSpace() > 255)
2570 return SelectCall(&I, "memset");
2572 case Intrinsic::trap: {
2573 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(
2574 Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP));
2580 bool ARMFastISel::SelectTrunc(const Instruction *I) {
2581 // The high bits for a type smaller than the register size are assumed to be
2583 Value *Op = I->getOperand(0);
2586 SrcVT = TLI.getValueType(Op->getType(), true);
2587 DestVT = TLI.getValueType(I->getType(), true);
2589 if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
2591 if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
2594 unsigned SrcReg = getRegForValue(Op);
2595 if (!SrcReg) return false;
2597 // Because the high bits are undefined, a truncate doesn't generate
2599 UpdateValueMap(I, SrcReg);
2603 unsigned ARMFastISel::ARMEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
2605 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
2607 if (SrcVT != MVT::i16 && SrcVT != MVT::i8 && SrcVT != MVT::i1)
2610 // Table of which combinations can be emitted as a single instruction,
2611 // and which will require two.
2612 static const uint8_t isSingleInstrTbl[3][2][2][2] = {
2614 // !hasV6Ops hasV6Ops !hasV6Ops hasV6Ops
2615 // ext: s z s z s z s z
2616 /* 1 */ { { { 0, 1 }, { 0, 1 } }, { { 0, 0 }, { 0, 1 } } },
2617 /* 8 */ { { { 0, 1 }, { 1, 1 } }, { { 0, 0 }, { 1, 1 } } },
2618 /* 16 */ { { { 0, 0 }, { 1, 1 } }, { { 0, 0 }, { 1, 1 } } }
2621 // Target registers for:
2622 // - For ARM can never be PC.
2623 // - For 16-bit Thumb are restricted to lower 8 registers.
2624 // - For 32-bit Thumb are restricted to non-SP and non-PC.
2625 static const TargetRegisterClass *RCTbl[2][2] = {
2626 // Instructions: Two Single
2627 /* ARM */ { &ARM::GPRnopcRegClass, &ARM::GPRnopcRegClass },
2628 /* Thumb */ { &ARM::tGPRRegClass, &ARM::rGPRRegClass }
2631 // Table governing the instruction(s) to be emitted.
2632 static const struct {
2633 // First entry for each of the following is sext, second zext.
2635 uint8_t Imm[2]; // All instructions have either a shift or a mask.
2636 uint8_t hasS[2]; // Some instructions have an S bit, always set it to 0.
2637 } OpcTbl[2][2][3] = {
2638 { // Two instructions (first is left shift, second is in this table).
2640 /* 1 */ { { ARM::ASRi, ARM::LSRi }, { 31, 31 }, { 1, 1 } },
2641 /* 8 */ { { ARM::ASRi, ARM::LSRi }, { 24, 24 }, { 1, 1 } },
2642 /* 16 */ { { ARM::ASRi, ARM::LSRi }, { 16, 16 }, { 1, 1 } }
2645 /* 1 */ { { ARM::tASRri, ARM::tLSRri }, { 31, 31 }, { 0, 0 } },
2646 /* 8 */ { { ARM::tASRri, ARM::tLSRri }, { 24, 24 }, { 0, 0 } },
2647 /* 16 */ { { ARM::tASRri, ARM::tLSRri }, { 16, 16 }, { 0, 0 } }
2650 { // Single instruction.
2652 /* 1 */ { { ARM::KILL, ARM::ANDri }, { 0, 1 }, { 0, 1 } },
2653 /* 8 */ { { ARM::SXTB, ARM::ANDri }, { 0, 255 }, { 0, 1 } },
2654 /* 16 */ { { ARM::SXTH, ARM::UXTH }, { 0, 0 }, { 0, 0 } }
2657 /* 1 */ { { ARM::KILL, ARM::t2ANDri }, { 0, 1 }, { 0, 1 } },
2658 /* 8 */ { { ARM::t2SXTB, ARM::t2ANDri }, { 0, 255 }, { 0, 1 } },
2659 /* 16 */ { { ARM::t2SXTH, ARM::t2UXTH }, { 0, 0 }, { 0, 0 } }
2664 unsigned SrcBits = SrcVT.getSizeInBits();
2665 unsigned DestBits = DestVT.getSizeInBits();
2667 assert((SrcBits < DestBits) && "can only extend to larger types");
2668 assert((DestBits == 32 || DestBits == 16 || DestBits == 8) &&
2669 "other sizes unimplemented");
2670 assert((SrcBits == 16 || SrcBits == 8 || SrcBits == 1) &&
2671 "other sizes unimplemented");
2673 bool hasV6Ops = Subtarget->hasV6Ops();
2674 unsigned Bitness = countTrailingZeros(SrcBits) >> 1; // {1,8,16}=>{0,1,2}
2675 assert((Bitness < 3) && "sanity-check table bounds");
2677 bool isSingleInstr = isSingleInstrTbl[Bitness][isThumb2][hasV6Ops][isZExt];
2678 const TargetRegisterClass *RC = RCTbl[isThumb2][isSingleInstr];
2679 unsigned Opc = OpcTbl[isSingleInstr][isThumb2][Bitness].Opc[isZExt];
2680 assert(ARM::KILL != Opc && "Invalid table entry");
2681 unsigned Imm = OpcTbl[isSingleInstr][isThumb2][Bitness].Imm[isZExt];
2682 unsigned hasS = OpcTbl[isSingleInstr][isThumb2][Bitness].hasS[isZExt];
2684 // 16-bit Thumb instructions always set CPSR (unless they're in an IT block).
2685 bool setsCPSR = &ARM::tGPRRegClass == RC;
2686 unsigned LSLOpc = isThumb2 ? ARM::tLSLri : ARM::LSLi;
2689 // Either one or two instructions are emitted.
2690 // They're always of the form:
2692 // CPSR is set only by 16-bit Thumb instructions.
2693 // Predicate, if any, is AL.
2694 // S bit, if available, is always 0.
2695 // When two are emitted the first's result will feed as the second's input,
2696 // that value is then dead.
2697 unsigned NumInstrsEmitted = isSingleInstr ? 1 : 2;
2698 for (unsigned Instr = 0; Instr != NumInstrsEmitted; ++Instr) {
2699 ResultReg = createResultReg(RC);
2700 unsigned Opcode = ((0 == Instr) && !isSingleInstr) ? LSLOpc : Opc;
2701 bool isKill = 1 == Instr;
2702 MachineInstrBuilder MIB = BuildMI(
2703 *FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opcode), ResultReg);
2705 MIB.addReg(ARM::CPSR, RegState::Define);
2706 AddDefaultPred(MIB.addReg(SrcReg, isKill * RegState::Kill).addImm(Imm));
2709 // Second instruction consumes the first's result.
2716 bool ARMFastISel::SelectIntExt(const Instruction *I) {
2717 // On ARM, in general, integer casts don't involve legal types; this code
2718 // handles promotable integers.
2719 Type *DestTy = I->getType();
2720 Value *Src = I->getOperand(0);
2721 Type *SrcTy = Src->getType();
2723 bool isZExt = isa<ZExtInst>(I);
2724 unsigned SrcReg = getRegForValue(Src);
2725 if (!SrcReg) return false;
2727 EVT SrcEVT, DestEVT;
2728 SrcEVT = TLI.getValueType(SrcTy, true);
2729 DestEVT = TLI.getValueType(DestTy, true);
2730 if (!SrcEVT.isSimple()) return false;
2731 if (!DestEVT.isSimple()) return false;
2733 MVT SrcVT = SrcEVT.getSimpleVT();
2734 MVT DestVT = DestEVT.getSimpleVT();
2735 unsigned ResultReg = ARMEmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2736 if (ResultReg == 0) return false;
2737 UpdateValueMap(I, ResultReg);
2741 bool ARMFastISel::SelectShift(const Instruction *I,
2742 ARM_AM::ShiftOpc ShiftTy) {
2743 // We handle thumb2 mode by target independent selector
2744 // or SelectionDAG ISel.
2748 // Only handle i32 now.
2749 EVT DestVT = TLI.getValueType(I->getType(), true);
2750 if (DestVT != MVT::i32)
2753 unsigned Opc = ARM::MOVsr;
2755 Value *Src2Value = I->getOperand(1);
2756 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Src2Value)) {
2757 ShiftImm = CI->getZExtValue();
2759 // Fall back to selection DAG isel if the shift amount
2760 // is zero or greater than the width of the value type.
2761 if (ShiftImm == 0 || ShiftImm >=32)
2767 Value *Src1Value = I->getOperand(0);
2768 unsigned Reg1 = getRegForValue(Src1Value);
2769 if (Reg1 == 0) return false;
2772 if (Opc == ARM::MOVsr) {
2773 Reg2 = getRegForValue(Src2Value);
2774 if (Reg2 == 0) return false;
2777 unsigned ResultReg = createResultReg(&ARM::GPRnopcRegClass);
2778 if(ResultReg == 0) return false;
2780 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2781 TII.get(Opc), ResultReg)
2784 if (Opc == ARM::MOVsi)
2785 MIB.addImm(ARM_AM::getSORegOpc(ShiftTy, ShiftImm));
2786 else if (Opc == ARM::MOVsr) {
2788 MIB.addImm(ARM_AM::getSORegOpc(ShiftTy, 0));
2791 AddOptionalDefs(MIB);
2792 UpdateValueMap(I, ResultReg);
2796 // TODO: SoftFP support.
2797 bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
2799 switch (I->getOpcode()) {
2800 case Instruction::Load:
2801 return SelectLoad(I);
2802 case Instruction::Store:
2803 return SelectStore(I);
2804 case Instruction::Br:
2805 return SelectBranch(I);
2806 case Instruction::IndirectBr:
2807 return SelectIndirectBr(I);
2808 case Instruction::ICmp:
2809 case Instruction::FCmp:
2810 return SelectCmp(I);
2811 case Instruction::FPExt:
2812 return SelectFPExt(I);
2813 case Instruction::FPTrunc:
2814 return SelectFPTrunc(I);
2815 case Instruction::SIToFP:
2816 return SelectIToFP(I, /*isSigned*/ true);
2817 case Instruction::UIToFP:
2818 return SelectIToFP(I, /*isSigned*/ false);
2819 case Instruction::FPToSI:
2820 return SelectFPToI(I, /*isSigned*/ true);
2821 case Instruction::FPToUI:
2822 return SelectFPToI(I, /*isSigned*/ false);
2823 case Instruction::Add:
2824 return SelectBinaryIntOp(I, ISD::ADD);
2825 case Instruction::Or:
2826 return SelectBinaryIntOp(I, ISD::OR);
2827 case Instruction::Sub:
2828 return SelectBinaryIntOp(I, ISD::SUB);
2829 case Instruction::FAdd:
2830 return SelectBinaryFPOp(I, ISD::FADD);
2831 case Instruction::FSub:
2832 return SelectBinaryFPOp(I, ISD::FSUB);
2833 case Instruction::FMul:
2834 return SelectBinaryFPOp(I, ISD::FMUL);
2835 case Instruction::SDiv:
2836 return SelectDiv(I, /*isSigned*/ true);
2837 case Instruction::UDiv:
2838 return SelectDiv(I, /*isSigned*/ false);
2839 case Instruction::SRem:
2840 return SelectRem(I, /*isSigned*/ true);
2841 case Instruction::URem:
2842 return SelectRem(I, /*isSigned*/ false);
2843 case Instruction::Call:
2844 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2845 return SelectIntrinsicCall(*II);
2846 return SelectCall(I);
2847 case Instruction::Select:
2848 return SelectSelect(I);
2849 case Instruction::Ret:
2850 return SelectRet(I);
2851 case Instruction::Trunc:
2852 return SelectTrunc(I);
2853 case Instruction::ZExt:
2854 case Instruction::SExt:
2855 return SelectIntExt(I);
2856 case Instruction::Shl:
2857 return SelectShift(I, ARM_AM::lsl);
2858 case Instruction::LShr:
2859 return SelectShift(I, ARM_AM::lsr);
2860 case Instruction::AShr:
2861 return SelectShift(I, ARM_AM::asr);
2868 // This table describes sign- and zero-extend instructions which can be
2869 // folded into a preceding load. All of these extends have an immediate
2870 // (sometimes a mask and sometimes a shift) that's applied after
2872 const struct FoldableLoadExtendsStruct {
2873 uint16_t Opc[2]; // ARM, Thumb.
2874 uint8_t ExpectedImm;
2876 uint8_t ExpectedVT : 7;
2877 } FoldableLoadExtends[] = {
2878 { { ARM::SXTH, ARM::t2SXTH }, 0, 0, MVT::i16 },
2879 { { ARM::UXTH, ARM::t2UXTH }, 0, 1, MVT::i16 },
2880 { { ARM::ANDri, ARM::t2ANDri }, 255, 1, MVT::i8 },
2881 { { ARM::SXTB, ARM::t2SXTB }, 0, 0, MVT::i8 },
2882 { { ARM::UXTB, ARM::t2UXTB }, 0, 1, MVT::i8 }
2886 /// \brief The specified machine instr operand is a vreg, and that
2887 /// vreg is being provided by the specified load instruction. If possible,
2888 /// try to fold the load as an operand to the instruction, returning true if
2890 bool ARMFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2891 const LoadInst *LI) {
2892 // Verify we have a legal type before going any further.
2894 if (!isLoadTypeLegal(LI->getType(), VT))
2897 // Combine load followed by zero- or sign-extend.
2898 // ldrb r1, [r0] ldrb r1, [r0]
2900 // mov r3, r2 mov r3, r1
2901 if (MI->getNumOperands() < 3 || !MI->getOperand(2).isImm())
2903 const uint64_t Imm = MI->getOperand(2).getImm();
2907 for (unsigned i = 0, e = array_lengthof(FoldableLoadExtends);
2909 if (FoldableLoadExtends[i].Opc[isThumb2] == MI->getOpcode() &&
2910 (uint64_t)FoldableLoadExtends[i].ExpectedImm == Imm &&
2911 MVT((MVT::SimpleValueType)FoldableLoadExtends[i].ExpectedVT) == VT) {
2913 isZExt = FoldableLoadExtends[i].isZExt;
2916 if (!Found) return false;
2918 // See if we can handle this address.
2920 if (!ARMComputeAddress(LI->getOperand(0), Addr)) return false;
2922 unsigned ResultReg = MI->getOperand(0).getReg();
2923 if (!ARMEmitLoad(VT, ResultReg, Addr, LI->getAlignment(), isZExt, false))
2925 MI->eraseFromParent();
2929 unsigned ARMFastISel::ARMLowerPICELF(const GlobalValue *GV,
2930 unsigned Align, MVT VT) {
2931 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2932 ARMConstantPoolConstant *CPV =
2933 ARMConstantPoolConstant::Create(GV, UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2934 unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
2937 unsigned DestReg1 = createResultReg(TLI.getRegClassFor(VT));
2940 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2941 TII.get(ARM::t2LDRpci), DestReg1)
2942 .addConstantPoolIndex(Idx));
2943 Opc = UseGOTOFF ? ARM::t2ADDrr : ARM::t2LDRs;
2945 // The extra immediate is for addrmode2.
2946 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2947 DL, TII.get(ARM::LDRcp), DestReg1)
2948 .addConstantPoolIndex(Idx).addImm(0));
2949 Opc = UseGOTOFF ? ARM::ADDrr : ARM::LDRrs;
2952 unsigned GlobalBaseReg = AFI->getGlobalBaseReg();
2953 if (GlobalBaseReg == 0) {
2954 GlobalBaseReg = MRI.createVirtualRegister(TLI.getRegClassFor(VT));
2955 AFI->setGlobalBaseReg(GlobalBaseReg);
2958 unsigned DestReg2 = createResultReg(TLI.getRegClassFor(VT));
2959 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2960 DL, TII.get(Opc), DestReg2)
2962 .addReg(GlobalBaseReg);
2965 AddOptionalDefs(MIB);
2970 bool ARMFastISel::FastLowerArguments() {
2971 if (!FuncInfo.CanLowerReturn)
2974 const Function *F = FuncInfo.Fn;
2978 CallingConv::ID CC = F->getCallingConv();
2982 case CallingConv::Fast:
2983 case CallingConv::C:
2984 case CallingConv::ARM_AAPCS_VFP:
2985 case CallingConv::ARM_AAPCS:
2986 case CallingConv::ARM_APCS:
2990 // Only handle simple cases. i.e. Up to 4 i8/i16/i32 scalar arguments
2991 // which are passed in r0 - r3.
2993 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2994 I != E; ++I, ++Idx) {
2998 if (F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2999 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
3000 F->getAttributes().hasAttribute(Idx, Attribute::ByVal))
3003 Type *ArgTy = I->getType();
3004 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3007 EVT ArgVT = TLI.getValueType(ArgTy);
3008 if (!ArgVT.isSimple()) return false;
3009 switch (ArgVT.getSimpleVT().SimpleTy) {
3020 static const uint16_t GPRArgRegs[] = {
3021 ARM::R0, ARM::R1, ARM::R2, ARM::R3
3024 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::i32);
3026 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
3027 I != E; ++I, ++Idx) {
3030 unsigned SrcReg = GPRArgRegs[Idx];
3031 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3032 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3033 // Without this, EmitLiveInCopies may eliminate the livein if its only
3034 // use is a bitcast (which isn't turned into an instruction).
3035 unsigned ResultReg = createResultReg(RC);
3036 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
3037 ResultReg).addReg(DstReg, getKillRegState(true));
3038 UpdateValueMap(I, ResultReg);
3045 FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo,
3046 const TargetLibraryInfo *libInfo) {
3047 // Completely untested on non-iOS.
3048 const TargetMachine &TM = funcInfo.MF->getTarget();
3050 // Darwin and thumb1 only for now.
3051 const ARMSubtarget *Subtarget = &TM.getSubtarget<ARMSubtarget>();
3052 if (Subtarget->isTargetIOS() && !Subtarget->isThumb1Only())
3053 return new ARMFastISel(funcInfo, libInfo);