1 //===-- AArch6464FastISel.cpp - AArch64 FastISel implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the AArch64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // AArch64GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "MCTargetDesc/AArch64AddressingModes.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/FastISel.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Support/CommandLine.h"
43 class AArch64FastISel final : public FastISel {
53 AArch64_AM::ShiftExtendType ExtType;
61 const GlobalValue *GV;
64 Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
65 OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
66 void setKind(BaseKind K) { Kind = K; }
67 BaseKind getKind() const { return Kind; }
68 void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
69 AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
70 bool isRegBase() const { return Kind == RegBase; }
71 bool isFIBase() const { return Kind == FrameIndexBase; }
72 void setReg(unsigned Reg) {
73 assert(isRegBase() && "Invalid base register access!");
76 unsigned getReg() const {
77 assert(isRegBase() && "Invalid base register access!");
80 void setOffsetReg(unsigned Reg) {
81 assert(isRegBase() && "Invalid offset register access!");
84 unsigned getOffsetReg() const {
85 assert(isRegBase() && "Invalid offset register access!");
88 void setFI(unsigned FI) {
89 assert(isFIBase() && "Invalid base frame index access!");
92 unsigned getFI() const {
93 assert(isFIBase() && "Invalid base frame index access!");
96 void setOffset(int64_t O) { Offset = O; }
97 int64_t getOffset() { return Offset; }
98 void setShift(unsigned S) { Shift = S; }
99 unsigned getShift() { return Shift; }
101 void setGlobalValue(const GlobalValue *G) { GV = G; }
102 const GlobalValue *getGlobalValue() { return GV; }
105 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
106 /// make the right decision when generating code for different targets.
107 const AArch64Subtarget *Subtarget;
108 LLVMContext *Context;
110 bool fastLowerArguments() override;
111 bool fastLowerCall(CallLoweringInfo &CLI) override;
112 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
115 // Selection routines.
116 bool selectAddSub(const Instruction *I);
117 bool selectLogicalOp(const Instruction *I);
118 bool selectLoad(const Instruction *I);
119 bool selectStore(const Instruction *I);
120 bool selectBranch(const Instruction *I);
121 bool selectIndirectBr(const Instruction *I);
122 bool selectCmp(const Instruction *I);
123 bool selectSelect(const Instruction *I);
124 bool selectFPExt(const Instruction *I);
125 bool selectFPTrunc(const Instruction *I);
126 bool selectFPToInt(const Instruction *I, bool Signed);
127 bool selectIntToFP(const Instruction *I, bool Signed);
128 bool selectRem(const Instruction *I, unsigned ISDOpcode);
129 bool selectRet(const Instruction *I);
130 bool selectTrunc(const Instruction *I);
131 bool selectIntExt(const Instruction *I);
132 bool selectMul(const Instruction *I);
133 bool selectShift(const Instruction *I);
134 bool selectBitCast(const Instruction *I);
135 bool selectFRem(const Instruction *I);
136 bool selectSDiv(const Instruction *I);
138 // Utility helper routines.
139 bool isTypeLegal(Type *Ty, MVT &VT);
140 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
141 bool isValueAvailable(const Value *V) const;
142 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
143 bool computeCallAddress(const Value *V, Address &Addr);
144 bool simplifyAddress(Address &Addr, MVT VT);
145 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
146 unsigned Flags, unsigned ScaleFactor,
147 MachineMemOperand *MMO);
148 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
149 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
151 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
153 bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
155 // Emit helper routines.
156 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
157 const Value *RHS, bool SetFlags = false,
158 bool WantResult = true, bool IsZExt = false);
159 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
160 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
161 bool SetFlags = false, bool WantResult = true);
162 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
163 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
164 bool WantResult = true);
165 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
166 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
167 AArch64_AM::ShiftExtendType ShiftType,
168 uint64_t ShiftImm, bool SetFlags = false,
169 bool WantResult = true);
170 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
171 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
172 AArch64_AM::ShiftExtendType ExtType,
173 uint64_t ShiftImm, bool SetFlags = false,
174 bool WantResult = true);
177 bool emitCompareAndBranch(const BranchInst *BI);
178 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
179 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
180 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
181 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
182 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
183 MachineMemOperand *MMO = nullptr);
184 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
185 MachineMemOperand *MMO = nullptr);
186 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
187 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
188 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
189 bool SetFlags = false, bool WantResult = true,
190 bool IsZExt = false);
191 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
192 bool SetFlags = false, bool WantResult = true,
193 bool IsZExt = false);
194 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
195 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
196 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
197 unsigned RHSReg, bool RHSIsKill,
198 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
199 bool WantResult = true);
200 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
202 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
203 bool LHSIsKill, uint64_t Imm);
204 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
205 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
207 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
208 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
209 unsigned Op1, bool Op1IsKill);
210 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
211 unsigned Op1, bool Op1IsKill);
212 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
213 unsigned Op1, bool Op1IsKill);
214 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
215 unsigned Op1Reg, bool Op1IsKill);
216 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
217 uint64_t Imm, bool IsZExt = true);
218 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
219 unsigned Op1Reg, bool Op1IsKill);
220 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
221 uint64_t Imm, bool IsZExt = true);
222 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
223 unsigned Op1Reg, bool Op1IsKill);
224 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
225 uint64_t Imm, bool IsZExt = false);
227 unsigned materializeInt(const ConstantInt *CI, MVT VT);
228 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
229 unsigned materializeGV(const GlobalValue *GV);
231 // Call handling routines.
233 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
234 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
236 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
239 // Backend specific FastISel code.
240 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
241 unsigned fastMaterializeConstant(const Constant *C) override;
242 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
244 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
245 const TargetLibraryInfo *LibInfo)
246 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
247 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
248 Context = &FuncInfo.Fn->getContext();
251 bool fastSelectInstruction(const Instruction *I) override;
253 #include "AArch64GenFastISel.inc"
256 } // end anonymous namespace
258 #include "AArch64GenCallingConv.inc"
260 /// \brief Check if the sign-/zero-extend will be a noop.
261 static bool isIntExtFree(const Instruction *I) {
262 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
263 "Unexpected integer extend instruction.");
264 assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
265 "Unexpected value type.");
266 bool IsZExt = isa<ZExtInst>(I);
268 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
272 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
273 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
279 /// \brief Determine the implicit scale factor that is applied by a memory
280 /// operation for a given value type.
281 static unsigned getImplicitScaleFactor(MVT VT) {
282 switch (VT.SimpleTy) {
285 case MVT::i1: // fall-through
290 case MVT::i32: // fall-through
293 case MVT::i64: // fall-through
299 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
300 if (CC == CallingConv::WebKit_JS)
301 return CC_AArch64_WebKit_JS;
302 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
305 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
306 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
307 "Alloca should always return a pointer.");
309 // Don't handle dynamic allocas.
310 if (!FuncInfo.StaticAllocaMap.count(AI))
313 DenseMap<const AllocaInst *, int>::iterator SI =
314 FuncInfo.StaticAllocaMap.find(AI);
316 if (SI != FuncInfo.StaticAllocaMap.end()) {
317 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
318 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
320 .addFrameIndex(SI->second)
329 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
334 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
336 // Create a copy from the zero register to materialize a "0" value.
337 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
338 : &AArch64::GPR32RegClass;
339 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
340 unsigned ResultReg = createResultReg(RC);
341 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
342 ResultReg).addReg(ZeroReg, getKillRegState(true));
346 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
347 // Positive zero (+0.0) has to be materialized with a fmov from the zero
348 // register, because the immediate version of fmov cannot encode zero.
349 if (CFP->isNullValue())
350 return fastMaterializeFloatZero(CFP);
352 if (VT != MVT::f32 && VT != MVT::f64)
355 const APFloat Val = CFP->getValueAPF();
356 bool Is64Bit = (VT == MVT::f64);
357 // This checks to see if we can use FMOV instructions to materialize
358 // a constant, otherwise we have to materialize via the constant pool.
359 if (TLI.isFPImmLegal(Val, VT)) {
361 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
362 assert((Imm != -1) && "Cannot encode floating-point constant.");
363 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
364 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
367 // Materialize via constant pool. MachineConstantPool wants an explicit
369 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
371 Align = DL.getTypeAllocSize(CFP->getType());
373 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
374 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
375 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
376 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
378 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
379 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
380 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
382 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
386 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
387 // We can't handle thread-local variables quickly yet.
388 if (GV->isThreadLocal())
391 // MachO still uses GOT for large code-model accesses, but ELF requires
392 // movz/movk sequences, which FastISel doesn't handle yet.
393 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
396 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
398 EVT DestEVT = TLI.getValueType(GV->getType(), true);
399 if (!DestEVT.isSimple())
402 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
405 if (OpFlags & AArch64II::MO_GOT) {
407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
409 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
411 ResultReg = createResultReg(&AArch64::GPR64RegClass);
412 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
415 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
417 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
418 // We can't handle addresses loaded from a constant pool quickly yet.
422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
424 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
426 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
427 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
430 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
436 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
437 EVT CEVT = TLI.getValueType(C->getType(), true);
439 // Only handle simple types.
440 if (!CEVT.isSimple())
442 MVT VT = CEVT.getSimpleVT();
444 if (const auto *CI = dyn_cast<ConstantInt>(C))
445 return materializeInt(CI, VT);
446 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
447 return materializeFP(CFP, VT);
448 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
449 return materializeGV(GV);
454 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
455 assert(CFP->isNullValue() &&
456 "Floating-point constant is not a positive zero.");
458 if (!isTypeLegal(CFP->getType(), VT))
461 if (VT != MVT::f32 && VT != MVT::f64)
464 bool Is64Bit = (VT == MVT::f64);
465 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
466 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
467 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
470 /// \brief Check if the multiply is by a power-of-2 constant.
471 static bool isMulPowOf2(const Value *I) {
472 if (const auto *MI = dyn_cast<MulOperator>(I)) {
473 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
474 if (C->getValue().isPowerOf2())
476 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
477 if (C->getValue().isPowerOf2())
483 // Computes the address to get to an object.
484 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
486 const User *U = nullptr;
487 unsigned Opcode = Instruction::UserOp1;
488 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
489 // Don't walk into other basic blocks unless the object is an alloca from
490 // another block, otherwise it may not have a virtual register assigned.
491 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
492 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
493 Opcode = I->getOpcode();
496 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
497 Opcode = C->getOpcode();
501 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
502 if (Ty->getAddressSpace() > 255)
503 // Fast instruction selection doesn't support the special
510 case Instruction::BitCast: {
511 // Look through bitcasts.
512 return computeAddress(U->getOperand(0), Addr, Ty);
514 case Instruction::IntToPtr: {
515 // Look past no-op inttoptrs.
516 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
517 return computeAddress(U->getOperand(0), Addr, Ty);
520 case Instruction::PtrToInt: {
521 // Look past no-op ptrtoints.
522 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
523 return computeAddress(U->getOperand(0), Addr, Ty);
526 case Instruction::GetElementPtr: {
527 Address SavedAddr = Addr;
528 uint64_t TmpOffset = Addr.getOffset();
530 // Iterate through the GEP folding the constants into offsets where
532 gep_type_iterator GTI = gep_type_begin(U);
533 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
535 const Value *Op = *i;
536 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
537 const StructLayout *SL = DL.getStructLayout(STy);
538 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
539 TmpOffset += SL->getElementOffset(Idx);
541 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
543 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
544 // Constant-offset addressing.
545 TmpOffset += CI->getSExtValue() * S;
548 if (canFoldAddIntoGEP(U, Op)) {
549 // A compatible add with a constant operand. Fold the constant.
551 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
552 TmpOffset += CI->getSExtValue() * S;
553 // Iterate on the other operand.
554 Op = cast<AddOperator>(Op)->getOperand(0);
558 goto unsupported_gep;
563 // Try to grab the base operand now.
564 Addr.setOffset(TmpOffset);
565 if (computeAddress(U->getOperand(0), Addr, Ty))
568 // We failed, restore everything and try the other options.
574 case Instruction::Alloca: {
575 const AllocaInst *AI = cast<AllocaInst>(Obj);
576 DenseMap<const AllocaInst *, int>::iterator SI =
577 FuncInfo.StaticAllocaMap.find(AI);
578 if (SI != FuncInfo.StaticAllocaMap.end()) {
579 Addr.setKind(Address::FrameIndexBase);
580 Addr.setFI(SI->second);
585 case Instruction::Add: {
586 // Adds of constants are common and easy enough.
587 const Value *LHS = U->getOperand(0);
588 const Value *RHS = U->getOperand(1);
590 if (isa<ConstantInt>(LHS))
593 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
594 Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
595 return computeAddress(LHS, Addr, Ty);
598 Address Backup = Addr;
599 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
605 case Instruction::Sub: {
606 // Subs of constants are common and easy enough.
607 const Value *LHS = U->getOperand(0);
608 const Value *RHS = U->getOperand(1);
610 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
611 Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
612 return computeAddress(LHS, Addr, Ty);
616 case Instruction::Shl: {
617 if (Addr.getOffsetReg())
620 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
624 unsigned Val = CI->getZExtValue();
625 if (Val < 1 || Val > 3)
628 uint64_t NumBytes = 0;
629 if (Ty && Ty->isSized()) {
630 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
631 NumBytes = NumBits / 8;
632 if (!isPowerOf2_64(NumBits))
636 if (NumBytes != (1ULL << Val))
640 Addr.setExtendType(AArch64_AM::LSL);
642 const Value *Src = U->getOperand(0);
643 if (const auto *I = dyn_cast<Instruction>(Src))
644 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
647 // Fold the zext or sext when it won't become a noop.
648 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
649 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
650 Addr.setExtendType(AArch64_AM::UXTW);
651 Src = ZE->getOperand(0);
653 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
654 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
655 Addr.setExtendType(AArch64_AM::SXTW);
656 Src = SE->getOperand(0);
660 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
661 if (AI->getOpcode() == Instruction::And) {
662 const Value *LHS = AI->getOperand(0);
663 const Value *RHS = AI->getOperand(1);
665 if (const auto *C = dyn_cast<ConstantInt>(LHS))
666 if (C->getValue() == 0xffffffff)
669 if (const auto *C = dyn_cast<ConstantInt>(RHS))
670 if (C->getValue() == 0xffffffff) {
671 Addr.setExtendType(AArch64_AM::UXTW);
672 unsigned Reg = getRegForValue(LHS);
675 bool RegIsKill = hasTrivialKill(LHS);
676 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
678 Addr.setOffsetReg(Reg);
683 unsigned Reg = getRegForValue(Src);
686 Addr.setOffsetReg(Reg);
689 case Instruction::Mul: {
690 if (Addr.getOffsetReg())
696 const Value *LHS = U->getOperand(0);
697 const Value *RHS = U->getOperand(1);
699 // Canonicalize power-of-2 value to the RHS.
700 if (const auto *C = dyn_cast<ConstantInt>(LHS))
701 if (C->getValue().isPowerOf2())
704 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
705 const auto *C = cast<ConstantInt>(RHS);
706 unsigned Val = C->getValue().logBase2();
707 if (Val < 1 || Val > 3)
710 uint64_t NumBytes = 0;
711 if (Ty && Ty->isSized()) {
712 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
713 NumBytes = NumBits / 8;
714 if (!isPowerOf2_64(NumBits))
718 if (NumBytes != (1ULL << Val))
722 Addr.setExtendType(AArch64_AM::LSL);
724 const Value *Src = LHS;
725 if (const auto *I = dyn_cast<Instruction>(Src))
726 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
730 // Fold the zext or sext when it won't become a noop.
731 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
732 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
733 Addr.setExtendType(AArch64_AM::UXTW);
734 Src = ZE->getOperand(0);
736 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
737 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
738 Addr.setExtendType(AArch64_AM::SXTW);
739 Src = SE->getOperand(0);
743 unsigned Reg = getRegForValue(Src);
746 Addr.setOffsetReg(Reg);
749 case Instruction::And: {
750 if (Addr.getOffsetReg())
753 if (DL.getTypeSizeInBits(Ty) != 8)
756 const Value *LHS = U->getOperand(0);
757 const Value *RHS = U->getOperand(1);
759 if (const auto *C = dyn_cast<ConstantInt>(LHS))
760 if (C->getValue() == 0xffffffff)
763 if (const auto *C = dyn_cast<ConstantInt>(RHS))
764 if (C->getValue() == 0xffffffff) {
766 Addr.setExtendType(AArch64_AM::LSL);
767 Addr.setExtendType(AArch64_AM::UXTW);
769 unsigned Reg = getRegForValue(LHS);
772 bool RegIsKill = hasTrivialKill(LHS);
773 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
775 Addr.setOffsetReg(Reg);
780 case Instruction::SExt:
781 case Instruction::ZExt: {
782 if (!Addr.getReg() || Addr.getOffsetReg())
785 const Value *Src = nullptr;
786 // Fold the zext or sext when it won't become a noop.
787 if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
788 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
789 Addr.setExtendType(AArch64_AM::UXTW);
790 Src = ZE->getOperand(0);
792 } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
793 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
794 Addr.setExtendType(AArch64_AM::SXTW);
795 Src = SE->getOperand(0);
803 unsigned Reg = getRegForValue(Src);
806 Addr.setOffsetReg(Reg);
812 if (!Addr.getOffsetReg()) {
813 unsigned Reg = getRegForValue(Obj);
816 Addr.setOffsetReg(Reg);
822 unsigned Reg = getRegForValue(Obj);
829 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
830 const User *U = nullptr;
831 unsigned Opcode = Instruction::UserOp1;
834 if (const auto *I = dyn_cast<Instruction>(V)) {
835 Opcode = I->getOpcode();
837 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
838 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
839 Opcode = C->getOpcode();
845 case Instruction::BitCast:
846 // Look past bitcasts if its operand is in the same BB.
848 return computeCallAddress(U->getOperand(0), Addr);
850 case Instruction::IntToPtr:
851 // Look past no-op inttoptrs if its operand is in the same BB.
853 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
854 return computeCallAddress(U->getOperand(0), Addr);
856 case Instruction::PtrToInt:
857 // Look past no-op ptrtoints if its operand is in the same BB.
859 TLI.getValueType(U->getType()) == TLI.getPointerTy())
860 return computeCallAddress(U->getOperand(0), Addr);
864 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
865 Addr.setGlobalValue(GV);
869 // If all else fails, try to materialize the value in a register.
870 if (!Addr.getGlobalValue()) {
871 Addr.setReg(getRegForValue(V));
872 return Addr.getReg() != 0;
879 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
880 EVT evt = TLI.getValueType(Ty, true);
882 // Only handle simple types.
883 if (evt == MVT::Other || !evt.isSimple())
885 VT = evt.getSimpleVT();
887 // This is a legal type, but it's not something we handle in fast-isel.
891 // Handle all other legal types, i.e. a register that will directly hold this
893 return TLI.isTypeLegal(VT);
896 /// \brief Determine if the value type is supported by FastISel.
898 /// FastISel for AArch64 can handle more value types than are legal. This adds
899 /// simple value type such as i1, i8, and i16.
900 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
901 if (Ty->isVectorTy() && !IsVectorAllowed)
904 if (isTypeLegal(Ty, VT))
907 // If this is a type than can be sign or zero-extended to a basic operation
908 // go ahead and accept it now.
909 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
915 bool AArch64FastISel::isValueAvailable(const Value *V) const {
916 if (!isa<Instruction>(V))
919 const auto *I = cast<Instruction>(V);
920 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
926 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
927 unsigned ScaleFactor = getImplicitScaleFactor(VT);
931 bool ImmediateOffsetNeedsLowering = false;
932 bool RegisterOffsetNeedsLowering = false;
933 int64_t Offset = Addr.getOffset();
934 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
935 ImmediateOffsetNeedsLowering = true;
936 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
937 !isUInt<12>(Offset / ScaleFactor))
938 ImmediateOffsetNeedsLowering = true;
940 // Cannot encode an offset register and an immediate offset in the same
941 // instruction. Fold the immediate offset into the load/store instruction and
942 // emit an additonal add to take care of the offset register.
943 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.isRegBase() &&
945 RegisterOffsetNeedsLowering = true;
947 // Cannot encode zero register as base.
948 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
949 RegisterOffsetNeedsLowering = true;
951 // If this is a stack pointer and the offset needs to be simplified then put
952 // the alloca address into a register, set the base type back to register and
953 // continue. This should almost never happen.
954 if (ImmediateOffsetNeedsLowering && Addr.isFIBase()) {
955 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
956 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
958 .addFrameIndex(Addr.getFI())
961 Addr.setKind(Address::RegBase);
962 Addr.setReg(ResultReg);
965 if (RegisterOffsetNeedsLowering) {
966 unsigned ResultReg = 0;
968 if (Addr.getExtendType() == AArch64_AM::SXTW ||
969 Addr.getExtendType() == AArch64_AM::UXTW )
970 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
971 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
972 /*TODO:IsKill=*/false, Addr.getExtendType(),
975 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
976 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
977 /*TODO:IsKill=*/false, AArch64_AM::LSL,
980 if (Addr.getExtendType() == AArch64_AM::UXTW)
981 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
982 /*Op0IsKill=*/false, Addr.getShift(),
984 else if (Addr.getExtendType() == AArch64_AM::SXTW)
985 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
986 /*Op0IsKill=*/false, Addr.getShift(),
989 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
990 /*Op0IsKill=*/false, Addr.getShift());
995 Addr.setReg(ResultReg);
996 Addr.setOffsetReg(0);
998 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1001 // Since the offset is too large for the load/store instruction get the
1002 // reg+offset into a register.
1003 if (ImmediateOffsetNeedsLowering) {
1005 if (Addr.getReg()) {
1006 // Try to fold the immediate into the add instruction.
1008 ResultReg = emitAddSub_ri(/*UseAdd=*/false, MVT::i64, Addr.getReg(),
1009 /*IsKill=*/false, -Offset);
1011 ResultReg = emitAddSub_ri(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
1012 /*IsKill=*/false, Offset);
1014 unsigned ImmReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1015 ResultReg = emitAddSub_rr(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
1016 /*IsKill=*/false, ImmReg, /*IsKill=*/true);
1019 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1023 Addr.setReg(ResultReg);
1029 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1030 const MachineInstrBuilder &MIB,
1032 unsigned ScaleFactor,
1033 MachineMemOperand *MMO) {
1034 int64_t Offset = Addr.getOffset() / ScaleFactor;
1035 // Frame base works a bit differently. Handle it separately.
1036 if (Addr.isFIBase()) {
1037 int FI = Addr.getFI();
1038 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1039 // and alignment should be based on the VT.
1040 MMO = FuncInfo.MF->getMachineMemOperand(
1041 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1042 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1043 // Now add the rest of the operands.
1044 MIB.addFrameIndex(FI).addImm(Offset);
1046 assert(Addr.isRegBase() && "Unexpected address kind.");
1047 const MCInstrDesc &II = MIB->getDesc();
1048 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1050 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1052 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1053 if (Addr.getOffsetReg()) {
1054 assert(Addr.getOffset() == 0 && "Unexpected offset");
1055 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1056 Addr.getExtendType() == AArch64_AM::SXTX;
1057 MIB.addReg(Addr.getReg());
1058 MIB.addReg(Addr.getOffsetReg());
1059 MIB.addImm(IsSigned);
1060 MIB.addImm(Addr.getShift() != 0);
1062 MIB.addReg(Addr.getReg());
1068 MIB.addMemOperand(MMO);
1071 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1072 const Value *RHS, bool SetFlags,
1073 bool WantResult, bool IsZExt) {
1074 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1075 bool NeedExtend = false;
1076 switch (RetVT.SimpleTy) {
1084 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1088 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1090 case MVT::i32: // fall-through
1095 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1097 // Canonicalize immediates to the RHS first.
1098 if (UseAdd && isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1099 std::swap(LHS, RHS);
1101 // Canonicalize mul by power of 2 to the RHS.
1102 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1103 if (isMulPowOf2(LHS))
1104 std::swap(LHS, RHS);
1106 // Canonicalize shift immediate to the RHS.
1107 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1108 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1109 if (isa<ConstantInt>(SI->getOperand(1)))
1110 if (SI->getOpcode() == Instruction::Shl ||
1111 SI->getOpcode() == Instruction::LShr ||
1112 SI->getOpcode() == Instruction::AShr )
1113 std::swap(LHS, RHS);
1115 unsigned LHSReg = getRegForValue(LHS);
1118 bool LHSIsKill = hasTrivialKill(LHS);
1121 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1123 unsigned ResultReg = 0;
1124 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1125 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1126 if (C->isNegative())
1127 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1128 SetFlags, WantResult);
1130 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1136 // Only extend the RHS within the instruction if there is a valid extend type.
1137 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1138 isValueAvailable(RHS)) {
1139 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1140 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1141 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1142 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1145 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1146 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1147 RHSIsKill, ExtendType, C->getZExtValue(),
1148 SetFlags, WantResult);
1150 unsigned RHSReg = getRegForValue(RHS);
1153 bool RHSIsKill = hasTrivialKill(RHS);
1154 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1155 ExtendType, 0, SetFlags, WantResult);
1158 // Check if the mul can be folded into the instruction.
1159 if (RHS->hasOneUse() && isValueAvailable(RHS))
1160 if (isMulPowOf2(RHS)) {
1161 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1162 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1164 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1165 if (C->getValue().isPowerOf2())
1166 std::swap(MulLHS, MulRHS);
1168 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1169 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1170 unsigned RHSReg = getRegForValue(MulLHS);
1173 bool RHSIsKill = hasTrivialKill(MulLHS);
1174 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1175 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1178 // Check if the shift can be folded into the instruction.
1179 if (RHS->hasOneUse() && isValueAvailable(RHS))
1180 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1181 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1182 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1183 switch (SI->getOpcode()) {
1185 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1186 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1187 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1189 uint64_t ShiftVal = C->getZExtValue();
1190 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1191 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1194 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1195 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1196 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1202 unsigned RHSReg = getRegForValue(RHS);
1205 bool RHSIsKill = hasTrivialKill(RHS);
1208 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1210 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1211 SetFlags, WantResult);
1214 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1215 bool LHSIsKill, unsigned RHSReg,
1216 bool RHSIsKill, bool SetFlags,
1218 assert(LHSReg && RHSReg && "Invalid register number.");
1220 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1223 static const unsigned OpcTable[2][2][2] = {
1224 { { AArch64::SUBWrr, AArch64::SUBXrr },
1225 { AArch64::ADDWrr, AArch64::ADDXrr } },
1226 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1227 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1229 bool Is64Bit = RetVT == MVT::i64;
1230 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1231 const TargetRegisterClass *RC =
1232 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1235 ResultReg = createResultReg(RC);
1237 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1239 const MCInstrDesc &II = TII.get(Opc);
1240 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1241 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1242 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1243 .addReg(LHSReg, getKillRegState(LHSIsKill))
1244 .addReg(RHSReg, getKillRegState(RHSIsKill));
1248 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1249 bool LHSIsKill, uint64_t Imm,
1250 bool SetFlags, bool WantResult) {
1251 assert(LHSReg && "Invalid register number.");
1253 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1257 if (isUInt<12>(Imm))
1259 else if ((Imm & 0xfff000) == Imm) {
1265 static const unsigned OpcTable[2][2][2] = {
1266 { { AArch64::SUBWri, AArch64::SUBXri },
1267 { AArch64::ADDWri, AArch64::ADDXri } },
1268 { { AArch64::SUBSWri, AArch64::SUBSXri },
1269 { AArch64::ADDSWri, AArch64::ADDSXri } }
1271 bool Is64Bit = RetVT == MVT::i64;
1272 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1273 const TargetRegisterClass *RC;
1275 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1277 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1280 ResultReg = createResultReg(RC);
1282 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1284 const MCInstrDesc &II = TII.get(Opc);
1285 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1286 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1287 .addReg(LHSReg, getKillRegState(LHSIsKill))
1289 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1293 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1294 bool LHSIsKill, unsigned RHSReg,
1296 AArch64_AM::ShiftExtendType ShiftType,
1297 uint64_t ShiftImm, bool SetFlags,
1299 assert(LHSReg && RHSReg && "Invalid register number.");
1301 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1304 static const unsigned OpcTable[2][2][2] = {
1305 { { AArch64::SUBWrs, AArch64::SUBXrs },
1306 { AArch64::ADDWrs, AArch64::ADDXrs } },
1307 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1308 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1310 bool Is64Bit = RetVT == MVT::i64;
1311 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1312 const TargetRegisterClass *RC =
1313 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1316 ResultReg = createResultReg(RC);
1318 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1320 const MCInstrDesc &II = TII.get(Opc);
1321 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1322 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1323 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1324 .addReg(LHSReg, getKillRegState(LHSIsKill))
1325 .addReg(RHSReg, getKillRegState(RHSIsKill))
1326 .addImm(getShifterImm(ShiftType, ShiftImm));
1330 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1331 bool LHSIsKill, unsigned RHSReg,
1333 AArch64_AM::ShiftExtendType ExtType,
1334 uint64_t ShiftImm, bool SetFlags,
1336 assert(LHSReg && RHSReg && "Invalid register number.");
1338 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1341 static const unsigned OpcTable[2][2][2] = {
1342 { { AArch64::SUBWrx, AArch64::SUBXrx },
1343 { AArch64::ADDWrx, AArch64::ADDXrx } },
1344 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1345 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1347 bool Is64Bit = RetVT == MVT::i64;
1348 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1349 const TargetRegisterClass *RC = nullptr;
1351 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1353 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1356 ResultReg = createResultReg(RC);
1358 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1360 const MCInstrDesc &II = TII.get(Opc);
1361 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1362 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1363 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1364 .addReg(LHSReg, getKillRegState(LHSIsKill))
1365 .addReg(RHSReg, getKillRegState(RHSIsKill))
1366 .addImm(getArithExtendImm(ExtType, ShiftImm));
1370 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1371 Type *Ty = LHS->getType();
1372 EVT EVT = TLI.getValueType(Ty, true);
1373 if (!EVT.isSimple())
1375 MVT VT = EVT.getSimpleVT();
1377 switch (VT.SimpleTy) {
1385 return emitICmp(VT, LHS, RHS, IsZExt);
1388 return emitFCmp(VT, LHS, RHS);
1392 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1394 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1398 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1400 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1401 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1404 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1405 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1408 // Check to see if the 2nd operand is a constant that we can encode directly
1410 bool UseImm = false;
1411 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1412 if (CFP->isZero() && !CFP->isNegative())
1415 unsigned LHSReg = getRegForValue(LHS);
1418 bool LHSIsKill = hasTrivialKill(LHS);
1421 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1423 .addReg(LHSReg, getKillRegState(LHSIsKill));
1427 unsigned RHSReg = getRegForValue(RHS);
1430 bool RHSIsKill = hasTrivialKill(RHS);
1432 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1434 .addReg(LHSReg, getKillRegState(LHSIsKill))
1435 .addReg(RHSReg, getKillRegState(RHSIsKill));
1439 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1440 bool SetFlags, bool WantResult, bool IsZExt) {
1441 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1445 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1446 bool SetFlags, bool WantResult, bool IsZExt) {
1447 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1451 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1452 bool LHSIsKill, unsigned RHSReg,
1453 bool RHSIsKill, bool WantResult) {
1454 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1455 RHSIsKill, /*SetFlags=*/true, WantResult);
1458 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1459 bool LHSIsKill, unsigned RHSReg,
1461 AArch64_AM::ShiftExtendType ShiftType,
1462 uint64_t ShiftImm, bool WantResult) {
1463 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1464 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1468 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1469 const Value *LHS, const Value *RHS) {
1470 // Canonicalize immediates to the RHS first.
1471 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1472 std::swap(LHS, RHS);
1474 // Canonicalize mul by power-of-2 to the RHS.
1475 if (LHS->hasOneUse() && isValueAvailable(LHS))
1476 if (isMulPowOf2(LHS))
1477 std::swap(LHS, RHS);
1479 // Canonicalize shift immediate to the RHS.
1480 if (LHS->hasOneUse() && isValueAvailable(LHS))
1481 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1482 if (isa<ConstantInt>(SI->getOperand(1)))
1483 std::swap(LHS, RHS);
1485 unsigned LHSReg = getRegForValue(LHS);
1488 bool LHSIsKill = hasTrivialKill(LHS);
1490 unsigned ResultReg = 0;
1491 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1492 uint64_t Imm = C->getZExtValue();
1493 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1498 // Check if the mul can be folded into the instruction.
1499 if (RHS->hasOneUse() && isValueAvailable(RHS))
1500 if (isMulPowOf2(RHS)) {
1501 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1502 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1504 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1505 if (C->getValue().isPowerOf2())
1506 std::swap(MulLHS, MulRHS);
1508 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1509 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1511 unsigned RHSReg = getRegForValue(MulLHS);
1514 bool RHSIsKill = hasTrivialKill(MulLHS);
1515 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1516 RHSIsKill, ShiftVal);
1519 // Check if the shift can be folded into the instruction.
1520 if (RHS->hasOneUse() && isValueAvailable(RHS))
1521 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1522 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1523 uint64_t ShiftVal = C->getZExtValue();
1524 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1527 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1528 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1529 RHSIsKill, ShiftVal);
1532 unsigned RHSReg = getRegForValue(RHS);
1535 bool RHSIsKill = hasTrivialKill(RHS);
1537 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1538 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1539 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1540 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1541 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1546 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1547 unsigned LHSReg, bool LHSIsKill,
1549 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1550 "ISD nodes are not consecutive!");
1551 static const unsigned OpcTable[3][2] = {
1552 { AArch64::ANDWri, AArch64::ANDXri },
1553 { AArch64::ORRWri, AArch64::ORRXri },
1554 { AArch64::EORWri, AArch64::EORXri }
1556 const TargetRegisterClass *RC;
1559 switch (RetVT.SimpleTy) {
1566 unsigned Idx = ISDOpc - ISD::AND;
1567 Opc = OpcTable[Idx][0];
1568 RC = &AArch64::GPR32spRegClass;
1573 Opc = OpcTable[ISDOpc - ISD::AND][1];
1574 RC = &AArch64::GPR64spRegClass;
1579 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1582 unsigned ResultReg =
1583 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1584 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1585 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1586 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1587 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1592 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1593 unsigned LHSReg, bool LHSIsKill,
1594 unsigned RHSReg, bool RHSIsKill,
1595 uint64_t ShiftImm) {
1596 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1597 "ISD nodes are not consecutive!");
1598 static const unsigned OpcTable[3][2] = {
1599 { AArch64::ANDWrs, AArch64::ANDXrs },
1600 { AArch64::ORRWrs, AArch64::ORRXrs },
1601 { AArch64::EORWrs, AArch64::EORXrs }
1603 const TargetRegisterClass *RC;
1605 switch (RetVT.SimpleTy) {
1612 Opc = OpcTable[ISDOpc - ISD::AND][0];
1613 RC = &AArch64::GPR32RegClass;
1616 Opc = OpcTable[ISDOpc - ISD::AND][1];
1617 RC = &AArch64::GPR64RegClass;
1620 unsigned ResultReg =
1621 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1622 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1623 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1624 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1625 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1630 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1632 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1635 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1636 bool WantZExt, MachineMemOperand *MMO) {
1637 // Simplify this down to something we can handle.
1638 if (!simplifyAddress(Addr, VT))
1641 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1643 llvm_unreachable("Unexpected value type.");
1645 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1646 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1647 bool UseScaled = true;
1648 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1653 static const unsigned GPOpcTable[2][8][4] = {
1655 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1657 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1659 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1661 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1663 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1665 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1667 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1669 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1673 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1675 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1677 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1679 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1681 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1683 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1685 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1687 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1692 static const unsigned FPOpcTable[4][2] = {
1693 { AArch64::LDURSi, AArch64::LDURDi },
1694 { AArch64::LDRSui, AArch64::LDRDui },
1695 { AArch64::LDRSroX, AArch64::LDRDroX },
1696 { AArch64::LDRSroW, AArch64::LDRDroW }
1700 const TargetRegisterClass *RC;
1701 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1702 Addr.getOffsetReg();
1703 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1704 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1705 Addr.getExtendType() == AArch64_AM::SXTW)
1708 bool IsRet64Bit = RetVT == MVT::i64;
1709 switch (VT.SimpleTy) {
1711 llvm_unreachable("Unexpected value type.");
1712 case MVT::i1: // Intentional fall-through.
1714 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1715 RC = (IsRet64Bit && !WantZExt) ?
1716 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1719 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1720 RC = (IsRet64Bit && !WantZExt) ?
1721 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1724 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1725 RC = (IsRet64Bit && !WantZExt) ?
1726 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1729 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1730 RC = &AArch64::GPR64RegClass;
1733 Opc = FPOpcTable[Idx][0];
1734 RC = &AArch64::FPR32RegClass;
1737 Opc = FPOpcTable[Idx][1];
1738 RC = &AArch64::FPR64RegClass;
1742 // Create the base instruction, then add the operands.
1743 unsigned ResultReg = createResultReg(RC);
1744 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1745 TII.get(Opc), ResultReg);
1746 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1748 // Loading an i1 requires special handling.
1749 if (VT == MVT::i1) {
1750 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1751 assert(ANDReg && "Unexpected AND instruction emission failure.");
1755 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1756 // the 32bit reg to a 64bit reg.
1757 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1758 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1759 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1760 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1762 .addReg(ResultReg, getKillRegState(true))
1763 .addImm(AArch64::sub_32);
1769 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1771 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1775 return selectOperator(I, I->getOpcode());
1778 switch (I->getOpcode()) {
1780 llvm_unreachable("Unexpected instruction.");
1781 case Instruction::Add:
1782 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1784 case Instruction::Sub:
1785 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1791 updateValueMap(I, ResultReg);
1795 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1797 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1801 return selectOperator(I, I->getOpcode());
1804 switch (I->getOpcode()) {
1806 llvm_unreachable("Unexpected instruction.");
1807 case Instruction::And:
1808 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1810 case Instruction::Or:
1811 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1813 case Instruction::Xor:
1814 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1820 updateValueMap(I, ResultReg);
1824 bool AArch64FastISel::selectLoad(const Instruction *I) {
1826 // Verify we have a legal type before going any further. Currently, we handle
1827 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1828 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1829 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1830 cast<LoadInst>(I)->isAtomic())
1833 // See if we can handle this address.
1835 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1838 // Fold the following sign-/zero-extend into the load instruction.
1839 bool WantZExt = true;
1841 const Value *IntExtVal = nullptr;
1842 if (I->hasOneUse()) {
1843 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1844 if (isTypeSupported(ZE->getType(), RetVT))
1848 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1849 if (isTypeSupported(SE->getType(), RetVT))
1857 unsigned ResultReg =
1858 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1862 // There are a few different cases we have to handle, because the load or the
1863 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1864 // SelectionDAG. There is also an ordering issue when both instructions are in
1865 // different basic blocks.
1866 // 1.) The load instruction is selected by FastISel, but the integer extend
1867 // not. This usually happens when the integer extend is in a different
1868 // basic block and SelectionDAG took over for that basic block.
1869 // 2.) The load instruction is selected before the integer extend. This only
1870 // happens when the integer extend is in a different basic block.
1871 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1872 // by FastISel. This happens if there are instructions between the load
1873 // and the integer extend that couldn't be selected by FastISel.
1875 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1876 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1877 // it when it selects the integer extend.
1878 unsigned Reg = lookUpRegForValue(IntExtVal);
1880 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1882 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1883 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1884 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1886 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1890 updateValueMap(I, ResultReg);
1894 // The integer extend has already been emitted - delete all the instructions
1895 // that have been emitted by the integer extend lowering code and use the
1896 // result from the load instruction directly.
1898 auto *MI = MRI.getUniqueVRegDef(Reg);
1902 for (auto &Opnd : MI->uses()) {
1904 Reg = Opnd.getReg();
1908 MI->eraseFromParent();
1910 updateValueMap(IntExtVal, ResultReg);
1914 updateValueMap(I, ResultReg);
1918 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1919 MachineMemOperand *MMO) {
1920 // Simplify this down to something we can handle.
1921 if (!simplifyAddress(Addr, VT))
1924 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1926 llvm_unreachable("Unexpected value type.");
1928 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1929 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1930 bool UseScaled = true;
1931 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1936 static const unsigned OpcTable[4][6] = {
1937 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1938 AArch64::STURSi, AArch64::STURDi },
1939 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1940 AArch64::STRSui, AArch64::STRDui },
1941 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1942 AArch64::STRSroX, AArch64::STRDroX },
1943 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1944 AArch64::STRSroW, AArch64::STRDroW }
1948 bool VTIsi1 = false;
1949 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1950 Addr.getOffsetReg();
1951 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1952 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1953 Addr.getExtendType() == AArch64_AM::SXTW)
1956 switch (VT.SimpleTy) {
1957 default: llvm_unreachable("Unexpected value type.");
1958 case MVT::i1: VTIsi1 = true;
1959 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1960 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1961 case MVT::i32: Opc = OpcTable[Idx][2]; break;
1962 case MVT::i64: Opc = OpcTable[Idx][3]; break;
1963 case MVT::f32: Opc = OpcTable[Idx][4]; break;
1964 case MVT::f64: Opc = OpcTable[Idx][5]; break;
1967 // Storing an i1 requires special handling.
1968 if (VTIsi1 && SrcReg != AArch64::WZR) {
1969 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1970 assert(ANDReg && "Unexpected AND instruction emission failure.");
1973 // Create the base instruction, then add the operands.
1974 const MCInstrDesc &II = TII.get(Opc);
1975 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
1976 MachineInstrBuilder MIB =
1977 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
1978 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
1983 bool AArch64FastISel::selectStore(const Instruction *I) {
1985 const Value *Op0 = I->getOperand(0);
1986 // Verify we have a legal type before going any further. Currently, we handle
1987 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1988 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1989 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
1990 cast<StoreInst>(I)->isAtomic())
1993 // Get the value to be stored into a register. Use the zero register directly
1994 // when possible to avoid an unnecessary copy and a wasted register.
1995 unsigned SrcReg = 0;
1996 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
1998 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
1999 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2000 if (CF->isZero() && !CF->isNegative()) {
2001 VT = MVT::getIntegerVT(VT.getSizeInBits());
2002 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2007 SrcReg = getRegForValue(Op0);
2012 // See if we can handle this address.
2014 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2017 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2022 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2024 case CmpInst::FCMP_ONE:
2025 case CmpInst::FCMP_UEQ:
2027 // AL is our "false" for now. The other two need more compares.
2028 return AArch64CC::AL;
2029 case CmpInst::ICMP_EQ:
2030 case CmpInst::FCMP_OEQ:
2031 return AArch64CC::EQ;
2032 case CmpInst::ICMP_SGT:
2033 case CmpInst::FCMP_OGT:
2034 return AArch64CC::GT;
2035 case CmpInst::ICMP_SGE:
2036 case CmpInst::FCMP_OGE:
2037 return AArch64CC::GE;
2038 case CmpInst::ICMP_UGT:
2039 case CmpInst::FCMP_UGT:
2040 return AArch64CC::HI;
2041 case CmpInst::FCMP_OLT:
2042 return AArch64CC::MI;
2043 case CmpInst::ICMP_ULE:
2044 case CmpInst::FCMP_OLE:
2045 return AArch64CC::LS;
2046 case CmpInst::FCMP_ORD:
2047 return AArch64CC::VC;
2048 case CmpInst::FCMP_UNO:
2049 return AArch64CC::VS;
2050 case CmpInst::FCMP_UGE:
2051 return AArch64CC::PL;
2052 case CmpInst::ICMP_SLT:
2053 case CmpInst::FCMP_ULT:
2054 return AArch64CC::LT;
2055 case CmpInst::ICMP_SLE:
2056 case CmpInst::FCMP_ULE:
2057 return AArch64CC::LE;
2058 case CmpInst::FCMP_UNE:
2059 case CmpInst::ICMP_NE:
2060 return AArch64CC::NE;
2061 case CmpInst::ICMP_UGE:
2062 return AArch64CC::HS;
2063 case CmpInst::ICMP_ULT:
2064 return AArch64CC::LO;
2068 /// \brief Try to emit a combined compare-and-branch instruction.
2069 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2070 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2071 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2072 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2074 const Value *LHS = CI->getOperand(0);
2075 const Value *RHS = CI->getOperand(1);
2077 Type *Ty = LHS->getType();
2078 if (!Ty->isIntegerTy())
2081 unsigned BW = cast<IntegerType>(Ty)->getBitWidth();
2082 if (BW != 1 && BW != 8 && BW != 16 && BW != 32 && BW != 64)
2085 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2086 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2088 // Try to take advantage of fallthrough opportunities.
2089 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2090 std::swap(TBB, FBB);
2091 Predicate = CmpInst::getInversePredicate(Predicate);
2096 if ((Predicate == CmpInst::ICMP_EQ) || (Predicate == CmpInst::ICMP_NE)) {
2097 if (const auto *C = dyn_cast<ConstantInt>(LHS))
2098 if (C->isNullValue())
2099 std::swap(LHS, RHS);
2101 if (!isa<ConstantInt>(RHS))
2104 if (!cast<ConstantInt>(RHS)->isNullValue())
2107 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2108 if (AI->getOpcode() == Instruction::And) {
2109 const Value *AndLHS = AI->getOperand(0);
2110 const Value *AndRHS = AI->getOperand(1);
2112 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2113 if (C->getValue().isPowerOf2())
2114 std::swap(AndLHS, AndRHS);
2116 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2117 if (C->getValue().isPowerOf2()) {
2118 TestBit = C->getValue().logBase2();
2122 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2123 } else if (Predicate == CmpInst::ICMP_SLT) {
2124 if (!isa<ConstantInt>(RHS))
2127 if (!cast<ConstantInt>(RHS)->isNullValue())
2132 } else if (Predicate == CmpInst::ICMP_SGT) {
2133 if (!isa<ConstantInt>(RHS))
2136 if (cast<ConstantInt>(RHS)->getValue() != -1)
2144 static const unsigned OpcTable[2][2][2] = {
2145 { {AArch64::CBZW, AArch64::CBZX },
2146 {AArch64::CBNZW, AArch64::CBNZX} },
2147 { {AArch64::TBZW, AArch64::TBZX },
2148 {AArch64::TBNZW, AArch64::TBNZX} }
2151 bool IsBitTest = TestBit != -1;
2152 bool Is64Bit = BW == 64;
2153 if (TestBit < 32 && TestBit >= 0)
2156 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2157 const MCInstrDesc &II = TII.get(Opc);
2159 unsigned SrcReg = getRegForValue(LHS);
2162 bool SrcIsKill = hasTrivialKill(LHS);
2164 if (BW == 64 && !Is64Bit)
2165 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2168 // Emit the combined compare and branch instruction.
2169 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2170 MachineInstrBuilder MIB =
2171 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2172 .addReg(SrcReg, getKillRegState(SrcIsKill));
2174 MIB.addImm(TestBit);
2177 // Obtain the branch weight and add the TrueBB to the successor list.
2178 uint32_t BranchWeight = 0;
2180 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2181 TBB->getBasicBlock());
2182 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2183 fastEmitBranch(FBB, DbgLoc);
2188 bool AArch64FastISel::selectBranch(const Instruction *I) {
2189 const BranchInst *BI = cast<BranchInst>(I);
2190 if (BI->isUnconditional()) {
2191 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2192 fastEmitBranch(MSucc, BI->getDebugLoc());
2196 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2197 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2199 AArch64CC::CondCode CC = AArch64CC::NE;
2200 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2201 if (CI->hasOneUse() && isValueAvailable(CI)) {
2202 // Try to optimize or fold the cmp.
2203 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2204 switch (Predicate) {
2207 case CmpInst::FCMP_FALSE:
2208 fastEmitBranch(FBB, DbgLoc);
2210 case CmpInst::FCMP_TRUE:
2211 fastEmitBranch(TBB, DbgLoc);
2215 // Try to emit a combined compare-and-branch first.
2216 if (emitCompareAndBranch(BI))
2219 // Try to take advantage of fallthrough opportunities.
2220 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2221 std::swap(TBB, FBB);
2222 Predicate = CmpInst::getInversePredicate(Predicate);
2226 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2229 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2231 CC = getCompareCC(Predicate);
2232 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2233 switch (Predicate) {
2236 case CmpInst::FCMP_UEQ:
2237 ExtraCC = AArch64CC::EQ;
2240 case CmpInst::FCMP_ONE:
2241 ExtraCC = AArch64CC::MI;
2245 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2247 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2248 if (ExtraCC != AArch64CC::AL) {
2249 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2255 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2259 // Obtain the branch weight and add the TrueBB to the successor list.
2260 uint32_t BranchWeight = 0;
2262 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2263 TBB->getBasicBlock());
2264 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2266 fastEmitBranch(FBB, DbgLoc);
2269 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2271 if (TI->hasOneUse() && isValueAvailable(TI) &&
2272 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2273 unsigned CondReg = getRegForValue(TI->getOperand(0));
2276 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2278 // Issue an extract_subreg to get the lower 32-bits.
2279 if (SrcVT == MVT::i64) {
2280 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2285 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2286 assert(ANDReg && "Unexpected AND instruction emission failure.");
2287 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2289 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2290 std::swap(TBB, FBB);
2293 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2297 // Obtain the branch weight and add the TrueBB to the successor list.
2298 uint32_t BranchWeight = 0;
2300 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2301 TBB->getBasicBlock());
2302 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2304 fastEmitBranch(FBB, DbgLoc);
2307 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2308 uint64_t Imm = CI->getZExtValue();
2309 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2310 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2313 // Obtain the branch weight and add the target to the successor list.
2314 uint32_t BranchWeight = 0;
2316 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2317 Target->getBasicBlock());
2318 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2320 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2321 // Fake request the condition, otherwise the intrinsic might be completely
2323 unsigned CondReg = getRegForValue(BI->getCondition());
2328 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2332 // Obtain the branch weight and add the TrueBB to the successor list.
2333 uint32_t BranchWeight = 0;
2335 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2336 TBB->getBasicBlock());
2337 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2339 fastEmitBranch(FBB, DbgLoc);
2343 unsigned CondReg = getRegForValue(BI->getCondition());
2346 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2348 // We've been divorced from our compare! Our block was split, and
2349 // now our compare lives in a predecessor block. We musn't
2350 // re-compare here, as the children of the compare aren't guaranteed
2351 // live across the block boundary (we *could* check for this).
2352 // Regardless, the compare has been done in the predecessor block,
2353 // and it left a value for us in a virtual register. Ergo, we test
2354 // the one-bit value left in the virtual register.
2355 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2357 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2358 std::swap(TBB, FBB);
2362 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2366 // Obtain the branch weight and add the TrueBB to the successor list.
2367 uint32_t BranchWeight = 0;
2369 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2370 TBB->getBasicBlock());
2371 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2373 fastEmitBranch(FBB, DbgLoc);
2377 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2378 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2379 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2383 // Emit the indirect branch.
2384 const MCInstrDesc &II = TII.get(AArch64::BR);
2385 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2386 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2388 // Make sure the CFG is up-to-date.
2389 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2390 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2395 bool AArch64FastISel::selectCmp(const Instruction *I) {
2396 const CmpInst *CI = cast<CmpInst>(I);
2398 // Try to optimize or fold the cmp.
2399 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2400 unsigned ResultReg = 0;
2401 switch (Predicate) {
2404 case CmpInst::FCMP_FALSE:
2405 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2406 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2407 TII.get(TargetOpcode::COPY), ResultReg)
2408 .addReg(AArch64::WZR, getKillRegState(true));
2410 case CmpInst::FCMP_TRUE:
2411 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2416 updateValueMap(I, ResultReg);
2421 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2424 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2426 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2427 // condition codes are inverted, because they are used by CSINC.
2428 static unsigned CondCodeTable[2][2] = {
2429 { AArch64CC::NE, AArch64CC::VC },
2430 { AArch64CC::PL, AArch64CC::LE }
2432 unsigned *CondCodes = nullptr;
2433 switch (Predicate) {
2436 case CmpInst::FCMP_UEQ:
2437 CondCodes = &CondCodeTable[0][0];
2439 case CmpInst::FCMP_ONE:
2440 CondCodes = &CondCodeTable[1][0];
2445 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2446 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2448 .addReg(AArch64::WZR, getKillRegState(true))
2449 .addReg(AArch64::WZR, getKillRegState(true))
2450 .addImm(CondCodes[0]);
2451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2453 .addReg(TmpReg1, getKillRegState(true))
2454 .addReg(AArch64::WZR, getKillRegState(true))
2455 .addImm(CondCodes[1]);
2457 updateValueMap(I, ResultReg);
2461 // Now set a register based on the comparison.
2462 AArch64CC::CondCode CC = getCompareCC(Predicate);
2463 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2464 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2465 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2467 .addReg(AArch64::WZR, getKillRegState(true))
2468 .addReg(AArch64::WZR, getKillRegState(true))
2469 .addImm(invertedCC);
2471 updateValueMap(I, ResultReg);
2475 bool AArch64FastISel::selectSelect(const Instruction *I) {
2476 const SelectInst *SI = cast<SelectInst>(I);
2478 EVT DestEVT = TLI.getValueType(SI->getType(), true);
2479 if (!DestEVT.isSimple())
2482 MVT DestVT = DestEVT.getSimpleVT();
2483 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
2488 const TargetRegisterClass *RC = nullptr;
2489 switch (DestVT.SimpleTy) {
2490 default: return false;
2492 SelectOpc = AArch64::CSELWr; RC = &AArch64::GPR32RegClass; break;
2494 SelectOpc = AArch64::CSELXr; RC = &AArch64::GPR64RegClass; break;
2496 SelectOpc = AArch64::FCSELSrrr; RC = &AArch64::FPR32RegClass; break;
2498 SelectOpc = AArch64::FCSELDrrr; RC = &AArch64::FPR64RegClass; break;
2501 const Value *Cond = SI->getCondition();
2502 bool NeedTest = true;
2503 AArch64CC::CondCode CC = AArch64CC::NE;
2504 if (foldXALUIntrinsic(CC, I, Cond))
2507 unsigned CondReg = getRegForValue(Cond);
2510 bool CondIsKill = hasTrivialKill(Cond);
2513 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2514 assert(ANDReg && "Unexpected AND instruction emission failure.");
2515 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2518 unsigned TrueReg = getRegForValue(SI->getTrueValue());
2519 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
2521 unsigned FalseReg = getRegForValue(SI->getFalseValue());
2522 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
2524 if (!TrueReg || !FalseReg)
2527 unsigned ResultReg = fastEmitInst_rri(SelectOpc, RC, TrueReg, TrueIsKill,
2528 FalseReg, FalseIsKill, CC);
2529 updateValueMap(I, ResultReg);
2533 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2534 Value *V = I->getOperand(0);
2535 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2538 unsigned Op = getRegForValue(V);
2542 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2543 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2544 ResultReg).addReg(Op);
2545 updateValueMap(I, ResultReg);
2549 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2550 Value *V = I->getOperand(0);
2551 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2554 unsigned Op = getRegForValue(V);
2558 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2559 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2560 ResultReg).addReg(Op);
2561 updateValueMap(I, ResultReg);
2565 // FPToUI and FPToSI
2566 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2568 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2571 unsigned SrcReg = getRegForValue(I->getOperand(0));
2575 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2576 if (SrcVT == MVT::f128)
2580 if (SrcVT == MVT::f64) {
2582 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2584 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2587 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2589 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2591 unsigned ResultReg = createResultReg(
2592 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2593 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2595 updateValueMap(I, ResultReg);
2599 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2601 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2603 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2604 "Unexpected value type.");
2606 unsigned SrcReg = getRegForValue(I->getOperand(0));
2609 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2611 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2613 // Handle sign-extension.
2614 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2616 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2623 if (SrcVT == MVT::i64) {
2625 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2627 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2630 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2632 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2635 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2637 updateValueMap(I, ResultReg);
2641 bool AArch64FastISel::fastLowerArguments() {
2642 if (!FuncInfo.CanLowerReturn)
2645 const Function *F = FuncInfo.Fn;
2649 CallingConv::ID CC = F->getCallingConv();
2650 if (CC != CallingConv::C)
2653 // Only handle simple cases of up to 8 GPR and FPR each.
2654 unsigned GPRCnt = 0;
2655 unsigned FPRCnt = 0;
2657 for (auto const &Arg : F->args()) {
2658 // The first argument is at index 1.
2660 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2661 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2662 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2663 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2666 Type *ArgTy = Arg.getType();
2667 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2670 EVT ArgVT = TLI.getValueType(ArgTy);
2671 if (!ArgVT.isSimple())
2674 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2675 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2678 if (VT.isVector() &&
2679 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2682 if (VT >= MVT::i1 && VT <= MVT::i64)
2684 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2685 VT.is128BitVector())
2690 if (GPRCnt > 8 || FPRCnt > 8)
2694 static const MCPhysReg Registers[6][8] = {
2695 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2696 AArch64::W5, AArch64::W6, AArch64::W7 },
2697 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2698 AArch64::X5, AArch64::X6, AArch64::X7 },
2699 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2700 AArch64::H5, AArch64::H6, AArch64::H7 },
2701 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2702 AArch64::S5, AArch64::S6, AArch64::S7 },
2703 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2704 AArch64::D5, AArch64::D6, AArch64::D7 },
2705 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2706 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2709 unsigned GPRIdx = 0;
2710 unsigned FPRIdx = 0;
2711 for (auto const &Arg : F->args()) {
2712 MVT VT = TLI.getSimpleValueType(Arg.getType());
2714 const TargetRegisterClass *RC;
2715 if (VT >= MVT::i1 && VT <= MVT::i32) {
2716 SrcReg = Registers[0][GPRIdx++];
2717 RC = &AArch64::GPR32RegClass;
2719 } else if (VT == MVT::i64) {
2720 SrcReg = Registers[1][GPRIdx++];
2721 RC = &AArch64::GPR64RegClass;
2722 } else if (VT == MVT::f16) {
2723 SrcReg = Registers[2][FPRIdx++];
2724 RC = &AArch64::FPR16RegClass;
2725 } else if (VT == MVT::f32) {
2726 SrcReg = Registers[3][FPRIdx++];
2727 RC = &AArch64::FPR32RegClass;
2728 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2729 SrcReg = Registers[4][FPRIdx++];
2730 RC = &AArch64::FPR64RegClass;
2731 } else if (VT.is128BitVector()) {
2732 SrcReg = Registers[5][FPRIdx++];
2733 RC = &AArch64::FPR128RegClass;
2735 llvm_unreachable("Unexpected value type.");
2737 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2738 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2739 // Without this, EmitLiveInCopies may eliminate the livein if its only
2740 // use is a bitcast (which isn't turned into an instruction).
2741 unsigned ResultReg = createResultReg(RC);
2742 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2743 TII.get(TargetOpcode::COPY), ResultReg)
2744 .addReg(DstReg, getKillRegState(true));
2745 updateValueMap(&Arg, ResultReg);
2750 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2751 SmallVectorImpl<MVT> &OutVTs,
2752 unsigned &NumBytes) {
2753 CallingConv::ID CC = CLI.CallConv;
2754 SmallVector<CCValAssign, 16> ArgLocs;
2755 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2756 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2758 // Get a count of how many bytes are to be pushed on the stack.
2759 NumBytes = CCInfo.getNextStackOffset();
2761 // Issue CALLSEQ_START
2762 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2763 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2766 // Process the args.
2767 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2768 CCValAssign &VA = ArgLocs[i];
2769 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2770 MVT ArgVT = OutVTs[VA.getValNo()];
2772 unsigned ArgReg = getRegForValue(ArgVal);
2776 // Handle arg promotion: SExt, ZExt, AExt.
2777 switch (VA.getLocInfo()) {
2778 case CCValAssign::Full:
2780 case CCValAssign::SExt: {
2781 MVT DestVT = VA.getLocVT();
2783 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2788 case CCValAssign::AExt:
2789 // Intentional fall-through.
2790 case CCValAssign::ZExt: {
2791 MVT DestVT = VA.getLocVT();
2793 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2799 llvm_unreachable("Unknown arg promotion!");
2802 // Now copy/store arg to correct locations.
2803 if (VA.isRegLoc() && !VA.needsCustom()) {
2804 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2805 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2806 CLI.OutRegs.push_back(VA.getLocReg());
2807 } else if (VA.needsCustom()) {
2808 // FIXME: Handle custom args.
2811 assert(VA.isMemLoc() && "Assuming store on stack.");
2813 // Don't emit stores for undef values.
2814 if (isa<UndefValue>(ArgVal))
2817 // Need to store on the stack.
2818 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2820 unsigned BEAlign = 0;
2821 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2822 BEAlign = 8 - ArgSize;
2825 Addr.setKind(Address::RegBase);
2826 Addr.setReg(AArch64::SP);
2827 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2829 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2830 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2831 MachinePointerInfo::getStack(Addr.getOffset()),
2832 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2834 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2841 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2842 unsigned NumBytes) {
2843 CallingConv::ID CC = CLI.CallConv;
2845 // Issue CALLSEQ_END
2846 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2847 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2848 .addImm(NumBytes).addImm(0);
2850 // Now the return value.
2851 if (RetVT != MVT::isVoid) {
2852 SmallVector<CCValAssign, 16> RVLocs;
2853 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2854 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
2856 // Only handle a single return value.
2857 if (RVLocs.size() != 1)
2860 // Copy all of the result registers out of their specified physreg.
2861 MVT CopyVT = RVLocs[0].getValVT();
2862 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
2863 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2864 TII.get(TargetOpcode::COPY), ResultReg)
2865 .addReg(RVLocs[0].getLocReg());
2866 CLI.InRegs.push_back(RVLocs[0].getLocReg());
2868 CLI.ResultReg = ResultReg;
2869 CLI.NumResultRegs = 1;
2875 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2876 CallingConv::ID CC = CLI.CallConv;
2877 bool IsTailCall = CLI.IsTailCall;
2878 bool IsVarArg = CLI.IsVarArg;
2879 const Value *Callee = CLI.Callee;
2880 const char *SymName = CLI.SymName;
2882 if (!Callee && !SymName)
2885 // Allow SelectionDAG isel to handle tail calls.
2889 CodeModel::Model CM = TM.getCodeModel();
2890 // Only support the small and large code model.
2891 if (CM != CodeModel::Small && CM != CodeModel::Large)
2894 // FIXME: Add large code model support for ELF.
2895 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
2898 // Let SDISel handle vararg functions.
2902 // FIXME: Only handle *simple* calls for now.
2904 if (CLI.RetTy->isVoidTy())
2905 RetVT = MVT::isVoid;
2906 else if (!isTypeLegal(CLI.RetTy, RetVT))
2909 for (auto Flag : CLI.OutFlags)
2910 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
2913 // Set up the argument vectors.
2914 SmallVector<MVT, 16> OutVTs;
2915 OutVTs.reserve(CLI.OutVals.size());
2917 for (auto *Val : CLI.OutVals) {
2919 if (!isTypeLegal(Val->getType(), VT) &&
2920 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
2923 // We don't handle vector parameters yet.
2924 if (VT.isVector() || VT.getSizeInBits() > 64)
2927 OutVTs.push_back(VT);
2931 if (Callee && !computeCallAddress(Callee, Addr))
2934 // Handle the arguments now that we've gotten them.
2936 if (!processCallArgs(CLI, OutVTs, NumBytes))
2940 MachineInstrBuilder MIB;
2941 if (CM == CodeModel::Small) {
2942 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
2943 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
2945 MIB.addExternalSymbol(SymName, 0);
2946 else if (Addr.getGlobalValue())
2947 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2948 else if (Addr.getReg()) {
2949 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
2954 unsigned CallReg = 0;
2956 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2959 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2961 CallReg = createResultReg(&AArch64::GPR64RegClass);
2962 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
2965 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
2967 } else if (Addr.getGlobalValue())
2968 CallReg = materializeGV(Addr.getGlobalValue());
2969 else if (Addr.getReg())
2970 CallReg = Addr.getReg();
2975 const MCInstrDesc &II = TII.get(AArch64::BLR);
2976 CallReg = constrainOperandRegClass(II, CallReg, 0);
2977 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
2980 // Add implicit physical register uses to the call.
2981 for (auto Reg : CLI.OutRegs)
2982 MIB.addReg(Reg, RegState::Implicit);
2984 // Add a register mask with the call-preserved registers.
2985 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2986 MIB.addRegMask(TRI.getCallPreservedMask(CC));
2990 // Finish off the call including any return values.
2991 return finishCall(CLI, RetVT, NumBytes);
2994 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
2996 return Len / Alignment <= 4;
3001 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3002 uint64_t Len, unsigned Alignment) {
3003 // Make sure we don't bloat code by inlining very large memcpy's.
3004 if (!isMemCpySmall(Len, Alignment))
3007 int64_t UnscaledOffset = 0;
3008 Address OrigDest = Dest;
3009 Address OrigSrc = Src;
3013 if (!Alignment || Alignment >= 8) {
3024 // Bound based on alignment.
3025 if (Len >= 4 && Alignment == 4)
3027 else if (Len >= 2 && Alignment == 2)
3034 unsigned ResultReg = emitLoad(VT, VT, Src);
3038 if (!emitStore(VT, ResultReg, Dest))
3041 int64_t Size = VT.getSizeInBits() / 8;
3043 UnscaledOffset += Size;
3045 // We need to recompute the unscaled offset for each iteration.
3046 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3047 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3053 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3054 /// into the user. The condition code will only be updated on success.
3055 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3056 const Instruction *I,
3057 const Value *Cond) {
3058 if (!isa<ExtractValueInst>(Cond))
3061 const auto *EV = cast<ExtractValueInst>(Cond);
3062 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3065 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3067 const Function *Callee = II->getCalledFunction();
3069 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3070 if (!isTypeLegal(RetTy, RetVT))
3073 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3076 const Value *LHS = II->getArgOperand(0);
3077 const Value *RHS = II->getArgOperand(1);
3079 // Canonicalize immediate to the RHS.
3080 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3081 isCommutativeIntrinsic(II))
3082 std::swap(LHS, RHS);
3084 // Simplify multiplies.
3085 unsigned IID = II->getIntrinsicID();
3089 case Intrinsic::smul_with_overflow:
3090 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3091 if (C->getValue() == 2)
3092 IID = Intrinsic::sadd_with_overflow;
3094 case Intrinsic::umul_with_overflow:
3095 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3096 if (C->getValue() == 2)
3097 IID = Intrinsic::uadd_with_overflow;
3101 AArch64CC::CondCode TmpCC;
3105 case Intrinsic::sadd_with_overflow:
3106 case Intrinsic::ssub_with_overflow:
3107 TmpCC = AArch64CC::VS;
3109 case Intrinsic::uadd_with_overflow:
3110 TmpCC = AArch64CC::HS;
3112 case Intrinsic::usub_with_overflow:
3113 TmpCC = AArch64CC::LO;
3115 case Intrinsic::smul_with_overflow:
3116 case Intrinsic::umul_with_overflow:
3117 TmpCC = AArch64CC::NE;
3121 // Check if both instructions are in the same basic block.
3122 if (!isValueAvailable(II))
3125 // Make sure nothing is in the way
3126 BasicBlock::const_iterator Start = I;
3127 BasicBlock::const_iterator End = II;
3128 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3129 // We only expect extractvalue instructions between the intrinsic and the
3130 // instruction to be selected.
3131 if (!isa<ExtractValueInst>(Itr))
3134 // Check that the extractvalue operand comes from the intrinsic.
3135 const auto *EVI = cast<ExtractValueInst>(Itr);
3136 if (EVI->getAggregateOperand() != II)
3144 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3145 // FIXME: Handle more intrinsics.
3146 switch (II->getIntrinsicID()) {
3147 default: return false;
3148 case Intrinsic::frameaddress: {
3149 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3150 MFI->setFrameAddressIsTaken(true);
3152 const AArch64RegisterInfo *RegInfo =
3153 static_cast<const AArch64RegisterInfo *>(
3154 TM.getSubtargetImpl()->getRegisterInfo());
3155 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3156 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3157 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3158 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3159 // Recursively load frame address
3165 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3167 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3168 SrcReg, /*IsKill=*/true, 0);
3169 assert(DestReg && "Unexpected LDR instruction emission failure.");
3173 updateValueMap(II, SrcReg);
3176 case Intrinsic::memcpy:
3177 case Intrinsic::memmove: {
3178 const auto *MTI = cast<MemTransferInst>(II);
3179 // Don't handle volatile.
3180 if (MTI->isVolatile())
3183 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3184 // we would emit dead code because we don't currently handle memmoves.
3185 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3186 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3187 // Small memcpy's are common enough that we want to do them without a call
3189 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3190 unsigned Alignment = MTI->getAlignment();
3191 if (isMemCpySmall(Len, Alignment)) {
3193 if (!computeAddress(MTI->getRawDest(), Dest) ||
3194 !computeAddress(MTI->getRawSource(), Src))
3196 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3201 if (!MTI->getLength()->getType()->isIntegerTy(64))
3204 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3205 // Fast instruction selection doesn't support the special
3209 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3210 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3212 case Intrinsic::memset: {
3213 const MemSetInst *MSI = cast<MemSetInst>(II);
3214 // Don't handle volatile.
3215 if (MSI->isVolatile())
3218 if (!MSI->getLength()->getType()->isIntegerTy(64))
3221 if (MSI->getDestAddressSpace() > 255)
3222 // Fast instruction selection doesn't support the special
3226 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3228 case Intrinsic::sin:
3229 case Intrinsic::cos:
3230 case Intrinsic::pow: {
3232 if (!isTypeLegal(II->getType(), RetVT))
3235 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3238 static const RTLIB::Libcall LibCallTable[3][2] = {
3239 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3240 { RTLIB::COS_F32, RTLIB::COS_F64 },
3241 { RTLIB::POW_F32, RTLIB::POW_F64 }
3244 bool Is64Bit = RetVT == MVT::f64;
3245 switch (II->getIntrinsicID()) {
3247 llvm_unreachable("Unexpected intrinsic.");
3248 case Intrinsic::sin:
3249 LC = LibCallTable[0][Is64Bit];
3251 case Intrinsic::cos:
3252 LC = LibCallTable[1][Is64Bit];
3254 case Intrinsic::pow:
3255 LC = LibCallTable[2][Is64Bit];
3260 Args.reserve(II->getNumArgOperands());
3262 // Populate the argument list.
3263 for (auto &Arg : II->arg_operands()) {
3266 Entry.Ty = Arg->getType();
3267 Args.push_back(Entry);
3270 CallLoweringInfo CLI;
3271 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3272 TLI.getLibcallName(LC), std::move(Args));
3273 if (!lowerCallTo(CLI))
3275 updateValueMap(II, CLI.ResultReg);
3278 case Intrinsic::trap: {
3279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3283 case Intrinsic::sqrt: {
3284 Type *RetTy = II->getCalledFunction()->getReturnType();
3287 if (!isTypeLegal(RetTy, VT))
3290 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3293 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3295 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3299 updateValueMap(II, ResultReg);
3302 case Intrinsic::sadd_with_overflow:
3303 case Intrinsic::uadd_with_overflow:
3304 case Intrinsic::ssub_with_overflow:
3305 case Intrinsic::usub_with_overflow:
3306 case Intrinsic::smul_with_overflow:
3307 case Intrinsic::umul_with_overflow: {
3308 // This implements the basic lowering of the xalu with overflow intrinsics.
3309 const Function *Callee = II->getCalledFunction();
3310 auto *Ty = cast<StructType>(Callee->getReturnType());
3311 Type *RetTy = Ty->getTypeAtIndex(0U);
3314 if (!isTypeLegal(RetTy, VT))
3317 if (VT != MVT::i32 && VT != MVT::i64)
3320 const Value *LHS = II->getArgOperand(0);
3321 const Value *RHS = II->getArgOperand(1);
3322 // Canonicalize immediate to the RHS.
3323 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3324 isCommutativeIntrinsic(II))
3325 std::swap(LHS, RHS);
3327 // Simplify multiplies.
3328 unsigned IID = II->getIntrinsicID();
3332 case Intrinsic::smul_with_overflow:
3333 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3334 if (C->getValue() == 2) {
3335 IID = Intrinsic::sadd_with_overflow;
3339 case Intrinsic::umul_with_overflow:
3340 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3341 if (C->getValue() == 2) {
3342 IID = Intrinsic::uadd_with_overflow;
3348 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3349 AArch64CC::CondCode CC = AArch64CC::Invalid;
3351 default: llvm_unreachable("Unexpected intrinsic!");
3352 case Intrinsic::sadd_with_overflow:
3353 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3356 case Intrinsic::uadd_with_overflow:
3357 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3360 case Intrinsic::ssub_with_overflow:
3361 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3364 case Intrinsic::usub_with_overflow:
3365 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3368 case Intrinsic::smul_with_overflow: {
3370 unsigned LHSReg = getRegForValue(LHS);
3373 bool LHSIsKill = hasTrivialKill(LHS);
3375 unsigned RHSReg = getRegForValue(RHS);
3378 bool RHSIsKill = hasTrivialKill(RHS);
3380 if (VT == MVT::i32) {
3381 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3382 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3383 /*IsKill=*/false, 32);
3384 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3386 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3388 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3389 AArch64_AM::ASR, 31, /*WantResult=*/false);
3391 assert(VT == MVT::i64 && "Unexpected value type.");
3392 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3393 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3395 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3396 AArch64_AM::ASR, 63, /*WantResult=*/false);
3400 case Intrinsic::umul_with_overflow: {
3402 unsigned LHSReg = getRegForValue(LHS);
3405 bool LHSIsKill = hasTrivialKill(LHS);
3407 unsigned RHSReg = getRegForValue(RHS);
3410 bool RHSIsKill = hasTrivialKill(RHS);
3412 if (VT == MVT::i32) {
3413 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3414 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3415 /*IsKill=*/false, AArch64_AM::LSR, 32,
3416 /*WantResult=*/false);
3417 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3420 assert(VT == MVT::i64 && "Unexpected value type.");
3421 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3422 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3424 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3425 /*IsKill=*/false, /*WantResult=*/false);
3432 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3434 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3437 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3438 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3439 /*IsKill=*/true, getInvertedCondCode(CC));
3441 assert((ResultReg1 + 1) == ResultReg2 &&
3442 "Nonconsecutive result registers.");
3443 updateValueMap(II, ResultReg1, 2);
3450 bool AArch64FastISel::selectRet(const Instruction *I) {
3451 const ReturnInst *Ret = cast<ReturnInst>(I);
3452 const Function &F = *I->getParent()->getParent();
3454 if (!FuncInfo.CanLowerReturn)
3460 // Build a list of return value registers.
3461 SmallVector<unsigned, 4> RetRegs;
3463 if (Ret->getNumOperands() > 0) {
3464 CallingConv::ID CC = F.getCallingConv();
3465 SmallVector<ISD::OutputArg, 4> Outs;
3466 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3468 // Analyze operands of the call, assigning locations to each operand.
3469 SmallVector<CCValAssign, 16> ValLocs;
3470 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3471 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3472 : RetCC_AArch64_AAPCS;
3473 CCInfo.AnalyzeReturn(Outs, RetCC);
3475 // Only handle a single return value for now.
3476 if (ValLocs.size() != 1)
3479 CCValAssign &VA = ValLocs[0];
3480 const Value *RV = Ret->getOperand(0);
3482 // Don't bother handling odd stuff for now.
3483 if ((VA.getLocInfo() != CCValAssign::Full) &&
3484 (VA.getLocInfo() != CCValAssign::BCvt))
3487 // Only handle register returns for now.
3491 unsigned Reg = getRegForValue(RV);
3495 unsigned SrcReg = Reg + VA.getValNo();
3496 unsigned DestReg = VA.getLocReg();
3497 // Avoid a cross-class copy. This is very unlikely.
3498 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3501 EVT RVEVT = TLI.getValueType(RV->getType());
3502 if (!RVEVT.isSimple())
3505 // Vectors (of > 1 lane) in big endian need tricky handling.
3506 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3507 !Subtarget->isLittleEndian())
3510 MVT RVVT = RVEVT.getSimpleVT();
3511 if (RVVT == MVT::f128)
3514 MVT DestVT = VA.getValVT();
3515 // Special handling for extended integers.
3516 if (RVVT != DestVT) {
3517 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3520 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3523 bool IsZExt = Outs[0].Flags.isZExt();
3524 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3530 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3531 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3533 // Add register to return instruction.
3534 RetRegs.push_back(VA.getLocReg());
3537 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3538 TII.get(AArch64::RET_ReallyLR));
3539 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3540 MIB.addReg(RetRegs[i], RegState::Implicit);
3544 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3545 Type *DestTy = I->getType();
3546 Value *Op = I->getOperand(0);
3547 Type *SrcTy = Op->getType();
3549 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3550 EVT DestEVT = TLI.getValueType(DestTy, true);
3551 if (!SrcEVT.isSimple())
3553 if (!DestEVT.isSimple())
3556 MVT SrcVT = SrcEVT.getSimpleVT();
3557 MVT DestVT = DestEVT.getSimpleVT();
3559 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3562 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3566 unsigned SrcReg = getRegForValue(Op);
3569 bool SrcIsKill = hasTrivialKill(Op);
3571 // If we're truncating from i64 to a smaller non-legal type then generate an
3572 // AND. Otherwise, we know the high bits are undefined and a truncate only
3573 // generate a COPY. We cannot mark the source register also as result
3574 // register, because this can incorrectly transfer the kill flag onto the
3577 if (SrcVT == MVT::i64) {
3579 switch (DestVT.SimpleTy) {
3581 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3593 // Issue an extract_subreg to get the lower 32-bits.
3594 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3596 // Create the AND instruction which performs the actual truncation.
3597 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3598 assert(ResultReg && "Unexpected AND instruction emission failure.");
3600 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3601 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3602 TII.get(TargetOpcode::COPY), ResultReg)
3603 .addReg(SrcReg, getKillRegState(SrcIsKill));
3606 updateValueMap(I, ResultReg);
3610 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3611 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3612 DestVT == MVT::i64) &&
3613 "Unexpected value type.");
3614 // Handle i8 and i16 as i32.
3615 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3619 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3620 assert(ResultReg && "Unexpected AND instruction emission failure.");
3621 if (DestVT == MVT::i64) {
3622 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3623 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3624 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3625 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3626 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3629 .addImm(AArch64::sub_32);
3634 if (DestVT == MVT::i64) {
3635 // FIXME: We're SExt i1 to i64.
3638 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3639 /*TODO:IsKill=*/false, 0, 0);
3643 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3644 unsigned Op1, bool Op1IsKill) {
3646 switch (RetVT.SimpleTy) {
3652 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3654 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3657 const TargetRegisterClass *RC =
3658 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3659 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3660 /*IsKill=*/ZReg, true);
3663 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3664 unsigned Op1, bool Op1IsKill) {
3665 if (RetVT != MVT::i64)
3668 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3669 Op0, Op0IsKill, Op1, Op1IsKill,
3670 AArch64::XZR, /*IsKill=*/true);
3673 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3674 unsigned Op1, bool Op1IsKill) {
3675 if (RetVT != MVT::i64)
3678 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3679 Op0, Op0IsKill, Op1, Op1IsKill,
3680 AArch64::XZR, /*IsKill=*/true);
3683 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3684 unsigned Op1Reg, bool Op1IsKill) {
3686 bool NeedTrunc = false;
3688 switch (RetVT.SimpleTy) {
3690 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3691 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3692 case MVT::i32: Opc = AArch64::LSLVWr; break;
3693 case MVT::i64: Opc = AArch64::LSLVXr; break;
3696 const TargetRegisterClass *RC =
3697 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3699 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3702 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3705 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3709 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3710 bool Op0IsKill, uint64_t Shift,
3712 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3713 "Unexpected source/return type pair.");
3714 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3715 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3716 "Unexpected source value type.");
3717 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3718 RetVT == MVT::i64) && "Unexpected return value type.");
3720 bool Is64Bit = (RetVT == MVT::i64);
3721 unsigned RegSize = Is64Bit ? 64 : 32;
3722 unsigned DstBits = RetVT.getSizeInBits();
3723 unsigned SrcBits = SrcVT.getSizeInBits();
3725 // Don't deal with undefined shifts.
3726 if (Shift >= DstBits)
3729 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3730 // {S|U}BFM Wd, Wn, #r, #s
3731 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3733 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3734 // %2 = shl i16 %1, 4
3735 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3736 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3737 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3738 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3740 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3741 // %2 = shl i16 %1, 8
3742 // Wd<32+7-24,32-24> = Wn<7:0>
3743 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3744 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3745 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3747 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3748 // %2 = shl i16 %1, 12
3749 // Wd<32+3-20,32-20> = Wn<3:0>
3750 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3751 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3752 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3754 unsigned ImmR = RegSize - Shift;
3755 // Limit the width to the length of the source type.
3756 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3757 static const unsigned OpcTable[2][2] = {
3758 {AArch64::SBFMWri, AArch64::SBFMXri},
3759 {AArch64::UBFMWri, AArch64::UBFMXri}
3761 unsigned Opc = OpcTable[IsZext][Is64Bit];
3762 const TargetRegisterClass *RC =
3763 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3764 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3765 unsigned TmpReg = MRI.createVirtualRegister(RC);
3766 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3767 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3769 .addReg(Op0, getKillRegState(Op0IsKill))
3770 .addImm(AArch64::sub_32);
3774 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3777 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3778 unsigned Op1Reg, bool Op1IsKill) {
3780 bool NeedTrunc = false;
3782 switch (RetVT.SimpleTy) {
3784 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3785 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3786 case MVT::i32: Opc = AArch64::LSRVWr; break;
3787 case MVT::i64: Opc = AArch64::LSRVXr; break;
3790 const TargetRegisterClass *RC =
3791 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3793 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3794 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3795 Op0IsKill = Op1IsKill = true;
3797 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3800 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3804 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3805 bool Op0IsKill, uint64_t Shift,
3807 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3808 "Unexpected source/return type pair.");
3809 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3810 SrcVT == MVT::i64) && "Unexpected source value type.");
3811 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3812 RetVT == MVT::i64) && "Unexpected return value type.");
3814 bool Is64Bit = (RetVT == MVT::i64);
3815 unsigned RegSize = Is64Bit ? 64 : 32;
3816 unsigned DstBits = RetVT.getSizeInBits();
3817 unsigned SrcBits = SrcVT.getSizeInBits();
3819 // Don't deal with undefined shifts.
3820 if (Shift >= DstBits)
3823 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3824 // {S|U}BFM Wd, Wn, #r, #s
3825 // Wd<s-r:0> = Wn<s:r> when r <= s
3827 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3828 // %2 = lshr i16 %1, 4
3829 // Wd<7-4:0> = Wn<7:4>
3830 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
3831 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3832 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3834 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3835 // %2 = lshr i16 %1, 8
3836 // Wd<7-7,0> = Wn<7:7>
3837 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
3838 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3839 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3841 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3842 // %2 = lshr i16 %1, 12
3843 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3844 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
3845 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3846 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3848 if (Shift >= SrcBits && IsZExt)
3849 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3851 // It is not possible to fold a sign-extend into the LShr instruction. In this
3852 // case emit a sign-extend.
3854 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3859 SrcBits = SrcVT.getSizeInBits();
3863 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3864 unsigned ImmS = SrcBits - 1;
3865 static const unsigned OpcTable[2][2] = {
3866 {AArch64::SBFMWri, AArch64::SBFMXri},
3867 {AArch64::UBFMWri, AArch64::UBFMXri}
3869 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3870 const TargetRegisterClass *RC =
3871 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3872 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3873 unsigned TmpReg = MRI.createVirtualRegister(RC);
3874 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3875 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3877 .addReg(Op0, getKillRegState(Op0IsKill))
3878 .addImm(AArch64::sub_32);
3882 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3885 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3886 unsigned Op1Reg, bool Op1IsKill) {
3888 bool NeedTrunc = false;
3890 switch (RetVT.SimpleTy) {
3892 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
3893 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
3894 case MVT::i32: Opc = AArch64::ASRVWr; break;
3895 case MVT::i64: Opc = AArch64::ASRVXr; break;
3898 const TargetRegisterClass *RC =
3899 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3901 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
3902 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3903 Op0IsKill = Op1IsKill = true;
3905 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3908 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3912 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3913 bool Op0IsKill, uint64_t Shift,
3915 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3916 "Unexpected source/return type pair.");
3917 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3918 SrcVT == MVT::i64) && "Unexpected source value type.");
3919 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3920 RetVT == MVT::i64) && "Unexpected return value type.");
3922 bool Is64Bit = (RetVT == MVT::i64);
3923 unsigned RegSize = Is64Bit ? 64 : 32;
3924 unsigned DstBits = RetVT.getSizeInBits();
3925 unsigned SrcBits = SrcVT.getSizeInBits();
3927 // Don't deal with undefined shifts.
3928 if (Shift >= DstBits)
3931 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3932 // {S|U}BFM Wd, Wn, #r, #s
3933 // Wd<s-r:0> = Wn<s:r> when r <= s
3935 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3936 // %2 = ashr i16 %1, 4
3937 // Wd<7-4:0> = Wn<7:4>
3938 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
3939 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3940 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3942 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3943 // %2 = ashr i16 %1, 8
3944 // Wd<7-7,0> = Wn<7:7>
3945 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3946 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3947 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3949 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3950 // %2 = ashr i16 %1, 12
3951 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3952 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3953 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3954 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3956 if (Shift >= SrcBits && IsZExt)
3957 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3959 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3960 unsigned ImmS = SrcBits - 1;
3961 static const unsigned OpcTable[2][2] = {
3962 {AArch64::SBFMWri, AArch64::SBFMXri},
3963 {AArch64::UBFMWri, AArch64::UBFMXri}
3965 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3966 const TargetRegisterClass *RC =
3967 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3968 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3969 unsigned TmpReg = MRI.createVirtualRegister(RC);
3970 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3971 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3973 .addReg(Op0, getKillRegState(Op0IsKill))
3974 .addImm(AArch64::sub_32);
3978 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3981 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
3983 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
3985 // FastISel does not have plumbing to deal with extensions where the SrcVT or
3986 // DestVT are odd things, so test to make sure that they are both types we can
3987 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
3988 // bail out to SelectionDAG.
3989 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
3990 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
3991 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
3992 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
3998 switch (SrcVT.SimpleTy) {
4002 return emiti1Ext(SrcReg, DestVT, IsZExt);
4004 if (DestVT == MVT::i64)
4005 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4007 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4011 if (DestVT == MVT::i64)
4012 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4014 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4018 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4019 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4024 // Handle i8 and i16 as i32.
4025 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4027 else if (DestVT == MVT::i64) {
4028 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4029 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4030 TII.get(AArch64::SUBREG_TO_REG), Src64)
4033 .addImm(AArch64::sub_32);
4037 const TargetRegisterClass *RC =
4038 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4039 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4042 static bool isZExtLoad(const MachineInstr *LI) {
4043 switch (LI->getOpcode()) {
4046 case AArch64::LDURBBi:
4047 case AArch64::LDURHHi:
4048 case AArch64::LDURWi:
4049 case AArch64::LDRBBui:
4050 case AArch64::LDRHHui:
4051 case AArch64::LDRWui:
4052 case AArch64::LDRBBroX:
4053 case AArch64::LDRHHroX:
4054 case AArch64::LDRWroX:
4055 case AArch64::LDRBBroW:
4056 case AArch64::LDRHHroW:
4057 case AArch64::LDRWroW:
4062 static bool isSExtLoad(const MachineInstr *LI) {
4063 switch (LI->getOpcode()) {
4066 case AArch64::LDURSBWi:
4067 case AArch64::LDURSHWi:
4068 case AArch64::LDURSBXi:
4069 case AArch64::LDURSHXi:
4070 case AArch64::LDURSWi:
4071 case AArch64::LDRSBWui:
4072 case AArch64::LDRSHWui:
4073 case AArch64::LDRSBXui:
4074 case AArch64::LDRSHXui:
4075 case AArch64::LDRSWui:
4076 case AArch64::LDRSBWroX:
4077 case AArch64::LDRSHWroX:
4078 case AArch64::LDRSBXroX:
4079 case AArch64::LDRSHXroX:
4080 case AArch64::LDRSWroX:
4081 case AArch64::LDRSBWroW:
4082 case AArch64::LDRSHWroW:
4083 case AArch64::LDRSBXroW:
4084 case AArch64::LDRSHXroW:
4085 case AArch64::LDRSWroW:
4090 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4092 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4093 if (!LI || !LI->hasOneUse())
4096 // Check if the load instruction has already been selected.
4097 unsigned Reg = lookUpRegForValue(LI);
4101 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4105 // Check if the correct load instruction has been emitted - SelectionDAG might
4106 // have emitted a zero-extending load, but we need a sign-extending load.
4107 bool IsZExt = isa<ZExtInst>(I);
4108 const auto *LoadMI = MI;
4109 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4110 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4111 unsigned LoadReg = MI->getOperand(1).getReg();
4112 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4113 assert(LoadMI && "Expected valid instruction");
4115 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4118 // Nothing to be done.
4119 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4120 updateValueMap(I, Reg);
4125 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4126 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4127 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4129 .addReg(Reg, getKillRegState(true))
4130 .addImm(AArch64::sub_32);
4133 assert((MI->getOpcode() == TargetOpcode::COPY &&
4134 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4135 "Expected copy instruction");
4136 Reg = MI->getOperand(1).getReg();
4137 MI->eraseFromParent();
4139 updateValueMap(I, Reg);
4143 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4144 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4145 "Unexpected integer extend instruction.");
4148 if (!isTypeSupported(I->getType(), RetVT))
4151 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4154 // Try to optimize already sign-/zero-extended values from load instructions.
4155 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4158 unsigned SrcReg = getRegForValue(I->getOperand(0));
4161 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4163 // Try to optimize already sign-/zero-extended values from function arguments.
4164 bool IsZExt = isa<ZExtInst>(I);
4165 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4166 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4167 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4168 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4169 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4170 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4172 .addReg(SrcReg, getKillRegState(SrcIsKill))
4173 .addImm(AArch64::sub_32);
4176 updateValueMap(I, SrcReg);
4181 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4185 updateValueMap(I, ResultReg);
4189 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4190 EVT DestEVT = TLI.getValueType(I->getType(), true);
4191 if (!DestEVT.isSimple())
4194 MVT DestVT = DestEVT.getSimpleVT();
4195 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4199 bool Is64bit = (DestVT == MVT::i64);
4200 switch (ISDOpcode) {
4204 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4207 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4210 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4211 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4214 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4216 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4219 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4221 const TargetRegisterClass *RC =
4222 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4223 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4224 Src1Reg, /*IsKill=*/false);
4225 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4226 // The remainder is computed as numerator - (quotient * denominator) using the
4227 // MSUB instruction.
4228 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4229 Src1Reg, Src1IsKill, Src0Reg,
4231 updateValueMap(I, ResultReg);
4235 bool AArch64FastISel::selectMul(const Instruction *I) {
4237 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4241 return selectBinaryOp(I, ISD::MUL);
4243 const Value *Src0 = I->getOperand(0);
4244 const Value *Src1 = I->getOperand(1);
4245 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4246 if (C->getValue().isPowerOf2())
4247 std::swap(Src0, Src1);
4249 // Try to simplify to a shift instruction.
4250 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4251 if (C->getValue().isPowerOf2()) {
4252 uint64_t ShiftVal = C->getValue().logBase2();
4255 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4256 if (!isIntExtFree(ZExt)) {
4258 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4261 Src0 = ZExt->getOperand(0);
4264 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4265 if (!isIntExtFree(SExt)) {
4267 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4270 Src0 = SExt->getOperand(0);
4275 unsigned Src0Reg = getRegForValue(Src0);
4278 bool Src0IsKill = hasTrivialKill(Src0);
4280 unsigned ResultReg =
4281 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4284 updateValueMap(I, ResultReg);
4289 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4292 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4294 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4297 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4299 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4304 updateValueMap(I, ResultReg);
4308 bool AArch64FastISel::selectShift(const Instruction *I) {
4310 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4313 if (RetVT.isVector())
4314 return selectOperator(I, I->getOpcode());
4316 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4317 unsigned ResultReg = 0;
4318 uint64_t ShiftVal = C->getZExtValue();
4320 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
4321 const Value *Op0 = I->getOperand(0);
4322 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4323 if (!isIntExtFree(ZExt)) {
4325 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4328 Op0 = ZExt->getOperand(0);
4331 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4332 if (!isIntExtFree(SExt)) {
4334 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4337 Op0 = SExt->getOperand(0);
4342 unsigned Op0Reg = getRegForValue(Op0);
4345 bool Op0IsKill = hasTrivialKill(Op0);
4347 switch (I->getOpcode()) {
4348 default: llvm_unreachable("Unexpected instruction.");
4349 case Instruction::Shl:
4350 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4352 case Instruction::AShr:
4353 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4355 case Instruction::LShr:
4356 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4362 updateValueMap(I, ResultReg);
4366 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4369 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4371 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4374 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4376 unsigned ResultReg = 0;
4377 switch (I->getOpcode()) {
4378 default: llvm_unreachable("Unexpected instruction.");
4379 case Instruction::Shl:
4380 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4382 case Instruction::AShr:
4383 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4385 case Instruction::LShr:
4386 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4393 updateValueMap(I, ResultReg);
4397 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4400 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4402 if (!isTypeLegal(I->getType(), RetVT))
4406 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4407 Opc = AArch64::FMOVWSr;
4408 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4409 Opc = AArch64::FMOVXDr;
4410 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4411 Opc = AArch64::FMOVSWr;
4412 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4413 Opc = AArch64::FMOVDXr;
4417 const TargetRegisterClass *RC = nullptr;
4418 switch (RetVT.SimpleTy) {
4419 default: llvm_unreachable("Unexpected value type.");
4420 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4421 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4422 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4423 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4425 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4428 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4429 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4434 updateValueMap(I, ResultReg);
4438 bool AArch64FastISel::selectFRem(const Instruction *I) {
4440 if (!isTypeLegal(I->getType(), RetVT))
4444 switch (RetVT.SimpleTy) {
4448 LC = RTLIB::REM_F32;
4451 LC = RTLIB::REM_F64;
4456 Args.reserve(I->getNumOperands());
4458 // Populate the argument list.
4459 for (auto &Arg : I->operands()) {
4462 Entry.Ty = Arg->getType();
4463 Args.push_back(Entry);
4466 CallLoweringInfo CLI;
4467 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4468 TLI.getLibcallName(LC), std::move(Args));
4469 if (!lowerCallTo(CLI))
4471 updateValueMap(I, CLI.ResultReg);
4475 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4477 if (!isTypeLegal(I->getType(), VT))
4480 if (!isa<ConstantInt>(I->getOperand(1)))
4481 return selectBinaryOp(I, ISD::SDIV);
4483 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4484 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4485 !(C.isPowerOf2() || (-C).isPowerOf2()))
4486 return selectBinaryOp(I, ISD::SDIV);
4488 unsigned Lg2 = C.countTrailingZeros();
4489 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4492 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4494 if (cast<BinaryOperator>(I)->isExact()) {
4495 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4498 updateValueMap(I, ResultReg);
4502 unsigned Pow2MinusOne = (1 << Lg2) - 1;
4503 unsigned AddReg = emitAddSub_ri(/*UseAdd=*/true, VT, Src0Reg,
4504 /*IsKill=*/false, Pow2MinusOne);
4508 // (Src0 < 0) ? Pow2 - 1 : 0;
4509 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4513 const TargetRegisterClass *RC;
4514 if (VT == MVT::i64) {
4515 SelectOpc = AArch64::CSELXr;
4516 RC = &AArch64::GPR64RegClass;
4518 SelectOpc = AArch64::CSELWr;
4519 RC = &AArch64::GPR32RegClass;
4521 unsigned SelectReg =
4522 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4523 Src0IsKill, AArch64CC::LT);
4527 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4528 // negate the result.
4529 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4532 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4533 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4535 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4540 updateValueMap(I, ResultReg);
4544 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4545 switch (I->getOpcode()) {
4548 case Instruction::Add:
4549 case Instruction::Sub:
4550 return selectAddSub(I);
4551 case Instruction::Mul:
4552 return selectMul(I);
4553 case Instruction::SDiv:
4554 return selectSDiv(I);
4555 case Instruction::SRem:
4556 if (!selectBinaryOp(I, ISD::SREM))
4557 return selectRem(I, ISD::SREM);
4559 case Instruction::URem:
4560 if (!selectBinaryOp(I, ISD::UREM))
4561 return selectRem(I, ISD::UREM);
4563 case Instruction::Shl:
4564 case Instruction::LShr:
4565 case Instruction::AShr:
4566 return selectShift(I);
4567 case Instruction::And:
4568 case Instruction::Or:
4569 case Instruction::Xor:
4570 return selectLogicalOp(I);
4571 case Instruction::Br:
4572 return selectBranch(I);
4573 case Instruction::IndirectBr:
4574 return selectIndirectBr(I);
4575 case Instruction::BitCast:
4576 if (!FastISel::selectBitCast(I))
4577 return selectBitCast(I);
4579 case Instruction::FPToSI:
4580 if (!selectCast(I, ISD::FP_TO_SINT))
4581 return selectFPToInt(I, /*Signed=*/true);
4583 case Instruction::FPToUI:
4584 return selectFPToInt(I, /*Signed=*/false);
4585 case Instruction::ZExt:
4586 case Instruction::SExt:
4587 return selectIntExt(I);
4588 case Instruction::Trunc:
4589 if (!selectCast(I, ISD::TRUNCATE))
4590 return selectTrunc(I);
4592 case Instruction::FPExt:
4593 return selectFPExt(I);
4594 case Instruction::FPTrunc:
4595 return selectFPTrunc(I);
4596 case Instruction::SIToFP:
4597 if (!selectCast(I, ISD::SINT_TO_FP))
4598 return selectIntToFP(I, /*Signed=*/true);
4600 case Instruction::UIToFP:
4601 return selectIntToFP(I, /*Signed=*/false);
4602 case Instruction::Load:
4603 return selectLoad(I);
4604 case Instruction::Store:
4605 return selectStore(I);
4606 case Instruction::FCmp:
4607 case Instruction::ICmp:
4608 return selectCmp(I);
4609 case Instruction::Select:
4610 return selectSelect(I);
4611 case Instruction::Ret:
4612 return selectRet(I);
4613 case Instruction::FRem:
4614 return selectFRem(I);
4617 // fall-back to target-independent instruction selection.
4618 return selectOperator(I, I->getOpcode());
4619 // Silence warnings.
4620 (void)&CC_AArch64_DarwinPCS_VarArg;
4624 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4625 const TargetLibraryInfo *LibInfo) {
4626 return new AArch64FastISel(FuncInfo, LibInfo);