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);
137 bool selectGetElementPtr(const Instruction *I);
139 // Utility helper routines.
140 bool isTypeLegal(Type *Ty, MVT &VT);
141 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
142 bool isValueAvailable(const Value *V) const;
143 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
144 bool computeCallAddress(const Value *V, Address &Addr);
145 bool simplifyAddress(Address &Addr, MVT VT);
146 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
147 unsigned Flags, unsigned ScaleFactor,
148 MachineMemOperand *MMO);
149 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
150 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
152 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
154 bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
156 // Emit helper routines.
157 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
158 const Value *RHS, bool SetFlags = false,
159 bool WantResult = true, bool IsZExt = false);
160 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
161 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
162 bool SetFlags = false, bool WantResult = true);
163 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
164 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
165 bool WantResult = true);
166 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
167 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
168 AArch64_AM::ShiftExtendType ShiftType,
169 uint64_t ShiftImm, bool SetFlags = false,
170 bool WantResult = true);
171 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
172 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
173 AArch64_AM::ShiftExtendType ExtType,
174 uint64_t ShiftImm, bool SetFlags = false,
175 bool WantResult = true);
178 bool emitCompareAndBranch(const BranchInst *BI);
179 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
180 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
181 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
182 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
183 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
184 MachineMemOperand *MMO = nullptr);
185 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
186 MachineMemOperand *MMO = nullptr);
187 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
188 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
189 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
190 bool SetFlags = false, bool WantResult = true,
191 bool IsZExt = false);
192 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
193 bool SetFlags = false, bool WantResult = true,
194 bool IsZExt = false);
195 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
196 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
197 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
198 unsigned RHSReg, bool RHSIsKill,
199 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
200 bool WantResult = true);
201 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
203 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
204 bool LHSIsKill, uint64_t Imm);
205 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
206 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
208 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
209 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
210 unsigned Op1, bool Op1IsKill);
211 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
212 unsigned Op1, bool Op1IsKill);
213 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
214 unsigned Op1, bool Op1IsKill);
215 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
216 unsigned Op1Reg, bool Op1IsKill);
217 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
218 uint64_t Imm, bool IsZExt = true);
219 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
220 unsigned Op1Reg, bool Op1IsKill);
221 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
222 uint64_t Imm, bool IsZExt = true);
223 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
224 unsigned Op1Reg, bool Op1IsKill);
225 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
226 uint64_t Imm, bool IsZExt = false);
228 unsigned materializeInt(const ConstantInt *CI, MVT VT);
229 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
230 unsigned materializeGV(const GlobalValue *GV);
232 // Call handling routines.
234 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
235 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
237 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
240 // Backend specific FastISel code.
241 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
242 unsigned fastMaterializeConstant(const Constant *C) override;
243 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
245 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
246 const TargetLibraryInfo *LibInfo)
247 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
248 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
249 Context = &FuncInfo.Fn->getContext();
252 bool fastSelectInstruction(const Instruction *I) override;
254 #include "AArch64GenFastISel.inc"
257 } // end anonymous namespace
259 #include "AArch64GenCallingConv.inc"
261 /// \brief Check if the sign-/zero-extend will be a noop.
262 static bool isIntExtFree(const Instruction *I) {
263 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
264 "Unexpected integer extend instruction.");
265 assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
266 "Unexpected value type.");
267 bool IsZExt = isa<ZExtInst>(I);
269 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
273 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
274 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
280 /// \brief Determine the implicit scale factor that is applied by a memory
281 /// operation for a given value type.
282 static unsigned getImplicitScaleFactor(MVT VT) {
283 switch (VT.SimpleTy) {
286 case MVT::i1: // fall-through
291 case MVT::i32: // fall-through
294 case MVT::i64: // fall-through
300 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
301 if (CC == CallingConv::WebKit_JS)
302 return CC_AArch64_WebKit_JS;
303 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
306 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
307 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
308 "Alloca should always return a pointer.");
310 // Don't handle dynamic allocas.
311 if (!FuncInfo.StaticAllocaMap.count(AI))
314 DenseMap<const AllocaInst *, int>::iterator SI =
315 FuncInfo.StaticAllocaMap.find(AI);
317 if (SI != FuncInfo.StaticAllocaMap.end()) {
318 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
319 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
321 .addFrameIndex(SI->second)
330 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
335 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
337 // Create a copy from the zero register to materialize a "0" value.
338 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
339 : &AArch64::GPR32RegClass;
340 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
341 unsigned ResultReg = createResultReg(RC);
342 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
343 ResultReg).addReg(ZeroReg, getKillRegState(true));
347 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
348 // Positive zero (+0.0) has to be materialized with a fmov from the zero
349 // register, because the immediate version of fmov cannot encode zero.
350 if (CFP->isNullValue())
351 return fastMaterializeFloatZero(CFP);
353 if (VT != MVT::f32 && VT != MVT::f64)
356 const APFloat Val = CFP->getValueAPF();
357 bool Is64Bit = (VT == MVT::f64);
358 // This checks to see if we can use FMOV instructions to materialize
359 // a constant, otherwise we have to materialize via the constant pool.
360 if (TLI.isFPImmLegal(Val, VT)) {
362 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
363 assert((Imm != -1) && "Cannot encode floating-point constant.");
364 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
365 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
368 // Materialize via constant pool. MachineConstantPool wants an explicit
370 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
372 Align = DL.getTypeAllocSize(CFP->getType());
374 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
375 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
376 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
377 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
379 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
380 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
383 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
387 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
388 // We can't handle thread-local variables quickly yet.
389 if (GV->isThreadLocal())
392 // MachO still uses GOT for large code-model accesses, but ELF requires
393 // movz/movk sequences, which FastISel doesn't handle yet.
394 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
397 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
399 EVT DestEVT = TLI.getValueType(GV->getType(), true);
400 if (!DestEVT.isSimple())
403 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
406 if (OpFlags & AArch64II::MO_GOT) {
408 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
410 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
412 ResultReg = createResultReg(&AArch64::GPR64RegClass);
413 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
416 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
418 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
419 // We can't handle addresses loaded from a constant pool quickly yet.
423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
425 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
427 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
431 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
437 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
438 EVT CEVT = TLI.getValueType(C->getType(), true);
440 // Only handle simple types.
441 if (!CEVT.isSimple())
443 MVT VT = CEVT.getSimpleVT();
445 if (const auto *CI = dyn_cast<ConstantInt>(C))
446 return materializeInt(CI, VT);
447 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
448 return materializeFP(CFP, VT);
449 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
450 return materializeGV(GV);
455 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
456 assert(CFP->isNullValue() &&
457 "Floating-point constant is not a positive zero.");
459 if (!isTypeLegal(CFP->getType(), VT))
462 if (VT != MVT::f32 && VT != MVT::f64)
465 bool Is64Bit = (VT == MVT::f64);
466 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
467 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
468 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
471 /// \brief Check if the multiply is by a power-of-2 constant.
472 static bool isMulPowOf2(const Value *I) {
473 if (const auto *MI = dyn_cast<MulOperator>(I)) {
474 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
475 if (C->getValue().isPowerOf2())
477 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
478 if (C->getValue().isPowerOf2())
484 // Computes the address to get to an object.
485 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
487 const User *U = nullptr;
488 unsigned Opcode = Instruction::UserOp1;
489 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
490 // Don't walk into other basic blocks unless the object is an alloca from
491 // another block, otherwise it may not have a virtual register assigned.
492 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
493 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
494 Opcode = I->getOpcode();
497 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
498 Opcode = C->getOpcode();
502 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
503 if (Ty->getAddressSpace() > 255)
504 // Fast instruction selection doesn't support the special
511 case Instruction::BitCast: {
512 // Look through bitcasts.
513 return computeAddress(U->getOperand(0), Addr, Ty);
515 case Instruction::IntToPtr: {
516 // Look past no-op inttoptrs.
517 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
518 return computeAddress(U->getOperand(0), Addr, Ty);
521 case Instruction::PtrToInt: {
522 // Look past no-op ptrtoints.
523 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
524 return computeAddress(U->getOperand(0), Addr, Ty);
527 case Instruction::GetElementPtr: {
528 Address SavedAddr = Addr;
529 uint64_t TmpOffset = Addr.getOffset();
531 // Iterate through the GEP folding the constants into offsets where
533 gep_type_iterator GTI = gep_type_begin(U);
534 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
536 const Value *Op = *i;
537 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
538 const StructLayout *SL = DL.getStructLayout(STy);
539 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
540 TmpOffset += SL->getElementOffset(Idx);
542 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
544 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
545 // Constant-offset addressing.
546 TmpOffset += CI->getSExtValue() * S;
549 if (canFoldAddIntoGEP(U, Op)) {
550 // A compatible add with a constant operand. Fold the constant.
552 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
553 TmpOffset += CI->getSExtValue() * S;
554 // Iterate on the other operand.
555 Op = cast<AddOperator>(Op)->getOperand(0);
559 goto unsupported_gep;
564 // Try to grab the base operand now.
565 Addr.setOffset(TmpOffset);
566 if (computeAddress(U->getOperand(0), Addr, Ty))
569 // We failed, restore everything and try the other options.
575 case Instruction::Alloca: {
576 const AllocaInst *AI = cast<AllocaInst>(Obj);
577 DenseMap<const AllocaInst *, int>::iterator SI =
578 FuncInfo.StaticAllocaMap.find(AI);
579 if (SI != FuncInfo.StaticAllocaMap.end()) {
580 Addr.setKind(Address::FrameIndexBase);
581 Addr.setFI(SI->second);
586 case Instruction::Add: {
587 // Adds of constants are common and easy enough.
588 const Value *LHS = U->getOperand(0);
589 const Value *RHS = U->getOperand(1);
591 if (isa<ConstantInt>(LHS))
594 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
595 Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
596 return computeAddress(LHS, Addr, Ty);
599 Address Backup = Addr;
600 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
606 case Instruction::Sub: {
607 // Subs of constants are common and easy enough.
608 const Value *LHS = U->getOperand(0);
609 const Value *RHS = U->getOperand(1);
611 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
612 Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
613 return computeAddress(LHS, Addr, Ty);
617 case Instruction::Shl: {
618 if (Addr.getOffsetReg())
621 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
625 unsigned Val = CI->getZExtValue();
626 if (Val < 1 || Val > 3)
629 uint64_t NumBytes = 0;
630 if (Ty && Ty->isSized()) {
631 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
632 NumBytes = NumBits / 8;
633 if (!isPowerOf2_64(NumBits))
637 if (NumBytes != (1ULL << Val))
641 Addr.setExtendType(AArch64_AM::LSL);
643 const Value *Src = U->getOperand(0);
644 if (const auto *I = dyn_cast<Instruction>(Src))
645 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
648 // Fold the zext or sext when it won't become a noop.
649 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
650 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
651 Addr.setExtendType(AArch64_AM::UXTW);
652 Src = ZE->getOperand(0);
654 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
655 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
656 Addr.setExtendType(AArch64_AM::SXTW);
657 Src = SE->getOperand(0);
661 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
662 if (AI->getOpcode() == Instruction::And) {
663 const Value *LHS = AI->getOperand(0);
664 const Value *RHS = AI->getOperand(1);
666 if (const auto *C = dyn_cast<ConstantInt>(LHS))
667 if (C->getValue() == 0xffffffff)
670 if (const auto *C = dyn_cast<ConstantInt>(RHS))
671 if (C->getValue() == 0xffffffff) {
672 Addr.setExtendType(AArch64_AM::UXTW);
673 unsigned Reg = getRegForValue(LHS);
676 bool RegIsKill = hasTrivialKill(LHS);
677 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
679 Addr.setOffsetReg(Reg);
684 unsigned Reg = getRegForValue(Src);
687 Addr.setOffsetReg(Reg);
690 case Instruction::Mul: {
691 if (Addr.getOffsetReg())
697 const Value *LHS = U->getOperand(0);
698 const Value *RHS = U->getOperand(1);
700 // Canonicalize power-of-2 value to the RHS.
701 if (const auto *C = dyn_cast<ConstantInt>(LHS))
702 if (C->getValue().isPowerOf2())
705 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
706 const auto *C = cast<ConstantInt>(RHS);
707 unsigned Val = C->getValue().logBase2();
708 if (Val < 1 || Val > 3)
711 uint64_t NumBytes = 0;
712 if (Ty && Ty->isSized()) {
713 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
714 NumBytes = NumBits / 8;
715 if (!isPowerOf2_64(NumBits))
719 if (NumBytes != (1ULL << Val))
723 Addr.setExtendType(AArch64_AM::LSL);
725 const Value *Src = LHS;
726 if (const auto *I = dyn_cast<Instruction>(Src))
727 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
731 // Fold the zext or sext when it won't become a noop.
732 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
733 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
734 Addr.setExtendType(AArch64_AM::UXTW);
735 Src = ZE->getOperand(0);
737 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
738 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
739 Addr.setExtendType(AArch64_AM::SXTW);
740 Src = SE->getOperand(0);
744 unsigned Reg = getRegForValue(Src);
747 Addr.setOffsetReg(Reg);
750 case Instruction::And: {
751 if (Addr.getOffsetReg())
754 if (DL.getTypeSizeInBits(Ty) != 8)
757 const Value *LHS = U->getOperand(0);
758 const Value *RHS = U->getOperand(1);
760 if (const auto *C = dyn_cast<ConstantInt>(LHS))
761 if (C->getValue() == 0xffffffff)
764 if (const auto *C = dyn_cast<ConstantInt>(RHS))
765 if (C->getValue() == 0xffffffff) {
767 Addr.setExtendType(AArch64_AM::LSL);
768 Addr.setExtendType(AArch64_AM::UXTW);
770 unsigned Reg = getRegForValue(LHS);
773 bool RegIsKill = hasTrivialKill(LHS);
774 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
776 Addr.setOffsetReg(Reg);
781 case Instruction::SExt:
782 case Instruction::ZExt: {
783 if (!Addr.getReg() || Addr.getOffsetReg())
786 const Value *Src = nullptr;
787 // Fold the zext or sext when it won't become a noop.
788 if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
789 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
790 Addr.setExtendType(AArch64_AM::UXTW);
791 Src = ZE->getOperand(0);
793 } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
794 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
795 Addr.setExtendType(AArch64_AM::SXTW);
796 Src = SE->getOperand(0);
804 unsigned Reg = getRegForValue(Src);
807 Addr.setOffsetReg(Reg);
813 if (!Addr.getOffsetReg()) {
814 unsigned Reg = getRegForValue(Obj);
817 Addr.setOffsetReg(Reg);
823 unsigned Reg = getRegForValue(Obj);
830 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
831 const User *U = nullptr;
832 unsigned Opcode = Instruction::UserOp1;
835 if (const auto *I = dyn_cast<Instruction>(V)) {
836 Opcode = I->getOpcode();
838 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
839 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
840 Opcode = C->getOpcode();
846 case Instruction::BitCast:
847 // Look past bitcasts if its operand is in the same BB.
849 return computeCallAddress(U->getOperand(0), Addr);
851 case Instruction::IntToPtr:
852 // Look past no-op inttoptrs if its operand is in the same BB.
854 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
855 return computeCallAddress(U->getOperand(0), Addr);
857 case Instruction::PtrToInt:
858 // Look past no-op ptrtoints if its operand is in the same BB.
860 TLI.getValueType(U->getType()) == TLI.getPointerTy())
861 return computeCallAddress(U->getOperand(0), Addr);
865 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
866 Addr.setGlobalValue(GV);
870 // If all else fails, try to materialize the value in a register.
871 if (!Addr.getGlobalValue()) {
872 Addr.setReg(getRegForValue(V));
873 return Addr.getReg() != 0;
880 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
881 EVT evt = TLI.getValueType(Ty, true);
883 // Only handle simple types.
884 if (evt == MVT::Other || !evt.isSimple())
886 VT = evt.getSimpleVT();
888 // This is a legal type, but it's not something we handle in fast-isel.
892 // Handle all other legal types, i.e. a register that will directly hold this
894 return TLI.isTypeLegal(VT);
897 /// \brief Determine if the value type is supported by FastISel.
899 /// FastISel for AArch64 can handle more value types than are legal. This adds
900 /// simple value type such as i1, i8, and i16.
901 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
902 if (Ty->isVectorTy() && !IsVectorAllowed)
905 if (isTypeLegal(Ty, VT))
908 // If this is a type than can be sign or zero-extended to a basic operation
909 // go ahead and accept it now.
910 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
916 bool AArch64FastISel::isValueAvailable(const Value *V) const {
917 if (!isa<Instruction>(V))
920 const auto *I = cast<Instruction>(V);
921 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
927 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
928 unsigned ScaleFactor = getImplicitScaleFactor(VT);
932 bool ImmediateOffsetNeedsLowering = false;
933 bool RegisterOffsetNeedsLowering = false;
934 int64_t Offset = Addr.getOffset();
935 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
936 ImmediateOffsetNeedsLowering = true;
937 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
938 !isUInt<12>(Offset / ScaleFactor))
939 ImmediateOffsetNeedsLowering = true;
941 // Cannot encode an offset register and an immediate offset in the same
942 // instruction. Fold the immediate offset into the load/store instruction and
943 // emit an additonal add to take care of the offset register.
944 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.isRegBase() &&
946 RegisterOffsetNeedsLowering = true;
948 // Cannot encode zero register as base.
949 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
950 RegisterOffsetNeedsLowering = true;
952 // If this is a stack pointer and the offset needs to be simplified then put
953 // the alloca address into a register, set the base type back to register and
954 // continue. This should almost never happen.
955 if (ImmediateOffsetNeedsLowering && Addr.isFIBase()) {
956 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
959 .addFrameIndex(Addr.getFI())
962 Addr.setKind(Address::RegBase);
963 Addr.setReg(ResultReg);
966 if (RegisterOffsetNeedsLowering) {
967 unsigned ResultReg = 0;
969 if (Addr.getExtendType() == AArch64_AM::SXTW ||
970 Addr.getExtendType() == AArch64_AM::UXTW )
971 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
972 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
973 /*TODO:IsKill=*/false, Addr.getExtendType(),
976 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
977 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
978 /*TODO:IsKill=*/false, AArch64_AM::LSL,
981 if (Addr.getExtendType() == AArch64_AM::UXTW)
982 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
983 /*Op0IsKill=*/false, Addr.getShift(),
985 else if (Addr.getExtendType() == AArch64_AM::SXTW)
986 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
987 /*Op0IsKill=*/false, Addr.getShift(),
990 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
991 /*Op0IsKill=*/false, Addr.getShift());
996 Addr.setReg(ResultReg);
997 Addr.setOffsetReg(0);
999 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1002 // Since the offset is too large for the load/store instruction get the
1003 // reg+offset into a register.
1004 if (ImmediateOffsetNeedsLowering) {
1006 if (Addr.getReg()) {
1007 // Try to fold the immediate into the add instruction.
1009 ResultReg = emitAddSub_ri(/*UseAdd=*/false, MVT::i64, Addr.getReg(),
1010 /*IsKill=*/false, -Offset);
1012 ResultReg = emitAddSub_ri(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
1013 /*IsKill=*/false, Offset);
1015 unsigned ImmReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1016 ResultReg = emitAddSub_rr(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
1017 /*IsKill=*/false, ImmReg, /*IsKill=*/true);
1020 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1024 Addr.setReg(ResultReg);
1030 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1031 const MachineInstrBuilder &MIB,
1033 unsigned ScaleFactor,
1034 MachineMemOperand *MMO) {
1035 int64_t Offset = Addr.getOffset() / ScaleFactor;
1036 // Frame base works a bit differently. Handle it separately.
1037 if (Addr.isFIBase()) {
1038 int FI = Addr.getFI();
1039 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1040 // and alignment should be based on the VT.
1041 MMO = FuncInfo.MF->getMachineMemOperand(
1042 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1043 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1044 // Now add the rest of the operands.
1045 MIB.addFrameIndex(FI).addImm(Offset);
1047 assert(Addr.isRegBase() && "Unexpected address kind.");
1048 const MCInstrDesc &II = MIB->getDesc();
1049 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1051 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1053 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1054 if (Addr.getOffsetReg()) {
1055 assert(Addr.getOffset() == 0 && "Unexpected offset");
1056 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1057 Addr.getExtendType() == AArch64_AM::SXTX;
1058 MIB.addReg(Addr.getReg());
1059 MIB.addReg(Addr.getOffsetReg());
1060 MIB.addImm(IsSigned);
1061 MIB.addImm(Addr.getShift() != 0);
1063 MIB.addReg(Addr.getReg());
1069 MIB.addMemOperand(MMO);
1072 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1073 const Value *RHS, bool SetFlags,
1074 bool WantResult, bool IsZExt) {
1075 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1076 bool NeedExtend = false;
1077 switch (RetVT.SimpleTy) {
1085 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1089 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1091 case MVT::i32: // fall-through
1096 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1098 // Canonicalize immediates to the RHS first.
1099 if (UseAdd && isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1100 std::swap(LHS, RHS);
1102 // Canonicalize mul by power of 2 to the RHS.
1103 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1104 if (isMulPowOf2(LHS))
1105 std::swap(LHS, RHS);
1107 // Canonicalize shift immediate to the RHS.
1108 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1109 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1110 if (isa<ConstantInt>(SI->getOperand(1)))
1111 if (SI->getOpcode() == Instruction::Shl ||
1112 SI->getOpcode() == Instruction::LShr ||
1113 SI->getOpcode() == Instruction::AShr )
1114 std::swap(LHS, RHS);
1116 unsigned LHSReg = getRegForValue(LHS);
1119 bool LHSIsKill = hasTrivialKill(LHS);
1122 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1124 unsigned ResultReg = 0;
1125 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1126 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1127 if (C->isNegative())
1128 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1129 SetFlags, WantResult);
1131 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1137 // Only extend the RHS within the instruction if there is a valid extend type.
1138 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1139 isValueAvailable(RHS)) {
1140 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1141 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1142 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1143 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1146 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1147 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1148 RHSIsKill, ExtendType, C->getZExtValue(),
1149 SetFlags, WantResult);
1151 unsigned RHSReg = getRegForValue(RHS);
1154 bool RHSIsKill = hasTrivialKill(RHS);
1155 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1156 ExtendType, 0, SetFlags, WantResult);
1159 // Check if the mul can be folded into the instruction.
1160 if (RHS->hasOneUse() && isValueAvailable(RHS))
1161 if (isMulPowOf2(RHS)) {
1162 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1163 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1165 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1166 if (C->getValue().isPowerOf2())
1167 std::swap(MulLHS, MulRHS);
1169 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1170 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1171 unsigned RHSReg = getRegForValue(MulLHS);
1174 bool RHSIsKill = hasTrivialKill(MulLHS);
1175 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1176 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1179 // Check if the shift can be folded into the instruction.
1180 if (RHS->hasOneUse() && isValueAvailable(RHS))
1181 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1182 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1183 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1184 switch (SI->getOpcode()) {
1186 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1187 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1188 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1190 uint64_t ShiftVal = C->getZExtValue();
1191 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1192 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1195 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1196 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1197 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1203 unsigned RHSReg = getRegForValue(RHS);
1206 bool RHSIsKill = hasTrivialKill(RHS);
1209 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1211 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1212 SetFlags, WantResult);
1215 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1216 bool LHSIsKill, unsigned RHSReg,
1217 bool RHSIsKill, bool SetFlags,
1219 assert(LHSReg && RHSReg && "Invalid register number.");
1221 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1224 static const unsigned OpcTable[2][2][2] = {
1225 { { AArch64::SUBWrr, AArch64::SUBXrr },
1226 { AArch64::ADDWrr, AArch64::ADDXrr } },
1227 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1228 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1230 bool Is64Bit = RetVT == MVT::i64;
1231 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1232 const TargetRegisterClass *RC =
1233 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1236 ResultReg = createResultReg(RC);
1238 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1240 const MCInstrDesc &II = TII.get(Opc);
1241 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1242 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1243 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1244 .addReg(LHSReg, getKillRegState(LHSIsKill))
1245 .addReg(RHSReg, getKillRegState(RHSIsKill));
1249 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1250 bool LHSIsKill, uint64_t Imm,
1251 bool SetFlags, bool WantResult) {
1252 assert(LHSReg && "Invalid register number.");
1254 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1258 if (isUInt<12>(Imm))
1260 else if ((Imm & 0xfff000) == Imm) {
1266 static const unsigned OpcTable[2][2][2] = {
1267 { { AArch64::SUBWri, AArch64::SUBXri },
1268 { AArch64::ADDWri, AArch64::ADDXri } },
1269 { { AArch64::SUBSWri, AArch64::SUBSXri },
1270 { AArch64::ADDSWri, AArch64::ADDSXri } }
1272 bool Is64Bit = RetVT == MVT::i64;
1273 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1274 const TargetRegisterClass *RC;
1276 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1278 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1281 ResultReg = createResultReg(RC);
1283 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1285 const MCInstrDesc &II = TII.get(Opc);
1286 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1287 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1288 .addReg(LHSReg, getKillRegState(LHSIsKill))
1290 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1294 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1295 bool LHSIsKill, unsigned RHSReg,
1297 AArch64_AM::ShiftExtendType ShiftType,
1298 uint64_t ShiftImm, bool SetFlags,
1300 assert(LHSReg && RHSReg && "Invalid register number.");
1302 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1305 static const unsigned OpcTable[2][2][2] = {
1306 { { AArch64::SUBWrs, AArch64::SUBXrs },
1307 { AArch64::ADDWrs, AArch64::ADDXrs } },
1308 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1309 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1311 bool Is64Bit = RetVT == MVT::i64;
1312 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1313 const TargetRegisterClass *RC =
1314 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1317 ResultReg = createResultReg(RC);
1319 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1321 const MCInstrDesc &II = TII.get(Opc);
1322 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1323 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1324 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1325 .addReg(LHSReg, getKillRegState(LHSIsKill))
1326 .addReg(RHSReg, getKillRegState(RHSIsKill))
1327 .addImm(getShifterImm(ShiftType, ShiftImm));
1331 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1332 bool LHSIsKill, unsigned RHSReg,
1334 AArch64_AM::ShiftExtendType ExtType,
1335 uint64_t ShiftImm, bool SetFlags,
1337 assert(LHSReg && RHSReg && "Invalid register number.");
1339 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1342 static const unsigned OpcTable[2][2][2] = {
1343 { { AArch64::SUBWrx, AArch64::SUBXrx },
1344 { AArch64::ADDWrx, AArch64::ADDXrx } },
1345 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1346 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1348 bool Is64Bit = RetVT == MVT::i64;
1349 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1350 const TargetRegisterClass *RC = nullptr;
1352 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1354 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1357 ResultReg = createResultReg(RC);
1359 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1361 const MCInstrDesc &II = TII.get(Opc);
1362 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1363 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1364 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1365 .addReg(LHSReg, getKillRegState(LHSIsKill))
1366 .addReg(RHSReg, getKillRegState(RHSIsKill))
1367 .addImm(getArithExtendImm(ExtType, ShiftImm));
1371 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1372 Type *Ty = LHS->getType();
1373 EVT EVT = TLI.getValueType(Ty, true);
1374 if (!EVT.isSimple())
1376 MVT VT = EVT.getSimpleVT();
1378 switch (VT.SimpleTy) {
1386 return emitICmp(VT, LHS, RHS, IsZExt);
1389 return emitFCmp(VT, LHS, RHS);
1393 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1395 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1399 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1401 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1402 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1405 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1406 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1409 // Check to see if the 2nd operand is a constant that we can encode directly
1411 bool UseImm = false;
1412 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1413 if (CFP->isZero() && !CFP->isNegative())
1416 unsigned LHSReg = getRegForValue(LHS);
1419 bool LHSIsKill = hasTrivialKill(LHS);
1422 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1424 .addReg(LHSReg, getKillRegState(LHSIsKill));
1428 unsigned RHSReg = getRegForValue(RHS);
1431 bool RHSIsKill = hasTrivialKill(RHS);
1433 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1434 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1435 .addReg(LHSReg, getKillRegState(LHSIsKill))
1436 .addReg(RHSReg, getKillRegState(RHSIsKill));
1440 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1441 bool SetFlags, bool WantResult, bool IsZExt) {
1442 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1446 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1447 bool SetFlags, bool WantResult, bool IsZExt) {
1448 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1452 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1453 bool LHSIsKill, unsigned RHSReg,
1454 bool RHSIsKill, bool WantResult) {
1455 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1456 RHSIsKill, /*SetFlags=*/true, WantResult);
1459 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1460 bool LHSIsKill, unsigned RHSReg,
1462 AArch64_AM::ShiftExtendType ShiftType,
1463 uint64_t ShiftImm, bool WantResult) {
1464 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1465 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1469 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1470 const Value *LHS, const Value *RHS) {
1471 // Canonicalize immediates to the RHS first.
1472 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1473 std::swap(LHS, RHS);
1475 // Canonicalize mul by power-of-2 to the RHS.
1476 if (LHS->hasOneUse() && isValueAvailable(LHS))
1477 if (isMulPowOf2(LHS))
1478 std::swap(LHS, RHS);
1480 // Canonicalize shift immediate to the RHS.
1481 if (LHS->hasOneUse() && isValueAvailable(LHS))
1482 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1483 if (isa<ConstantInt>(SI->getOperand(1)))
1484 std::swap(LHS, RHS);
1486 unsigned LHSReg = getRegForValue(LHS);
1489 bool LHSIsKill = hasTrivialKill(LHS);
1491 unsigned ResultReg = 0;
1492 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1493 uint64_t Imm = C->getZExtValue();
1494 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1499 // Check if the mul can be folded into the instruction.
1500 if (RHS->hasOneUse() && isValueAvailable(RHS))
1501 if (isMulPowOf2(RHS)) {
1502 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1503 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1505 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1506 if (C->getValue().isPowerOf2())
1507 std::swap(MulLHS, MulRHS);
1509 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1510 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1512 unsigned RHSReg = getRegForValue(MulLHS);
1515 bool RHSIsKill = hasTrivialKill(MulLHS);
1516 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1517 RHSIsKill, ShiftVal);
1520 // Check if the shift can be folded into the instruction.
1521 if (RHS->hasOneUse() && isValueAvailable(RHS))
1522 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1523 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1524 uint64_t ShiftVal = C->getZExtValue();
1525 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1528 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1529 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1530 RHSIsKill, ShiftVal);
1533 unsigned RHSReg = getRegForValue(RHS);
1536 bool RHSIsKill = hasTrivialKill(RHS);
1538 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1539 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1540 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1541 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1542 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1547 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1548 unsigned LHSReg, bool LHSIsKill,
1550 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1551 "ISD nodes are not consecutive!");
1552 static const unsigned OpcTable[3][2] = {
1553 { AArch64::ANDWri, AArch64::ANDXri },
1554 { AArch64::ORRWri, AArch64::ORRXri },
1555 { AArch64::EORWri, AArch64::EORXri }
1557 const TargetRegisterClass *RC;
1560 switch (RetVT.SimpleTy) {
1567 unsigned Idx = ISDOpc - ISD::AND;
1568 Opc = OpcTable[Idx][0];
1569 RC = &AArch64::GPR32spRegClass;
1574 Opc = OpcTable[ISDOpc - ISD::AND][1];
1575 RC = &AArch64::GPR64spRegClass;
1580 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1583 unsigned ResultReg =
1584 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1585 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1586 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1587 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1588 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1593 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1594 unsigned LHSReg, bool LHSIsKill,
1595 unsigned RHSReg, bool RHSIsKill,
1596 uint64_t ShiftImm) {
1597 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1598 "ISD nodes are not consecutive!");
1599 static const unsigned OpcTable[3][2] = {
1600 { AArch64::ANDWrs, AArch64::ANDXrs },
1601 { AArch64::ORRWrs, AArch64::ORRXrs },
1602 { AArch64::EORWrs, AArch64::EORXrs }
1604 const TargetRegisterClass *RC;
1606 switch (RetVT.SimpleTy) {
1613 Opc = OpcTable[ISDOpc - ISD::AND][0];
1614 RC = &AArch64::GPR32RegClass;
1617 Opc = OpcTable[ISDOpc - ISD::AND][1];
1618 RC = &AArch64::GPR64RegClass;
1621 unsigned ResultReg =
1622 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1623 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1624 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1625 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1626 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1631 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1633 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1636 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1637 bool WantZExt, MachineMemOperand *MMO) {
1638 // Simplify this down to something we can handle.
1639 if (!simplifyAddress(Addr, VT))
1642 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1644 llvm_unreachable("Unexpected value type.");
1646 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1647 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1648 bool UseScaled = true;
1649 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1654 static const unsigned GPOpcTable[2][8][4] = {
1656 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1658 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1660 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1662 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1664 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1666 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1668 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1670 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1674 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1676 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1678 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1680 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1682 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1684 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1686 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1688 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1693 static const unsigned FPOpcTable[4][2] = {
1694 { AArch64::LDURSi, AArch64::LDURDi },
1695 { AArch64::LDRSui, AArch64::LDRDui },
1696 { AArch64::LDRSroX, AArch64::LDRDroX },
1697 { AArch64::LDRSroW, AArch64::LDRDroW }
1701 const TargetRegisterClass *RC;
1702 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1703 Addr.getOffsetReg();
1704 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1705 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1706 Addr.getExtendType() == AArch64_AM::SXTW)
1709 bool IsRet64Bit = RetVT == MVT::i64;
1710 switch (VT.SimpleTy) {
1712 llvm_unreachable("Unexpected value type.");
1713 case MVT::i1: // Intentional fall-through.
1715 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1716 RC = (IsRet64Bit && !WantZExt) ?
1717 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1720 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1721 RC = (IsRet64Bit && !WantZExt) ?
1722 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1725 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1726 RC = (IsRet64Bit && !WantZExt) ?
1727 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1730 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1731 RC = &AArch64::GPR64RegClass;
1734 Opc = FPOpcTable[Idx][0];
1735 RC = &AArch64::FPR32RegClass;
1738 Opc = FPOpcTable[Idx][1];
1739 RC = &AArch64::FPR64RegClass;
1743 // Create the base instruction, then add the operands.
1744 unsigned ResultReg = createResultReg(RC);
1745 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1746 TII.get(Opc), ResultReg);
1747 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1749 // Loading an i1 requires special handling.
1750 if (VT == MVT::i1) {
1751 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1752 assert(ANDReg && "Unexpected AND instruction emission failure.");
1756 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1757 // the 32bit reg to a 64bit reg.
1758 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1759 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1760 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1761 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1763 .addReg(ResultReg, getKillRegState(true))
1764 .addImm(AArch64::sub_32);
1770 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1772 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1776 return selectOperator(I, I->getOpcode());
1779 switch (I->getOpcode()) {
1781 llvm_unreachable("Unexpected instruction.");
1782 case Instruction::Add:
1783 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1785 case Instruction::Sub:
1786 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1792 updateValueMap(I, ResultReg);
1796 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1798 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1802 return selectOperator(I, I->getOpcode());
1805 switch (I->getOpcode()) {
1807 llvm_unreachable("Unexpected instruction.");
1808 case Instruction::And:
1809 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1811 case Instruction::Or:
1812 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1814 case Instruction::Xor:
1815 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1821 updateValueMap(I, ResultReg);
1825 bool AArch64FastISel::selectLoad(const Instruction *I) {
1827 // Verify we have a legal type before going any further. Currently, we handle
1828 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1829 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1830 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1831 cast<LoadInst>(I)->isAtomic())
1834 // See if we can handle this address.
1836 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1839 // Fold the following sign-/zero-extend into the load instruction.
1840 bool WantZExt = true;
1842 const Value *IntExtVal = nullptr;
1843 if (I->hasOneUse()) {
1844 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1845 if (isTypeSupported(ZE->getType(), RetVT))
1849 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1850 if (isTypeSupported(SE->getType(), RetVT))
1858 unsigned ResultReg =
1859 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1863 // There are a few different cases we have to handle, because the load or the
1864 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1865 // SelectionDAG. There is also an ordering issue when both instructions are in
1866 // different basic blocks.
1867 // 1.) The load instruction is selected by FastISel, but the integer extend
1868 // not. This usually happens when the integer extend is in a different
1869 // basic block and SelectionDAG took over for that basic block.
1870 // 2.) The load instruction is selected before the integer extend. This only
1871 // happens when the integer extend is in a different basic block.
1872 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1873 // by FastISel. This happens if there are instructions between the load
1874 // and the integer extend that couldn't be selected by FastISel.
1876 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1877 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1878 // it when it selects the integer extend.
1879 unsigned Reg = lookUpRegForValue(IntExtVal);
1881 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1883 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1884 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1885 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1887 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1891 updateValueMap(I, ResultReg);
1895 // The integer extend has already been emitted - delete all the instructions
1896 // that have been emitted by the integer extend lowering code and use the
1897 // result from the load instruction directly.
1899 auto *MI = MRI.getUniqueVRegDef(Reg);
1903 for (auto &Opnd : MI->uses()) {
1905 Reg = Opnd.getReg();
1909 MI->eraseFromParent();
1911 updateValueMap(IntExtVal, ResultReg);
1915 updateValueMap(I, ResultReg);
1919 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1920 MachineMemOperand *MMO) {
1921 // Simplify this down to something we can handle.
1922 if (!simplifyAddress(Addr, VT))
1925 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1927 llvm_unreachable("Unexpected value type.");
1929 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1930 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1931 bool UseScaled = true;
1932 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1937 static const unsigned OpcTable[4][6] = {
1938 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1939 AArch64::STURSi, AArch64::STURDi },
1940 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1941 AArch64::STRSui, AArch64::STRDui },
1942 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1943 AArch64::STRSroX, AArch64::STRDroX },
1944 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1945 AArch64::STRSroW, AArch64::STRDroW }
1949 bool VTIsi1 = false;
1950 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1951 Addr.getOffsetReg();
1952 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1953 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1954 Addr.getExtendType() == AArch64_AM::SXTW)
1957 switch (VT.SimpleTy) {
1958 default: llvm_unreachable("Unexpected value type.");
1959 case MVT::i1: VTIsi1 = true;
1960 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1961 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1962 case MVT::i32: Opc = OpcTable[Idx][2]; break;
1963 case MVT::i64: Opc = OpcTable[Idx][3]; break;
1964 case MVT::f32: Opc = OpcTable[Idx][4]; break;
1965 case MVT::f64: Opc = OpcTable[Idx][5]; break;
1968 // Storing an i1 requires special handling.
1969 if (VTIsi1 && SrcReg != AArch64::WZR) {
1970 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1971 assert(ANDReg && "Unexpected AND instruction emission failure.");
1974 // Create the base instruction, then add the operands.
1975 const MCInstrDesc &II = TII.get(Opc);
1976 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
1977 MachineInstrBuilder MIB =
1978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
1979 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
1984 bool AArch64FastISel::selectStore(const Instruction *I) {
1986 const Value *Op0 = I->getOperand(0);
1987 // Verify we have a legal type before going any further. Currently, we handle
1988 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1989 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1990 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
1991 cast<StoreInst>(I)->isAtomic())
1994 // Get the value to be stored into a register. Use the zero register directly
1995 // when possible to avoid an unnecessary copy and a wasted register.
1996 unsigned SrcReg = 0;
1997 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
1999 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2000 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2001 if (CF->isZero() && !CF->isNegative()) {
2002 VT = MVT::getIntegerVT(VT.getSizeInBits());
2003 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2008 SrcReg = getRegForValue(Op0);
2013 // See if we can handle this address.
2015 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2018 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2023 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2025 case CmpInst::FCMP_ONE:
2026 case CmpInst::FCMP_UEQ:
2028 // AL is our "false" for now. The other two need more compares.
2029 return AArch64CC::AL;
2030 case CmpInst::ICMP_EQ:
2031 case CmpInst::FCMP_OEQ:
2032 return AArch64CC::EQ;
2033 case CmpInst::ICMP_SGT:
2034 case CmpInst::FCMP_OGT:
2035 return AArch64CC::GT;
2036 case CmpInst::ICMP_SGE:
2037 case CmpInst::FCMP_OGE:
2038 return AArch64CC::GE;
2039 case CmpInst::ICMP_UGT:
2040 case CmpInst::FCMP_UGT:
2041 return AArch64CC::HI;
2042 case CmpInst::FCMP_OLT:
2043 return AArch64CC::MI;
2044 case CmpInst::ICMP_ULE:
2045 case CmpInst::FCMP_OLE:
2046 return AArch64CC::LS;
2047 case CmpInst::FCMP_ORD:
2048 return AArch64CC::VC;
2049 case CmpInst::FCMP_UNO:
2050 return AArch64CC::VS;
2051 case CmpInst::FCMP_UGE:
2052 return AArch64CC::PL;
2053 case CmpInst::ICMP_SLT:
2054 case CmpInst::FCMP_ULT:
2055 return AArch64CC::LT;
2056 case CmpInst::ICMP_SLE:
2057 case CmpInst::FCMP_ULE:
2058 return AArch64CC::LE;
2059 case CmpInst::FCMP_UNE:
2060 case CmpInst::ICMP_NE:
2061 return AArch64CC::NE;
2062 case CmpInst::ICMP_UGE:
2063 return AArch64CC::HS;
2064 case CmpInst::ICMP_ULT:
2065 return AArch64CC::LO;
2069 /// \brief Try to emit a combined compare-and-branch instruction.
2070 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2071 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2072 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2073 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2075 const Value *LHS = CI->getOperand(0);
2076 const Value *RHS = CI->getOperand(1);
2078 Type *Ty = LHS->getType();
2079 if (!Ty->isIntegerTy())
2082 unsigned BW = cast<IntegerType>(Ty)->getBitWidth();
2083 if (BW != 1 && BW != 8 && BW != 16 && BW != 32 && BW != 64)
2086 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2087 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2089 // Try to take advantage of fallthrough opportunities.
2090 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2091 std::swap(TBB, FBB);
2092 Predicate = CmpInst::getInversePredicate(Predicate);
2097 if ((Predicate == CmpInst::ICMP_EQ) || (Predicate == CmpInst::ICMP_NE)) {
2098 if (const auto *C = dyn_cast<ConstantInt>(LHS))
2099 if (C->isNullValue())
2100 std::swap(LHS, RHS);
2102 if (!isa<ConstantInt>(RHS))
2105 if (!cast<ConstantInt>(RHS)->isNullValue())
2108 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2109 if (AI->getOpcode() == Instruction::And) {
2110 const Value *AndLHS = AI->getOperand(0);
2111 const Value *AndRHS = AI->getOperand(1);
2113 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2114 if (C->getValue().isPowerOf2())
2115 std::swap(AndLHS, AndRHS);
2117 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2118 if (C->getValue().isPowerOf2()) {
2119 TestBit = C->getValue().logBase2();
2123 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2124 } else if (Predicate == CmpInst::ICMP_SLT) {
2125 if (!isa<ConstantInt>(RHS))
2128 if (!cast<ConstantInt>(RHS)->isNullValue())
2133 } else if (Predicate == CmpInst::ICMP_SGT) {
2134 if (!isa<ConstantInt>(RHS))
2137 if (cast<ConstantInt>(RHS)->getValue() != -1)
2145 static const unsigned OpcTable[2][2][2] = {
2146 { {AArch64::CBZW, AArch64::CBZX },
2147 {AArch64::CBNZW, AArch64::CBNZX} },
2148 { {AArch64::TBZW, AArch64::TBZX },
2149 {AArch64::TBNZW, AArch64::TBNZX} }
2152 bool IsBitTest = TestBit != -1;
2153 bool Is64Bit = BW == 64;
2154 if (TestBit < 32 && TestBit >= 0)
2157 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2158 const MCInstrDesc &II = TII.get(Opc);
2160 unsigned SrcReg = getRegForValue(LHS);
2163 bool SrcIsKill = hasTrivialKill(LHS);
2165 if (BW == 64 && !Is64Bit)
2166 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2169 // Emit the combined compare and branch instruction.
2170 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2171 MachineInstrBuilder MIB =
2172 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2173 .addReg(SrcReg, getKillRegState(SrcIsKill));
2175 MIB.addImm(TestBit);
2178 // Obtain the branch weight and add the TrueBB to the successor list.
2179 uint32_t BranchWeight = 0;
2181 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2182 TBB->getBasicBlock());
2183 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2184 fastEmitBranch(FBB, DbgLoc);
2189 bool AArch64FastISel::selectBranch(const Instruction *I) {
2190 const BranchInst *BI = cast<BranchInst>(I);
2191 if (BI->isUnconditional()) {
2192 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2193 fastEmitBranch(MSucc, BI->getDebugLoc());
2197 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2198 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2200 AArch64CC::CondCode CC = AArch64CC::NE;
2201 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2202 if (CI->hasOneUse() && isValueAvailable(CI)) {
2203 // Try to optimize or fold the cmp.
2204 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2205 switch (Predicate) {
2208 case CmpInst::FCMP_FALSE:
2209 fastEmitBranch(FBB, DbgLoc);
2211 case CmpInst::FCMP_TRUE:
2212 fastEmitBranch(TBB, DbgLoc);
2216 // Try to emit a combined compare-and-branch first.
2217 if (emitCompareAndBranch(BI))
2220 // Try to take advantage of fallthrough opportunities.
2221 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2222 std::swap(TBB, FBB);
2223 Predicate = CmpInst::getInversePredicate(Predicate);
2227 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2230 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2232 CC = getCompareCC(Predicate);
2233 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2234 switch (Predicate) {
2237 case CmpInst::FCMP_UEQ:
2238 ExtraCC = AArch64CC::EQ;
2241 case CmpInst::FCMP_ONE:
2242 ExtraCC = AArch64CC::MI;
2246 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2248 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2249 if (ExtraCC != AArch64CC::AL) {
2250 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2256 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2260 // Obtain the branch weight and add the TrueBB to the successor list.
2261 uint32_t BranchWeight = 0;
2263 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2264 TBB->getBasicBlock());
2265 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2267 fastEmitBranch(FBB, DbgLoc);
2270 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2272 if (TI->hasOneUse() && isValueAvailable(TI) &&
2273 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2274 unsigned CondReg = getRegForValue(TI->getOperand(0));
2277 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2279 // Issue an extract_subreg to get the lower 32-bits.
2280 if (SrcVT == MVT::i64) {
2281 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2286 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2287 assert(ANDReg && "Unexpected AND instruction emission failure.");
2288 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2290 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2291 std::swap(TBB, FBB);
2294 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2298 // Obtain the branch weight and add the TrueBB to the successor list.
2299 uint32_t BranchWeight = 0;
2301 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2302 TBB->getBasicBlock());
2303 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2305 fastEmitBranch(FBB, DbgLoc);
2308 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2309 uint64_t Imm = CI->getZExtValue();
2310 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2314 // Obtain the branch weight and add the target to the successor list.
2315 uint32_t BranchWeight = 0;
2317 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2318 Target->getBasicBlock());
2319 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2321 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2322 // Fake request the condition, otherwise the intrinsic might be completely
2324 unsigned CondReg = getRegForValue(BI->getCondition());
2329 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2333 // Obtain the branch weight and add the TrueBB to the successor list.
2334 uint32_t BranchWeight = 0;
2336 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2337 TBB->getBasicBlock());
2338 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2340 fastEmitBranch(FBB, DbgLoc);
2344 unsigned CondReg = getRegForValue(BI->getCondition());
2347 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2349 // We've been divorced from our compare! Our block was split, and
2350 // now our compare lives in a predecessor block. We musn't
2351 // re-compare here, as the children of the compare aren't guaranteed
2352 // live across the block boundary (we *could* check for this).
2353 // Regardless, the compare has been done in the predecessor block,
2354 // and it left a value for us in a virtual register. Ergo, we test
2355 // the one-bit value left in the virtual register.
2356 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2358 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2359 std::swap(TBB, FBB);
2363 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2367 // Obtain the branch weight and add the TrueBB to the successor list.
2368 uint32_t BranchWeight = 0;
2370 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2371 TBB->getBasicBlock());
2372 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2374 fastEmitBranch(FBB, DbgLoc);
2378 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2379 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2380 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2384 // Emit the indirect branch.
2385 const MCInstrDesc &II = TII.get(AArch64::BR);
2386 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2387 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2389 // Make sure the CFG is up-to-date.
2390 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2391 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2396 bool AArch64FastISel::selectCmp(const Instruction *I) {
2397 const CmpInst *CI = cast<CmpInst>(I);
2399 // Try to optimize or fold the cmp.
2400 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2401 unsigned ResultReg = 0;
2402 switch (Predicate) {
2405 case CmpInst::FCMP_FALSE:
2406 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2408 TII.get(TargetOpcode::COPY), ResultReg)
2409 .addReg(AArch64::WZR, getKillRegState(true));
2411 case CmpInst::FCMP_TRUE:
2412 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2417 updateValueMap(I, ResultReg);
2422 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2425 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2427 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2428 // condition codes are inverted, because they are used by CSINC.
2429 static unsigned CondCodeTable[2][2] = {
2430 { AArch64CC::NE, AArch64CC::VC },
2431 { AArch64CC::PL, AArch64CC::LE }
2433 unsigned *CondCodes = nullptr;
2434 switch (Predicate) {
2437 case CmpInst::FCMP_UEQ:
2438 CondCodes = &CondCodeTable[0][0];
2440 case CmpInst::FCMP_ONE:
2441 CondCodes = &CondCodeTable[1][0];
2446 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2449 .addReg(AArch64::WZR, getKillRegState(true))
2450 .addReg(AArch64::WZR, getKillRegState(true))
2451 .addImm(CondCodes[0]);
2452 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2454 .addReg(TmpReg1, getKillRegState(true))
2455 .addReg(AArch64::WZR, getKillRegState(true))
2456 .addImm(CondCodes[1]);
2458 updateValueMap(I, ResultReg);
2462 // Now set a register based on the comparison.
2463 AArch64CC::CondCode CC = getCompareCC(Predicate);
2464 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2465 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2466 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2468 .addReg(AArch64::WZR, getKillRegState(true))
2469 .addReg(AArch64::WZR, getKillRegState(true))
2470 .addImm(invertedCC);
2472 updateValueMap(I, ResultReg);
2476 bool AArch64FastISel::selectSelect(const Instruction *I) {
2477 const SelectInst *SI = cast<SelectInst>(I);
2479 EVT DestEVT = TLI.getValueType(SI->getType(), true);
2480 if (!DestEVT.isSimple())
2483 MVT DestVT = DestEVT.getSimpleVT();
2484 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
2489 const TargetRegisterClass *RC = nullptr;
2490 switch (DestVT.SimpleTy) {
2491 default: return false;
2493 SelectOpc = AArch64::CSELWr; RC = &AArch64::GPR32RegClass; break;
2495 SelectOpc = AArch64::CSELXr; RC = &AArch64::GPR64RegClass; break;
2497 SelectOpc = AArch64::FCSELSrrr; RC = &AArch64::FPR32RegClass; break;
2499 SelectOpc = AArch64::FCSELDrrr; RC = &AArch64::FPR64RegClass; break;
2502 const Value *Cond = SI->getCondition();
2503 bool NeedTest = true;
2504 AArch64CC::CondCode CC = AArch64CC::NE;
2505 if (foldXALUIntrinsic(CC, I, Cond))
2508 unsigned CondReg = getRegForValue(Cond);
2511 bool CondIsKill = hasTrivialKill(Cond);
2514 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2515 assert(ANDReg && "Unexpected AND instruction emission failure.");
2516 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2519 unsigned TrueReg = getRegForValue(SI->getTrueValue());
2520 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
2522 unsigned FalseReg = getRegForValue(SI->getFalseValue());
2523 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
2525 if (!TrueReg || !FalseReg)
2528 unsigned ResultReg = fastEmitInst_rri(SelectOpc, RC, TrueReg, TrueIsKill,
2529 FalseReg, FalseIsKill, CC);
2530 updateValueMap(I, ResultReg);
2534 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2535 Value *V = I->getOperand(0);
2536 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2539 unsigned Op = getRegForValue(V);
2543 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2544 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2545 ResultReg).addReg(Op);
2546 updateValueMap(I, ResultReg);
2550 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2551 Value *V = I->getOperand(0);
2552 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2555 unsigned Op = getRegForValue(V);
2559 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2560 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2561 ResultReg).addReg(Op);
2562 updateValueMap(I, ResultReg);
2566 // FPToUI and FPToSI
2567 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2569 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2572 unsigned SrcReg = getRegForValue(I->getOperand(0));
2576 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2577 if (SrcVT == MVT::f128)
2581 if (SrcVT == MVT::f64) {
2583 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2585 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2588 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2590 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2592 unsigned ResultReg = createResultReg(
2593 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2594 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2596 updateValueMap(I, ResultReg);
2600 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2602 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2604 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2605 "Unexpected value type.");
2607 unsigned SrcReg = getRegForValue(I->getOperand(0));
2610 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2612 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2614 // Handle sign-extension.
2615 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2617 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2624 if (SrcVT == MVT::i64) {
2626 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2628 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2631 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2633 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2636 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2638 updateValueMap(I, ResultReg);
2642 bool AArch64FastISel::fastLowerArguments() {
2643 if (!FuncInfo.CanLowerReturn)
2646 const Function *F = FuncInfo.Fn;
2650 CallingConv::ID CC = F->getCallingConv();
2651 if (CC != CallingConv::C)
2654 // Only handle simple cases of up to 8 GPR and FPR each.
2655 unsigned GPRCnt = 0;
2656 unsigned FPRCnt = 0;
2658 for (auto const &Arg : F->args()) {
2659 // The first argument is at index 1.
2661 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2662 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2663 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2664 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2667 Type *ArgTy = Arg.getType();
2668 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2671 EVT ArgVT = TLI.getValueType(ArgTy);
2672 if (!ArgVT.isSimple())
2675 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2676 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2679 if (VT.isVector() &&
2680 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2683 if (VT >= MVT::i1 && VT <= MVT::i64)
2685 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2686 VT.is128BitVector())
2691 if (GPRCnt > 8 || FPRCnt > 8)
2695 static const MCPhysReg Registers[6][8] = {
2696 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2697 AArch64::W5, AArch64::W6, AArch64::W7 },
2698 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2699 AArch64::X5, AArch64::X6, AArch64::X7 },
2700 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2701 AArch64::H5, AArch64::H6, AArch64::H7 },
2702 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2703 AArch64::S5, AArch64::S6, AArch64::S7 },
2704 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2705 AArch64::D5, AArch64::D6, AArch64::D7 },
2706 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2707 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2710 unsigned GPRIdx = 0;
2711 unsigned FPRIdx = 0;
2712 for (auto const &Arg : F->args()) {
2713 MVT VT = TLI.getSimpleValueType(Arg.getType());
2715 const TargetRegisterClass *RC;
2716 if (VT >= MVT::i1 && VT <= MVT::i32) {
2717 SrcReg = Registers[0][GPRIdx++];
2718 RC = &AArch64::GPR32RegClass;
2720 } else if (VT == MVT::i64) {
2721 SrcReg = Registers[1][GPRIdx++];
2722 RC = &AArch64::GPR64RegClass;
2723 } else if (VT == MVT::f16) {
2724 SrcReg = Registers[2][FPRIdx++];
2725 RC = &AArch64::FPR16RegClass;
2726 } else if (VT == MVT::f32) {
2727 SrcReg = Registers[3][FPRIdx++];
2728 RC = &AArch64::FPR32RegClass;
2729 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2730 SrcReg = Registers[4][FPRIdx++];
2731 RC = &AArch64::FPR64RegClass;
2732 } else if (VT.is128BitVector()) {
2733 SrcReg = Registers[5][FPRIdx++];
2734 RC = &AArch64::FPR128RegClass;
2736 llvm_unreachable("Unexpected value type.");
2738 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2739 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2740 // Without this, EmitLiveInCopies may eliminate the livein if its only
2741 // use is a bitcast (which isn't turned into an instruction).
2742 unsigned ResultReg = createResultReg(RC);
2743 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2744 TII.get(TargetOpcode::COPY), ResultReg)
2745 .addReg(DstReg, getKillRegState(true));
2746 updateValueMap(&Arg, ResultReg);
2751 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2752 SmallVectorImpl<MVT> &OutVTs,
2753 unsigned &NumBytes) {
2754 CallingConv::ID CC = CLI.CallConv;
2755 SmallVector<CCValAssign, 16> ArgLocs;
2756 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2757 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2759 // Get a count of how many bytes are to be pushed on the stack.
2760 NumBytes = CCInfo.getNextStackOffset();
2762 // Issue CALLSEQ_START
2763 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2764 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2767 // Process the args.
2768 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2769 CCValAssign &VA = ArgLocs[i];
2770 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2771 MVT ArgVT = OutVTs[VA.getValNo()];
2773 unsigned ArgReg = getRegForValue(ArgVal);
2777 // Handle arg promotion: SExt, ZExt, AExt.
2778 switch (VA.getLocInfo()) {
2779 case CCValAssign::Full:
2781 case CCValAssign::SExt: {
2782 MVT DestVT = VA.getLocVT();
2784 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2789 case CCValAssign::AExt:
2790 // Intentional fall-through.
2791 case CCValAssign::ZExt: {
2792 MVT DestVT = VA.getLocVT();
2794 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2800 llvm_unreachable("Unknown arg promotion!");
2803 // Now copy/store arg to correct locations.
2804 if (VA.isRegLoc() && !VA.needsCustom()) {
2805 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2806 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2807 CLI.OutRegs.push_back(VA.getLocReg());
2808 } else if (VA.needsCustom()) {
2809 // FIXME: Handle custom args.
2812 assert(VA.isMemLoc() && "Assuming store on stack.");
2814 // Don't emit stores for undef values.
2815 if (isa<UndefValue>(ArgVal))
2818 // Need to store on the stack.
2819 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2821 unsigned BEAlign = 0;
2822 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2823 BEAlign = 8 - ArgSize;
2826 Addr.setKind(Address::RegBase);
2827 Addr.setReg(AArch64::SP);
2828 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2830 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2831 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2832 MachinePointerInfo::getStack(Addr.getOffset()),
2833 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2835 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2842 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2843 unsigned NumBytes) {
2844 CallingConv::ID CC = CLI.CallConv;
2846 // Issue CALLSEQ_END
2847 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2848 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2849 .addImm(NumBytes).addImm(0);
2851 // Now the return value.
2852 if (RetVT != MVT::isVoid) {
2853 SmallVector<CCValAssign, 16> RVLocs;
2854 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2855 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
2857 // Only handle a single return value.
2858 if (RVLocs.size() != 1)
2861 // Copy all of the result registers out of their specified physreg.
2862 MVT CopyVT = RVLocs[0].getValVT();
2863 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
2864 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2865 TII.get(TargetOpcode::COPY), ResultReg)
2866 .addReg(RVLocs[0].getLocReg());
2867 CLI.InRegs.push_back(RVLocs[0].getLocReg());
2869 CLI.ResultReg = ResultReg;
2870 CLI.NumResultRegs = 1;
2876 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2877 CallingConv::ID CC = CLI.CallConv;
2878 bool IsTailCall = CLI.IsTailCall;
2879 bool IsVarArg = CLI.IsVarArg;
2880 const Value *Callee = CLI.Callee;
2881 const char *SymName = CLI.SymName;
2883 if (!Callee && !SymName)
2886 // Allow SelectionDAG isel to handle tail calls.
2890 CodeModel::Model CM = TM.getCodeModel();
2891 // Only support the small and large code model.
2892 if (CM != CodeModel::Small && CM != CodeModel::Large)
2895 // FIXME: Add large code model support for ELF.
2896 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
2899 // Let SDISel handle vararg functions.
2903 // FIXME: Only handle *simple* calls for now.
2905 if (CLI.RetTy->isVoidTy())
2906 RetVT = MVT::isVoid;
2907 else if (!isTypeLegal(CLI.RetTy, RetVT))
2910 for (auto Flag : CLI.OutFlags)
2911 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
2914 // Set up the argument vectors.
2915 SmallVector<MVT, 16> OutVTs;
2916 OutVTs.reserve(CLI.OutVals.size());
2918 for (auto *Val : CLI.OutVals) {
2920 if (!isTypeLegal(Val->getType(), VT) &&
2921 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
2924 // We don't handle vector parameters yet.
2925 if (VT.isVector() || VT.getSizeInBits() > 64)
2928 OutVTs.push_back(VT);
2932 if (Callee && !computeCallAddress(Callee, Addr))
2935 // Handle the arguments now that we've gotten them.
2937 if (!processCallArgs(CLI, OutVTs, NumBytes))
2941 MachineInstrBuilder MIB;
2942 if (CM == CodeModel::Small) {
2943 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
2944 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
2946 MIB.addExternalSymbol(SymName, 0);
2947 else if (Addr.getGlobalValue())
2948 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2949 else if (Addr.getReg()) {
2950 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
2955 unsigned CallReg = 0;
2957 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2958 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2960 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2962 CallReg = createResultReg(&AArch64::GPR64RegClass);
2963 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
2966 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
2968 } else if (Addr.getGlobalValue())
2969 CallReg = materializeGV(Addr.getGlobalValue());
2970 else if (Addr.getReg())
2971 CallReg = Addr.getReg();
2976 const MCInstrDesc &II = TII.get(AArch64::BLR);
2977 CallReg = constrainOperandRegClass(II, CallReg, 0);
2978 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
2981 // Add implicit physical register uses to the call.
2982 for (auto Reg : CLI.OutRegs)
2983 MIB.addReg(Reg, RegState::Implicit);
2985 // Add a register mask with the call-preserved registers.
2986 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2987 MIB.addRegMask(TRI.getCallPreservedMask(CC));
2991 // Finish off the call including any return values.
2992 return finishCall(CLI, RetVT, NumBytes);
2995 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
2997 return Len / Alignment <= 4;
3002 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3003 uint64_t Len, unsigned Alignment) {
3004 // Make sure we don't bloat code by inlining very large memcpy's.
3005 if (!isMemCpySmall(Len, Alignment))
3008 int64_t UnscaledOffset = 0;
3009 Address OrigDest = Dest;
3010 Address OrigSrc = Src;
3014 if (!Alignment || Alignment >= 8) {
3025 // Bound based on alignment.
3026 if (Len >= 4 && Alignment == 4)
3028 else if (Len >= 2 && Alignment == 2)
3035 unsigned ResultReg = emitLoad(VT, VT, Src);
3039 if (!emitStore(VT, ResultReg, Dest))
3042 int64_t Size = VT.getSizeInBits() / 8;
3044 UnscaledOffset += Size;
3046 // We need to recompute the unscaled offset for each iteration.
3047 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3048 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3054 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3055 /// into the user. The condition code will only be updated on success.
3056 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3057 const Instruction *I,
3058 const Value *Cond) {
3059 if (!isa<ExtractValueInst>(Cond))
3062 const auto *EV = cast<ExtractValueInst>(Cond);
3063 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3066 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3068 const Function *Callee = II->getCalledFunction();
3070 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3071 if (!isTypeLegal(RetTy, RetVT))
3074 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3077 const Value *LHS = II->getArgOperand(0);
3078 const Value *RHS = II->getArgOperand(1);
3080 // Canonicalize immediate to the RHS.
3081 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3082 isCommutativeIntrinsic(II))
3083 std::swap(LHS, RHS);
3085 // Simplify multiplies.
3086 unsigned IID = II->getIntrinsicID();
3090 case Intrinsic::smul_with_overflow:
3091 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3092 if (C->getValue() == 2)
3093 IID = Intrinsic::sadd_with_overflow;
3095 case Intrinsic::umul_with_overflow:
3096 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3097 if (C->getValue() == 2)
3098 IID = Intrinsic::uadd_with_overflow;
3102 AArch64CC::CondCode TmpCC;
3106 case Intrinsic::sadd_with_overflow:
3107 case Intrinsic::ssub_with_overflow:
3108 TmpCC = AArch64CC::VS;
3110 case Intrinsic::uadd_with_overflow:
3111 TmpCC = AArch64CC::HS;
3113 case Intrinsic::usub_with_overflow:
3114 TmpCC = AArch64CC::LO;
3116 case Intrinsic::smul_with_overflow:
3117 case Intrinsic::umul_with_overflow:
3118 TmpCC = AArch64CC::NE;
3122 // Check if both instructions are in the same basic block.
3123 if (!isValueAvailable(II))
3126 // Make sure nothing is in the way
3127 BasicBlock::const_iterator Start = I;
3128 BasicBlock::const_iterator End = II;
3129 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3130 // We only expect extractvalue instructions between the intrinsic and the
3131 // instruction to be selected.
3132 if (!isa<ExtractValueInst>(Itr))
3135 // Check that the extractvalue operand comes from the intrinsic.
3136 const auto *EVI = cast<ExtractValueInst>(Itr);
3137 if (EVI->getAggregateOperand() != II)
3145 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3146 // FIXME: Handle more intrinsics.
3147 switch (II->getIntrinsicID()) {
3148 default: return false;
3149 case Intrinsic::frameaddress: {
3150 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3151 MFI->setFrameAddressIsTaken(true);
3153 const AArch64RegisterInfo *RegInfo =
3154 static_cast<const AArch64RegisterInfo *>(
3155 TM.getSubtargetImpl()->getRegisterInfo());
3156 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3157 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3158 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3159 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3160 // Recursively load frame address
3166 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3168 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3169 SrcReg, /*IsKill=*/true, 0);
3170 assert(DestReg && "Unexpected LDR instruction emission failure.");
3174 updateValueMap(II, SrcReg);
3177 case Intrinsic::memcpy:
3178 case Intrinsic::memmove: {
3179 const auto *MTI = cast<MemTransferInst>(II);
3180 // Don't handle volatile.
3181 if (MTI->isVolatile())
3184 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3185 // we would emit dead code because we don't currently handle memmoves.
3186 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3187 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3188 // Small memcpy's are common enough that we want to do them without a call
3190 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3191 unsigned Alignment = MTI->getAlignment();
3192 if (isMemCpySmall(Len, Alignment)) {
3194 if (!computeAddress(MTI->getRawDest(), Dest) ||
3195 !computeAddress(MTI->getRawSource(), Src))
3197 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3202 if (!MTI->getLength()->getType()->isIntegerTy(64))
3205 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3206 // Fast instruction selection doesn't support the special
3210 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3211 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3213 case Intrinsic::memset: {
3214 const MemSetInst *MSI = cast<MemSetInst>(II);
3215 // Don't handle volatile.
3216 if (MSI->isVolatile())
3219 if (!MSI->getLength()->getType()->isIntegerTy(64))
3222 if (MSI->getDestAddressSpace() > 255)
3223 // Fast instruction selection doesn't support the special
3227 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3229 case Intrinsic::sin:
3230 case Intrinsic::cos:
3231 case Intrinsic::pow: {
3233 if (!isTypeLegal(II->getType(), RetVT))
3236 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3239 static const RTLIB::Libcall LibCallTable[3][2] = {
3240 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3241 { RTLIB::COS_F32, RTLIB::COS_F64 },
3242 { RTLIB::POW_F32, RTLIB::POW_F64 }
3245 bool Is64Bit = RetVT == MVT::f64;
3246 switch (II->getIntrinsicID()) {
3248 llvm_unreachable("Unexpected intrinsic.");
3249 case Intrinsic::sin:
3250 LC = LibCallTable[0][Is64Bit];
3252 case Intrinsic::cos:
3253 LC = LibCallTable[1][Is64Bit];
3255 case Intrinsic::pow:
3256 LC = LibCallTable[2][Is64Bit];
3261 Args.reserve(II->getNumArgOperands());
3263 // Populate the argument list.
3264 for (auto &Arg : II->arg_operands()) {
3267 Entry.Ty = Arg->getType();
3268 Args.push_back(Entry);
3271 CallLoweringInfo CLI;
3272 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3273 TLI.getLibcallName(LC), std::move(Args));
3274 if (!lowerCallTo(CLI))
3276 updateValueMap(II, CLI.ResultReg);
3279 case Intrinsic::trap: {
3280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3284 case Intrinsic::sqrt: {
3285 Type *RetTy = II->getCalledFunction()->getReturnType();
3288 if (!isTypeLegal(RetTy, VT))
3291 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3294 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3296 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3300 updateValueMap(II, ResultReg);
3303 case Intrinsic::sadd_with_overflow:
3304 case Intrinsic::uadd_with_overflow:
3305 case Intrinsic::ssub_with_overflow:
3306 case Intrinsic::usub_with_overflow:
3307 case Intrinsic::smul_with_overflow:
3308 case Intrinsic::umul_with_overflow: {
3309 // This implements the basic lowering of the xalu with overflow intrinsics.
3310 const Function *Callee = II->getCalledFunction();
3311 auto *Ty = cast<StructType>(Callee->getReturnType());
3312 Type *RetTy = Ty->getTypeAtIndex(0U);
3315 if (!isTypeLegal(RetTy, VT))
3318 if (VT != MVT::i32 && VT != MVT::i64)
3321 const Value *LHS = II->getArgOperand(0);
3322 const Value *RHS = II->getArgOperand(1);
3323 // Canonicalize immediate to the RHS.
3324 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3325 isCommutativeIntrinsic(II))
3326 std::swap(LHS, RHS);
3328 // Simplify multiplies.
3329 unsigned IID = II->getIntrinsicID();
3333 case Intrinsic::smul_with_overflow:
3334 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3335 if (C->getValue() == 2) {
3336 IID = Intrinsic::sadd_with_overflow;
3340 case Intrinsic::umul_with_overflow:
3341 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3342 if (C->getValue() == 2) {
3343 IID = Intrinsic::uadd_with_overflow;
3349 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3350 AArch64CC::CondCode CC = AArch64CC::Invalid;
3352 default: llvm_unreachable("Unexpected intrinsic!");
3353 case Intrinsic::sadd_with_overflow:
3354 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3357 case Intrinsic::uadd_with_overflow:
3358 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3361 case Intrinsic::ssub_with_overflow:
3362 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3365 case Intrinsic::usub_with_overflow:
3366 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3369 case Intrinsic::smul_with_overflow: {
3371 unsigned LHSReg = getRegForValue(LHS);
3374 bool LHSIsKill = hasTrivialKill(LHS);
3376 unsigned RHSReg = getRegForValue(RHS);
3379 bool RHSIsKill = hasTrivialKill(RHS);
3381 if (VT == MVT::i32) {
3382 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3383 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3384 /*IsKill=*/false, 32);
3385 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3387 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3389 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3390 AArch64_AM::ASR, 31, /*WantResult=*/false);
3392 assert(VT == MVT::i64 && "Unexpected value type.");
3393 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3394 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3396 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3397 AArch64_AM::ASR, 63, /*WantResult=*/false);
3401 case Intrinsic::umul_with_overflow: {
3403 unsigned LHSReg = getRegForValue(LHS);
3406 bool LHSIsKill = hasTrivialKill(LHS);
3408 unsigned RHSReg = getRegForValue(RHS);
3411 bool RHSIsKill = hasTrivialKill(RHS);
3413 if (VT == MVT::i32) {
3414 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3415 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3416 /*IsKill=*/false, AArch64_AM::LSR, 32,
3417 /*WantResult=*/false);
3418 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3421 assert(VT == MVT::i64 && "Unexpected value type.");
3422 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3423 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3425 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3426 /*IsKill=*/false, /*WantResult=*/false);
3433 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3434 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3435 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3438 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3439 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3440 /*IsKill=*/true, getInvertedCondCode(CC));
3442 assert((ResultReg1 + 1) == ResultReg2 &&
3443 "Nonconsecutive result registers.");
3444 updateValueMap(II, ResultReg1, 2);
3451 bool AArch64FastISel::selectRet(const Instruction *I) {
3452 const ReturnInst *Ret = cast<ReturnInst>(I);
3453 const Function &F = *I->getParent()->getParent();
3455 if (!FuncInfo.CanLowerReturn)
3461 // Build a list of return value registers.
3462 SmallVector<unsigned, 4> RetRegs;
3464 if (Ret->getNumOperands() > 0) {
3465 CallingConv::ID CC = F.getCallingConv();
3466 SmallVector<ISD::OutputArg, 4> Outs;
3467 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3469 // Analyze operands of the call, assigning locations to each operand.
3470 SmallVector<CCValAssign, 16> ValLocs;
3471 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3472 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3473 : RetCC_AArch64_AAPCS;
3474 CCInfo.AnalyzeReturn(Outs, RetCC);
3476 // Only handle a single return value for now.
3477 if (ValLocs.size() != 1)
3480 CCValAssign &VA = ValLocs[0];
3481 const Value *RV = Ret->getOperand(0);
3483 // Don't bother handling odd stuff for now.
3484 if ((VA.getLocInfo() != CCValAssign::Full) &&
3485 (VA.getLocInfo() != CCValAssign::BCvt))
3488 // Only handle register returns for now.
3492 unsigned Reg = getRegForValue(RV);
3496 unsigned SrcReg = Reg + VA.getValNo();
3497 unsigned DestReg = VA.getLocReg();
3498 // Avoid a cross-class copy. This is very unlikely.
3499 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3502 EVT RVEVT = TLI.getValueType(RV->getType());
3503 if (!RVEVT.isSimple())
3506 // Vectors (of > 1 lane) in big endian need tricky handling.
3507 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3508 !Subtarget->isLittleEndian())
3511 MVT RVVT = RVEVT.getSimpleVT();
3512 if (RVVT == MVT::f128)
3515 MVT DestVT = VA.getValVT();
3516 // Special handling for extended integers.
3517 if (RVVT != DestVT) {
3518 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3521 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3524 bool IsZExt = Outs[0].Flags.isZExt();
3525 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3531 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3532 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3534 // Add register to return instruction.
3535 RetRegs.push_back(VA.getLocReg());
3538 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3539 TII.get(AArch64::RET_ReallyLR));
3540 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3541 MIB.addReg(RetRegs[i], RegState::Implicit);
3545 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3546 Type *DestTy = I->getType();
3547 Value *Op = I->getOperand(0);
3548 Type *SrcTy = Op->getType();
3550 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3551 EVT DestEVT = TLI.getValueType(DestTy, true);
3552 if (!SrcEVT.isSimple())
3554 if (!DestEVT.isSimple())
3557 MVT SrcVT = SrcEVT.getSimpleVT();
3558 MVT DestVT = DestEVT.getSimpleVT();
3560 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3563 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3567 unsigned SrcReg = getRegForValue(Op);
3570 bool SrcIsKill = hasTrivialKill(Op);
3572 // If we're truncating from i64 to a smaller non-legal type then generate an
3573 // AND. Otherwise, we know the high bits are undefined and a truncate only
3574 // generate a COPY. We cannot mark the source register also as result
3575 // register, because this can incorrectly transfer the kill flag onto the
3578 if (SrcVT == MVT::i64) {
3580 switch (DestVT.SimpleTy) {
3582 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3594 // Issue an extract_subreg to get the lower 32-bits.
3595 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3597 // Create the AND instruction which performs the actual truncation.
3598 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3599 assert(ResultReg && "Unexpected AND instruction emission failure.");
3601 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3602 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3603 TII.get(TargetOpcode::COPY), ResultReg)
3604 .addReg(SrcReg, getKillRegState(SrcIsKill));
3607 updateValueMap(I, ResultReg);
3611 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3612 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3613 DestVT == MVT::i64) &&
3614 "Unexpected value type.");
3615 // Handle i8 and i16 as i32.
3616 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3620 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3621 assert(ResultReg && "Unexpected AND instruction emission failure.");
3622 if (DestVT == MVT::i64) {
3623 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3624 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3625 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3626 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3627 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3630 .addImm(AArch64::sub_32);
3635 if (DestVT == MVT::i64) {
3636 // FIXME: We're SExt i1 to i64.
3639 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3640 /*TODO:IsKill=*/false, 0, 0);
3644 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3645 unsigned Op1, bool Op1IsKill) {
3647 switch (RetVT.SimpleTy) {
3653 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3655 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3658 const TargetRegisterClass *RC =
3659 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3660 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3661 /*IsKill=*/ZReg, true);
3664 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3665 unsigned Op1, bool Op1IsKill) {
3666 if (RetVT != MVT::i64)
3669 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3670 Op0, Op0IsKill, Op1, Op1IsKill,
3671 AArch64::XZR, /*IsKill=*/true);
3674 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3675 unsigned Op1, bool Op1IsKill) {
3676 if (RetVT != MVT::i64)
3679 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3680 Op0, Op0IsKill, Op1, Op1IsKill,
3681 AArch64::XZR, /*IsKill=*/true);
3684 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3685 unsigned Op1Reg, bool Op1IsKill) {
3687 bool NeedTrunc = false;
3689 switch (RetVT.SimpleTy) {
3691 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3692 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3693 case MVT::i32: Opc = AArch64::LSLVWr; break;
3694 case MVT::i64: Opc = AArch64::LSLVXr; break;
3697 const TargetRegisterClass *RC =
3698 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3700 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3703 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3706 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3710 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3711 bool Op0IsKill, uint64_t Shift,
3713 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3714 "Unexpected source/return type pair.");
3715 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3716 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3717 "Unexpected source value type.");
3718 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3719 RetVT == MVT::i64) && "Unexpected return value type.");
3721 bool Is64Bit = (RetVT == MVT::i64);
3722 unsigned RegSize = Is64Bit ? 64 : 32;
3723 unsigned DstBits = RetVT.getSizeInBits();
3724 unsigned SrcBits = SrcVT.getSizeInBits();
3726 // Don't deal with undefined shifts.
3727 if (Shift >= DstBits)
3730 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3731 // {S|U}BFM Wd, Wn, #r, #s
3732 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3734 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3735 // %2 = shl i16 %1, 4
3736 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3737 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3738 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3739 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3741 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3742 // %2 = shl i16 %1, 8
3743 // Wd<32+7-24,32-24> = Wn<7:0>
3744 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3745 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3746 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3748 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3749 // %2 = shl i16 %1, 12
3750 // Wd<32+3-20,32-20> = Wn<3:0>
3751 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3752 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3753 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3755 unsigned ImmR = RegSize - Shift;
3756 // Limit the width to the length of the source type.
3757 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3758 static const unsigned OpcTable[2][2] = {
3759 {AArch64::SBFMWri, AArch64::SBFMXri},
3760 {AArch64::UBFMWri, AArch64::UBFMXri}
3762 unsigned Opc = OpcTable[IsZext][Is64Bit];
3763 const TargetRegisterClass *RC =
3764 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3765 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3766 unsigned TmpReg = MRI.createVirtualRegister(RC);
3767 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3768 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3770 .addReg(Op0, getKillRegState(Op0IsKill))
3771 .addImm(AArch64::sub_32);
3775 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3778 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3779 unsigned Op1Reg, bool Op1IsKill) {
3781 bool NeedTrunc = false;
3783 switch (RetVT.SimpleTy) {
3785 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3786 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3787 case MVT::i32: Opc = AArch64::LSRVWr; break;
3788 case MVT::i64: Opc = AArch64::LSRVXr; break;
3791 const TargetRegisterClass *RC =
3792 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3794 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3795 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3796 Op0IsKill = Op1IsKill = true;
3798 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3801 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3805 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3806 bool Op0IsKill, uint64_t Shift,
3808 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3809 "Unexpected source/return type pair.");
3810 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3811 SrcVT == MVT::i64) && "Unexpected source value type.");
3812 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3813 RetVT == MVT::i64) && "Unexpected return value type.");
3815 bool Is64Bit = (RetVT == MVT::i64);
3816 unsigned RegSize = Is64Bit ? 64 : 32;
3817 unsigned DstBits = RetVT.getSizeInBits();
3818 unsigned SrcBits = SrcVT.getSizeInBits();
3820 // Don't deal with undefined shifts.
3821 if (Shift >= DstBits)
3824 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3825 // {S|U}BFM Wd, Wn, #r, #s
3826 // Wd<s-r:0> = Wn<s:r> when r <= s
3828 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3829 // %2 = lshr i16 %1, 4
3830 // Wd<7-4:0> = Wn<7:4>
3831 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
3832 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3833 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3835 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3836 // %2 = lshr i16 %1, 8
3837 // Wd<7-7,0> = Wn<7:7>
3838 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
3839 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3840 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3842 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3843 // %2 = lshr i16 %1, 12
3844 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3845 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
3846 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3847 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3849 if (Shift >= SrcBits && IsZExt)
3850 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3852 // It is not possible to fold a sign-extend into the LShr instruction. In this
3853 // case emit a sign-extend.
3855 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3860 SrcBits = SrcVT.getSizeInBits();
3864 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3865 unsigned ImmS = SrcBits - 1;
3866 static const unsigned OpcTable[2][2] = {
3867 {AArch64::SBFMWri, AArch64::SBFMXri},
3868 {AArch64::UBFMWri, AArch64::UBFMXri}
3870 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3871 const TargetRegisterClass *RC =
3872 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3873 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3874 unsigned TmpReg = MRI.createVirtualRegister(RC);
3875 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3876 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3878 .addReg(Op0, getKillRegState(Op0IsKill))
3879 .addImm(AArch64::sub_32);
3883 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3886 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3887 unsigned Op1Reg, bool Op1IsKill) {
3889 bool NeedTrunc = false;
3891 switch (RetVT.SimpleTy) {
3893 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
3894 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
3895 case MVT::i32: Opc = AArch64::ASRVWr; break;
3896 case MVT::i64: Opc = AArch64::ASRVXr; break;
3899 const TargetRegisterClass *RC =
3900 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3902 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
3903 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3904 Op0IsKill = Op1IsKill = true;
3906 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3909 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3913 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3914 bool Op0IsKill, uint64_t Shift,
3916 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3917 "Unexpected source/return type pair.");
3918 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3919 SrcVT == MVT::i64) && "Unexpected source value type.");
3920 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3921 RetVT == MVT::i64) && "Unexpected return value type.");
3923 bool Is64Bit = (RetVT == MVT::i64);
3924 unsigned RegSize = Is64Bit ? 64 : 32;
3925 unsigned DstBits = RetVT.getSizeInBits();
3926 unsigned SrcBits = SrcVT.getSizeInBits();
3928 // Don't deal with undefined shifts.
3929 if (Shift >= DstBits)
3932 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3933 // {S|U}BFM Wd, Wn, #r, #s
3934 // Wd<s-r:0> = Wn<s:r> when r <= s
3936 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3937 // %2 = ashr i16 %1, 4
3938 // Wd<7-4:0> = Wn<7:4>
3939 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
3940 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3941 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3943 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3944 // %2 = ashr i16 %1, 8
3945 // Wd<7-7,0> = Wn<7:7>
3946 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3947 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3948 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3950 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3951 // %2 = ashr i16 %1, 12
3952 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3953 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3954 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3955 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3957 if (Shift >= SrcBits && IsZExt)
3958 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3960 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3961 unsigned ImmS = SrcBits - 1;
3962 static const unsigned OpcTable[2][2] = {
3963 {AArch64::SBFMWri, AArch64::SBFMXri},
3964 {AArch64::UBFMWri, AArch64::UBFMXri}
3966 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3967 const TargetRegisterClass *RC =
3968 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3969 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3970 unsigned TmpReg = MRI.createVirtualRegister(RC);
3971 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3972 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3974 .addReg(Op0, getKillRegState(Op0IsKill))
3975 .addImm(AArch64::sub_32);
3979 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3982 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
3984 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
3986 // FastISel does not have plumbing to deal with extensions where the SrcVT or
3987 // DestVT are odd things, so test to make sure that they are both types we can
3988 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
3989 // bail out to SelectionDAG.
3990 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
3991 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
3992 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
3993 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
3999 switch (SrcVT.SimpleTy) {
4003 return emiti1Ext(SrcReg, DestVT, IsZExt);
4005 if (DestVT == MVT::i64)
4006 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4008 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4012 if (DestVT == MVT::i64)
4013 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4015 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4019 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4020 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4025 // Handle i8 and i16 as i32.
4026 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4028 else if (DestVT == MVT::i64) {
4029 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4030 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4031 TII.get(AArch64::SUBREG_TO_REG), Src64)
4034 .addImm(AArch64::sub_32);
4038 const TargetRegisterClass *RC =
4039 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4040 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4043 static bool isZExtLoad(const MachineInstr *LI) {
4044 switch (LI->getOpcode()) {
4047 case AArch64::LDURBBi:
4048 case AArch64::LDURHHi:
4049 case AArch64::LDURWi:
4050 case AArch64::LDRBBui:
4051 case AArch64::LDRHHui:
4052 case AArch64::LDRWui:
4053 case AArch64::LDRBBroX:
4054 case AArch64::LDRHHroX:
4055 case AArch64::LDRWroX:
4056 case AArch64::LDRBBroW:
4057 case AArch64::LDRHHroW:
4058 case AArch64::LDRWroW:
4063 static bool isSExtLoad(const MachineInstr *LI) {
4064 switch (LI->getOpcode()) {
4067 case AArch64::LDURSBWi:
4068 case AArch64::LDURSHWi:
4069 case AArch64::LDURSBXi:
4070 case AArch64::LDURSHXi:
4071 case AArch64::LDURSWi:
4072 case AArch64::LDRSBWui:
4073 case AArch64::LDRSHWui:
4074 case AArch64::LDRSBXui:
4075 case AArch64::LDRSHXui:
4076 case AArch64::LDRSWui:
4077 case AArch64::LDRSBWroX:
4078 case AArch64::LDRSHWroX:
4079 case AArch64::LDRSBXroX:
4080 case AArch64::LDRSHXroX:
4081 case AArch64::LDRSWroX:
4082 case AArch64::LDRSBWroW:
4083 case AArch64::LDRSHWroW:
4084 case AArch64::LDRSBXroW:
4085 case AArch64::LDRSHXroW:
4086 case AArch64::LDRSWroW:
4091 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4093 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4094 if (!LI || !LI->hasOneUse())
4097 // Check if the load instruction has already been selected.
4098 unsigned Reg = lookUpRegForValue(LI);
4102 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4106 // Check if the correct load instruction has been emitted - SelectionDAG might
4107 // have emitted a zero-extending load, but we need a sign-extending load.
4108 bool IsZExt = isa<ZExtInst>(I);
4109 const auto *LoadMI = MI;
4110 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4111 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4112 unsigned LoadReg = MI->getOperand(1).getReg();
4113 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4114 assert(LoadMI && "Expected valid instruction");
4116 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4119 // Nothing to be done.
4120 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4121 updateValueMap(I, Reg);
4126 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4127 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4128 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4130 .addReg(Reg, getKillRegState(true))
4131 .addImm(AArch64::sub_32);
4134 assert((MI->getOpcode() == TargetOpcode::COPY &&
4135 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4136 "Expected copy instruction");
4137 Reg = MI->getOperand(1).getReg();
4138 MI->eraseFromParent();
4140 updateValueMap(I, Reg);
4144 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4145 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4146 "Unexpected integer extend instruction.");
4149 if (!isTypeSupported(I->getType(), RetVT))
4152 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4155 // Try to optimize already sign-/zero-extended values from load instructions.
4156 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4159 unsigned SrcReg = getRegForValue(I->getOperand(0));
4162 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4164 // Try to optimize already sign-/zero-extended values from function arguments.
4165 bool IsZExt = isa<ZExtInst>(I);
4166 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4167 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4168 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4169 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4170 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4171 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4173 .addReg(SrcReg, getKillRegState(SrcIsKill))
4174 .addImm(AArch64::sub_32);
4177 updateValueMap(I, SrcReg);
4182 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4186 updateValueMap(I, ResultReg);
4190 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4191 EVT DestEVT = TLI.getValueType(I->getType(), true);
4192 if (!DestEVT.isSimple())
4195 MVT DestVT = DestEVT.getSimpleVT();
4196 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4200 bool Is64bit = (DestVT == MVT::i64);
4201 switch (ISDOpcode) {
4205 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4208 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4211 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4212 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4215 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4217 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4220 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4222 const TargetRegisterClass *RC =
4223 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4224 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4225 Src1Reg, /*IsKill=*/false);
4226 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4227 // The remainder is computed as numerator - (quotient * denominator) using the
4228 // MSUB instruction.
4229 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4230 Src1Reg, Src1IsKill, Src0Reg,
4232 updateValueMap(I, ResultReg);
4236 bool AArch64FastISel::selectMul(const Instruction *I) {
4238 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4242 return selectBinaryOp(I, ISD::MUL);
4244 const Value *Src0 = I->getOperand(0);
4245 const Value *Src1 = I->getOperand(1);
4246 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4247 if (C->getValue().isPowerOf2())
4248 std::swap(Src0, Src1);
4250 // Try to simplify to a shift instruction.
4251 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4252 if (C->getValue().isPowerOf2()) {
4253 uint64_t ShiftVal = C->getValue().logBase2();
4256 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4257 if (!isIntExtFree(ZExt)) {
4259 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4262 Src0 = ZExt->getOperand(0);
4265 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4266 if (!isIntExtFree(SExt)) {
4268 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4271 Src0 = SExt->getOperand(0);
4276 unsigned Src0Reg = getRegForValue(Src0);
4279 bool Src0IsKill = hasTrivialKill(Src0);
4281 unsigned ResultReg =
4282 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4285 updateValueMap(I, ResultReg);
4290 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4293 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4295 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4298 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4300 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4305 updateValueMap(I, ResultReg);
4309 bool AArch64FastISel::selectShift(const Instruction *I) {
4311 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4314 if (RetVT.isVector())
4315 return selectOperator(I, I->getOpcode());
4317 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4318 unsigned ResultReg = 0;
4319 uint64_t ShiftVal = C->getZExtValue();
4321 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
4322 const Value *Op0 = I->getOperand(0);
4323 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4324 if (!isIntExtFree(ZExt)) {
4326 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4329 Op0 = ZExt->getOperand(0);
4332 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4333 if (!isIntExtFree(SExt)) {
4335 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4338 Op0 = SExt->getOperand(0);
4343 unsigned Op0Reg = getRegForValue(Op0);
4346 bool Op0IsKill = hasTrivialKill(Op0);
4348 switch (I->getOpcode()) {
4349 default: llvm_unreachable("Unexpected instruction.");
4350 case Instruction::Shl:
4351 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4353 case Instruction::AShr:
4354 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4356 case Instruction::LShr:
4357 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4363 updateValueMap(I, ResultReg);
4367 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4370 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4372 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4375 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4377 unsigned ResultReg = 0;
4378 switch (I->getOpcode()) {
4379 default: llvm_unreachable("Unexpected instruction.");
4380 case Instruction::Shl:
4381 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4383 case Instruction::AShr:
4384 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4386 case Instruction::LShr:
4387 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4394 updateValueMap(I, ResultReg);
4398 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4401 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4403 if (!isTypeLegal(I->getType(), RetVT))
4407 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4408 Opc = AArch64::FMOVWSr;
4409 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4410 Opc = AArch64::FMOVXDr;
4411 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4412 Opc = AArch64::FMOVSWr;
4413 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4414 Opc = AArch64::FMOVDXr;
4418 const TargetRegisterClass *RC = nullptr;
4419 switch (RetVT.SimpleTy) {
4420 default: llvm_unreachable("Unexpected value type.");
4421 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4422 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4423 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4424 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4426 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4429 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4430 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4435 updateValueMap(I, ResultReg);
4439 bool AArch64FastISel::selectFRem(const Instruction *I) {
4441 if (!isTypeLegal(I->getType(), RetVT))
4445 switch (RetVT.SimpleTy) {
4449 LC = RTLIB::REM_F32;
4452 LC = RTLIB::REM_F64;
4457 Args.reserve(I->getNumOperands());
4459 // Populate the argument list.
4460 for (auto &Arg : I->operands()) {
4463 Entry.Ty = Arg->getType();
4464 Args.push_back(Entry);
4467 CallLoweringInfo CLI;
4468 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4469 TLI.getLibcallName(LC), std::move(Args));
4470 if (!lowerCallTo(CLI))
4472 updateValueMap(I, CLI.ResultReg);
4476 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4478 if (!isTypeLegal(I->getType(), VT))
4481 if (!isa<ConstantInt>(I->getOperand(1)))
4482 return selectBinaryOp(I, ISD::SDIV);
4484 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4485 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4486 !(C.isPowerOf2() || (-C).isPowerOf2()))
4487 return selectBinaryOp(I, ISD::SDIV);
4489 unsigned Lg2 = C.countTrailingZeros();
4490 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4493 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4495 if (cast<BinaryOperator>(I)->isExact()) {
4496 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4499 updateValueMap(I, ResultReg);
4503 unsigned Pow2MinusOne = (1 << Lg2) - 1;
4504 unsigned AddReg = emitAddSub_ri(/*UseAdd=*/true, VT, Src0Reg,
4505 /*IsKill=*/false, Pow2MinusOne);
4509 // (Src0 < 0) ? Pow2 - 1 : 0;
4510 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4514 const TargetRegisterClass *RC;
4515 if (VT == MVT::i64) {
4516 SelectOpc = AArch64::CSELXr;
4517 RC = &AArch64::GPR64RegClass;
4519 SelectOpc = AArch64::CSELWr;
4520 RC = &AArch64::GPR32RegClass;
4522 unsigned SelectReg =
4523 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4524 Src0IsKill, AArch64CC::LT);
4528 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4529 // negate the result.
4530 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4533 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4534 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4536 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4541 updateValueMap(I, ResultReg);
4545 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4546 unsigned N = getRegForValue(I->getOperand(0));
4549 bool NIsKill = hasTrivialKill(I->getOperand(0));
4551 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4552 // into a single N = N + TotalOffset.
4553 uint64_t TotalOffs = 0;
4554 Type *Ty = I->getOperand(0)->getType();
4555 MVT VT = TLI.getPointerTy();
4556 for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4557 const Value *Idx = *OI;
4558 if (auto *StTy = dyn_cast<StructType>(Ty)) {
4559 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4562 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4563 Ty = StTy->getElementType(Field);
4565 Ty = cast<SequentialType>(Ty)->getElementType();
4566 // If this is a constant subscript, handle it quickly.
4567 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4572 DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4576 N = emitAddSub_ri(/*UseAdd=*/true, VT, N, NIsKill, TotalOffs);
4578 unsigned C = fastEmit_i(VT, VT, ISD::Constant, TotalOffs);
4581 N = emitAddSub_rr(/*UseAdd=*/true, VT, N, NIsKill, C, true);
4589 // N = N + Idx * ElementSize;
4590 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4591 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4592 unsigned IdxN = Pair.first;
4593 bool IdxNIsKill = Pair.second;
4597 if (ElementSize != 1) {
4598 unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4601 IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4606 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4612 N = emitAddSub_ri(/*UseAdd=*/true, VT, N, NIsKill, TotalOffs);
4614 unsigned C = fastEmit_i(VT, VT, ISD::Constant, TotalOffs);
4617 N = emitAddSub_rr(/*UseAdd=*/true, VT, N, NIsKill, C, true);
4623 updateValueMap(I, N);
4627 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4628 switch (I->getOpcode()) {
4631 case Instruction::Add:
4632 case Instruction::Sub:
4633 return selectAddSub(I);
4634 case Instruction::Mul:
4635 return selectMul(I);
4636 case Instruction::SDiv:
4637 return selectSDiv(I);
4638 case Instruction::SRem:
4639 if (!selectBinaryOp(I, ISD::SREM))
4640 return selectRem(I, ISD::SREM);
4642 case Instruction::URem:
4643 if (!selectBinaryOp(I, ISD::UREM))
4644 return selectRem(I, ISD::UREM);
4646 case Instruction::Shl:
4647 case Instruction::LShr:
4648 case Instruction::AShr:
4649 return selectShift(I);
4650 case Instruction::And:
4651 case Instruction::Or:
4652 case Instruction::Xor:
4653 return selectLogicalOp(I);
4654 case Instruction::Br:
4655 return selectBranch(I);
4656 case Instruction::IndirectBr:
4657 return selectIndirectBr(I);
4658 case Instruction::BitCast:
4659 if (!FastISel::selectBitCast(I))
4660 return selectBitCast(I);
4662 case Instruction::FPToSI:
4663 if (!selectCast(I, ISD::FP_TO_SINT))
4664 return selectFPToInt(I, /*Signed=*/true);
4666 case Instruction::FPToUI:
4667 return selectFPToInt(I, /*Signed=*/false);
4668 case Instruction::ZExt:
4669 case Instruction::SExt:
4670 return selectIntExt(I);
4671 case Instruction::Trunc:
4672 if (!selectCast(I, ISD::TRUNCATE))
4673 return selectTrunc(I);
4675 case Instruction::FPExt:
4676 return selectFPExt(I);
4677 case Instruction::FPTrunc:
4678 return selectFPTrunc(I);
4679 case Instruction::SIToFP:
4680 if (!selectCast(I, ISD::SINT_TO_FP))
4681 return selectIntToFP(I, /*Signed=*/true);
4683 case Instruction::UIToFP:
4684 return selectIntToFP(I, /*Signed=*/false);
4685 case Instruction::Load:
4686 return selectLoad(I);
4687 case Instruction::Store:
4688 return selectStore(I);
4689 case Instruction::FCmp:
4690 case Instruction::ICmp:
4691 return selectCmp(I);
4692 case Instruction::Select:
4693 return selectSelect(I);
4694 case Instruction::Ret:
4695 return selectRet(I);
4696 case Instruction::FRem:
4697 return selectFRem(I);
4698 case Instruction::GetElementPtr:
4699 return selectGetElementPtr(I);
4702 // fall-back to target-independent instruction selection.
4703 return selectOperator(I, I->getOpcode());
4704 // Silence warnings.
4705 (void)&CC_AArch64_DarwinPCS_VarArg;
4709 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4710 const TargetLibraryInfo *LibInfo) {
4711 return new AArch64FastISel(FuncInfo, LibInfo);