1 //===-- AArch6464FastISel.cpp - AArch64 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 AArch64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // AArch64GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "MCTargetDesc/AArch64AddressingModes.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/FastISel.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Support/CommandLine.h"
43 class AArch64FastISel final : public FastISel {
53 AArch64_AM::ShiftExtendType ExtType;
61 const GlobalValue *GV;
64 Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
65 OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
66 void setKind(BaseKind K) { Kind = K; }
67 BaseKind getKind() const { return Kind; }
68 void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
69 AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
70 bool isRegBase() const { return Kind == RegBase; }
71 bool isFIBase() const { return Kind == FrameIndexBase; }
72 void setReg(unsigned Reg) {
73 assert(isRegBase() && "Invalid base register access!");
76 unsigned getReg() const {
77 assert(isRegBase() && "Invalid base register access!");
80 void setOffsetReg(unsigned Reg) {
81 assert(isRegBase() && "Invalid offset register access!");
84 unsigned getOffsetReg() const {
85 assert(isRegBase() && "Invalid offset register access!");
88 void setFI(unsigned FI) {
89 assert(isFIBase() && "Invalid base frame index access!");
92 unsigned getFI() const {
93 assert(isFIBase() && "Invalid base frame index access!");
96 void setOffset(int64_t O) { Offset = O; }
97 int64_t getOffset() { return Offset; }
98 void setShift(unsigned S) { Shift = S; }
99 unsigned getShift() { return Shift; }
101 void setGlobalValue(const GlobalValue *G) { GV = G; }
102 const GlobalValue *getGlobalValue() { return GV; }
105 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
106 /// make the right decision when generating code for different targets.
107 const AArch64Subtarget *Subtarget;
108 LLVMContext *Context;
110 bool fastLowerArguments() override;
111 bool fastLowerCall(CallLoweringInfo &CLI) override;
112 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
115 // Selection routines.
116 bool selectAddSub(const Instruction *I);
117 bool selectLogicalOp(const Instruction *I);
118 bool selectLoad(const Instruction *I);
119 bool selectStore(const Instruction *I);
120 bool selectBranch(const Instruction *I);
121 bool selectIndirectBr(const Instruction *I);
122 bool selectCmp(const Instruction *I);
123 bool selectSelect(const Instruction *I);
124 bool selectFPExt(const Instruction *I);
125 bool selectFPTrunc(const Instruction *I);
126 bool selectFPToInt(const Instruction *I, bool Signed);
127 bool selectIntToFP(const Instruction *I, bool Signed);
128 bool selectRem(const Instruction *I, unsigned ISDOpcode);
129 bool selectRet(const Instruction *I);
130 bool selectTrunc(const Instruction *I);
131 bool selectIntExt(const Instruction *I);
132 bool selectMul(const Instruction *I);
133 bool selectShift(const Instruction *I);
134 bool selectBitCast(const Instruction *I);
135 bool selectFRem(const Instruction *I);
136 bool selectSDiv(const Instruction *I);
138 // Utility helper routines.
139 bool isTypeLegal(Type *Ty, MVT &VT);
140 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
141 bool isValueAvailable(const Value *V) const;
142 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
143 bool computeCallAddress(const Value *V, Address &Addr);
144 bool simplifyAddress(Address &Addr, MVT VT);
145 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
146 unsigned Flags, unsigned ScaleFactor,
147 MachineMemOperand *MMO);
148 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
149 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
151 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
154 // Emit helper routines.
155 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
156 const Value *RHS, bool SetFlags = false,
157 bool WantResult = true, bool IsZExt = false);
158 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
159 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
160 bool SetFlags = false, bool WantResult = true);
161 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
162 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
163 bool WantResult = true);
164 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
165 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
166 AArch64_AM::ShiftExtendType ShiftType,
167 uint64_t ShiftImm, bool SetFlags = false,
168 bool WantResult = true);
169 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
170 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
171 AArch64_AM::ShiftExtendType ExtType,
172 uint64_t ShiftImm, bool SetFlags = false,
173 bool WantResult = true);
176 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
177 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
178 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
179 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
180 bool emitLoad(MVT VT, unsigned &ResultReg, Address Addr,
181 MachineMemOperand *MMO = nullptr);
182 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
183 MachineMemOperand *MMO = nullptr);
184 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
185 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
186 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
187 bool SetFlags = false, bool WantResult = true,
188 bool IsZExt = false);
189 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
190 bool SetFlags = false, bool WantResult = true,
191 bool IsZExt = false);
192 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
193 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
194 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
195 unsigned RHSReg, bool RHSIsKill,
196 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
197 bool WantResult = true);
198 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
200 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
201 bool LHSIsKill, uint64_t Imm);
202 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
203 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
205 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
206 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
207 unsigned Op1, bool Op1IsKill);
208 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
209 unsigned Op1, bool Op1IsKill);
210 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
211 unsigned Op1, bool Op1IsKill);
212 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
213 unsigned Op1Reg, bool Op1IsKill);
214 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
215 uint64_t Imm, bool IsZExt = true);
216 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
217 unsigned Op1Reg, bool Op1IsKill);
218 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
219 uint64_t Imm, bool IsZExt = true);
220 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
221 unsigned Op1Reg, bool Op1IsKill);
222 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
223 uint64_t Imm, bool IsZExt = false);
225 unsigned materializeInt(const ConstantInt *CI, MVT VT);
226 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
227 unsigned materializeGV(const GlobalValue *GV);
229 // Call handling routines.
231 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
232 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
234 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
237 // Backend specific FastISel code.
238 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
239 unsigned fastMaterializeConstant(const Constant *C) override;
240 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
242 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
243 const TargetLibraryInfo *LibInfo)
244 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
245 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
246 Context = &FuncInfo.Fn->getContext();
249 bool fastSelectInstruction(const Instruction *I) override;
251 #include "AArch64GenFastISel.inc"
254 } // end anonymous namespace
256 #include "AArch64GenCallingConv.inc"
258 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
259 if (CC == CallingConv::WebKit_JS)
260 return CC_AArch64_WebKit_JS;
261 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
264 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
265 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
266 "Alloca should always return a pointer.");
268 // Don't handle dynamic allocas.
269 if (!FuncInfo.StaticAllocaMap.count(AI))
272 DenseMap<const AllocaInst *, int>::iterator SI =
273 FuncInfo.StaticAllocaMap.find(AI);
275 if (SI != FuncInfo.StaticAllocaMap.end()) {
276 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
277 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
279 .addFrameIndex(SI->second)
288 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
293 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
295 // Create a copy from the zero register to materialize a "0" value.
296 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
297 : &AArch64::GPR32RegClass;
298 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
299 unsigned ResultReg = createResultReg(RC);
300 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
301 ResultReg).addReg(ZeroReg, getKillRegState(true));
305 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
306 // Positive zero (+0.0) has to be materialized with a fmov from the zero
307 // register, because the immediate version of fmov cannot encode zero.
308 if (CFP->isNullValue())
309 return fastMaterializeFloatZero(CFP);
311 if (VT != MVT::f32 && VT != MVT::f64)
314 const APFloat Val = CFP->getValueAPF();
315 bool Is64Bit = (VT == MVT::f64);
316 // This checks to see if we can use FMOV instructions to materialize
317 // a constant, otherwise we have to materialize via the constant pool.
318 if (TLI.isFPImmLegal(Val, VT)) {
320 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
321 assert((Imm != -1) && "Cannot encode floating-point constant.");
322 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
323 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
326 // Materialize via constant pool. MachineConstantPool wants an explicit
328 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
330 Align = DL.getTypeAllocSize(CFP->getType());
332 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
333 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
334 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
335 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
337 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
338 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
339 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
341 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
345 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
346 // We can't handle thread-local variables quickly yet.
347 if (GV->isThreadLocal())
350 // MachO still uses GOT for large code-model accesses, but ELF requires
351 // movz/movk sequences, which FastISel doesn't handle yet.
352 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
355 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
357 EVT DestEVT = TLI.getValueType(GV->getType(), true);
358 if (!DestEVT.isSimple())
361 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
364 if (OpFlags & AArch64II::MO_GOT) {
366 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
368 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
370 ResultReg = createResultReg(&AArch64::GPR64RegClass);
371 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
374 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
376 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
377 // We can't handle addresses loaded from a constant pool quickly yet.
381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
383 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
385 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
386 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
389 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
395 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
396 EVT CEVT = TLI.getValueType(C->getType(), true);
398 // Only handle simple types.
399 if (!CEVT.isSimple())
401 MVT VT = CEVT.getSimpleVT();
403 if (const auto *CI = dyn_cast<ConstantInt>(C))
404 return materializeInt(CI, VT);
405 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
406 return materializeFP(CFP, VT);
407 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
408 return materializeGV(GV);
413 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
414 assert(CFP->isNullValue() &&
415 "Floating-point constant is not a positive zero.");
417 if (!isTypeLegal(CFP->getType(), VT))
420 if (VT != MVT::f32 && VT != MVT::f64)
423 bool Is64Bit = (VT == MVT::f64);
424 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
425 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
426 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
429 /// \brief Check if the multiply is by a power-of-2 constant.
430 static bool isMulPowOf2(const Value *I) {
431 if (const auto *MI = dyn_cast<MulOperator>(I)) {
432 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
433 if (C->getValue().isPowerOf2())
435 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
436 if (C->getValue().isPowerOf2())
442 // Computes the address to get to an object.
443 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
445 const User *U = nullptr;
446 unsigned Opcode = Instruction::UserOp1;
447 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
448 // Don't walk into other basic blocks unless the object is an alloca from
449 // another block, otherwise it may not have a virtual register assigned.
450 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
451 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
452 Opcode = I->getOpcode();
455 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
456 Opcode = C->getOpcode();
460 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
461 if (Ty->getAddressSpace() > 255)
462 // Fast instruction selection doesn't support the special
469 case Instruction::BitCast: {
470 // Look through bitcasts.
471 return computeAddress(U->getOperand(0), Addr, Ty);
473 case Instruction::IntToPtr: {
474 // Look past no-op inttoptrs.
475 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
476 return computeAddress(U->getOperand(0), Addr, Ty);
479 case Instruction::PtrToInt: {
480 // Look past no-op ptrtoints.
481 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
482 return computeAddress(U->getOperand(0), Addr, Ty);
485 case Instruction::GetElementPtr: {
486 Address SavedAddr = Addr;
487 uint64_t TmpOffset = Addr.getOffset();
489 // Iterate through the GEP folding the constants into offsets where
491 gep_type_iterator GTI = gep_type_begin(U);
492 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
494 const Value *Op = *i;
495 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
496 const StructLayout *SL = DL.getStructLayout(STy);
497 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
498 TmpOffset += SL->getElementOffset(Idx);
500 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
502 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
503 // Constant-offset addressing.
504 TmpOffset += CI->getSExtValue() * S;
507 if (canFoldAddIntoGEP(U, Op)) {
508 // A compatible add with a constant operand. Fold the constant.
510 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
511 TmpOffset += CI->getSExtValue() * S;
512 // Iterate on the other operand.
513 Op = cast<AddOperator>(Op)->getOperand(0);
517 goto unsupported_gep;
522 // Try to grab the base operand now.
523 Addr.setOffset(TmpOffset);
524 if (computeAddress(U->getOperand(0), Addr, Ty))
527 // We failed, restore everything and try the other options.
533 case Instruction::Alloca: {
534 const AllocaInst *AI = cast<AllocaInst>(Obj);
535 DenseMap<const AllocaInst *, int>::iterator SI =
536 FuncInfo.StaticAllocaMap.find(AI);
537 if (SI != FuncInfo.StaticAllocaMap.end()) {
538 Addr.setKind(Address::FrameIndexBase);
539 Addr.setFI(SI->second);
544 case Instruction::Add: {
545 // Adds of constants are common and easy enough.
546 const Value *LHS = U->getOperand(0);
547 const Value *RHS = U->getOperand(1);
549 if (isa<ConstantInt>(LHS))
552 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
553 Addr.setOffset(Addr.getOffset() + (uint64_t)CI->getSExtValue());
554 return computeAddress(LHS, Addr, Ty);
557 Address Backup = Addr;
558 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
564 case Instruction::Shl:
565 if (Addr.getOffsetReg())
568 if (const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
569 unsigned Val = CI->getZExtValue();
570 if (Val < 1 || Val > 3)
573 uint64_t NumBytes = 0;
574 if (Ty && Ty->isSized()) {
575 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
576 NumBytes = NumBits / 8;
577 if (!isPowerOf2_64(NumBits))
581 if (NumBytes != (1ULL << Val))
585 Addr.setExtendType(AArch64_AM::LSL);
587 if (const auto *I = dyn_cast<Instruction>(U->getOperand(0)))
588 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
591 if (const auto *ZE = dyn_cast<ZExtInst>(U))
592 if (ZE->getOperand(0)->getType()->isIntegerTy(32))
593 Addr.setExtendType(AArch64_AM::UXTW);
595 if (const auto *SE = dyn_cast<SExtInst>(U))
596 if (SE->getOperand(0)->getType()->isIntegerTy(32))
597 Addr.setExtendType(AArch64_AM::SXTW);
599 unsigned Reg = getRegForValue(U->getOperand(0));
602 Addr.setOffsetReg(Reg);
606 case Instruction::Mul: {
607 if (Addr.getOffsetReg())
613 const Value *LHS = U->getOperand(0);
614 const Value *RHS = U->getOperand(1);
616 // Canonicalize power-of-2 value to the RHS.
617 if (const auto *C = dyn_cast<ConstantInt>(LHS))
618 if (C->getValue().isPowerOf2())
621 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
622 const auto *C = cast<ConstantInt>(RHS);
623 unsigned Val = C->getValue().logBase2();
624 if (Val < 1 || Val > 3)
627 uint64_t NumBytes = 0;
628 if (Ty && Ty->isSized()) {
629 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
630 NumBytes = NumBits / 8;
631 if (!isPowerOf2_64(NumBits))
635 if (NumBytes != (1ULL << Val))
639 Addr.setExtendType(AArch64_AM::LSL);
641 if (const auto *I = dyn_cast<Instruction>(LHS))
642 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
645 if (const auto *ZE = dyn_cast<ZExtInst>(U))
646 if (ZE->getOperand(0)->getType()->isIntegerTy(32)) {
647 Addr.setExtendType(AArch64_AM::UXTW);
648 LHS = U->getOperand(0);
651 if (const auto *SE = dyn_cast<SExtInst>(U))
652 if (SE->getOperand(0)->getType()->isIntegerTy(32)) {
653 Addr.setExtendType(AArch64_AM::SXTW);
654 LHS = U->getOperand(0);
657 unsigned Reg = getRegForValue(LHS);
660 Addr.setOffsetReg(Reg);
666 if (!Addr.getOffsetReg()) {
667 unsigned Reg = getRegForValue(Obj);
670 Addr.setOffsetReg(Reg);
676 unsigned Reg = getRegForValue(Obj);
683 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
684 const User *U = nullptr;
685 unsigned Opcode = Instruction::UserOp1;
688 if (const auto *I = dyn_cast<Instruction>(V)) {
689 Opcode = I->getOpcode();
691 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
692 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
693 Opcode = C->getOpcode();
699 case Instruction::BitCast:
700 // Look past bitcasts if its operand is in the same BB.
702 return computeCallAddress(U->getOperand(0), Addr);
704 case Instruction::IntToPtr:
705 // Look past no-op inttoptrs if its operand is in the same BB.
707 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
708 return computeCallAddress(U->getOperand(0), Addr);
710 case Instruction::PtrToInt:
711 // Look past no-op ptrtoints if its operand is in the same BB.
713 TLI.getValueType(U->getType()) == TLI.getPointerTy())
714 return computeCallAddress(U->getOperand(0), Addr);
718 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
719 Addr.setGlobalValue(GV);
723 // If all else fails, try to materialize the value in a register.
724 if (!Addr.getGlobalValue()) {
725 Addr.setReg(getRegForValue(V));
726 return Addr.getReg() != 0;
733 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
734 EVT evt = TLI.getValueType(Ty, true);
736 // Only handle simple types.
737 if (evt == MVT::Other || !evt.isSimple())
739 VT = evt.getSimpleVT();
741 // This is a legal type, but it's not something we handle in fast-isel.
745 // Handle all other legal types, i.e. a register that will directly hold this
747 return TLI.isTypeLegal(VT);
750 /// \brief Determine if the value type is supported by FastISel.
752 /// FastISel for AArch64 can handle more value types than are legal. This adds
753 /// simple value type such as i1, i8, and i16.
754 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
755 if (Ty->isVectorTy() && !IsVectorAllowed)
758 if (isTypeLegal(Ty, VT))
761 // If this is a type than can be sign or zero-extended to a basic operation
762 // go ahead and accept it now.
763 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
769 bool AArch64FastISel::isValueAvailable(const Value *V) const {
770 if (!isa<Instruction>(V))
773 const auto *I = cast<Instruction>(V);
774 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
780 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
781 unsigned ScaleFactor;
782 switch (VT.SimpleTy) {
783 default: return false;
784 case MVT::i1: // fall-through
785 case MVT::i8: ScaleFactor = 1; break;
786 case MVT::i16: ScaleFactor = 2; break;
787 case MVT::i32: // fall-through
788 case MVT::f32: ScaleFactor = 4; break;
789 case MVT::i64: // fall-through
790 case MVT::f64: ScaleFactor = 8; break;
793 bool ImmediateOffsetNeedsLowering = false;
794 bool RegisterOffsetNeedsLowering = false;
795 int64_t Offset = Addr.getOffset();
796 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
797 ImmediateOffsetNeedsLowering = true;
798 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
799 !isUInt<12>(Offset / ScaleFactor))
800 ImmediateOffsetNeedsLowering = true;
802 // Cannot encode an offset register and an immediate offset in the same
803 // instruction. Fold the immediate offset into the load/store instruction and
804 // emit an additonal add to take care of the offset register.
805 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.isRegBase() &&
807 RegisterOffsetNeedsLowering = true;
809 // Cannot encode zero register as base.
810 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
811 RegisterOffsetNeedsLowering = true;
813 // If this is a stack pointer and the offset needs to be simplified then put
814 // the alloca address into a register, set the base type back to register and
815 // continue. This should almost never happen.
816 if (ImmediateOffsetNeedsLowering && Addr.isFIBase()) {
817 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
818 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
820 .addFrameIndex(Addr.getFI())
823 Addr.setKind(Address::RegBase);
824 Addr.setReg(ResultReg);
827 if (RegisterOffsetNeedsLowering) {
828 unsigned ResultReg = 0;
830 if (Addr.getExtendType() == AArch64_AM::SXTW ||
831 Addr.getExtendType() == AArch64_AM::UXTW )
832 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
833 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
834 /*TODO:IsKill=*/false, Addr.getExtendType(),
837 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
838 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
839 /*TODO:IsKill=*/false, AArch64_AM::LSL,
842 if (Addr.getExtendType() == AArch64_AM::UXTW)
843 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
844 /*Op0IsKill=*/false, Addr.getShift(),
846 else if (Addr.getExtendType() == AArch64_AM::SXTW)
847 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
848 /*Op0IsKill=*/false, Addr.getShift(),
851 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
852 /*Op0IsKill=*/false, Addr.getShift());
857 Addr.setReg(ResultReg);
858 Addr.setOffsetReg(0);
860 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
863 // Since the offset is too large for the load/store instruction get the
864 // reg+offset into a register.
865 if (ImmediateOffsetNeedsLowering) {
866 unsigned ResultReg = 0;
868 ResultReg = fastEmit_ri_(MVT::i64, ISD::ADD, Addr.getReg(),
869 /*IsKill=*/false, Offset, MVT::i64);
871 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
875 Addr.setReg(ResultReg);
881 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
882 const MachineInstrBuilder &MIB,
884 unsigned ScaleFactor,
885 MachineMemOperand *MMO) {
886 int64_t Offset = Addr.getOffset() / ScaleFactor;
887 // Frame base works a bit differently. Handle it separately.
888 if (Addr.isFIBase()) {
889 int FI = Addr.getFI();
890 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
891 // and alignment should be based on the VT.
892 MMO = FuncInfo.MF->getMachineMemOperand(
893 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
894 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
895 // Now add the rest of the operands.
896 MIB.addFrameIndex(FI).addImm(Offset);
898 assert(Addr.isRegBase() && "Unexpected address kind.");
899 const MCInstrDesc &II = MIB->getDesc();
900 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
902 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
904 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
905 if (Addr.getOffsetReg()) {
906 assert(Addr.getOffset() == 0 && "Unexpected offset");
907 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
908 Addr.getExtendType() == AArch64_AM::SXTX;
909 MIB.addReg(Addr.getReg());
910 MIB.addReg(Addr.getOffsetReg());
911 MIB.addImm(IsSigned);
912 MIB.addImm(Addr.getShift() != 0);
914 MIB.addReg(Addr.getReg());
920 MIB.addMemOperand(MMO);
923 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
924 const Value *RHS, bool SetFlags,
925 bool WantResult, bool IsZExt) {
926 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
927 bool NeedExtend = false;
928 switch (RetVT.SimpleTy) {
936 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
940 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
942 case MVT::i32: // fall-through
947 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
949 // Canonicalize immediates to the RHS first.
950 if (UseAdd && isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
953 // Canonicalize mul by power of 2 to the RHS.
954 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
955 if (isMulPowOf2(LHS))
958 // Canonicalize shift immediate to the RHS.
959 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
960 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
961 if (isa<ConstantInt>(SI->getOperand(1)))
962 if (SI->getOpcode() == Instruction::Shl ||
963 SI->getOpcode() == Instruction::LShr ||
964 SI->getOpcode() == Instruction::AShr )
967 unsigned LHSReg = getRegForValue(LHS);
970 bool LHSIsKill = hasTrivialKill(LHS);
973 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
975 unsigned ResultReg = 0;
976 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
977 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
979 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
980 SetFlags, WantResult);
982 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
988 // Only extend the RHS within the instruction if there is a valid extend type.
989 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
990 isValueAvailable(RHS)) {
991 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
992 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
993 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
994 unsigned RHSReg = getRegForValue(SI->getOperand(0));
997 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
998 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
999 RHSIsKill, ExtendType, C->getZExtValue(),
1000 SetFlags, WantResult);
1002 unsigned RHSReg = getRegForValue(RHS);
1005 bool RHSIsKill = hasTrivialKill(RHS);
1006 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1007 ExtendType, 0, SetFlags, WantResult);
1010 // Check if the mul can be folded into the instruction.
1011 if (RHS->hasOneUse() && isValueAvailable(RHS))
1012 if (isMulPowOf2(RHS)) {
1013 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1014 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1016 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1017 if (C->getValue().isPowerOf2())
1018 std::swap(MulLHS, MulRHS);
1020 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1021 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1022 unsigned RHSReg = getRegForValue(MulLHS);
1025 bool RHSIsKill = hasTrivialKill(MulLHS);
1026 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1027 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1030 // Check if the shift can be folded into the instruction.
1031 if (RHS->hasOneUse() && isValueAvailable(RHS))
1032 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1033 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1034 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1035 switch (SI->getOpcode()) {
1037 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1038 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1039 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1041 uint64_t ShiftVal = C->getZExtValue();
1042 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1043 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1046 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1047 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1048 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1054 unsigned RHSReg = getRegForValue(RHS);
1057 bool RHSIsKill = hasTrivialKill(RHS);
1060 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1062 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1063 SetFlags, WantResult);
1066 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1067 bool LHSIsKill, unsigned RHSReg,
1068 bool RHSIsKill, bool SetFlags,
1070 assert(LHSReg && RHSReg && "Invalid register number.");
1072 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1075 static const unsigned OpcTable[2][2][2] = {
1076 { { AArch64::SUBWrr, AArch64::SUBXrr },
1077 { AArch64::ADDWrr, AArch64::ADDXrr } },
1078 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1079 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1081 bool Is64Bit = RetVT == MVT::i64;
1082 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1083 const TargetRegisterClass *RC =
1084 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1087 ResultReg = createResultReg(RC);
1089 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1091 const MCInstrDesc &II = TII.get(Opc);
1092 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1093 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1094 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1095 .addReg(LHSReg, getKillRegState(LHSIsKill))
1096 .addReg(RHSReg, getKillRegState(RHSIsKill));
1100 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1101 bool LHSIsKill, uint64_t Imm,
1102 bool SetFlags, bool WantResult) {
1103 assert(LHSReg && "Invalid register number.");
1105 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1109 if (isUInt<12>(Imm))
1111 else if ((Imm & 0xfff000) == Imm) {
1117 static const unsigned OpcTable[2][2][2] = {
1118 { { AArch64::SUBWri, AArch64::SUBXri },
1119 { AArch64::ADDWri, AArch64::ADDXri } },
1120 { { AArch64::SUBSWri, AArch64::SUBSXri },
1121 { AArch64::ADDSWri, AArch64::ADDSXri } }
1123 bool Is64Bit = RetVT == MVT::i64;
1124 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1125 const TargetRegisterClass *RC;
1127 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1129 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1132 ResultReg = createResultReg(RC);
1134 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1136 const MCInstrDesc &II = TII.get(Opc);
1137 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1138 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1139 .addReg(LHSReg, getKillRegState(LHSIsKill))
1141 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1145 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1146 bool LHSIsKill, unsigned RHSReg,
1148 AArch64_AM::ShiftExtendType ShiftType,
1149 uint64_t ShiftImm, bool SetFlags,
1151 assert(LHSReg && RHSReg && "Invalid register number.");
1153 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1156 static const unsigned OpcTable[2][2][2] = {
1157 { { AArch64::SUBWrs, AArch64::SUBXrs },
1158 { AArch64::ADDWrs, AArch64::ADDXrs } },
1159 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1160 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1162 bool Is64Bit = RetVT == MVT::i64;
1163 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1164 const TargetRegisterClass *RC =
1165 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1168 ResultReg = createResultReg(RC);
1170 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1172 const MCInstrDesc &II = TII.get(Opc);
1173 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1174 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1175 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1176 .addReg(LHSReg, getKillRegState(LHSIsKill))
1177 .addReg(RHSReg, getKillRegState(RHSIsKill))
1178 .addImm(getShifterImm(ShiftType, ShiftImm));
1182 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1183 bool LHSIsKill, unsigned RHSReg,
1185 AArch64_AM::ShiftExtendType ExtType,
1186 uint64_t ShiftImm, bool SetFlags,
1188 assert(LHSReg && RHSReg && "Invalid register number.");
1190 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1193 static const unsigned OpcTable[2][2][2] = {
1194 { { AArch64::SUBWrx, AArch64::SUBXrx },
1195 { AArch64::ADDWrx, AArch64::ADDXrx } },
1196 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1197 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1199 bool Is64Bit = RetVT == MVT::i64;
1200 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1201 const TargetRegisterClass *RC = nullptr;
1203 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1205 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1208 ResultReg = createResultReg(RC);
1210 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1212 const MCInstrDesc &II = TII.get(Opc);
1213 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1214 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1216 .addReg(LHSReg, getKillRegState(LHSIsKill))
1217 .addReg(RHSReg, getKillRegState(RHSIsKill))
1218 .addImm(getArithExtendImm(ExtType, ShiftImm));
1222 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1223 Type *Ty = LHS->getType();
1224 EVT EVT = TLI.getValueType(Ty, true);
1225 if (!EVT.isSimple())
1227 MVT VT = EVT.getSimpleVT();
1229 switch (VT.SimpleTy) {
1237 return emitICmp(VT, LHS, RHS, IsZExt);
1240 return emitFCmp(VT, LHS, RHS);
1244 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1246 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1250 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1252 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1253 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1256 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1257 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1260 // Check to see if the 2nd operand is a constant that we can encode directly
1262 bool UseImm = false;
1263 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1264 if (CFP->isZero() && !CFP->isNegative())
1267 unsigned LHSReg = getRegForValue(LHS);
1270 bool LHSIsKill = hasTrivialKill(LHS);
1273 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1275 .addReg(LHSReg, getKillRegState(LHSIsKill));
1279 unsigned RHSReg = getRegForValue(RHS);
1282 bool RHSIsKill = hasTrivialKill(RHS);
1284 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1285 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1286 .addReg(LHSReg, getKillRegState(LHSIsKill))
1287 .addReg(RHSReg, getKillRegState(RHSIsKill));
1291 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1292 bool SetFlags, bool WantResult, bool IsZExt) {
1293 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1297 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1298 bool SetFlags, bool WantResult, bool IsZExt) {
1299 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1303 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1304 bool LHSIsKill, unsigned RHSReg,
1305 bool RHSIsKill, bool WantResult) {
1306 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1307 RHSIsKill, /*SetFlags=*/true, WantResult);
1310 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1311 bool LHSIsKill, unsigned RHSReg,
1313 AArch64_AM::ShiftExtendType ShiftType,
1314 uint64_t ShiftImm, bool WantResult) {
1315 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1316 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1320 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1321 const Value *LHS, const Value *RHS) {
1322 // Canonicalize immediates to the RHS first.
1323 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1324 std::swap(LHS, RHS);
1326 // Canonicalize mul by power-of-2 to the RHS.
1327 if (LHS->hasOneUse() && isValueAvailable(LHS))
1328 if (isMulPowOf2(LHS))
1329 std::swap(LHS, RHS);
1331 // Canonicalize shift immediate to the RHS.
1332 if (LHS->hasOneUse() && isValueAvailable(LHS))
1333 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1334 if (isa<ConstantInt>(SI->getOperand(1)))
1335 std::swap(LHS, RHS);
1337 unsigned LHSReg = getRegForValue(LHS);
1340 bool LHSIsKill = hasTrivialKill(LHS);
1342 unsigned ResultReg = 0;
1343 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1344 uint64_t Imm = C->getZExtValue();
1345 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1350 // Check if the mul can be folded into the instruction.
1351 if (RHS->hasOneUse() && isValueAvailable(RHS))
1352 if (isMulPowOf2(RHS)) {
1353 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1354 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1356 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1357 if (C->getValue().isPowerOf2())
1358 std::swap(MulLHS, MulRHS);
1360 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1361 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1363 unsigned RHSReg = getRegForValue(MulLHS);
1366 bool RHSIsKill = hasTrivialKill(MulLHS);
1367 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1368 RHSIsKill, ShiftVal);
1371 // Check if the shift can be folded into the instruction.
1372 if (RHS->hasOneUse() && isValueAvailable(RHS))
1373 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1374 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1375 uint64_t ShiftVal = C->getZExtValue();
1376 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1379 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1380 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1381 RHSIsKill, ShiftVal);
1384 unsigned RHSReg = getRegForValue(RHS);
1387 bool RHSIsKill = hasTrivialKill(RHS);
1389 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1390 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1391 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1392 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1393 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1398 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1399 unsigned LHSReg, bool LHSIsKill,
1401 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1402 "ISD nodes are not consecutive!");
1403 static const unsigned OpcTable[3][2] = {
1404 { AArch64::ANDWri, AArch64::ANDXri },
1405 { AArch64::ORRWri, AArch64::ORRXri },
1406 { AArch64::EORWri, AArch64::EORXri }
1408 const TargetRegisterClass *RC;
1411 switch (RetVT.SimpleTy) {
1418 unsigned Idx = ISDOpc - ISD::AND;
1419 Opc = OpcTable[Idx][0];
1420 RC = &AArch64::GPR32spRegClass;
1425 Opc = OpcTable[ISDOpc - ISD::AND][1];
1426 RC = &AArch64::GPR64spRegClass;
1431 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1434 unsigned ResultReg =
1435 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1436 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1437 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1438 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1439 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1444 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1445 unsigned LHSReg, bool LHSIsKill,
1446 unsigned RHSReg, bool RHSIsKill,
1447 uint64_t ShiftImm) {
1448 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1449 "ISD nodes are not consecutive!");
1450 static const unsigned OpcTable[3][2] = {
1451 { AArch64::ANDWrs, AArch64::ANDXrs },
1452 { AArch64::ORRWrs, AArch64::ORRXrs },
1453 { AArch64::EORWrs, AArch64::EORXrs }
1455 const TargetRegisterClass *RC;
1457 switch (RetVT.SimpleTy) {
1464 Opc = OpcTable[ISDOpc - ISD::AND][0];
1465 RC = &AArch64::GPR32RegClass;
1468 Opc = OpcTable[ISDOpc - ISD::AND][1];
1469 RC = &AArch64::GPR64RegClass;
1472 unsigned ResultReg =
1473 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1474 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1475 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1476 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1477 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1482 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1484 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1487 bool AArch64FastISel::emitLoad(MVT VT, unsigned &ResultReg, Address Addr,
1488 MachineMemOperand *MMO) {
1489 // Simplify this down to something we can handle.
1490 if (!simplifyAddress(Addr, VT))
1493 unsigned ScaleFactor;
1494 switch (VT.SimpleTy) {
1495 default: llvm_unreachable("Unexpected value type.");
1496 case MVT::i1: // fall-through
1497 case MVT::i8: ScaleFactor = 1; break;
1498 case MVT::i16: ScaleFactor = 2; break;
1499 case MVT::i32: // fall-through
1500 case MVT::f32: ScaleFactor = 4; break;
1501 case MVT::i64: // fall-through
1502 case MVT::f64: ScaleFactor = 8; break;
1505 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1506 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1507 bool UseScaled = true;
1508 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1513 static const unsigned OpcTable[4][6] = {
1514 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi, AArch64::LDURXi,
1515 AArch64::LDURSi, AArch64::LDURDi },
1516 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui, AArch64::LDRXui,
1517 AArch64::LDRSui, AArch64::LDRDui },
1518 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX, AArch64::LDRXroX,
1519 AArch64::LDRSroX, AArch64::LDRDroX },
1520 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW, AArch64::LDRXroW,
1521 AArch64::LDRSroW, AArch64::LDRDroW }
1525 const TargetRegisterClass *RC;
1526 bool VTIsi1 = false;
1527 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1528 Addr.getOffsetReg();
1529 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1530 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1531 Addr.getExtendType() == AArch64_AM::SXTW)
1534 switch (VT.SimpleTy) {
1535 default: llvm_unreachable("Unexpected value type.");
1536 case MVT::i1: VTIsi1 = true; // Intentional fall-through.
1537 case MVT::i8: Opc = OpcTable[Idx][0]; RC = &AArch64::GPR32RegClass; break;
1538 case MVT::i16: Opc = OpcTable[Idx][1]; RC = &AArch64::GPR32RegClass; break;
1539 case MVT::i32: Opc = OpcTable[Idx][2]; RC = &AArch64::GPR32RegClass; break;
1540 case MVT::i64: Opc = OpcTable[Idx][3]; RC = &AArch64::GPR64RegClass; break;
1541 case MVT::f32: Opc = OpcTable[Idx][4]; RC = &AArch64::FPR32RegClass; break;
1542 case MVT::f64: Opc = OpcTable[Idx][5]; RC = &AArch64::FPR64RegClass; break;
1545 // Create the base instruction, then add the operands.
1546 ResultReg = createResultReg(RC);
1547 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1548 TII.get(Opc), ResultReg);
1549 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1551 // Loading an i1 requires special handling.
1553 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1554 assert(ANDReg && "Unexpected AND instruction emission failure.");
1560 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1562 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1566 return selectOperator(I, I->getOpcode());
1569 switch (I->getOpcode()) {
1571 llvm_unreachable("Unexpected instruction.");
1572 case Instruction::Add:
1573 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1575 case Instruction::Sub:
1576 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1582 updateValueMap(I, ResultReg);
1586 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1588 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1592 return selectOperator(I, I->getOpcode());
1595 switch (I->getOpcode()) {
1597 llvm_unreachable("Unexpected instruction.");
1598 case Instruction::And:
1599 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1601 case Instruction::Or:
1602 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1604 case Instruction::Xor:
1605 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1611 updateValueMap(I, ResultReg);
1615 bool AArch64FastISel::selectLoad(const Instruction *I) {
1617 // Verify we have a legal type before going any further. Currently, we handle
1618 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1619 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1620 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1621 cast<LoadInst>(I)->isAtomic())
1624 // See if we can handle this address.
1626 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1630 if (!emitLoad(VT, ResultReg, Addr, createMachineMemOperandFor(I)))
1633 updateValueMap(I, ResultReg);
1637 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1638 MachineMemOperand *MMO) {
1639 // Simplify this down to something we can handle.
1640 if (!simplifyAddress(Addr, VT))
1643 unsigned ScaleFactor;
1644 switch (VT.SimpleTy) {
1645 default: llvm_unreachable("Unexpected value type.");
1646 case MVT::i1: // fall-through
1647 case MVT::i8: ScaleFactor = 1; break;
1648 case MVT::i16: ScaleFactor = 2; break;
1649 case MVT::i32: // fall-through
1650 case MVT::f32: ScaleFactor = 4; break;
1651 case MVT::i64: // fall-through
1652 case MVT::f64: ScaleFactor = 8; break;
1655 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1656 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1657 bool UseScaled = true;
1658 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1664 static const unsigned OpcTable[4][6] = {
1665 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1666 AArch64::STURSi, AArch64::STURDi },
1667 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1668 AArch64::STRSui, AArch64::STRDui },
1669 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1670 AArch64::STRSroX, AArch64::STRDroX },
1671 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1672 AArch64::STRSroW, AArch64::STRDroW }
1677 bool VTIsi1 = false;
1678 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1679 Addr.getOffsetReg();
1680 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1681 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1682 Addr.getExtendType() == AArch64_AM::SXTW)
1685 switch (VT.SimpleTy) {
1686 default: llvm_unreachable("Unexpected value type.");
1687 case MVT::i1: VTIsi1 = true;
1688 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1689 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1690 case MVT::i32: Opc = OpcTable[Idx][2]; break;
1691 case MVT::i64: Opc = OpcTable[Idx][3]; break;
1692 case MVT::f32: Opc = OpcTable[Idx][4]; break;
1693 case MVT::f64: Opc = OpcTable[Idx][5]; break;
1696 // Storing an i1 requires special handling.
1697 if (VTIsi1 && SrcReg != AArch64::WZR) {
1698 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1699 assert(ANDReg && "Unexpected AND instruction emission failure.");
1702 // Create the base instruction, then add the operands.
1703 const MCInstrDesc &II = TII.get(Opc);
1704 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
1705 MachineInstrBuilder MIB =
1706 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
1707 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
1712 bool AArch64FastISel::selectStore(const Instruction *I) {
1714 const Value *Op0 = I->getOperand(0);
1715 // Verify we have a legal type before going any further. Currently, we handle
1716 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1717 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1718 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
1719 cast<StoreInst>(I)->isAtomic())
1722 // Get the value to be stored into a register. Use the zero register directly
1723 // when possible to avoid an unnecessary copy and a wasted register.
1724 unsigned SrcReg = 0;
1725 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
1727 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
1728 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
1729 if (CF->isZero() && !CF->isNegative()) {
1730 VT = MVT::getIntegerVT(VT.getSizeInBits());
1731 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
1736 SrcReg = getRegForValue(Op0);
1741 // See if we can handle this address.
1743 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
1746 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
1751 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
1753 case CmpInst::FCMP_ONE:
1754 case CmpInst::FCMP_UEQ:
1756 // AL is our "false" for now. The other two need more compares.
1757 return AArch64CC::AL;
1758 case CmpInst::ICMP_EQ:
1759 case CmpInst::FCMP_OEQ:
1760 return AArch64CC::EQ;
1761 case CmpInst::ICMP_SGT:
1762 case CmpInst::FCMP_OGT:
1763 return AArch64CC::GT;
1764 case CmpInst::ICMP_SGE:
1765 case CmpInst::FCMP_OGE:
1766 return AArch64CC::GE;
1767 case CmpInst::ICMP_UGT:
1768 case CmpInst::FCMP_UGT:
1769 return AArch64CC::HI;
1770 case CmpInst::FCMP_OLT:
1771 return AArch64CC::MI;
1772 case CmpInst::ICMP_ULE:
1773 case CmpInst::FCMP_OLE:
1774 return AArch64CC::LS;
1775 case CmpInst::FCMP_ORD:
1776 return AArch64CC::VC;
1777 case CmpInst::FCMP_UNO:
1778 return AArch64CC::VS;
1779 case CmpInst::FCMP_UGE:
1780 return AArch64CC::PL;
1781 case CmpInst::ICMP_SLT:
1782 case CmpInst::FCMP_ULT:
1783 return AArch64CC::LT;
1784 case CmpInst::ICMP_SLE:
1785 case CmpInst::FCMP_ULE:
1786 return AArch64CC::LE;
1787 case CmpInst::FCMP_UNE:
1788 case CmpInst::ICMP_NE:
1789 return AArch64CC::NE;
1790 case CmpInst::ICMP_UGE:
1791 return AArch64CC::HS;
1792 case CmpInst::ICMP_ULT:
1793 return AArch64CC::LO;
1797 /// \brief Check if the comparison against zero and the following branch can be
1798 /// folded into a single instruction (CBZ or CBNZ).
1799 static bool canFoldZeroCheckIntoBranch(const CmpInst *CI) {
1800 CmpInst::Predicate Predicate = CI->getPredicate();
1801 if ((Predicate != CmpInst::ICMP_EQ) && (Predicate != CmpInst::ICMP_NE))
1804 Type *Ty = CI->getOperand(0)->getType();
1805 if (!Ty->isIntegerTy())
1808 unsigned BW = cast<IntegerType>(Ty)->getBitWidth();
1809 if (BW != 1 && BW != 8 && BW != 16 && BW != 32 && BW != 64)
1812 if (const auto *C = dyn_cast<ConstantInt>(CI->getOperand(0)))
1813 if (C->isNullValue())
1816 if (const auto *C = dyn_cast<ConstantInt>(CI->getOperand(1)))
1817 if (C->isNullValue())
1823 bool AArch64FastISel::selectBranch(const Instruction *I) {
1824 const BranchInst *BI = cast<BranchInst>(I);
1825 if (BI->isUnconditional()) {
1826 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
1827 fastEmitBranch(MSucc, BI->getDebugLoc());
1831 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1832 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1834 AArch64CC::CondCode CC = AArch64CC::NE;
1835 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1836 if (CI->hasOneUse() && isValueAvailable(CI)) {
1837 // Try to optimize or fold the cmp.
1838 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1839 switch (Predicate) {
1842 case CmpInst::FCMP_FALSE:
1843 fastEmitBranch(FBB, DbgLoc);
1845 case CmpInst::FCMP_TRUE:
1846 fastEmitBranch(TBB, DbgLoc);
1850 // Try to take advantage of fallthrough opportunities.
1851 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1852 std::swap(TBB, FBB);
1853 Predicate = CmpInst::getInversePredicate(Predicate);
1856 // Try to optimize comparisons against zero.
1857 if (canFoldZeroCheckIntoBranch(CI)) {
1858 const Value *LHS = CI->getOperand(0);
1859 const Value *RHS = CI->getOperand(1);
1861 // Canonicalize zero values to the RHS.
1862 if (const auto *C = dyn_cast<ConstantInt>(LHS))
1863 if (C->isNullValue())
1864 std::swap(LHS, RHS);
1867 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
1868 if (AI->getOpcode() == Instruction::And) {
1869 const Value *AndLHS = AI->getOperand(0);
1870 const Value *AndRHS = AI->getOperand(1);
1872 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
1873 if (C->getValue().isPowerOf2())
1874 std::swap(AndLHS, AndRHS);
1876 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
1877 if (C->getValue().isPowerOf2()) {
1878 TestBit = C->getValue().logBase2();
1883 static const unsigned OpcTable[2][2][2] = {
1884 { {AArch64::CBZW, AArch64::CBZX },
1885 {AArch64::CBNZW, AArch64::CBNZX} },
1886 { {AArch64::TBZW, AArch64::TBZX },
1887 {AArch64::TBNZW, AArch64::TBNZX} }
1889 bool IsBitTest = TestBit != -1;
1890 bool IsCmpNE = Predicate == CmpInst::ICMP_NE;
1891 bool Is64Bit = LHS->getType()->isIntegerTy(64);
1892 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
1894 unsigned SrcReg = getRegForValue(LHS);
1897 bool SrcIsKill = hasTrivialKill(LHS);
1899 // Emit the combined compare and branch instruction.
1900 MachineInstrBuilder MIB =
1901 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1902 .addReg(SrcReg, getKillRegState(SrcIsKill));
1904 MIB.addImm(TestBit);
1907 // Obtain the branch weight and add the TrueBB to the successor list.
1908 uint32_t BranchWeight = 0;
1910 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1911 TBB->getBasicBlock());
1912 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1914 fastEmitBranch(FBB, DbgLoc);
1919 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1922 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
1924 CC = getCompareCC(Predicate);
1925 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
1926 switch (Predicate) {
1929 case CmpInst::FCMP_UEQ:
1930 ExtraCC = AArch64CC::EQ;
1933 case CmpInst::FCMP_ONE:
1934 ExtraCC = AArch64CC::MI;
1938 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
1940 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
1941 if (ExtraCC != AArch64CC::AL) {
1942 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1948 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1952 // Obtain the branch weight and add the TrueBB to the successor list.
1953 uint32_t BranchWeight = 0;
1955 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1956 TBB->getBasicBlock());
1957 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1959 fastEmitBranch(FBB, DbgLoc);
1962 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1964 if (TI->hasOneUse() && isValueAvailable(TI) &&
1965 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
1966 unsigned CondReg = getRegForValue(TI->getOperand(0));
1969 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
1971 // Issue an extract_subreg to get the lower 32-bits.
1972 if (SrcVT == MVT::i64) {
1973 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
1978 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
1979 assert(ANDReg && "Unexpected AND instruction emission failure.");
1980 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
1982 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1983 std::swap(TBB, FBB);
1986 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1990 // Obtain the branch weight and add the TrueBB to the successor list.
1991 uint32_t BranchWeight = 0;
1993 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1994 TBB->getBasicBlock());
1995 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1997 fastEmitBranch(FBB, DbgLoc);
2000 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2001 uint64_t Imm = CI->getZExtValue();
2002 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2003 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2006 // Obtain the branch weight and add the target to the successor list.
2007 uint32_t BranchWeight = 0;
2009 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2010 Target->getBasicBlock());
2011 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2013 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2014 // Fake request the condition, otherwise the intrinsic might be completely
2016 unsigned CondReg = getRegForValue(BI->getCondition());
2021 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2025 // Obtain the branch weight and add the TrueBB to the successor list.
2026 uint32_t BranchWeight = 0;
2028 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2029 TBB->getBasicBlock());
2030 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2032 fastEmitBranch(FBB, DbgLoc);
2036 unsigned CondReg = getRegForValue(BI->getCondition());
2039 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2041 // We've been divorced from our compare! Our block was split, and
2042 // now our compare lives in a predecessor block. We musn't
2043 // re-compare here, as the children of the compare aren't guaranteed
2044 // live across the block boundary (we *could* check for this).
2045 // Regardless, the compare has been done in the predecessor block,
2046 // and it left a value for us in a virtual register. Ergo, we test
2047 // the one-bit value left in the virtual register.
2048 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2050 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2051 std::swap(TBB, FBB);
2055 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2059 // Obtain the branch weight and add the TrueBB to the successor list.
2060 uint32_t BranchWeight = 0;
2062 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2063 TBB->getBasicBlock());
2064 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2066 fastEmitBranch(FBB, DbgLoc);
2070 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2071 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2072 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2076 // Emit the indirect branch.
2077 const MCInstrDesc &II = TII.get(AArch64::BR);
2078 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2079 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2081 // Make sure the CFG is up-to-date.
2082 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2083 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2088 bool AArch64FastISel::selectCmp(const Instruction *I) {
2089 const CmpInst *CI = cast<CmpInst>(I);
2091 // Try to optimize or fold the cmp.
2092 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2093 unsigned ResultReg = 0;
2094 switch (Predicate) {
2097 case CmpInst::FCMP_FALSE:
2098 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2099 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2100 TII.get(TargetOpcode::COPY), ResultReg)
2101 .addReg(AArch64::WZR, getKillRegState(true));
2103 case CmpInst::FCMP_TRUE:
2104 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2109 updateValueMap(I, ResultReg);
2114 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2117 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2119 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2120 // condition codes are inverted, because they are used by CSINC.
2121 static unsigned CondCodeTable[2][2] = {
2122 { AArch64CC::NE, AArch64CC::VC },
2123 { AArch64CC::PL, AArch64CC::LE }
2125 unsigned *CondCodes = nullptr;
2126 switch (Predicate) {
2129 case CmpInst::FCMP_UEQ:
2130 CondCodes = &CondCodeTable[0][0];
2132 case CmpInst::FCMP_ONE:
2133 CondCodes = &CondCodeTable[1][0];
2138 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2139 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2141 .addReg(AArch64::WZR, getKillRegState(true))
2142 .addReg(AArch64::WZR, getKillRegState(true))
2143 .addImm(CondCodes[0]);
2144 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2146 .addReg(TmpReg1, getKillRegState(true))
2147 .addReg(AArch64::WZR, getKillRegState(true))
2148 .addImm(CondCodes[1]);
2150 updateValueMap(I, ResultReg);
2154 // Now set a register based on the comparison.
2155 AArch64CC::CondCode CC = getCompareCC(Predicate);
2156 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2157 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2158 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2160 .addReg(AArch64::WZR, getKillRegState(true))
2161 .addReg(AArch64::WZR, getKillRegState(true))
2162 .addImm(invertedCC);
2164 updateValueMap(I, ResultReg);
2168 bool AArch64FastISel::selectSelect(const Instruction *I) {
2169 const SelectInst *SI = cast<SelectInst>(I);
2171 EVT DestEVT = TLI.getValueType(SI->getType(), true);
2172 if (!DestEVT.isSimple())
2175 MVT DestVT = DestEVT.getSimpleVT();
2176 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
2181 const TargetRegisterClass *RC = nullptr;
2182 switch (DestVT.SimpleTy) {
2183 default: return false;
2185 SelectOpc = AArch64::CSELWr; RC = &AArch64::GPR32RegClass; break;
2187 SelectOpc = AArch64::CSELXr; RC = &AArch64::GPR64RegClass; break;
2189 SelectOpc = AArch64::FCSELSrrr; RC = &AArch64::FPR32RegClass; break;
2191 SelectOpc = AArch64::FCSELDrrr; RC = &AArch64::FPR64RegClass; break;
2194 const Value *Cond = SI->getCondition();
2195 bool NeedTest = true;
2196 AArch64CC::CondCode CC = AArch64CC::NE;
2197 if (foldXALUIntrinsic(CC, I, Cond))
2200 unsigned CondReg = getRegForValue(Cond);
2203 bool CondIsKill = hasTrivialKill(Cond);
2206 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2207 assert(ANDReg && "Unexpected AND instruction emission failure.");
2208 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2211 unsigned TrueReg = getRegForValue(SI->getTrueValue());
2212 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
2214 unsigned FalseReg = getRegForValue(SI->getFalseValue());
2215 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
2217 if (!TrueReg || !FalseReg)
2220 unsigned ResultReg = fastEmitInst_rri(SelectOpc, RC, TrueReg, TrueIsKill,
2221 FalseReg, FalseIsKill, CC);
2222 updateValueMap(I, ResultReg);
2226 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2227 Value *V = I->getOperand(0);
2228 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2231 unsigned Op = getRegForValue(V);
2235 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2236 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2237 ResultReg).addReg(Op);
2238 updateValueMap(I, ResultReg);
2242 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2243 Value *V = I->getOperand(0);
2244 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2247 unsigned Op = getRegForValue(V);
2251 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2252 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2253 ResultReg).addReg(Op);
2254 updateValueMap(I, ResultReg);
2258 // FPToUI and FPToSI
2259 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2261 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2264 unsigned SrcReg = getRegForValue(I->getOperand(0));
2268 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2269 if (SrcVT == MVT::f128)
2273 if (SrcVT == MVT::f64) {
2275 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2277 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2280 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2282 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2284 unsigned ResultReg = createResultReg(
2285 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2286 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2288 updateValueMap(I, ResultReg);
2292 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2294 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2296 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2297 "Unexpected value type.");
2299 unsigned SrcReg = getRegForValue(I->getOperand(0));
2302 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2304 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2306 // Handle sign-extension.
2307 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2309 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2316 if (SrcVT == MVT::i64) {
2318 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2320 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2323 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2325 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2328 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2330 updateValueMap(I, ResultReg);
2334 bool AArch64FastISel::fastLowerArguments() {
2335 if (!FuncInfo.CanLowerReturn)
2338 const Function *F = FuncInfo.Fn;
2342 CallingConv::ID CC = F->getCallingConv();
2343 if (CC != CallingConv::C)
2346 // Only handle simple cases of up to 8 GPR and FPR each.
2347 unsigned GPRCnt = 0;
2348 unsigned FPRCnt = 0;
2350 for (auto const &Arg : F->args()) {
2351 // The first argument is at index 1.
2353 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2354 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2355 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2356 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2359 Type *ArgTy = Arg.getType();
2360 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2363 EVT ArgVT = TLI.getValueType(ArgTy);
2364 if (!ArgVT.isSimple())
2367 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2368 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2371 if (VT.isVector() &&
2372 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2375 if (VT >= MVT::i1 && VT <= MVT::i64)
2377 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2378 VT.is128BitVector())
2383 if (GPRCnt > 8 || FPRCnt > 8)
2387 static const MCPhysReg Registers[6][8] = {
2388 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2389 AArch64::W5, AArch64::W6, AArch64::W7 },
2390 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2391 AArch64::X5, AArch64::X6, AArch64::X7 },
2392 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2393 AArch64::H5, AArch64::H6, AArch64::H7 },
2394 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2395 AArch64::S5, AArch64::S6, AArch64::S7 },
2396 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2397 AArch64::D5, AArch64::D6, AArch64::D7 },
2398 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2399 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2402 unsigned GPRIdx = 0;
2403 unsigned FPRIdx = 0;
2404 for (auto const &Arg : F->args()) {
2405 MVT VT = TLI.getSimpleValueType(Arg.getType());
2407 const TargetRegisterClass *RC;
2408 if (VT >= MVT::i1 && VT <= MVT::i32) {
2409 SrcReg = Registers[0][GPRIdx++];
2410 RC = &AArch64::GPR32RegClass;
2412 } else if (VT == MVT::i64) {
2413 SrcReg = Registers[1][GPRIdx++];
2414 RC = &AArch64::GPR64RegClass;
2415 } else if (VT == MVT::f16) {
2416 SrcReg = Registers[2][FPRIdx++];
2417 RC = &AArch64::FPR16RegClass;
2418 } else if (VT == MVT::f32) {
2419 SrcReg = Registers[3][FPRIdx++];
2420 RC = &AArch64::FPR32RegClass;
2421 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2422 SrcReg = Registers[4][FPRIdx++];
2423 RC = &AArch64::FPR64RegClass;
2424 } else if (VT.is128BitVector()) {
2425 SrcReg = Registers[5][FPRIdx++];
2426 RC = &AArch64::FPR128RegClass;
2428 llvm_unreachable("Unexpected value type.");
2430 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2431 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2432 // Without this, EmitLiveInCopies may eliminate the livein if its only
2433 // use is a bitcast (which isn't turned into an instruction).
2434 unsigned ResultReg = createResultReg(RC);
2435 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2436 TII.get(TargetOpcode::COPY), ResultReg)
2437 .addReg(DstReg, getKillRegState(true));
2438 updateValueMap(&Arg, ResultReg);
2443 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2444 SmallVectorImpl<MVT> &OutVTs,
2445 unsigned &NumBytes) {
2446 CallingConv::ID CC = CLI.CallConv;
2447 SmallVector<CCValAssign, 16> ArgLocs;
2448 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2449 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2451 // Get a count of how many bytes are to be pushed on the stack.
2452 NumBytes = CCInfo.getNextStackOffset();
2454 // Issue CALLSEQ_START
2455 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2456 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2459 // Process the args.
2460 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2461 CCValAssign &VA = ArgLocs[i];
2462 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2463 MVT ArgVT = OutVTs[VA.getValNo()];
2465 unsigned ArgReg = getRegForValue(ArgVal);
2469 // Handle arg promotion: SExt, ZExt, AExt.
2470 switch (VA.getLocInfo()) {
2471 case CCValAssign::Full:
2473 case CCValAssign::SExt: {
2474 MVT DestVT = VA.getLocVT();
2476 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2481 case CCValAssign::AExt:
2482 // Intentional fall-through.
2483 case CCValAssign::ZExt: {
2484 MVT DestVT = VA.getLocVT();
2486 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2492 llvm_unreachable("Unknown arg promotion!");
2495 // Now copy/store arg to correct locations.
2496 if (VA.isRegLoc() && !VA.needsCustom()) {
2497 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2498 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2499 CLI.OutRegs.push_back(VA.getLocReg());
2500 } else if (VA.needsCustom()) {
2501 // FIXME: Handle custom args.
2504 assert(VA.isMemLoc() && "Assuming store on stack.");
2506 // Don't emit stores for undef values.
2507 if (isa<UndefValue>(ArgVal))
2510 // Need to store on the stack.
2511 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2513 unsigned BEAlign = 0;
2514 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2515 BEAlign = 8 - ArgSize;
2518 Addr.setKind(Address::RegBase);
2519 Addr.setReg(AArch64::SP);
2520 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2522 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2523 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2524 MachinePointerInfo::getStack(Addr.getOffset()),
2525 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2527 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2534 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2535 unsigned NumBytes) {
2536 CallingConv::ID CC = CLI.CallConv;
2538 // Issue CALLSEQ_END
2539 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2540 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2541 .addImm(NumBytes).addImm(0);
2543 // Now the return value.
2544 if (RetVT != MVT::isVoid) {
2545 SmallVector<CCValAssign, 16> RVLocs;
2546 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2547 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
2549 // Only handle a single return value.
2550 if (RVLocs.size() != 1)
2553 // Copy all of the result registers out of their specified physreg.
2554 MVT CopyVT = RVLocs[0].getValVT();
2555 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
2556 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2557 TII.get(TargetOpcode::COPY), ResultReg)
2558 .addReg(RVLocs[0].getLocReg());
2559 CLI.InRegs.push_back(RVLocs[0].getLocReg());
2561 CLI.ResultReg = ResultReg;
2562 CLI.NumResultRegs = 1;
2568 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2569 CallingConv::ID CC = CLI.CallConv;
2570 bool IsTailCall = CLI.IsTailCall;
2571 bool IsVarArg = CLI.IsVarArg;
2572 const Value *Callee = CLI.Callee;
2573 const char *SymName = CLI.SymName;
2575 if (!Callee && !SymName)
2578 // Allow SelectionDAG isel to handle tail calls.
2582 CodeModel::Model CM = TM.getCodeModel();
2583 // Only support the small and large code model.
2584 if (CM != CodeModel::Small && CM != CodeModel::Large)
2587 // FIXME: Add large code model support for ELF.
2588 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
2591 // Let SDISel handle vararg functions.
2595 // FIXME: Only handle *simple* calls for now.
2597 if (CLI.RetTy->isVoidTy())
2598 RetVT = MVT::isVoid;
2599 else if (!isTypeLegal(CLI.RetTy, RetVT))
2602 for (auto Flag : CLI.OutFlags)
2603 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
2606 // Set up the argument vectors.
2607 SmallVector<MVT, 16> OutVTs;
2608 OutVTs.reserve(CLI.OutVals.size());
2610 for (auto *Val : CLI.OutVals) {
2612 if (!isTypeLegal(Val->getType(), VT) &&
2613 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
2616 // We don't handle vector parameters yet.
2617 if (VT.isVector() || VT.getSizeInBits() > 64)
2620 OutVTs.push_back(VT);
2624 if (Callee && !computeCallAddress(Callee, Addr))
2627 // Handle the arguments now that we've gotten them.
2629 if (!processCallArgs(CLI, OutVTs, NumBytes))
2633 MachineInstrBuilder MIB;
2634 if (CM == CodeModel::Small) {
2635 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
2636 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
2638 MIB.addExternalSymbol(SymName, 0);
2639 else if (Addr.getGlobalValue())
2640 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2641 else if (Addr.getReg()) {
2642 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
2647 unsigned CallReg = 0;
2649 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2650 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2652 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2654 CallReg = createResultReg(&AArch64::GPR64RegClass);
2655 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
2658 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
2660 } else if (Addr.getGlobalValue())
2661 CallReg = materializeGV(Addr.getGlobalValue());
2662 else if (Addr.getReg())
2663 CallReg = Addr.getReg();
2668 const MCInstrDesc &II = TII.get(AArch64::BLR);
2669 CallReg = constrainOperandRegClass(II, CallReg, 0);
2670 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
2673 // Add implicit physical register uses to the call.
2674 for (auto Reg : CLI.OutRegs)
2675 MIB.addReg(Reg, RegState::Implicit);
2677 // Add a register mask with the call-preserved registers.
2678 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2679 MIB.addRegMask(TRI.getCallPreservedMask(CC));
2683 // Finish off the call including any return values.
2684 return finishCall(CLI, RetVT, NumBytes);
2687 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
2689 return Len / Alignment <= 4;
2694 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
2695 uint64_t Len, unsigned Alignment) {
2696 // Make sure we don't bloat code by inlining very large memcpy's.
2697 if (!isMemCpySmall(Len, Alignment))
2700 int64_t UnscaledOffset = 0;
2701 Address OrigDest = Dest;
2702 Address OrigSrc = Src;
2706 if (!Alignment || Alignment >= 8) {
2717 // Bound based on alignment.
2718 if (Len >= 4 && Alignment == 4)
2720 else if (Len >= 2 && Alignment == 2)
2729 RV = emitLoad(VT, ResultReg, Src);
2733 RV = emitStore(VT, ResultReg, Dest);
2737 int64_t Size = VT.getSizeInBits() / 8;
2739 UnscaledOffset += Size;
2741 // We need to recompute the unscaled offset for each iteration.
2742 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
2743 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
2749 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
2750 /// into the user. The condition code will only be updated on success.
2751 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
2752 const Instruction *I,
2753 const Value *Cond) {
2754 if (!isa<ExtractValueInst>(Cond))
2757 const auto *EV = cast<ExtractValueInst>(Cond);
2758 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
2761 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
2763 const Function *Callee = II->getCalledFunction();
2765 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
2766 if (!isTypeLegal(RetTy, RetVT))
2769 if (RetVT != MVT::i32 && RetVT != MVT::i64)
2772 AArch64CC::CondCode TmpCC;
2773 switch (II->getIntrinsicID()) {
2774 default: return false;
2775 case Intrinsic::sadd_with_overflow:
2776 case Intrinsic::ssub_with_overflow: TmpCC = AArch64CC::VS; break;
2777 case Intrinsic::uadd_with_overflow: TmpCC = AArch64CC::HS; break;
2778 case Intrinsic::usub_with_overflow: TmpCC = AArch64CC::LO; break;
2779 case Intrinsic::smul_with_overflow:
2780 case Intrinsic::umul_with_overflow: TmpCC = AArch64CC::NE; break;
2783 // Check if both instructions are in the same basic block.
2784 if (!isValueAvailable(II))
2787 // Make sure nothing is in the way
2788 BasicBlock::const_iterator Start = I;
2789 BasicBlock::const_iterator End = II;
2790 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
2791 // We only expect extractvalue instructions between the intrinsic and the
2792 // instruction to be selected.
2793 if (!isa<ExtractValueInst>(Itr))
2796 // Check that the extractvalue operand comes from the intrinsic.
2797 const auto *EVI = cast<ExtractValueInst>(Itr);
2798 if (EVI->getAggregateOperand() != II)
2806 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2807 // FIXME: Handle more intrinsics.
2808 switch (II->getIntrinsicID()) {
2809 default: return false;
2810 case Intrinsic::frameaddress: {
2811 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2812 MFI->setFrameAddressIsTaken(true);
2814 const AArch64RegisterInfo *RegInfo =
2815 static_cast<const AArch64RegisterInfo *>(
2816 TM.getSubtargetImpl()->getRegisterInfo());
2817 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
2818 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2819 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2820 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
2821 // Recursively load frame address
2827 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2829 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
2830 SrcReg, /*IsKill=*/true, 0);
2831 assert(DestReg && "Unexpected LDR instruction emission failure.");
2835 updateValueMap(II, SrcReg);
2838 case Intrinsic::memcpy:
2839 case Intrinsic::memmove: {
2840 const auto *MTI = cast<MemTransferInst>(II);
2841 // Don't handle volatile.
2842 if (MTI->isVolatile())
2845 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
2846 // we would emit dead code because we don't currently handle memmoves.
2847 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
2848 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
2849 // Small memcpy's are common enough that we want to do them without a call
2851 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
2852 unsigned Alignment = MTI->getAlignment();
2853 if (isMemCpySmall(Len, Alignment)) {
2855 if (!computeAddress(MTI->getRawDest(), Dest) ||
2856 !computeAddress(MTI->getRawSource(), Src))
2858 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
2863 if (!MTI->getLength()->getType()->isIntegerTy(64))
2866 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
2867 // Fast instruction selection doesn't support the special
2871 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
2872 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
2874 case Intrinsic::memset: {
2875 const MemSetInst *MSI = cast<MemSetInst>(II);
2876 // Don't handle volatile.
2877 if (MSI->isVolatile())
2880 if (!MSI->getLength()->getType()->isIntegerTy(64))
2883 if (MSI->getDestAddressSpace() > 255)
2884 // Fast instruction selection doesn't support the special
2888 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2890 case Intrinsic::sin:
2891 case Intrinsic::cos:
2892 case Intrinsic::pow: {
2894 if (!isTypeLegal(II->getType(), RetVT))
2897 if (RetVT != MVT::f32 && RetVT != MVT::f64)
2900 static const RTLIB::Libcall LibCallTable[3][2] = {
2901 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
2902 { RTLIB::COS_F32, RTLIB::COS_F64 },
2903 { RTLIB::POW_F32, RTLIB::POW_F64 }
2906 bool Is64Bit = RetVT == MVT::f64;
2907 switch (II->getIntrinsicID()) {
2909 llvm_unreachable("Unexpected intrinsic.");
2910 case Intrinsic::sin:
2911 LC = LibCallTable[0][Is64Bit];
2913 case Intrinsic::cos:
2914 LC = LibCallTable[1][Is64Bit];
2916 case Intrinsic::pow:
2917 LC = LibCallTable[2][Is64Bit];
2922 Args.reserve(II->getNumArgOperands());
2924 // Populate the argument list.
2925 for (auto &Arg : II->arg_operands()) {
2928 Entry.Ty = Arg->getType();
2929 Args.push_back(Entry);
2932 CallLoweringInfo CLI;
2933 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
2934 TLI.getLibcallName(LC), std::move(Args));
2935 if (!lowerCallTo(CLI))
2937 updateValueMap(II, CLI.ResultReg);
2940 case Intrinsic::trap: {
2941 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
2945 case Intrinsic::sqrt: {
2946 Type *RetTy = II->getCalledFunction()->getReturnType();
2949 if (!isTypeLegal(RetTy, VT))
2952 unsigned Op0Reg = getRegForValue(II->getOperand(0));
2955 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
2957 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
2961 updateValueMap(II, ResultReg);
2964 case Intrinsic::sadd_with_overflow:
2965 case Intrinsic::uadd_with_overflow:
2966 case Intrinsic::ssub_with_overflow:
2967 case Intrinsic::usub_with_overflow:
2968 case Intrinsic::smul_with_overflow:
2969 case Intrinsic::umul_with_overflow: {
2970 // This implements the basic lowering of the xalu with overflow intrinsics.
2971 const Function *Callee = II->getCalledFunction();
2972 auto *Ty = cast<StructType>(Callee->getReturnType());
2973 Type *RetTy = Ty->getTypeAtIndex(0U);
2976 if (!isTypeLegal(RetTy, VT))
2979 if (VT != MVT::i32 && VT != MVT::i64)
2982 const Value *LHS = II->getArgOperand(0);
2983 const Value *RHS = II->getArgOperand(1);
2984 // Canonicalize immediate to the RHS.
2985 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2986 isCommutativeIntrinsic(II))
2987 std::swap(LHS, RHS);
2989 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
2990 AArch64CC::CondCode CC = AArch64CC::Invalid;
2991 switch (II->getIntrinsicID()) {
2992 default: llvm_unreachable("Unexpected intrinsic!");
2993 case Intrinsic::sadd_with_overflow:
2994 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
2997 case Intrinsic::uadd_with_overflow:
2998 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3001 case Intrinsic::ssub_with_overflow:
3002 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3005 case Intrinsic::usub_with_overflow:
3006 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3009 case Intrinsic::smul_with_overflow: {
3011 unsigned LHSReg = getRegForValue(LHS);
3014 bool LHSIsKill = hasTrivialKill(LHS);
3016 unsigned RHSReg = getRegForValue(RHS);
3019 bool RHSIsKill = hasTrivialKill(RHS);
3021 if (VT == MVT::i32) {
3022 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3023 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3024 /*IsKill=*/false, 32);
3025 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3027 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3029 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3030 AArch64_AM::ASR, 31, /*WantResult=*/false);
3032 assert(VT == MVT::i64 && "Unexpected value type.");
3033 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3034 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3036 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3037 AArch64_AM::ASR, 63, /*WantResult=*/false);
3041 case Intrinsic::umul_with_overflow: {
3043 unsigned LHSReg = getRegForValue(LHS);
3046 bool LHSIsKill = hasTrivialKill(LHS);
3048 unsigned RHSReg = getRegForValue(RHS);
3051 bool RHSIsKill = hasTrivialKill(RHS);
3053 if (VT == MVT::i32) {
3054 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3055 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3056 /*IsKill=*/false, AArch64_AM::LSR, 32,
3057 /*WantResult=*/false);
3058 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3061 assert(VT == MVT::i64 && "Unexpected value type.");
3062 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3063 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3065 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3066 /*IsKill=*/false, /*WantResult=*/false);
3073 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3074 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3075 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3078 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3079 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3080 /*IsKill=*/true, getInvertedCondCode(CC));
3081 assert((ResultReg1 + 1) == ResultReg2 &&
3082 "Nonconsecutive result registers.");
3083 updateValueMap(II, ResultReg1, 2);
3090 bool AArch64FastISel::selectRet(const Instruction *I) {
3091 const ReturnInst *Ret = cast<ReturnInst>(I);
3092 const Function &F = *I->getParent()->getParent();
3094 if (!FuncInfo.CanLowerReturn)
3100 // Build a list of return value registers.
3101 SmallVector<unsigned, 4> RetRegs;
3103 if (Ret->getNumOperands() > 0) {
3104 CallingConv::ID CC = F.getCallingConv();
3105 SmallVector<ISD::OutputArg, 4> Outs;
3106 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3108 // Analyze operands of the call, assigning locations to each operand.
3109 SmallVector<CCValAssign, 16> ValLocs;
3110 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3111 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3112 : RetCC_AArch64_AAPCS;
3113 CCInfo.AnalyzeReturn(Outs, RetCC);
3115 // Only handle a single return value for now.
3116 if (ValLocs.size() != 1)
3119 CCValAssign &VA = ValLocs[0];
3120 const Value *RV = Ret->getOperand(0);
3122 // Don't bother handling odd stuff for now.
3123 if ((VA.getLocInfo() != CCValAssign::Full) &&
3124 (VA.getLocInfo() != CCValAssign::BCvt))
3127 // Only handle register returns for now.
3131 unsigned Reg = getRegForValue(RV);
3135 unsigned SrcReg = Reg + VA.getValNo();
3136 unsigned DestReg = VA.getLocReg();
3137 // Avoid a cross-class copy. This is very unlikely.
3138 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3141 EVT RVEVT = TLI.getValueType(RV->getType());
3142 if (!RVEVT.isSimple())
3145 // Vectors (of > 1 lane) in big endian need tricky handling.
3146 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3147 !Subtarget->isLittleEndian())
3150 MVT RVVT = RVEVT.getSimpleVT();
3151 if (RVVT == MVT::f128)
3154 MVT DestVT = VA.getValVT();
3155 // Special handling for extended integers.
3156 if (RVVT != DestVT) {
3157 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3160 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3163 bool IsZExt = Outs[0].Flags.isZExt();
3164 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3170 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3171 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3173 // Add register to return instruction.
3174 RetRegs.push_back(VA.getLocReg());
3177 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3178 TII.get(AArch64::RET_ReallyLR));
3179 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3180 MIB.addReg(RetRegs[i], RegState::Implicit);
3184 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3185 Type *DestTy = I->getType();
3186 Value *Op = I->getOperand(0);
3187 Type *SrcTy = Op->getType();
3189 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3190 EVT DestEVT = TLI.getValueType(DestTy, true);
3191 if (!SrcEVT.isSimple())
3193 if (!DestEVT.isSimple())
3196 MVT SrcVT = SrcEVT.getSimpleVT();
3197 MVT DestVT = DestEVT.getSimpleVT();
3199 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3202 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3206 unsigned SrcReg = getRegForValue(Op);
3209 bool SrcIsKill = hasTrivialKill(Op);
3211 // If we're truncating from i64 to a smaller non-legal type then generate an
3212 // AND. Otherwise, we know the high bits are undefined and a truncate only
3213 // generate a COPY. We cannot mark the source register also as result
3214 // register, because this can incorrectly transfer the kill flag onto the
3217 if (SrcVT == MVT::i64) {
3219 switch (DestVT.SimpleTy) {
3221 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3233 // Issue an extract_subreg to get the lower 32-bits.
3234 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3236 // Create the AND instruction which performs the actual truncation.
3237 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3238 assert(ResultReg && "Unexpected AND instruction emission failure.");
3240 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3241 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3242 TII.get(TargetOpcode::COPY), ResultReg)
3243 .addReg(SrcReg, getKillRegState(SrcIsKill));
3246 updateValueMap(I, ResultReg);
3250 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3251 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3252 DestVT == MVT::i64) &&
3253 "Unexpected value type.");
3254 // Handle i8 and i16 as i32.
3255 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3259 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3260 assert(ResultReg && "Unexpected AND instruction emission failure.");
3261 if (DestVT == MVT::i64) {
3262 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3263 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3264 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3265 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3266 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3269 .addImm(AArch64::sub_32);
3274 if (DestVT == MVT::i64) {
3275 // FIXME: We're SExt i1 to i64.
3278 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3279 /*TODO:IsKill=*/false, 0, 0);
3283 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3284 unsigned Op1, bool Op1IsKill) {
3286 switch (RetVT.SimpleTy) {
3292 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3294 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3297 const TargetRegisterClass *RC =
3298 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3299 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3300 /*IsKill=*/ZReg, true);
3303 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3304 unsigned Op1, bool Op1IsKill) {
3305 if (RetVT != MVT::i64)
3308 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3309 Op0, Op0IsKill, Op1, Op1IsKill,
3310 AArch64::XZR, /*IsKill=*/true);
3313 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3314 unsigned Op1, bool Op1IsKill) {
3315 if (RetVT != MVT::i64)
3318 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3319 Op0, Op0IsKill, Op1, Op1IsKill,
3320 AArch64::XZR, /*IsKill=*/true);
3323 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3324 unsigned Op1Reg, bool Op1IsKill) {
3326 bool NeedTrunc = false;
3328 switch (RetVT.SimpleTy) {
3330 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3331 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3332 case MVT::i32: Opc = AArch64::LSLVWr; break;
3333 case MVT::i64: Opc = AArch64::LSLVXr; break;
3336 const TargetRegisterClass *RC =
3337 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3339 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3342 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3345 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3349 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3350 bool Op0IsKill, uint64_t Shift,
3352 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3353 "Unexpected source/return type pair.");
3354 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3355 SrcVT == MVT::i64) && "Unexpected source value type.");
3356 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3357 RetVT == MVT::i64) && "Unexpected return value type.");
3359 bool Is64Bit = (RetVT == MVT::i64);
3360 unsigned RegSize = Is64Bit ? 64 : 32;
3361 unsigned DstBits = RetVT.getSizeInBits();
3362 unsigned SrcBits = SrcVT.getSizeInBits();
3364 // Don't deal with undefined shifts.
3365 if (Shift >= DstBits)
3368 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3369 // {S|U}BFM Wd, Wn, #r, #s
3370 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3372 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3373 // %2 = shl i16 %1, 4
3374 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3375 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3376 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3377 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3379 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3380 // %2 = shl i16 %1, 8
3381 // Wd<32+7-24,32-24> = Wn<7:0>
3382 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3383 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3384 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3386 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3387 // %2 = shl i16 %1, 12
3388 // Wd<32+3-20,32-20> = Wn<3:0>
3389 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3390 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3391 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3393 unsigned ImmR = RegSize - Shift;
3394 // Limit the width to the length of the source type.
3395 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3396 static const unsigned OpcTable[2][2] = {
3397 {AArch64::SBFMWri, AArch64::SBFMXri},
3398 {AArch64::UBFMWri, AArch64::UBFMXri}
3400 unsigned Opc = OpcTable[IsZext][Is64Bit];
3401 const TargetRegisterClass *RC =
3402 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3403 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3404 unsigned TmpReg = MRI.createVirtualRegister(RC);
3405 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3406 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3408 .addReg(Op0, getKillRegState(Op0IsKill))
3409 .addImm(AArch64::sub_32);
3413 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3416 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3417 unsigned Op1Reg, bool Op1IsKill) {
3419 bool NeedTrunc = false;
3421 switch (RetVT.SimpleTy) {
3423 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3424 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3425 case MVT::i32: Opc = AArch64::LSRVWr; break;
3426 case MVT::i64: Opc = AArch64::LSRVXr; break;
3429 const TargetRegisterClass *RC =
3430 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3432 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3433 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3434 Op0IsKill = Op1IsKill = true;
3436 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3439 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3443 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3444 bool Op0IsKill, uint64_t Shift,
3446 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3447 "Unexpected source/return type pair.");
3448 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3449 SrcVT == MVT::i64) && "Unexpected source value type.");
3450 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3451 RetVT == MVT::i64) && "Unexpected return value type.");
3453 bool Is64Bit = (RetVT == MVT::i64);
3454 unsigned RegSize = Is64Bit ? 64 : 32;
3455 unsigned DstBits = RetVT.getSizeInBits();
3456 unsigned SrcBits = SrcVT.getSizeInBits();
3458 // Don't deal with undefined shifts.
3459 if (Shift >= DstBits)
3462 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3463 // {S|U}BFM Wd, Wn, #r, #s
3464 // Wd<s-r:0> = Wn<s:r> when r <= s
3466 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3467 // %2 = lshr i16 %1, 4
3468 // Wd<7-4:0> = Wn<7:4>
3469 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
3470 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3471 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3473 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3474 // %2 = lshr i16 %1, 8
3475 // Wd<7-7,0> = Wn<7:7>
3476 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
3477 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3478 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3480 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3481 // %2 = lshr i16 %1, 12
3482 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3483 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
3484 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3485 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3487 if (Shift >= SrcBits && IsZExt)
3488 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3490 // It is not possible to fold a sign-extend into the LShr instruction. In this
3491 // case emit a sign-extend.
3493 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3498 SrcBits = SrcVT.getSizeInBits();
3502 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3503 unsigned ImmS = SrcBits - 1;
3504 static const unsigned OpcTable[2][2] = {
3505 {AArch64::SBFMWri, AArch64::SBFMXri},
3506 {AArch64::UBFMWri, AArch64::UBFMXri}
3508 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3509 const TargetRegisterClass *RC =
3510 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3511 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3512 unsigned TmpReg = MRI.createVirtualRegister(RC);
3513 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3514 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3516 .addReg(Op0, getKillRegState(Op0IsKill))
3517 .addImm(AArch64::sub_32);
3521 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3524 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3525 unsigned Op1Reg, bool Op1IsKill) {
3527 bool NeedTrunc = false;
3529 switch (RetVT.SimpleTy) {
3531 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
3532 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
3533 case MVT::i32: Opc = AArch64::ASRVWr; break;
3534 case MVT::i64: Opc = AArch64::ASRVXr; break;
3537 const TargetRegisterClass *RC =
3538 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3540 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
3541 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3542 Op0IsKill = Op1IsKill = true;
3544 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3547 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3551 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3552 bool Op0IsKill, uint64_t Shift,
3554 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3555 "Unexpected source/return type pair.");
3556 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3557 SrcVT == MVT::i64) && "Unexpected source value type.");
3558 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3559 RetVT == MVT::i64) && "Unexpected return value type.");
3561 bool Is64Bit = (RetVT == MVT::i64);
3562 unsigned RegSize = Is64Bit ? 64 : 32;
3563 unsigned DstBits = RetVT.getSizeInBits();
3564 unsigned SrcBits = SrcVT.getSizeInBits();
3566 // Don't deal with undefined shifts.
3567 if (Shift >= DstBits)
3570 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3571 // {S|U}BFM Wd, Wn, #r, #s
3572 // Wd<s-r:0> = Wn<s:r> when r <= s
3574 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3575 // %2 = ashr i16 %1, 4
3576 // Wd<7-4:0> = Wn<7:4>
3577 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
3578 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3579 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3581 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3582 // %2 = ashr i16 %1, 8
3583 // Wd<7-7,0> = Wn<7:7>
3584 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3585 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3586 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3588 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3589 // %2 = ashr i16 %1, 12
3590 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3591 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3592 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3593 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3595 if (Shift >= SrcBits && IsZExt)
3596 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3598 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3599 unsigned ImmS = SrcBits - 1;
3600 static const unsigned OpcTable[2][2] = {
3601 {AArch64::SBFMWri, AArch64::SBFMXri},
3602 {AArch64::UBFMWri, AArch64::UBFMXri}
3604 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3605 const TargetRegisterClass *RC =
3606 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3607 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3608 unsigned TmpReg = MRI.createVirtualRegister(RC);
3609 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3610 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3612 .addReg(Op0, getKillRegState(Op0IsKill))
3613 .addImm(AArch64::sub_32);
3617 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3620 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
3622 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
3624 // FastISel does not have plumbing to deal with extensions where the SrcVT or
3625 // DestVT are odd things, so test to make sure that they are both types we can
3626 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
3627 // bail out to SelectionDAG.
3628 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
3629 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
3630 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
3631 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
3637 switch (SrcVT.SimpleTy) {
3641 return emiti1Ext(SrcReg, DestVT, IsZExt);
3643 if (DestVT == MVT::i64)
3644 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3646 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
3650 if (DestVT == MVT::i64)
3651 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3653 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
3657 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
3658 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3663 // Handle i8 and i16 as i32.
3664 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3666 else if (DestVT == MVT::i64) {
3667 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3669 TII.get(AArch64::SUBREG_TO_REG), Src64)
3672 .addImm(AArch64::sub_32);
3676 const TargetRegisterClass *RC =
3677 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3678 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
3681 bool AArch64FastISel::selectIntExt(const Instruction *I) {
3682 // On ARM, in general, integer casts don't involve legal types; this code
3683 // handles promotable integers. The high bits for a type smaller than
3684 // the register size are assumed to be undefined.
3685 Type *DestTy = I->getType();
3686 Value *Src = I->getOperand(0);
3687 Type *SrcTy = Src->getType();
3689 unsigned SrcReg = getRegForValue(Src);
3693 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3694 EVT DestEVT = TLI.getValueType(DestTy, true);
3695 if (!SrcEVT.isSimple())
3697 if (!DestEVT.isSimple())
3700 MVT SrcVT = SrcEVT.getSimpleVT();
3701 MVT DestVT = DestEVT.getSimpleVT();
3702 unsigned ResultReg = 0;
3704 bool IsZExt = isa<ZExtInst>(I);
3705 // Check if it is an argument and if it is already zero/sign-extended.
3706 if (const auto *Arg = dyn_cast<Argument>(Src)) {
3707 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
3708 if (DestVT == MVT::i64) {
3709 ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
3710 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3711 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
3714 .addImm(AArch64::sub_32);
3721 ResultReg = emitIntExt(SrcVT, SrcReg, DestVT, IsZExt);
3726 updateValueMap(I, ResultReg);
3730 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
3731 EVT DestEVT = TLI.getValueType(I->getType(), true);
3732 if (!DestEVT.isSimple())
3735 MVT DestVT = DestEVT.getSimpleVT();
3736 if (DestVT != MVT::i64 && DestVT != MVT::i32)
3740 bool Is64bit = (DestVT == MVT::i64);
3741 switch (ISDOpcode) {
3745 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
3748 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
3751 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
3752 unsigned Src0Reg = getRegForValue(I->getOperand(0));
3755 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
3757 unsigned Src1Reg = getRegForValue(I->getOperand(1));
3760 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
3762 const TargetRegisterClass *RC =
3763 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3764 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
3765 Src1Reg, /*IsKill=*/false);
3766 assert(QuotReg && "Unexpected DIV instruction emission failure.");
3767 // The remainder is computed as numerator - (quotient * denominator) using the
3768 // MSUB instruction.
3769 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
3770 Src1Reg, Src1IsKill, Src0Reg,
3772 updateValueMap(I, ResultReg);
3776 bool AArch64FastISel::selectMul(const Instruction *I) {
3778 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
3782 return selectBinaryOp(I, ISD::MUL);
3784 const Value *Src0 = I->getOperand(0);
3785 const Value *Src1 = I->getOperand(1);
3786 if (const auto *C = dyn_cast<ConstantInt>(Src0))
3787 if (C->getValue().isPowerOf2())
3788 std::swap(Src0, Src1);
3790 // Try to simplify to a shift instruction.
3791 if (const auto *C = dyn_cast<ConstantInt>(Src1))
3792 if (C->getValue().isPowerOf2()) {
3793 uint64_t ShiftVal = C->getValue().logBase2();
3796 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
3798 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
3801 Src0 = ZExt->getOperand(0);
3803 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
3805 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
3808 Src0 = SExt->getOperand(0);
3812 unsigned Src0Reg = getRegForValue(Src0);
3815 bool Src0IsKill = hasTrivialKill(Src0);
3817 unsigned ResultReg =
3818 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
3821 updateValueMap(I, ResultReg);
3826 unsigned Src0Reg = getRegForValue(I->getOperand(0));
3829 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
3831 unsigned Src1Reg = getRegForValue(I->getOperand(1));
3834 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
3836 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
3841 updateValueMap(I, ResultReg);
3845 bool AArch64FastISel::selectShift(const Instruction *I) {
3847 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
3850 if (RetVT.isVector())
3851 return selectOperator(I, I->getOpcode());
3853 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
3854 unsigned ResultReg = 0;
3855 uint64_t ShiftVal = C->getZExtValue();
3857 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
3858 const Value *Op0 = I->getOperand(0);
3859 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
3861 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
3864 Op0 = ZExt->getOperand(0);
3866 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
3868 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
3871 Op0 = SExt->getOperand(0);
3875 unsigned Op0Reg = getRegForValue(Op0);
3878 bool Op0IsKill = hasTrivialKill(Op0);
3880 switch (I->getOpcode()) {
3881 default: llvm_unreachable("Unexpected instruction.");
3882 case Instruction::Shl:
3883 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3885 case Instruction::AShr:
3886 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3888 case Instruction::LShr:
3889 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3895 updateValueMap(I, ResultReg);
3899 unsigned Op0Reg = getRegForValue(I->getOperand(0));
3902 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
3904 unsigned Op1Reg = getRegForValue(I->getOperand(1));
3907 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
3909 unsigned ResultReg = 0;
3910 switch (I->getOpcode()) {
3911 default: llvm_unreachable("Unexpected instruction.");
3912 case Instruction::Shl:
3913 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3915 case Instruction::AShr:
3916 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3918 case Instruction::LShr:
3919 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3926 updateValueMap(I, ResultReg);
3930 bool AArch64FastISel::selectBitCast(const Instruction *I) {
3933 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
3935 if (!isTypeLegal(I->getType(), RetVT))
3939 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
3940 Opc = AArch64::FMOVWSr;
3941 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
3942 Opc = AArch64::FMOVXDr;
3943 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
3944 Opc = AArch64::FMOVSWr;
3945 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
3946 Opc = AArch64::FMOVDXr;
3950 const TargetRegisterClass *RC = nullptr;
3951 switch (RetVT.SimpleTy) {
3952 default: llvm_unreachable("Unexpected value type.");
3953 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
3954 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
3955 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
3956 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
3958 unsigned Op0Reg = getRegForValue(I->getOperand(0));
3961 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
3962 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
3967 updateValueMap(I, ResultReg);
3971 bool AArch64FastISel::selectFRem(const Instruction *I) {
3973 if (!isTypeLegal(I->getType(), RetVT))
3977 switch (RetVT.SimpleTy) {
3981 LC = RTLIB::REM_F32;
3984 LC = RTLIB::REM_F64;
3989 Args.reserve(I->getNumOperands());
3991 // Populate the argument list.
3992 for (auto &Arg : I->operands()) {
3995 Entry.Ty = Arg->getType();
3996 Args.push_back(Entry);
3999 CallLoweringInfo CLI;
4000 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4001 TLI.getLibcallName(LC), std::move(Args));
4002 if (!lowerCallTo(CLI))
4004 updateValueMap(I, CLI.ResultReg);
4008 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4010 if (!isTypeLegal(I->getType(), VT))
4013 if (!isa<ConstantInt>(I->getOperand(1)))
4014 return selectBinaryOp(I, ISD::SDIV);
4016 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4017 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4018 !(C.isPowerOf2() || (-C).isPowerOf2()))
4019 return selectBinaryOp(I, ISD::SDIV);
4021 unsigned Lg2 = C.countTrailingZeros();
4022 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4025 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4027 if (cast<BinaryOperator>(I)->isExact()) {
4028 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4031 updateValueMap(I, ResultReg);
4035 unsigned Pow2MinusOne = (1 << Lg2) - 1;
4036 unsigned AddReg = emitAddSub_ri(/*UseAdd=*/true, VT, Src0Reg,
4037 /*IsKill=*/false, Pow2MinusOne);
4041 // (Src0 < 0) ? Pow2 - 1 : 0;
4042 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4046 const TargetRegisterClass *RC;
4047 if (VT == MVT::i64) {
4048 SelectOpc = AArch64::CSELXr;
4049 RC = &AArch64::GPR64RegClass;
4051 SelectOpc = AArch64::CSELWr;
4052 RC = &AArch64::GPR32RegClass;
4054 unsigned SelectReg =
4055 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4056 Src0IsKill, AArch64CC::LT);
4060 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4061 // negate the result.
4062 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4065 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4066 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4068 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4073 updateValueMap(I, ResultReg);
4077 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4078 switch (I->getOpcode()) {
4081 case Instruction::Add:
4082 case Instruction::Sub:
4083 return selectAddSub(I);
4084 case Instruction::Mul:
4085 return selectMul(I);
4086 case Instruction::SDiv:
4087 return selectSDiv(I);
4088 case Instruction::SRem:
4089 if (!selectBinaryOp(I, ISD::SREM))
4090 return selectRem(I, ISD::SREM);
4092 case Instruction::URem:
4093 if (!selectBinaryOp(I, ISD::UREM))
4094 return selectRem(I, ISD::UREM);
4096 case Instruction::Shl:
4097 case Instruction::LShr:
4098 case Instruction::AShr:
4099 return selectShift(I);
4100 case Instruction::And:
4101 case Instruction::Or:
4102 case Instruction::Xor:
4103 return selectLogicalOp(I);
4104 case Instruction::Br:
4105 return selectBranch(I);
4106 case Instruction::IndirectBr:
4107 return selectIndirectBr(I);
4108 case Instruction::BitCast:
4109 if (!FastISel::selectBitCast(I))
4110 return selectBitCast(I);
4112 case Instruction::FPToSI:
4113 if (!selectCast(I, ISD::FP_TO_SINT))
4114 return selectFPToInt(I, /*Signed=*/true);
4116 case Instruction::FPToUI:
4117 return selectFPToInt(I, /*Signed=*/false);
4118 case Instruction::ZExt:
4119 if (!selectCast(I, ISD::ZERO_EXTEND))
4120 return selectIntExt(I);
4122 case Instruction::SExt:
4123 if (!selectCast(I, ISD::SIGN_EXTEND))
4124 return selectIntExt(I);
4126 case Instruction::Trunc:
4127 if (!selectCast(I, ISD::TRUNCATE))
4128 return selectTrunc(I);
4130 case Instruction::FPExt:
4131 return selectFPExt(I);
4132 case Instruction::FPTrunc:
4133 return selectFPTrunc(I);
4134 case Instruction::SIToFP:
4135 if (!selectCast(I, ISD::SINT_TO_FP))
4136 return selectIntToFP(I, /*Signed=*/true);
4138 case Instruction::UIToFP:
4139 return selectIntToFP(I, /*Signed=*/false);
4140 case Instruction::Load:
4141 return selectLoad(I);
4142 case Instruction::Store:
4143 return selectStore(I);
4144 case Instruction::FCmp:
4145 case Instruction::ICmp:
4146 return selectCmp(I);
4147 case Instruction::Select:
4148 return selectSelect(I);
4149 case Instruction::Ret:
4150 return selectRet(I);
4151 case Instruction::FRem:
4152 return selectFRem(I);
4155 // fall-back to target-independent instruction selection.
4156 return selectOperator(I, I->getOpcode());
4157 // Silence warnings.
4158 (void)&CC_AArch64_DarwinPCS_VarArg;
4162 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4163 const TargetLibraryInfo *LibInfo) {
4164 return new AArch64FastISel(FuncInfo, LibInfo);