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 canFoldZeroIntoBranch(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 (canFoldZeroIntoBranch(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);
1866 static const unsigned OpcTable[2][2] = {
1867 {AArch64::CBZW, AArch64::CBZX }, {AArch64::CBNZW, AArch64::CBNZX}
1869 bool IsCmpNE = Predicate == CmpInst::ICMP_NE;
1870 bool Is64Bit = LHS->getType()->isIntegerTy(64);
1871 unsigned Opc = OpcTable[IsCmpNE][Is64Bit];
1873 unsigned SrcReg = getRegForValue(LHS);
1876 bool SrcIsKill = hasTrivialKill(LHS);
1878 // Emit the combined compare and branch instruction.
1879 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1880 .addReg(SrcReg, getKillRegState(SrcIsKill))
1883 // Obtain the branch weight and add the TrueBB to the successor list.
1884 uint32_t BranchWeight = 0;
1886 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1887 TBB->getBasicBlock());
1888 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1890 fastEmitBranch(FBB, DbgLoc);
1895 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1898 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
1900 CC = getCompareCC(Predicate);
1901 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
1902 switch (Predicate) {
1905 case CmpInst::FCMP_UEQ:
1906 ExtraCC = AArch64CC::EQ;
1909 case CmpInst::FCMP_ONE:
1910 ExtraCC = AArch64CC::MI;
1914 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
1916 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
1917 if (ExtraCC != AArch64CC::AL) {
1918 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1924 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1928 // Obtain the branch weight and add the TrueBB to the successor list.
1929 uint32_t BranchWeight = 0;
1931 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1932 TBB->getBasicBlock());
1933 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1935 fastEmitBranch(FBB, DbgLoc);
1938 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1940 if (TI->hasOneUse() && isValueAvailable(TI) &&
1941 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
1942 unsigned CondReg = getRegForValue(TI->getOperand(0));
1945 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
1947 // Issue an extract_subreg to get the lower 32-bits.
1948 if (SrcVT == MVT::i64) {
1949 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
1954 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
1955 assert(ANDReg && "Unexpected AND instruction emission failure.");
1956 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
1958 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1959 std::swap(TBB, FBB);
1962 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1966 // Obtain the branch weight and add the TrueBB to the successor list.
1967 uint32_t BranchWeight = 0;
1969 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1970 TBB->getBasicBlock());
1971 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1973 fastEmitBranch(FBB, DbgLoc);
1976 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
1977 uint64_t Imm = CI->getZExtValue();
1978 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1979 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
1982 // Obtain the branch weight and add the target to the successor list.
1983 uint32_t BranchWeight = 0;
1985 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1986 Target->getBasicBlock());
1987 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
1989 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
1990 // Fake request the condition, otherwise the intrinsic might be completely
1992 unsigned CondReg = getRegForValue(BI->getCondition());
1997 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2001 // Obtain the branch weight and add the TrueBB to the successor list.
2002 uint32_t BranchWeight = 0;
2004 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2005 TBB->getBasicBlock());
2006 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2008 fastEmitBranch(FBB, DbgLoc);
2012 unsigned CondReg = getRegForValue(BI->getCondition());
2015 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2017 // We've been divorced from our compare! Our block was split, and
2018 // now our compare lives in a predecessor block. We musn't
2019 // re-compare here, as the children of the compare aren't guaranteed
2020 // live across the block boundary (we *could* check for this).
2021 // Regardless, the compare has been done in the predecessor block,
2022 // and it left a value for us in a virtual register. Ergo, we test
2023 // the one-bit value left in the virtual register.
2024 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2026 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2027 std::swap(TBB, FBB);
2031 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2035 // Obtain the branch weight and add the TrueBB to the successor list.
2036 uint32_t BranchWeight = 0;
2038 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2039 TBB->getBasicBlock());
2040 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2042 fastEmitBranch(FBB, DbgLoc);
2046 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2047 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2048 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2052 // Emit the indirect branch.
2053 const MCInstrDesc &II = TII.get(AArch64::BR);
2054 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2055 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2057 // Make sure the CFG is up-to-date.
2058 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2059 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2064 bool AArch64FastISel::selectCmp(const Instruction *I) {
2065 const CmpInst *CI = cast<CmpInst>(I);
2067 // Try to optimize or fold the cmp.
2068 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2069 unsigned ResultReg = 0;
2070 switch (Predicate) {
2073 case CmpInst::FCMP_FALSE:
2074 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2075 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2076 TII.get(TargetOpcode::COPY), ResultReg)
2077 .addReg(AArch64::WZR, getKillRegState(true));
2079 case CmpInst::FCMP_TRUE:
2080 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2085 updateValueMap(I, ResultReg);
2090 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2093 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2095 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2096 // condition codes are inverted, because they are used by CSINC.
2097 static unsigned CondCodeTable[2][2] = {
2098 { AArch64CC::NE, AArch64CC::VC },
2099 { AArch64CC::PL, AArch64CC::LE }
2101 unsigned *CondCodes = nullptr;
2102 switch (Predicate) {
2105 case CmpInst::FCMP_UEQ:
2106 CondCodes = &CondCodeTable[0][0];
2108 case CmpInst::FCMP_ONE:
2109 CondCodes = &CondCodeTable[1][0];
2114 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2115 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2117 .addReg(AArch64::WZR, getKillRegState(true))
2118 .addReg(AArch64::WZR, getKillRegState(true))
2119 .addImm(CondCodes[0]);
2120 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2122 .addReg(TmpReg1, getKillRegState(true))
2123 .addReg(AArch64::WZR, getKillRegState(true))
2124 .addImm(CondCodes[1]);
2126 updateValueMap(I, ResultReg);
2130 // Now set a register based on the comparison.
2131 AArch64CC::CondCode CC = getCompareCC(Predicate);
2132 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2133 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2134 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2136 .addReg(AArch64::WZR, getKillRegState(true))
2137 .addReg(AArch64::WZR, getKillRegState(true))
2138 .addImm(invertedCC);
2140 updateValueMap(I, ResultReg);
2144 bool AArch64FastISel::selectSelect(const Instruction *I) {
2145 const SelectInst *SI = cast<SelectInst>(I);
2147 EVT DestEVT = TLI.getValueType(SI->getType(), true);
2148 if (!DestEVT.isSimple())
2151 MVT DestVT = DestEVT.getSimpleVT();
2152 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
2157 const TargetRegisterClass *RC = nullptr;
2158 switch (DestVT.SimpleTy) {
2159 default: return false;
2161 SelectOpc = AArch64::CSELWr; RC = &AArch64::GPR32RegClass; break;
2163 SelectOpc = AArch64::CSELXr; RC = &AArch64::GPR64RegClass; break;
2165 SelectOpc = AArch64::FCSELSrrr; RC = &AArch64::FPR32RegClass; break;
2167 SelectOpc = AArch64::FCSELDrrr; RC = &AArch64::FPR64RegClass; break;
2170 const Value *Cond = SI->getCondition();
2171 bool NeedTest = true;
2172 AArch64CC::CondCode CC = AArch64CC::NE;
2173 if (foldXALUIntrinsic(CC, I, Cond))
2176 unsigned CondReg = getRegForValue(Cond);
2179 bool CondIsKill = hasTrivialKill(Cond);
2182 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2183 assert(ANDReg && "Unexpected AND instruction emission failure.");
2184 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2187 unsigned TrueReg = getRegForValue(SI->getTrueValue());
2188 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
2190 unsigned FalseReg = getRegForValue(SI->getFalseValue());
2191 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
2193 if (!TrueReg || !FalseReg)
2196 unsigned ResultReg = fastEmitInst_rri(SelectOpc, RC, TrueReg, TrueIsKill,
2197 FalseReg, FalseIsKill, CC);
2198 updateValueMap(I, ResultReg);
2202 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2203 Value *V = I->getOperand(0);
2204 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2207 unsigned Op = getRegForValue(V);
2211 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2212 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2213 ResultReg).addReg(Op);
2214 updateValueMap(I, ResultReg);
2218 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2219 Value *V = I->getOperand(0);
2220 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2223 unsigned Op = getRegForValue(V);
2227 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2228 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2229 ResultReg).addReg(Op);
2230 updateValueMap(I, ResultReg);
2234 // FPToUI and FPToSI
2235 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2237 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2240 unsigned SrcReg = getRegForValue(I->getOperand(0));
2244 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2245 if (SrcVT == MVT::f128)
2249 if (SrcVT == MVT::f64) {
2251 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2253 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2256 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2258 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2260 unsigned ResultReg = createResultReg(
2261 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2262 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2264 updateValueMap(I, ResultReg);
2268 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2270 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2272 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2273 "Unexpected value type.");
2275 unsigned SrcReg = getRegForValue(I->getOperand(0));
2278 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2280 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2282 // Handle sign-extension.
2283 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2285 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2292 if (SrcVT == MVT::i64) {
2294 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2296 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2299 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2301 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2304 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2306 updateValueMap(I, ResultReg);
2310 bool AArch64FastISel::fastLowerArguments() {
2311 if (!FuncInfo.CanLowerReturn)
2314 const Function *F = FuncInfo.Fn;
2318 CallingConv::ID CC = F->getCallingConv();
2319 if (CC != CallingConv::C)
2322 // Only handle simple cases of up to 8 GPR and FPR each.
2323 unsigned GPRCnt = 0;
2324 unsigned FPRCnt = 0;
2326 for (auto const &Arg : F->args()) {
2327 // The first argument is at index 1.
2329 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2330 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2331 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2332 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2335 Type *ArgTy = Arg.getType();
2336 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2339 EVT ArgVT = TLI.getValueType(ArgTy);
2340 if (!ArgVT.isSimple())
2343 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2344 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2347 if (VT.isVector() &&
2348 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2351 if (VT >= MVT::i1 && VT <= MVT::i64)
2353 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2354 VT.is128BitVector())
2359 if (GPRCnt > 8 || FPRCnt > 8)
2363 static const MCPhysReg Registers[6][8] = {
2364 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2365 AArch64::W5, AArch64::W6, AArch64::W7 },
2366 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2367 AArch64::X5, AArch64::X6, AArch64::X7 },
2368 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2369 AArch64::H5, AArch64::H6, AArch64::H7 },
2370 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2371 AArch64::S5, AArch64::S6, AArch64::S7 },
2372 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2373 AArch64::D5, AArch64::D6, AArch64::D7 },
2374 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2375 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2378 unsigned GPRIdx = 0;
2379 unsigned FPRIdx = 0;
2380 for (auto const &Arg : F->args()) {
2381 MVT VT = TLI.getSimpleValueType(Arg.getType());
2383 const TargetRegisterClass *RC;
2384 if (VT >= MVT::i1 && VT <= MVT::i32) {
2385 SrcReg = Registers[0][GPRIdx++];
2386 RC = &AArch64::GPR32RegClass;
2388 } else if (VT == MVT::i64) {
2389 SrcReg = Registers[1][GPRIdx++];
2390 RC = &AArch64::GPR64RegClass;
2391 } else if (VT == MVT::f16) {
2392 SrcReg = Registers[2][FPRIdx++];
2393 RC = &AArch64::FPR16RegClass;
2394 } else if (VT == MVT::f32) {
2395 SrcReg = Registers[3][FPRIdx++];
2396 RC = &AArch64::FPR32RegClass;
2397 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2398 SrcReg = Registers[4][FPRIdx++];
2399 RC = &AArch64::FPR64RegClass;
2400 } else if (VT.is128BitVector()) {
2401 SrcReg = Registers[5][FPRIdx++];
2402 RC = &AArch64::FPR128RegClass;
2404 llvm_unreachable("Unexpected value type.");
2406 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2407 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2408 // Without this, EmitLiveInCopies may eliminate the livein if its only
2409 // use is a bitcast (which isn't turned into an instruction).
2410 unsigned ResultReg = createResultReg(RC);
2411 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2412 TII.get(TargetOpcode::COPY), ResultReg)
2413 .addReg(DstReg, getKillRegState(true));
2414 updateValueMap(&Arg, ResultReg);
2419 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2420 SmallVectorImpl<MVT> &OutVTs,
2421 unsigned &NumBytes) {
2422 CallingConv::ID CC = CLI.CallConv;
2423 SmallVector<CCValAssign, 16> ArgLocs;
2424 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2425 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2427 // Get a count of how many bytes are to be pushed on the stack.
2428 NumBytes = CCInfo.getNextStackOffset();
2430 // Issue CALLSEQ_START
2431 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2432 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2435 // Process the args.
2436 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2437 CCValAssign &VA = ArgLocs[i];
2438 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2439 MVT ArgVT = OutVTs[VA.getValNo()];
2441 unsigned ArgReg = getRegForValue(ArgVal);
2445 // Handle arg promotion: SExt, ZExt, AExt.
2446 switch (VA.getLocInfo()) {
2447 case CCValAssign::Full:
2449 case CCValAssign::SExt: {
2450 MVT DestVT = VA.getLocVT();
2452 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2457 case CCValAssign::AExt:
2458 // Intentional fall-through.
2459 case CCValAssign::ZExt: {
2460 MVT DestVT = VA.getLocVT();
2462 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2468 llvm_unreachable("Unknown arg promotion!");
2471 // Now copy/store arg to correct locations.
2472 if (VA.isRegLoc() && !VA.needsCustom()) {
2473 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2474 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2475 CLI.OutRegs.push_back(VA.getLocReg());
2476 } else if (VA.needsCustom()) {
2477 // FIXME: Handle custom args.
2480 assert(VA.isMemLoc() && "Assuming store on stack.");
2482 // Don't emit stores for undef values.
2483 if (isa<UndefValue>(ArgVal))
2486 // Need to store on the stack.
2487 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2489 unsigned BEAlign = 0;
2490 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2491 BEAlign = 8 - ArgSize;
2494 Addr.setKind(Address::RegBase);
2495 Addr.setReg(AArch64::SP);
2496 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2498 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2499 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2500 MachinePointerInfo::getStack(Addr.getOffset()),
2501 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2503 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2510 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2511 unsigned NumBytes) {
2512 CallingConv::ID CC = CLI.CallConv;
2514 // Issue CALLSEQ_END
2515 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2517 .addImm(NumBytes).addImm(0);
2519 // Now the return value.
2520 if (RetVT != MVT::isVoid) {
2521 SmallVector<CCValAssign, 16> RVLocs;
2522 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2523 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
2525 // Only handle a single return value.
2526 if (RVLocs.size() != 1)
2529 // Copy all of the result registers out of their specified physreg.
2530 MVT CopyVT = RVLocs[0].getValVT();
2531 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
2532 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2533 TII.get(TargetOpcode::COPY), ResultReg)
2534 .addReg(RVLocs[0].getLocReg());
2535 CLI.InRegs.push_back(RVLocs[0].getLocReg());
2537 CLI.ResultReg = ResultReg;
2538 CLI.NumResultRegs = 1;
2544 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2545 CallingConv::ID CC = CLI.CallConv;
2546 bool IsTailCall = CLI.IsTailCall;
2547 bool IsVarArg = CLI.IsVarArg;
2548 const Value *Callee = CLI.Callee;
2549 const char *SymName = CLI.SymName;
2551 if (!Callee && !SymName)
2554 // Allow SelectionDAG isel to handle tail calls.
2558 CodeModel::Model CM = TM.getCodeModel();
2559 // Only support the small and large code model.
2560 if (CM != CodeModel::Small && CM != CodeModel::Large)
2563 // FIXME: Add large code model support for ELF.
2564 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
2567 // Let SDISel handle vararg functions.
2571 // FIXME: Only handle *simple* calls for now.
2573 if (CLI.RetTy->isVoidTy())
2574 RetVT = MVT::isVoid;
2575 else if (!isTypeLegal(CLI.RetTy, RetVT))
2578 for (auto Flag : CLI.OutFlags)
2579 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
2582 // Set up the argument vectors.
2583 SmallVector<MVT, 16> OutVTs;
2584 OutVTs.reserve(CLI.OutVals.size());
2586 for (auto *Val : CLI.OutVals) {
2588 if (!isTypeLegal(Val->getType(), VT) &&
2589 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
2592 // We don't handle vector parameters yet.
2593 if (VT.isVector() || VT.getSizeInBits() > 64)
2596 OutVTs.push_back(VT);
2600 if (Callee && !computeCallAddress(Callee, Addr))
2603 // Handle the arguments now that we've gotten them.
2605 if (!processCallArgs(CLI, OutVTs, NumBytes))
2609 MachineInstrBuilder MIB;
2610 if (CM == CodeModel::Small) {
2611 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
2612 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
2614 MIB.addExternalSymbol(SymName, 0);
2615 else if (Addr.getGlobalValue())
2616 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2617 else if (Addr.getReg()) {
2618 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
2623 unsigned CallReg = 0;
2625 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2626 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2628 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2630 CallReg = createResultReg(&AArch64::GPR64RegClass);
2631 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
2634 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
2636 } else if (Addr.getGlobalValue())
2637 CallReg = materializeGV(Addr.getGlobalValue());
2638 else if (Addr.getReg())
2639 CallReg = Addr.getReg();
2644 const MCInstrDesc &II = TII.get(AArch64::BLR);
2645 CallReg = constrainOperandRegClass(II, CallReg, 0);
2646 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
2649 // Add implicit physical register uses to the call.
2650 for (auto Reg : CLI.OutRegs)
2651 MIB.addReg(Reg, RegState::Implicit);
2653 // Add a register mask with the call-preserved registers.
2654 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2655 MIB.addRegMask(TRI.getCallPreservedMask(CC));
2659 // Finish off the call including any return values.
2660 return finishCall(CLI, RetVT, NumBytes);
2663 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
2665 return Len / Alignment <= 4;
2670 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
2671 uint64_t Len, unsigned Alignment) {
2672 // Make sure we don't bloat code by inlining very large memcpy's.
2673 if (!isMemCpySmall(Len, Alignment))
2676 int64_t UnscaledOffset = 0;
2677 Address OrigDest = Dest;
2678 Address OrigSrc = Src;
2682 if (!Alignment || Alignment >= 8) {
2693 // Bound based on alignment.
2694 if (Len >= 4 && Alignment == 4)
2696 else if (Len >= 2 && Alignment == 2)
2705 RV = emitLoad(VT, ResultReg, Src);
2709 RV = emitStore(VT, ResultReg, Dest);
2713 int64_t Size = VT.getSizeInBits() / 8;
2715 UnscaledOffset += Size;
2717 // We need to recompute the unscaled offset for each iteration.
2718 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
2719 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
2725 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
2726 /// into the user. The condition code will only be updated on success.
2727 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
2728 const Instruction *I,
2729 const Value *Cond) {
2730 if (!isa<ExtractValueInst>(Cond))
2733 const auto *EV = cast<ExtractValueInst>(Cond);
2734 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
2737 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
2739 const Function *Callee = II->getCalledFunction();
2741 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
2742 if (!isTypeLegal(RetTy, RetVT))
2745 if (RetVT != MVT::i32 && RetVT != MVT::i64)
2748 AArch64CC::CondCode TmpCC;
2749 switch (II->getIntrinsicID()) {
2750 default: return false;
2751 case Intrinsic::sadd_with_overflow:
2752 case Intrinsic::ssub_with_overflow: TmpCC = AArch64CC::VS; break;
2753 case Intrinsic::uadd_with_overflow: TmpCC = AArch64CC::HS; break;
2754 case Intrinsic::usub_with_overflow: TmpCC = AArch64CC::LO; break;
2755 case Intrinsic::smul_with_overflow:
2756 case Intrinsic::umul_with_overflow: TmpCC = AArch64CC::NE; break;
2759 // Check if both instructions are in the same basic block.
2760 if (!isValueAvailable(II))
2763 // Make sure nothing is in the way
2764 BasicBlock::const_iterator Start = I;
2765 BasicBlock::const_iterator End = II;
2766 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
2767 // We only expect extractvalue instructions between the intrinsic and the
2768 // instruction to be selected.
2769 if (!isa<ExtractValueInst>(Itr))
2772 // Check that the extractvalue operand comes from the intrinsic.
2773 const auto *EVI = cast<ExtractValueInst>(Itr);
2774 if (EVI->getAggregateOperand() != II)
2782 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2783 // FIXME: Handle more intrinsics.
2784 switch (II->getIntrinsicID()) {
2785 default: return false;
2786 case Intrinsic::frameaddress: {
2787 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2788 MFI->setFrameAddressIsTaken(true);
2790 const AArch64RegisterInfo *RegInfo =
2791 static_cast<const AArch64RegisterInfo *>(
2792 TM.getSubtargetImpl()->getRegisterInfo());
2793 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
2794 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2795 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2796 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
2797 // Recursively load frame address
2803 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2805 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
2806 SrcReg, /*IsKill=*/true, 0);
2807 assert(DestReg && "Unexpected LDR instruction emission failure.");
2811 updateValueMap(II, SrcReg);
2814 case Intrinsic::memcpy:
2815 case Intrinsic::memmove: {
2816 const auto *MTI = cast<MemTransferInst>(II);
2817 // Don't handle volatile.
2818 if (MTI->isVolatile())
2821 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
2822 // we would emit dead code because we don't currently handle memmoves.
2823 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
2824 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
2825 // Small memcpy's are common enough that we want to do them without a call
2827 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
2828 unsigned Alignment = MTI->getAlignment();
2829 if (isMemCpySmall(Len, Alignment)) {
2831 if (!computeAddress(MTI->getRawDest(), Dest) ||
2832 !computeAddress(MTI->getRawSource(), Src))
2834 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
2839 if (!MTI->getLength()->getType()->isIntegerTy(64))
2842 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
2843 // Fast instruction selection doesn't support the special
2847 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
2848 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
2850 case Intrinsic::memset: {
2851 const MemSetInst *MSI = cast<MemSetInst>(II);
2852 // Don't handle volatile.
2853 if (MSI->isVolatile())
2856 if (!MSI->getLength()->getType()->isIntegerTy(64))
2859 if (MSI->getDestAddressSpace() > 255)
2860 // Fast instruction selection doesn't support the special
2864 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2866 case Intrinsic::sin:
2867 case Intrinsic::cos:
2868 case Intrinsic::pow: {
2870 if (!isTypeLegal(II->getType(), RetVT))
2873 if (RetVT != MVT::f32 && RetVT != MVT::f64)
2876 static const RTLIB::Libcall LibCallTable[3][2] = {
2877 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
2878 { RTLIB::COS_F32, RTLIB::COS_F64 },
2879 { RTLIB::POW_F32, RTLIB::POW_F64 }
2882 bool Is64Bit = RetVT == MVT::f64;
2883 switch (II->getIntrinsicID()) {
2885 llvm_unreachable("Unexpected intrinsic.");
2886 case Intrinsic::sin:
2887 LC = LibCallTable[0][Is64Bit];
2889 case Intrinsic::cos:
2890 LC = LibCallTable[1][Is64Bit];
2892 case Intrinsic::pow:
2893 LC = LibCallTable[2][Is64Bit];
2898 Args.reserve(II->getNumArgOperands());
2900 // Populate the argument list.
2901 for (auto &Arg : II->arg_operands()) {
2904 Entry.Ty = Arg->getType();
2905 Args.push_back(Entry);
2908 CallLoweringInfo CLI;
2909 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
2910 TLI.getLibcallName(LC), std::move(Args));
2911 if (!lowerCallTo(CLI))
2913 updateValueMap(II, CLI.ResultReg);
2916 case Intrinsic::trap: {
2917 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
2921 case Intrinsic::sqrt: {
2922 Type *RetTy = II->getCalledFunction()->getReturnType();
2925 if (!isTypeLegal(RetTy, VT))
2928 unsigned Op0Reg = getRegForValue(II->getOperand(0));
2931 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
2933 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
2937 updateValueMap(II, ResultReg);
2940 case Intrinsic::sadd_with_overflow:
2941 case Intrinsic::uadd_with_overflow:
2942 case Intrinsic::ssub_with_overflow:
2943 case Intrinsic::usub_with_overflow:
2944 case Intrinsic::smul_with_overflow:
2945 case Intrinsic::umul_with_overflow: {
2946 // This implements the basic lowering of the xalu with overflow intrinsics.
2947 const Function *Callee = II->getCalledFunction();
2948 auto *Ty = cast<StructType>(Callee->getReturnType());
2949 Type *RetTy = Ty->getTypeAtIndex(0U);
2952 if (!isTypeLegal(RetTy, VT))
2955 if (VT != MVT::i32 && VT != MVT::i64)
2958 const Value *LHS = II->getArgOperand(0);
2959 const Value *RHS = II->getArgOperand(1);
2960 // Canonicalize immediate to the RHS.
2961 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2962 isCommutativeIntrinsic(II))
2963 std::swap(LHS, RHS);
2965 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
2966 AArch64CC::CondCode CC = AArch64CC::Invalid;
2967 switch (II->getIntrinsicID()) {
2968 default: llvm_unreachable("Unexpected intrinsic!");
2969 case Intrinsic::sadd_with_overflow:
2970 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
2973 case Intrinsic::uadd_with_overflow:
2974 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
2977 case Intrinsic::ssub_with_overflow:
2978 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
2981 case Intrinsic::usub_with_overflow:
2982 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
2985 case Intrinsic::smul_with_overflow: {
2987 unsigned LHSReg = getRegForValue(LHS);
2990 bool LHSIsKill = hasTrivialKill(LHS);
2992 unsigned RHSReg = getRegForValue(RHS);
2995 bool RHSIsKill = hasTrivialKill(RHS);
2997 if (VT == MVT::i32) {
2998 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2999 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3000 /*IsKill=*/false, 32);
3001 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3003 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3005 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3006 AArch64_AM::ASR, 31, /*WantResult=*/false);
3008 assert(VT == MVT::i64 && "Unexpected value type.");
3009 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3010 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3012 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3013 AArch64_AM::ASR, 63, /*WantResult=*/false);
3017 case Intrinsic::umul_with_overflow: {
3019 unsigned LHSReg = getRegForValue(LHS);
3022 bool LHSIsKill = hasTrivialKill(LHS);
3024 unsigned RHSReg = getRegForValue(RHS);
3027 bool RHSIsKill = hasTrivialKill(RHS);
3029 if (VT == MVT::i32) {
3030 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3031 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3032 /*IsKill=*/false, AArch64_AM::LSR, 32,
3033 /*WantResult=*/false);
3034 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3037 assert(VT == MVT::i64 && "Unexpected value type.");
3038 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3039 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3041 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3042 /*IsKill=*/false, /*WantResult=*/false);
3049 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3050 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3051 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3054 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3055 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3056 /*IsKill=*/true, getInvertedCondCode(CC));
3057 assert((ResultReg1 + 1) == ResultReg2 &&
3058 "Nonconsecutive result registers.");
3059 updateValueMap(II, ResultReg1, 2);
3066 bool AArch64FastISel::selectRet(const Instruction *I) {
3067 const ReturnInst *Ret = cast<ReturnInst>(I);
3068 const Function &F = *I->getParent()->getParent();
3070 if (!FuncInfo.CanLowerReturn)
3076 // Build a list of return value registers.
3077 SmallVector<unsigned, 4> RetRegs;
3079 if (Ret->getNumOperands() > 0) {
3080 CallingConv::ID CC = F.getCallingConv();
3081 SmallVector<ISD::OutputArg, 4> Outs;
3082 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3084 // Analyze operands of the call, assigning locations to each operand.
3085 SmallVector<CCValAssign, 16> ValLocs;
3086 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3087 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3088 : RetCC_AArch64_AAPCS;
3089 CCInfo.AnalyzeReturn(Outs, RetCC);
3091 // Only handle a single return value for now.
3092 if (ValLocs.size() != 1)
3095 CCValAssign &VA = ValLocs[0];
3096 const Value *RV = Ret->getOperand(0);
3098 // Don't bother handling odd stuff for now.
3099 if ((VA.getLocInfo() != CCValAssign::Full) &&
3100 (VA.getLocInfo() != CCValAssign::BCvt))
3103 // Only handle register returns for now.
3107 unsigned Reg = getRegForValue(RV);
3111 unsigned SrcReg = Reg + VA.getValNo();
3112 unsigned DestReg = VA.getLocReg();
3113 // Avoid a cross-class copy. This is very unlikely.
3114 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3117 EVT RVEVT = TLI.getValueType(RV->getType());
3118 if (!RVEVT.isSimple())
3121 // Vectors (of > 1 lane) in big endian need tricky handling.
3122 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3123 !Subtarget->isLittleEndian())
3126 MVT RVVT = RVEVT.getSimpleVT();
3127 if (RVVT == MVT::f128)
3130 MVT DestVT = VA.getValVT();
3131 // Special handling for extended integers.
3132 if (RVVT != DestVT) {
3133 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3136 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3139 bool IsZExt = Outs[0].Flags.isZExt();
3140 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3146 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3147 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3149 // Add register to return instruction.
3150 RetRegs.push_back(VA.getLocReg());
3153 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3154 TII.get(AArch64::RET_ReallyLR));
3155 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3156 MIB.addReg(RetRegs[i], RegState::Implicit);
3160 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3161 Type *DestTy = I->getType();
3162 Value *Op = I->getOperand(0);
3163 Type *SrcTy = Op->getType();
3165 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3166 EVT DestEVT = TLI.getValueType(DestTy, true);
3167 if (!SrcEVT.isSimple())
3169 if (!DestEVT.isSimple())
3172 MVT SrcVT = SrcEVT.getSimpleVT();
3173 MVT DestVT = DestEVT.getSimpleVT();
3175 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3178 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3182 unsigned SrcReg = getRegForValue(Op);
3185 bool SrcIsKill = hasTrivialKill(Op);
3187 // If we're truncating from i64 to a smaller non-legal type then generate an
3188 // AND. Otherwise, we know the high bits are undefined and a truncate only
3189 // generate a COPY. We cannot mark the source register also as result
3190 // register, because this can incorrectly transfer the kill flag onto the
3193 if (SrcVT == MVT::i64) {
3195 switch (DestVT.SimpleTy) {
3197 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3209 // Issue an extract_subreg to get the lower 32-bits.
3210 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3212 // Create the AND instruction which performs the actual truncation.
3213 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3214 assert(ResultReg && "Unexpected AND instruction emission failure.");
3216 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3217 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3218 TII.get(TargetOpcode::COPY), ResultReg)
3219 .addReg(SrcReg, getKillRegState(SrcIsKill));
3222 updateValueMap(I, ResultReg);
3226 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3227 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3228 DestVT == MVT::i64) &&
3229 "Unexpected value type.");
3230 // Handle i8 and i16 as i32.
3231 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3235 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3236 assert(ResultReg && "Unexpected AND instruction emission failure.");
3237 if (DestVT == MVT::i64) {
3238 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3239 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3240 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3241 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3242 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3245 .addImm(AArch64::sub_32);
3250 if (DestVT == MVT::i64) {
3251 // FIXME: We're SExt i1 to i64.
3254 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3255 /*TODO:IsKill=*/false, 0, 0);
3259 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3260 unsigned Op1, bool Op1IsKill) {
3262 switch (RetVT.SimpleTy) {
3268 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3270 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3273 const TargetRegisterClass *RC =
3274 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3275 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3276 /*IsKill=*/ZReg, true);
3279 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3280 unsigned Op1, bool Op1IsKill) {
3281 if (RetVT != MVT::i64)
3284 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3285 Op0, Op0IsKill, Op1, Op1IsKill,
3286 AArch64::XZR, /*IsKill=*/true);
3289 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3290 unsigned Op1, bool Op1IsKill) {
3291 if (RetVT != MVT::i64)
3294 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3295 Op0, Op0IsKill, Op1, Op1IsKill,
3296 AArch64::XZR, /*IsKill=*/true);
3299 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3300 unsigned Op1Reg, bool Op1IsKill) {
3302 bool NeedTrunc = false;
3304 switch (RetVT.SimpleTy) {
3306 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3307 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3308 case MVT::i32: Opc = AArch64::LSLVWr; break;
3309 case MVT::i64: Opc = AArch64::LSLVXr; break;
3312 const TargetRegisterClass *RC =
3313 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3315 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3318 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3321 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3325 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3326 bool Op0IsKill, uint64_t Shift,
3328 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3329 "Unexpected source/return type pair.");
3330 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3331 SrcVT == MVT::i64) && "Unexpected source value type.");
3332 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3333 RetVT == MVT::i64) && "Unexpected return value type.");
3335 bool Is64Bit = (RetVT == MVT::i64);
3336 unsigned RegSize = Is64Bit ? 64 : 32;
3337 unsigned DstBits = RetVT.getSizeInBits();
3338 unsigned SrcBits = SrcVT.getSizeInBits();
3340 // Don't deal with undefined shifts.
3341 if (Shift >= DstBits)
3344 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3345 // {S|U}BFM Wd, Wn, #r, #s
3346 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3348 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3349 // %2 = shl i16 %1, 4
3350 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3351 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3352 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3353 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3355 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3356 // %2 = shl i16 %1, 8
3357 // Wd<32+7-24,32-24> = Wn<7:0>
3358 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3359 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3360 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3362 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3363 // %2 = shl i16 %1, 12
3364 // Wd<32+3-20,32-20> = Wn<3:0>
3365 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3366 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3367 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3369 unsigned ImmR = RegSize - Shift;
3370 // Limit the width to the length of the source type.
3371 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3372 static const unsigned OpcTable[2][2] = {
3373 {AArch64::SBFMWri, AArch64::SBFMXri},
3374 {AArch64::UBFMWri, AArch64::UBFMXri}
3376 unsigned Opc = OpcTable[IsZext][Is64Bit];
3377 const TargetRegisterClass *RC =
3378 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3379 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3380 unsigned TmpReg = MRI.createVirtualRegister(RC);
3381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3382 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3384 .addReg(Op0, getKillRegState(Op0IsKill))
3385 .addImm(AArch64::sub_32);
3389 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3392 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3393 unsigned Op1Reg, bool Op1IsKill) {
3395 bool NeedTrunc = false;
3397 switch (RetVT.SimpleTy) {
3399 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3400 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3401 case MVT::i32: Opc = AArch64::LSRVWr; break;
3402 case MVT::i64: Opc = AArch64::LSRVXr; break;
3405 const TargetRegisterClass *RC =
3406 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3408 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3409 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3410 Op0IsKill = Op1IsKill = true;
3412 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3415 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3419 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3420 bool Op0IsKill, uint64_t Shift,
3422 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3423 "Unexpected source/return type pair.");
3424 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3425 SrcVT == MVT::i64) && "Unexpected source value type.");
3426 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3427 RetVT == MVT::i64) && "Unexpected return value type.");
3429 bool Is64Bit = (RetVT == MVT::i64);
3430 unsigned RegSize = Is64Bit ? 64 : 32;
3431 unsigned DstBits = RetVT.getSizeInBits();
3432 unsigned SrcBits = SrcVT.getSizeInBits();
3434 // Don't deal with undefined shifts.
3435 if (Shift >= DstBits)
3438 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3439 // {S|U}BFM Wd, Wn, #r, #s
3440 // Wd<s-r:0> = Wn<s:r> when r <= s
3442 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3443 // %2 = lshr i16 %1, 4
3444 // Wd<7-4:0> = Wn<7:4>
3445 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
3446 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3447 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3449 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3450 // %2 = lshr i16 %1, 8
3451 // Wd<7-7,0> = Wn<7:7>
3452 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
3453 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3454 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3456 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3457 // %2 = lshr i16 %1, 12
3458 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3459 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
3460 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3461 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3463 if (Shift >= SrcBits && IsZExt)
3464 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3466 // It is not possible to fold a sign-extend into the LShr instruction. In this
3467 // case emit a sign-extend.
3469 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3474 SrcBits = SrcVT.getSizeInBits();
3478 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3479 unsigned ImmS = SrcBits - 1;
3480 static const unsigned OpcTable[2][2] = {
3481 {AArch64::SBFMWri, AArch64::SBFMXri},
3482 {AArch64::UBFMWri, AArch64::UBFMXri}
3484 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3485 const TargetRegisterClass *RC =
3486 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3487 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3488 unsigned TmpReg = MRI.createVirtualRegister(RC);
3489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3490 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3492 .addReg(Op0, getKillRegState(Op0IsKill))
3493 .addImm(AArch64::sub_32);
3497 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3500 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3501 unsigned Op1Reg, bool Op1IsKill) {
3503 bool NeedTrunc = false;
3505 switch (RetVT.SimpleTy) {
3507 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
3508 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
3509 case MVT::i32: Opc = AArch64::ASRVWr; break;
3510 case MVT::i64: Opc = AArch64::ASRVXr; break;
3513 const TargetRegisterClass *RC =
3514 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3516 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
3517 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3518 Op0IsKill = Op1IsKill = true;
3520 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3523 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3527 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3528 bool Op0IsKill, uint64_t Shift,
3530 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3531 "Unexpected source/return type pair.");
3532 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3533 SrcVT == MVT::i64) && "Unexpected source value type.");
3534 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3535 RetVT == MVT::i64) && "Unexpected return value type.");
3537 bool Is64Bit = (RetVT == MVT::i64);
3538 unsigned RegSize = Is64Bit ? 64 : 32;
3539 unsigned DstBits = RetVT.getSizeInBits();
3540 unsigned SrcBits = SrcVT.getSizeInBits();
3542 // Don't deal with undefined shifts.
3543 if (Shift >= DstBits)
3546 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3547 // {S|U}BFM Wd, Wn, #r, #s
3548 // Wd<s-r:0> = Wn<s:r> when r <= s
3550 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3551 // %2 = ashr i16 %1, 4
3552 // Wd<7-4:0> = Wn<7:4>
3553 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
3554 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3555 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3557 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3558 // %2 = ashr i16 %1, 8
3559 // Wd<7-7,0> = Wn<7:7>
3560 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3561 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3562 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3564 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3565 // %2 = ashr i16 %1, 12
3566 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3567 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3568 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3569 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3571 if (Shift >= SrcBits && IsZExt)
3572 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3574 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3575 unsigned ImmS = SrcBits - 1;
3576 static const unsigned OpcTable[2][2] = {
3577 {AArch64::SBFMWri, AArch64::SBFMXri},
3578 {AArch64::UBFMWri, AArch64::UBFMXri}
3580 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3581 const TargetRegisterClass *RC =
3582 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3583 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3584 unsigned TmpReg = MRI.createVirtualRegister(RC);
3585 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3586 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3588 .addReg(Op0, getKillRegState(Op0IsKill))
3589 .addImm(AArch64::sub_32);
3593 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3596 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
3598 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
3600 // FastISel does not have plumbing to deal with extensions where the SrcVT or
3601 // DestVT are odd things, so test to make sure that they are both types we can
3602 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
3603 // bail out to SelectionDAG.
3604 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
3605 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
3606 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
3607 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
3613 switch (SrcVT.SimpleTy) {
3617 return emiti1Ext(SrcReg, DestVT, IsZExt);
3619 if (DestVT == MVT::i64)
3620 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3622 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
3626 if (DestVT == MVT::i64)
3627 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3629 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
3633 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
3634 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3639 // Handle i8 and i16 as i32.
3640 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3642 else if (DestVT == MVT::i64) {
3643 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3644 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3645 TII.get(AArch64::SUBREG_TO_REG), Src64)
3648 .addImm(AArch64::sub_32);
3652 const TargetRegisterClass *RC =
3653 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3654 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
3657 bool AArch64FastISel::selectIntExt(const Instruction *I) {
3658 // On ARM, in general, integer casts don't involve legal types; this code
3659 // handles promotable integers. The high bits for a type smaller than
3660 // the register size are assumed to be undefined.
3661 Type *DestTy = I->getType();
3662 Value *Src = I->getOperand(0);
3663 Type *SrcTy = Src->getType();
3665 unsigned SrcReg = getRegForValue(Src);
3669 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3670 EVT DestEVT = TLI.getValueType(DestTy, true);
3671 if (!SrcEVT.isSimple())
3673 if (!DestEVT.isSimple())
3676 MVT SrcVT = SrcEVT.getSimpleVT();
3677 MVT DestVT = DestEVT.getSimpleVT();
3678 unsigned ResultReg = 0;
3680 bool IsZExt = isa<ZExtInst>(I);
3681 // Check if it is an argument and if it is already zero/sign-extended.
3682 if (const auto *Arg = dyn_cast<Argument>(Src)) {
3683 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
3684 if (DestVT == MVT::i64) {
3685 ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
3686 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3687 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
3690 .addImm(AArch64::sub_32);
3697 ResultReg = emitIntExt(SrcVT, SrcReg, DestVT, IsZExt);
3702 updateValueMap(I, ResultReg);
3706 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
3707 EVT DestEVT = TLI.getValueType(I->getType(), true);
3708 if (!DestEVT.isSimple())
3711 MVT DestVT = DestEVT.getSimpleVT();
3712 if (DestVT != MVT::i64 && DestVT != MVT::i32)
3716 bool Is64bit = (DestVT == MVT::i64);
3717 switch (ISDOpcode) {
3721 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
3724 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
3727 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
3728 unsigned Src0Reg = getRegForValue(I->getOperand(0));
3731 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
3733 unsigned Src1Reg = getRegForValue(I->getOperand(1));
3736 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
3738 const TargetRegisterClass *RC =
3739 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3740 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
3741 Src1Reg, /*IsKill=*/false);
3742 assert(QuotReg && "Unexpected DIV instruction emission failure.");
3743 // The remainder is computed as numerator - (quotient * denominator) using the
3744 // MSUB instruction.
3745 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
3746 Src1Reg, Src1IsKill, Src0Reg,
3748 updateValueMap(I, ResultReg);
3752 bool AArch64FastISel::selectMul(const Instruction *I) {
3754 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
3758 return selectBinaryOp(I, ISD::MUL);
3760 const Value *Src0 = I->getOperand(0);
3761 const Value *Src1 = I->getOperand(1);
3762 if (const auto *C = dyn_cast<ConstantInt>(Src0))
3763 if (C->getValue().isPowerOf2())
3764 std::swap(Src0, Src1);
3766 // Try to simplify to a shift instruction.
3767 if (const auto *C = dyn_cast<ConstantInt>(Src1))
3768 if (C->getValue().isPowerOf2()) {
3769 uint64_t ShiftVal = C->getValue().logBase2();
3772 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
3774 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
3777 Src0 = ZExt->getOperand(0);
3779 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
3781 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
3784 Src0 = SExt->getOperand(0);
3788 unsigned Src0Reg = getRegForValue(Src0);
3791 bool Src0IsKill = hasTrivialKill(Src0);
3793 unsigned ResultReg =
3794 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
3797 updateValueMap(I, ResultReg);
3802 unsigned Src0Reg = getRegForValue(I->getOperand(0));
3805 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
3807 unsigned Src1Reg = getRegForValue(I->getOperand(1));
3810 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
3812 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
3817 updateValueMap(I, ResultReg);
3821 bool AArch64FastISel::selectShift(const Instruction *I) {
3823 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
3826 if (RetVT.isVector())
3827 return selectOperator(I, I->getOpcode());
3829 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
3830 unsigned ResultReg = 0;
3831 uint64_t ShiftVal = C->getZExtValue();
3833 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
3834 const Value *Op0 = I->getOperand(0);
3835 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
3837 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
3840 Op0 = ZExt->getOperand(0);
3842 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
3844 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
3847 Op0 = SExt->getOperand(0);
3851 unsigned Op0Reg = getRegForValue(Op0);
3854 bool Op0IsKill = hasTrivialKill(Op0);
3856 switch (I->getOpcode()) {
3857 default: llvm_unreachable("Unexpected instruction.");
3858 case Instruction::Shl:
3859 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3861 case Instruction::AShr:
3862 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3864 case Instruction::LShr:
3865 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3871 updateValueMap(I, ResultReg);
3875 unsigned Op0Reg = getRegForValue(I->getOperand(0));
3878 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
3880 unsigned Op1Reg = getRegForValue(I->getOperand(1));
3883 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
3885 unsigned ResultReg = 0;
3886 switch (I->getOpcode()) {
3887 default: llvm_unreachable("Unexpected instruction.");
3888 case Instruction::Shl:
3889 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3891 case Instruction::AShr:
3892 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3894 case Instruction::LShr:
3895 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3902 updateValueMap(I, ResultReg);
3906 bool AArch64FastISel::selectBitCast(const Instruction *I) {
3909 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
3911 if (!isTypeLegal(I->getType(), RetVT))
3915 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
3916 Opc = AArch64::FMOVWSr;
3917 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
3918 Opc = AArch64::FMOVXDr;
3919 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
3920 Opc = AArch64::FMOVSWr;
3921 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
3922 Opc = AArch64::FMOVDXr;
3926 const TargetRegisterClass *RC = nullptr;
3927 switch (RetVT.SimpleTy) {
3928 default: llvm_unreachable("Unexpected value type.");
3929 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
3930 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
3931 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
3932 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
3934 unsigned Op0Reg = getRegForValue(I->getOperand(0));
3937 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
3938 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
3943 updateValueMap(I, ResultReg);
3947 bool AArch64FastISel::selectFRem(const Instruction *I) {
3949 if (!isTypeLegal(I->getType(), RetVT))
3953 switch (RetVT.SimpleTy) {
3957 LC = RTLIB::REM_F32;
3960 LC = RTLIB::REM_F64;
3965 Args.reserve(I->getNumOperands());
3967 // Populate the argument list.
3968 for (auto &Arg : I->operands()) {
3971 Entry.Ty = Arg->getType();
3972 Args.push_back(Entry);
3975 CallLoweringInfo CLI;
3976 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
3977 TLI.getLibcallName(LC), std::move(Args));
3978 if (!lowerCallTo(CLI))
3980 updateValueMap(I, CLI.ResultReg);
3984 bool AArch64FastISel::selectSDiv(const Instruction *I) {
3986 if (!isTypeLegal(I->getType(), VT))
3989 if (!isa<ConstantInt>(I->getOperand(1)))
3990 return selectBinaryOp(I, ISD::SDIV);
3992 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
3993 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
3994 !(C.isPowerOf2() || (-C).isPowerOf2()))
3995 return selectBinaryOp(I, ISD::SDIV);
3997 unsigned Lg2 = C.countTrailingZeros();
3998 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4001 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4003 if (cast<BinaryOperator>(I)->isExact()) {
4004 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4007 updateValueMap(I, ResultReg);
4011 unsigned Pow2MinusOne = (1 << Lg2) - 1;
4012 unsigned AddReg = emitAddSub_ri(/*UseAdd=*/true, VT, Src0Reg,
4013 /*IsKill=*/false, Pow2MinusOne);
4017 // (Src0 < 0) ? Pow2 - 1 : 0;
4018 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4022 const TargetRegisterClass *RC;
4023 if (VT == MVT::i64) {
4024 SelectOpc = AArch64::CSELXr;
4025 RC = &AArch64::GPR64RegClass;
4027 SelectOpc = AArch64::CSELWr;
4028 RC = &AArch64::GPR32RegClass;
4030 unsigned SelectReg =
4031 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4032 Src0IsKill, AArch64CC::LT);
4036 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4037 // negate the result.
4038 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4041 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4042 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4044 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4049 updateValueMap(I, ResultReg);
4053 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4054 switch (I->getOpcode()) {
4057 case Instruction::Add:
4058 case Instruction::Sub:
4059 return selectAddSub(I);
4060 case Instruction::Mul:
4061 return selectMul(I);
4062 case Instruction::SDiv:
4063 return selectSDiv(I);
4064 case Instruction::SRem:
4065 if (!selectBinaryOp(I, ISD::SREM))
4066 return selectRem(I, ISD::SREM);
4068 case Instruction::URem:
4069 if (!selectBinaryOp(I, ISD::UREM))
4070 return selectRem(I, ISD::UREM);
4072 case Instruction::Shl:
4073 case Instruction::LShr:
4074 case Instruction::AShr:
4075 return selectShift(I);
4076 case Instruction::And:
4077 case Instruction::Or:
4078 case Instruction::Xor:
4079 return selectLogicalOp(I);
4080 case Instruction::Br:
4081 return selectBranch(I);
4082 case Instruction::IndirectBr:
4083 return selectIndirectBr(I);
4084 case Instruction::BitCast:
4085 if (!FastISel::selectBitCast(I))
4086 return selectBitCast(I);
4088 case Instruction::FPToSI:
4089 if (!selectCast(I, ISD::FP_TO_SINT))
4090 return selectFPToInt(I, /*Signed=*/true);
4092 case Instruction::FPToUI:
4093 return selectFPToInt(I, /*Signed=*/false);
4094 case Instruction::ZExt:
4095 if (!selectCast(I, ISD::ZERO_EXTEND))
4096 return selectIntExt(I);
4098 case Instruction::SExt:
4099 if (!selectCast(I, ISD::SIGN_EXTEND))
4100 return selectIntExt(I);
4102 case Instruction::Trunc:
4103 if (!selectCast(I, ISD::TRUNCATE))
4104 return selectTrunc(I);
4106 case Instruction::FPExt:
4107 return selectFPExt(I);
4108 case Instruction::FPTrunc:
4109 return selectFPTrunc(I);
4110 case Instruction::SIToFP:
4111 if (!selectCast(I, ISD::SINT_TO_FP))
4112 return selectIntToFP(I, /*Signed=*/true);
4114 case Instruction::UIToFP:
4115 return selectIntToFP(I, /*Signed=*/false);
4116 case Instruction::Load:
4117 return selectLoad(I);
4118 case Instruction::Store:
4119 return selectStore(I);
4120 case Instruction::FCmp:
4121 case Instruction::ICmp:
4122 return selectCmp(I);
4123 case Instruction::Select:
4124 return selectSelect(I);
4125 case Instruction::Ret:
4126 return selectRet(I);
4127 case Instruction::FRem:
4128 return selectFRem(I);
4131 // fall-back to target-independent instruction selection.
4132 return selectOperator(I, I->getOpcode());
4133 // Silence warnings.
4134 (void)&CC_AArch64_DarwinPCS_VarArg;
4138 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4139 const TargetLibraryInfo *LibInfo) {
4140 return new AArch64FastISel(FuncInfo, LibInfo);