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) {
83 unsigned getOffsetReg() const {
86 void setFI(unsigned FI) {
87 assert(isFIBase() && "Invalid base frame index access!");
90 unsigned getFI() const {
91 assert(isFIBase() && "Invalid base frame index access!");
94 void setOffset(int64_t O) { Offset = O; }
95 int64_t getOffset() { return Offset; }
96 void setShift(unsigned S) { Shift = S; }
97 unsigned getShift() { return Shift; }
99 void setGlobalValue(const GlobalValue *G) { GV = G; }
100 const GlobalValue *getGlobalValue() { return GV; }
103 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
104 /// make the right decision when generating code for different targets.
105 const AArch64Subtarget *Subtarget;
106 LLVMContext *Context;
108 bool fastLowerArguments() override;
109 bool fastLowerCall(CallLoweringInfo &CLI) override;
110 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
113 // Selection routines.
114 bool selectAddSub(const Instruction *I);
115 bool selectLogicalOp(const Instruction *I);
116 bool selectLoad(const Instruction *I);
117 bool selectStore(const Instruction *I);
118 bool selectBranch(const Instruction *I);
119 bool selectIndirectBr(const Instruction *I);
120 bool selectCmp(const Instruction *I);
121 bool selectSelect(const Instruction *I);
122 bool selectFPExt(const Instruction *I);
123 bool selectFPTrunc(const Instruction *I);
124 bool selectFPToInt(const Instruction *I, bool Signed);
125 bool selectIntToFP(const Instruction *I, bool Signed);
126 bool selectRem(const Instruction *I, unsigned ISDOpcode);
127 bool selectRet(const Instruction *I);
128 bool selectTrunc(const Instruction *I);
129 bool selectIntExt(const Instruction *I);
130 bool selectMul(const Instruction *I);
131 bool selectShift(const Instruction *I);
132 bool selectBitCast(const Instruction *I);
133 bool selectFRem(const Instruction *I);
134 bool selectSDiv(const Instruction *I);
135 bool selectGetElementPtr(const Instruction *I);
137 // Utility helper routines.
138 bool isTypeLegal(Type *Ty, MVT &VT);
139 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
140 bool isValueAvailable(const Value *V) const;
141 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
142 bool computeCallAddress(const Value *V, Address &Addr);
143 bool simplifyAddress(Address &Addr, MVT VT);
144 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
145 unsigned Flags, unsigned ScaleFactor,
146 MachineMemOperand *MMO);
147 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
148 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
150 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
152 bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
154 // Emit helper routines.
155 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
156 const Value *RHS, bool SetFlags = false,
157 bool WantResult = true, bool IsZExt = false);
158 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
159 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
160 bool SetFlags = false, bool WantResult = true);
161 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
162 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
163 bool WantResult = true);
164 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
165 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
166 AArch64_AM::ShiftExtendType ShiftType,
167 uint64_t ShiftImm, bool SetFlags = false,
168 bool WantResult = true);
169 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
170 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
171 AArch64_AM::ShiftExtendType ExtType,
172 uint64_t ShiftImm, bool SetFlags = false,
173 bool WantResult = true);
176 bool emitCompareAndBranch(const BranchInst *BI);
177 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
178 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
179 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
180 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
181 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
182 MachineMemOperand *MMO = nullptr);
183 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
184 MachineMemOperand *MMO = nullptr);
185 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
186 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
187 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
188 bool SetFlags = false, bool WantResult = true,
189 bool IsZExt = false);
190 unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
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);
811 if (Addr.isRegBase() && !Addr.getReg()) {
812 unsigned Reg = getRegForValue(Obj);
819 if (!Addr.getOffsetReg()) {
820 unsigned Reg = getRegForValue(Obj);
823 Addr.setOffsetReg(Reg);
830 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
831 const User *U = nullptr;
832 unsigned Opcode = Instruction::UserOp1;
835 if (const auto *I = dyn_cast<Instruction>(V)) {
836 Opcode = I->getOpcode();
838 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
839 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
840 Opcode = C->getOpcode();
846 case Instruction::BitCast:
847 // Look past bitcasts if its operand is in the same BB.
849 return computeCallAddress(U->getOperand(0), Addr);
851 case Instruction::IntToPtr:
852 // Look past no-op inttoptrs if its operand is in the same BB.
854 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
855 return computeCallAddress(U->getOperand(0), Addr);
857 case Instruction::PtrToInt:
858 // Look past no-op ptrtoints if its operand is in the same BB.
860 TLI.getValueType(U->getType()) == TLI.getPointerTy())
861 return computeCallAddress(U->getOperand(0), Addr);
865 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
866 Addr.setGlobalValue(GV);
870 // If all else fails, try to materialize the value in a register.
871 if (!Addr.getGlobalValue()) {
872 Addr.setReg(getRegForValue(V));
873 return Addr.getReg() != 0;
880 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
881 EVT evt = TLI.getValueType(Ty, true);
883 // Only handle simple types.
884 if (evt == MVT::Other || !evt.isSimple())
886 VT = evt.getSimpleVT();
888 // This is a legal type, but it's not something we handle in fast-isel.
892 // Handle all other legal types, i.e. a register that will directly hold this
894 return TLI.isTypeLegal(VT);
897 /// \brief Determine if the value type is supported by FastISel.
899 /// FastISel for AArch64 can handle more value types than are legal. This adds
900 /// simple value type such as i1, i8, and i16.
901 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
902 if (Ty->isVectorTy() && !IsVectorAllowed)
905 if (isTypeLegal(Ty, VT))
908 // If this is a type than can be sign or zero-extended to a basic operation
909 // go ahead and accept it now.
910 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
916 bool AArch64FastISel::isValueAvailable(const Value *V) const {
917 if (!isa<Instruction>(V))
920 const auto *I = cast<Instruction>(V);
921 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
927 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
928 unsigned ScaleFactor = getImplicitScaleFactor(VT);
932 bool ImmediateOffsetNeedsLowering = false;
933 bool RegisterOffsetNeedsLowering = false;
934 int64_t Offset = Addr.getOffset();
935 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
936 ImmediateOffsetNeedsLowering = true;
937 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
938 !isUInt<12>(Offset / ScaleFactor))
939 ImmediateOffsetNeedsLowering = true;
941 // Cannot encode an offset register and an immediate offset in the same
942 // instruction. Fold the immediate offset into the load/store instruction and
943 // emit an additonal add to take care of the offset register.
944 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.getOffsetReg())
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.getOffsetReg()) && Addr.isFIBase())
956 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
959 .addFrameIndex(Addr.getFI())
962 Addr.setKind(Address::RegBase);
963 Addr.setReg(ResultReg);
966 if (RegisterOffsetNeedsLowering) {
967 unsigned ResultReg = 0;
969 if (Addr.getExtendType() == AArch64_AM::SXTW ||
970 Addr.getExtendType() == AArch64_AM::UXTW )
971 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
972 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
973 /*TODO:IsKill=*/false, Addr.getExtendType(),
976 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
977 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
978 /*TODO:IsKill=*/false, AArch64_AM::LSL,
981 if (Addr.getExtendType() == AArch64_AM::UXTW)
982 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
983 /*Op0IsKill=*/false, Addr.getShift(),
985 else if (Addr.getExtendType() == AArch64_AM::SXTW)
986 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
987 /*Op0IsKill=*/false, Addr.getShift(),
990 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
991 /*Op0IsKill=*/false, Addr.getShift());
996 Addr.setReg(ResultReg);
997 Addr.setOffsetReg(0);
999 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1002 // Since the offset is too large for the load/store instruction get the
1003 // reg+offset into a register.
1004 if (ImmediateOffsetNeedsLowering) {
1007 // Try to fold the immediate into the add instruction.
1008 ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1010 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1014 Addr.setReg(ResultReg);
1020 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1021 const MachineInstrBuilder &MIB,
1023 unsigned ScaleFactor,
1024 MachineMemOperand *MMO) {
1025 int64_t Offset = Addr.getOffset() / ScaleFactor;
1026 // Frame base works a bit differently. Handle it separately.
1027 if (Addr.isFIBase()) {
1028 int FI = Addr.getFI();
1029 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1030 // and alignment should be based on the VT.
1031 MMO = FuncInfo.MF->getMachineMemOperand(
1032 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1033 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1034 // Now add the rest of the operands.
1035 MIB.addFrameIndex(FI).addImm(Offset);
1037 assert(Addr.isRegBase() && "Unexpected address kind.");
1038 const MCInstrDesc &II = MIB->getDesc();
1039 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1041 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1043 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1044 if (Addr.getOffsetReg()) {
1045 assert(Addr.getOffset() == 0 && "Unexpected offset");
1046 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1047 Addr.getExtendType() == AArch64_AM::SXTX;
1048 MIB.addReg(Addr.getReg());
1049 MIB.addReg(Addr.getOffsetReg());
1050 MIB.addImm(IsSigned);
1051 MIB.addImm(Addr.getShift() != 0);
1053 MIB.addReg(Addr.getReg()).addImm(Offset);
1057 MIB.addMemOperand(MMO);
1060 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1061 const Value *RHS, bool SetFlags,
1062 bool WantResult, bool IsZExt) {
1063 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1064 bool NeedExtend = false;
1065 switch (RetVT.SimpleTy) {
1073 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1077 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1079 case MVT::i32: // fall-through
1084 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1086 // Canonicalize immediates to the RHS first.
1087 if (UseAdd && isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1088 std::swap(LHS, RHS);
1090 // Canonicalize mul by power of 2 to the RHS.
1091 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1092 if (isMulPowOf2(LHS))
1093 std::swap(LHS, RHS);
1095 // Canonicalize shift immediate to the RHS.
1096 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1097 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1098 if (isa<ConstantInt>(SI->getOperand(1)))
1099 if (SI->getOpcode() == Instruction::Shl ||
1100 SI->getOpcode() == Instruction::LShr ||
1101 SI->getOpcode() == Instruction::AShr )
1102 std::swap(LHS, RHS);
1104 unsigned LHSReg = getRegForValue(LHS);
1107 bool LHSIsKill = hasTrivialKill(LHS);
1110 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1112 unsigned ResultReg = 0;
1113 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1114 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1115 if (C->isNegative())
1116 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1117 SetFlags, WantResult);
1119 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1125 // Only extend the RHS within the instruction if there is a valid extend type.
1126 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1127 isValueAvailable(RHS)) {
1128 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1129 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1130 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1131 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1134 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1135 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1136 RHSIsKill, ExtendType, C->getZExtValue(),
1137 SetFlags, WantResult);
1139 unsigned RHSReg = getRegForValue(RHS);
1142 bool RHSIsKill = hasTrivialKill(RHS);
1143 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1144 ExtendType, 0, SetFlags, WantResult);
1147 // Check if the mul can be folded into the instruction.
1148 if (RHS->hasOneUse() && isValueAvailable(RHS))
1149 if (isMulPowOf2(RHS)) {
1150 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1151 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1153 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1154 if (C->getValue().isPowerOf2())
1155 std::swap(MulLHS, MulRHS);
1157 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1158 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1159 unsigned RHSReg = getRegForValue(MulLHS);
1162 bool RHSIsKill = hasTrivialKill(MulLHS);
1163 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1164 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1167 // Check if the shift can be folded into the instruction.
1168 if (RHS->hasOneUse() && isValueAvailable(RHS))
1169 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1170 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1171 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1172 switch (SI->getOpcode()) {
1174 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1175 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1176 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1178 uint64_t ShiftVal = C->getZExtValue();
1179 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1180 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1183 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1184 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1185 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1191 unsigned RHSReg = getRegForValue(RHS);
1194 bool RHSIsKill = hasTrivialKill(RHS);
1197 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1199 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1200 SetFlags, WantResult);
1203 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1204 bool LHSIsKill, unsigned RHSReg,
1205 bool RHSIsKill, bool SetFlags,
1207 assert(LHSReg && RHSReg && "Invalid register number.");
1209 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1212 static const unsigned OpcTable[2][2][2] = {
1213 { { AArch64::SUBWrr, AArch64::SUBXrr },
1214 { AArch64::ADDWrr, AArch64::ADDXrr } },
1215 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1216 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1218 bool Is64Bit = RetVT == MVT::i64;
1219 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1220 const TargetRegisterClass *RC =
1221 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1224 ResultReg = createResultReg(RC);
1226 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1228 const MCInstrDesc &II = TII.get(Opc);
1229 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1230 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1231 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1232 .addReg(LHSReg, getKillRegState(LHSIsKill))
1233 .addReg(RHSReg, getKillRegState(RHSIsKill));
1237 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1238 bool LHSIsKill, uint64_t Imm,
1239 bool SetFlags, bool WantResult) {
1240 assert(LHSReg && "Invalid register number.");
1242 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1246 if (isUInt<12>(Imm))
1248 else if ((Imm & 0xfff000) == Imm) {
1254 static const unsigned OpcTable[2][2][2] = {
1255 { { AArch64::SUBWri, AArch64::SUBXri },
1256 { AArch64::ADDWri, AArch64::ADDXri } },
1257 { { AArch64::SUBSWri, AArch64::SUBSXri },
1258 { AArch64::ADDSWri, AArch64::ADDSXri } }
1260 bool Is64Bit = RetVT == MVT::i64;
1261 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1262 const TargetRegisterClass *RC;
1264 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1266 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1269 ResultReg = createResultReg(RC);
1271 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1273 const MCInstrDesc &II = TII.get(Opc);
1274 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1275 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1276 .addReg(LHSReg, getKillRegState(LHSIsKill))
1278 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1282 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1283 bool LHSIsKill, unsigned RHSReg,
1285 AArch64_AM::ShiftExtendType ShiftType,
1286 uint64_t ShiftImm, bool SetFlags,
1288 assert(LHSReg && RHSReg && "Invalid register number.");
1290 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1293 static const unsigned OpcTable[2][2][2] = {
1294 { { AArch64::SUBWrs, AArch64::SUBXrs },
1295 { AArch64::ADDWrs, AArch64::ADDXrs } },
1296 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1297 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1299 bool Is64Bit = RetVT == MVT::i64;
1300 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1301 const TargetRegisterClass *RC =
1302 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1305 ResultReg = createResultReg(RC);
1307 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1309 const MCInstrDesc &II = TII.get(Opc);
1310 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1311 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1312 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1313 .addReg(LHSReg, getKillRegState(LHSIsKill))
1314 .addReg(RHSReg, getKillRegState(RHSIsKill))
1315 .addImm(getShifterImm(ShiftType, ShiftImm));
1319 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1320 bool LHSIsKill, unsigned RHSReg,
1322 AArch64_AM::ShiftExtendType ExtType,
1323 uint64_t ShiftImm, bool SetFlags,
1325 assert(LHSReg && RHSReg && "Invalid register number.");
1327 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1330 static const unsigned OpcTable[2][2][2] = {
1331 { { AArch64::SUBWrx, AArch64::SUBXrx },
1332 { AArch64::ADDWrx, AArch64::ADDXrx } },
1333 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1334 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1336 bool Is64Bit = RetVT == MVT::i64;
1337 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1338 const TargetRegisterClass *RC = nullptr;
1340 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1342 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1345 ResultReg = createResultReg(RC);
1347 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1349 const MCInstrDesc &II = TII.get(Opc);
1350 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1351 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1352 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1353 .addReg(LHSReg, getKillRegState(LHSIsKill))
1354 .addReg(RHSReg, getKillRegState(RHSIsKill))
1355 .addImm(getArithExtendImm(ExtType, ShiftImm));
1359 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1360 Type *Ty = LHS->getType();
1361 EVT EVT = TLI.getValueType(Ty, true);
1362 if (!EVT.isSimple())
1364 MVT VT = EVT.getSimpleVT();
1366 switch (VT.SimpleTy) {
1374 return emitICmp(VT, LHS, RHS, IsZExt);
1377 return emitFCmp(VT, LHS, RHS);
1381 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1383 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1387 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1389 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1390 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1393 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1394 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1397 // Check to see if the 2nd operand is a constant that we can encode directly
1399 bool UseImm = false;
1400 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1401 if (CFP->isZero() && !CFP->isNegative())
1404 unsigned LHSReg = getRegForValue(LHS);
1407 bool LHSIsKill = hasTrivialKill(LHS);
1410 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1411 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1412 .addReg(LHSReg, getKillRegState(LHSIsKill));
1416 unsigned RHSReg = getRegForValue(RHS);
1419 bool RHSIsKill = hasTrivialKill(RHS);
1421 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1423 .addReg(LHSReg, getKillRegState(LHSIsKill))
1424 .addReg(RHSReg, getKillRegState(RHSIsKill));
1428 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1429 bool SetFlags, bool WantResult, bool IsZExt) {
1430 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1434 /// \brief This method is a wrapper to simplify add emission.
1436 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1437 /// that fails, then try to materialize the immediate into a register and use
1438 /// emitAddSub_rr instead.
1439 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1443 ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1445 ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1450 unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1454 ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1458 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1459 bool SetFlags, bool WantResult, bool IsZExt) {
1460 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1464 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1465 bool LHSIsKill, unsigned RHSReg,
1466 bool RHSIsKill, bool WantResult) {
1467 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1468 RHSIsKill, /*SetFlags=*/true, WantResult);
1471 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1472 bool LHSIsKill, unsigned RHSReg,
1474 AArch64_AM::ShiftExtendType ShiftType,
1475 uint64_t ShiftImm, bool WantResult) {
1476 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1477 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1481 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1482 const Value *LHS, const Value *RHS) {
1483 // Canonicalize immediates to the RHS first.
1484 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1485 std::swap(LHS, RHS);
1487 // Canonicalize mul by power-of-2 to the RHS.
1488 if (LHS->hasOneUse() && isValueAvailable(LHS))
1489 if (isMulPowOf2(LHS))
1490 std::swap(LHS, RHS);
1492 // Canonicalize shift immediate to the RHS.
1493 if (LHS->hasOneUse() && isValueAvailable(LHS))
1494 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1495 if (isa<ConstantInt>(SI->getOperand(1)))
1496 std::swap(LHS, RHS);
1498 unsigned LHSReg = getRegForValue(LHS);
1501 bool LHSIsKill = hasTrivialKill(LHS);
1503 unsigned ResultReg = 0;
1504 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1505 uint64_t Imm = C->getZExtValue();
1506 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1511 // Check if the mul can be folded into the instruction.
1512 if (RHS->hasOneUse() && isValueAvailable(RHS))
1513 if (isMulPowOf2(RHS)) {
1514 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1515 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1517 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1518 if (C->getValue().isPowerOf2())
1519 std::swap(MulLHS, MulRHS);
1521 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1522 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1524 unsigned RHSReg = getRegForValue(MulLHS);
1527 bool RHSIsKill = hasTrivialKill(MulLHS);
1528 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1529 RHSIsKill, ShiftVal);
1532 // Check if the shift can be folded into the instruction.
1533 if (RHS->hasOneUse() && isValueAvailable(RHS))
1534 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1535 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1536 uint64_t ShiftVal = C->getZExtValue();
1537 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1540 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1541 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1542 RHSIsKill, ShiftVal);
1545 unsigned RHSReg = getRegForValue(RHS);
1548 bool RHSIsKill = hasTrivialKill(RHS);
1550 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1551 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1552 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1553 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1554 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1559 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1560 unsigned LHSReg, bool LHSIsKill,
1562 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1563 "ISD nodes are not consecutive!");
1564 static const unsigned OpcTable[3][2] = {
1565 { AArch64::ANDWri, AArch64::ANDXri },
1566 { AArch64::ORRWri, AArch64::ORRXri },
1567 { AArch64::EORWri, AArch64::EORXri }
1569 const TargetRegisterClass *RC;
1572 switch (RetVT.SimpleTy) {
1579 unsigned Idx = ISDOpc - ISD::AND;
1580 Opc = OpcTable[Idx][0];
1581 RC = &AArch64::GPR32spRegClass;
1586 Opc = OpcTable[ISDOpc - ISD::AND][1];
1587 RC = &AArch64::GPR64spRegClass;
1592 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1595 unsigned ResultReg =
1596 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1597 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1598 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1599 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1600 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1605 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1606 unsigned LHSReg, bool LHSIsKill,
1607 unsigned RHSReg, bool RHSIsKill,
1608 uint64_t ShiftImm) {
1609 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1610 "ISD nodes are not consecutive!");
1611 static const unsigned OpcTable[3][2] = {
1612 { AArch64::ANDWrs, AArch64::ANDXrs },
1613 { AArch64::ORRWrs, AArch64::ORRXrs },
1614 { AArch64::EORWrs, AArch64::EORXrs }
1616 const TargetRegisterClass *RC;
1618 switch (RetVT.SimpleTy) {
1625 Opc = OpcTable[ISDOpc - ISD::AND][0];
1626 RC = &AArch64::GPR32RegClass;
1629 Opc = OpcTable[ISDOpc - ISD::AND][1];
1630 RC = &AArch64::GPR64RegClass;
1633 unsigned ResultReg =
1634 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1635 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1636 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1637 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1638 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1643 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1645 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1648 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1649 bool WantZExt, MachineMemOperand *MMO) {
1650 // Simplify this down to something we can handle.
1651 if (!simplifyAddress(Addr, VT))
1654 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1656 llvm_unreachable("Unexpected value type.");
1658 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1659 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1660 bool UseScaled = true;
1661 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1666 static const unsigned GPOpcTable[2][8][4] = {
1668 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1670 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1672 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1674 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1676 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1678 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1680 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1682 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1686 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1688 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1690 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1692 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1694 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1696 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1698 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1700 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1705 static const unsigned FPOpcTable[4][2] = {
1706 { AArch64::LDURSi, AArch64::LDURDi },
1707 { AArch64::LDRSui, AArch64::LDRDui },
1708 { AArch64::LDRSroX, AArch64::LDRDroX },
1709 { AArch64::LDRSroW, AArch64::LDRDroW }
1713 const TargetRegisterClass *RC;
1714 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1715 Addr.getOffsetReg();
1716 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1717 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1718 Addr.getExtendType() == AArch64_AM::SXTW)
1721 bool IsRet64Bit = RetVT == MVT::i64;
1722 switch (VT.SimpleTy) {
1724 llvm_unreachable("Unexpected value type.");
1725 case MVT::i1: // Intentional fall-through.
1727 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1728 RC = (IsRet64Bit && !WantZExt) ?
1729 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1732 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1733 RC = (IsRet64Bit && !WantZExt) ?
1734 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1737 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1738 RC = (IsRet64Bit && !WantZExt) ?
1739 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1742 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1743 RC = &AArch64::GPR64RegClass;
1746 Opc = FPOpcTable[Idx][0];
1747 RC = &AArch64::FPR32RegClass;
1750 Opc = FPOpcTable[Idx][1];
1751 RC = &AArch64::FPR64RegClass;
1755 // Create the base instruction, then add the operands.
1756 unsigned ResultReg = createResultReg(RC);
1757 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1758 TII.get(Opc), ResultReg);
1759 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1761 // Loading an i1 requires special handling.
1762 if (VT == MVT::i1) {
1763 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1764 assert(ANDReg && "Unexpected AND instruction emission failure.");
1768 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1769 // the 32bit reg to a 64bit reg.
1770 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1771 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1772 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1773 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1775 .addReg(ResultReg, getKillRegState(true))
1776 .addImm(AArch64::sub_32);
1782 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1784 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1788 return selectOperator(I, I->getOpcode());
1791 switch (I->getOpcode()) {
1793 llvm_unreachable("Unexpected instruction.");
1794 case Instruction::Add:
1795 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1797 case Instruction::Sub:
1798 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1804 updateValueMap(I, ResultReg);
1808 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1810 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1814 return selectOperator(I, I->getOpcode());
1817 switch (I->getOpcode()) {
1819 llvm_unreachable("Unexpected instruction.");
1820 case Instruction::And:
1821 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1823 case Instruction::Or:
1824 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1826 case Instruction::Xor:
1827 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1833 updateValueMap(I, ResultReg);
1837 bool AArch64FastISel::selectLoad(const Instruction *I) {
1839 // Verify we have a legal type before going any further. Currently, we handle
1840 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1841 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1842 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1843 cast<LoadInst>(I)->isAtomic())
1846 // See if we can handle this address.
1848 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1851 // Fold the following sign-/zero-extend into the load instruction.
1852 bool WantZExt = true;
1854 const Value *IntExtVal = nullptr;
1855 if (I->hasOneUse()) {
1856 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1857 if (isTypeSupported(ZE->getType(), RetVT))
1861 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1862 if (isTypeSupported(SE->getType(), RetVT))
1870 unsigned ResultReg =
1871 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1875 // There are a few different cases we have to handle, because the load or the
1876 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1877 // SelectionDAG. There is also an ordering issue when both instructions are in
1878 // different basic blocks.
1879 // 1.) The load instruction is selected by FastISel, but the integer extend
1880 // not. This usually happens when the integer extend is in a different
1881 // basic block and SelectionDAG took over for that basic block.
1882 // 2.) The load instruction is selected before the integer extend. This only
1883 // happens when the integer extend is in a different basic block.
1884 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1885 // by FastISel. This happens if there are instructions between the load
1886 // and the integer extend that couldn't be selected by FastISel.
1888 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1889 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1890 // it when it selects the integer extend.
1891 unsigned Reg = lookUpRegForValue(IntExtVal);
1893 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1895 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1896 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1897 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1899 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1903 updateValueMap(I, ResultReg);
1907 // The integer extend has already been emitted - delete all the instructions
1908 // that have been emitted by the integer extend lowering code and use the
1909 // result from the load instruction directly.
1911 auto *MI = MRI.getUniqueVRegDef(Reg);
1915 for (auto &Opnd : MI->uses()) {
1917 Reg = Opnd.getReg();
1921 MI->eraseFromParent();
1923 updateValueMap(IntExtVal, ResultReg);
1927 updateValueMap(I, ResultReg);
1931 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1932 MachineMemOperand *MMO) {
1933 // Simplify this down to something we can handle.
1934 if (!simplifyAddress(Addr, VT))
1937 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1939 llvm_unreachable("Unexpected value type.");
1941 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1942 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1943 bool UseScaled = true;
1944 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1949 static const unsigned OpcTable[4][6] = {
1950 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1951 AArch64::STURSi, AArch64::STURDi },
1952 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1953 AArch64::STRSui, AArch64::STRDui },
1954 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1955 AArch64::STRSroX, AArch64::STRDroX },
1956 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1957 AArch64::STRSroW, AArch64::STRDroW }
1961 bool VTIsi1 = false;
1962 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1963 Addr.getOffsetReg();
1964 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1965 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1966 Addr.getExtendType() == AArch64_AM::SXTW)
1969 switch (VT.SimpleTy) {
1970 default: llvm_unreachable("Unexpected value type.");
1971 case MVT::i1: VTIsi1 = true;
1972 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1973 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1974 case MVT::i32: Opc = OpcTable[Idx][2]; break;
1975 case MVT::i64: Opc = OpcTable[Idx][3]; break;
1976 case MVT::f32: Opc = OpcTable[Idx][4]; break;
1977 case MVT::f64: Opc = OpcTable[Idx][5]; break;
1980 // Storing an i1 requires special handling.
1981 if (VTIsi1 && SrcReg != AArch64::WZR) {
1982 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1983 assert(ANDReg && "Unexpected AND instruction emission failure.");
1986 // Create the base instruction, then add the operands.
1987 const MCInstrDesc &II = TII.get(Opc);
1988 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
1989 MachineInstrBuilder MIB =
1990 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
1991 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
1996 bool AArch64FastISel::selectStore(const Instruction *I) {
1998 const Value *Op0 = I->getOperand(0);
1999 // Verify we have a legal type before going any further. Currently, we handle
2000 // simple types that will directly fit in a register (i32/f32/i64/f64) or
2001 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2002 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2003 cast<StoreInst>(I)->isAtomic())
2006 // Get the value to be stored into a register. Use the zero register directly
2007 // when possible to avoid an unnecessary copy and a wasted register.
2008 unsigned SrcReg = 0;
2009 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2011 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2012 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2013 if (CF->isZero() && !CF->isNegative()) {
2014 VT = MVT::getIntegerVT(VT.getSizeInBits());
2015 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2020 SrcReg = getRegForValue(Op0);
2025 // See if we can handle this address.
2027 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2030 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2035 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2037 case CmpInst::FCMP_ONE:
2038 case CmpInst::FCMP_UEQ:
2040 // AL is our "false" for now. The other two need more compares.
2041 return AArch64CC::AL;
2042 case CmpInst::ICMP_EQ:
2043 case CmpInst::FCMP_OEQ:
2044 return AArch64CC::EQ;
2045 case CmpInst::ICMP_SGT:
2046 case CmpInst::FCMP_OGT:
2047 return AArch64CC::GT;
2048 case CmpInst::ICMP_SGE:
2049 case CmpInst::FCMP_OGE:
2050 return AArch64CC::GE;
2051 case CmpInst::ICMP_UGT:
2052 case CmpInst::FCMP_UGT:
2053 return AArch64CC::HI;
2054 case CmpInst::FCMP_OLT:
2055 return AArch64CC::MI;
2056 case CmpInst::ICMP_ULE:
2057 case CmpInst::FCMP_OLE:
2058 return AArch64CC::LS;
2059 case CmpInst::FCMP_ORD:
2060 return AArch64CC::VC;
2061 case CmpInst::FCMP_UNO:
2062 return AArch64CC::VS;
2063 case CmpInst::FCMP_UGE:
2064 return AArch64CC::PL;
2065 case CmpInst::ICMP_SLT:
2066 case CmpInst::FCMP_ULT:
2067 return AArch64CC::LT;
2068 case CmpInst::ICMP_SLE:
2069 case CmpInst::FCMP_ULE:
2070 return AArch64CC::LE;
2071 case CmpInst::FCMP_UNE:
2072 case CmpInst::ICMP_NE:
2073 return AArch64CC::NE;
2074 case CmpInst::ICMP_UGE:
2075 return AArch64CC::HS;
2076 case CmpInst::ICMP_ULT:
2077 return AArch64CC::LO;
2081 /// \brief Try to emit a combined compare-and-branch instruction.
2082 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2083 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2084 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2085 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2087 const Value *LHS = CI->getOperand(0);
2088 const Value *RHS = CI->getOperand(1);
2090 Type *Ty = LHS->getType();
2091 if (!Ty->isIntegerTy())
2094 unsigned BW = cast<IntegerType>(Ty)->getBitWidth();
2095 if (BW != 1 && BW != 8 && BW != 16 && BW != 32 && BW != 64)
2098 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2099 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2101 // Try to take advantage of fallthrough opportunities.
2102 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2103 std::swap(TBB, FBB);
2104 Predicate = CmpInst::getInversePredicate(Predicate);
2109 if ((Predicate == CmpInst::ICMP_EQ) || (Predicate == CmpInst::ICMP_NE)) {
2110 if (const auto *C = dyn_cast<ConstantInt>(LHS))
2111 if (C->isNullValue())
2112 std::swap(LHS, RHS);
2114 if (!isa<ConstantInt>(RHS))
2117 if (!cast<ConstantInt>(RHS)->isNullValue())
2120 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2121 if (AI->getOpcode() == Instruction::And) {
2122 const Value *AndLHS = AI->getOperand(0);
2123 const Value *AndRHS = AI->getOperand(1);
2125 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2126 if (C->getValue().isPowerOf2())
2127 std::swap(AndLHS, AndRHS);
2129 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2130 if (C->getValue().isPowerOf2()) {
2131 TestBit = C->getValue().logBase2();
2135 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2136 } else if (Predicate == CmpInst::ICMP_SLT) {
2137 if (!isa<ConstantInt>(RHS))
2140 if (!cast<ConstantInt>(RHS)->isNullValue())
2145 } else if (Predicate == CmpInst::ICMP_SGT) {
2146 if (!isa<ConstantInt>(RHS))
2149 if (cast<ConstantInt>(RHS)->getValue() != -1)
2157 static const unsigned OpcTable[2][2][2] = {
2158 { {AArch64::CBZW, AArch64::CBZX },
2159 {AArch64::CBNZW, AArch64::CBNZX} },
2160 { {AArch64::TBZW, AArch64::TBZX },
2161 {AArch64::TBNZW, AArch64::TBNZX} }
2164 bool IsBitTest = TestBit != -1;
2165 bool Is64Bit = BW == 64;
2166 if (TestBit < 32 && TestBit >= 0)
2169 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2170 const MCInstrDesc &II = TII.get(Opc);
2172 unsigned SrcReg = getRegForValue(LHS);
2175 bool SrcIsKill = hasTrivialKill(LHS);
2177 if (BW == 64 && !Is64Bit)
2178 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2181 if ((BW < 32) && !IsBitTest) {
2182 EVT CmpEVT = TLI.getValueType(Ty, true);
2184 emitIntExt(CmpEVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ true);
2187 // Emit the combined compare and branch instruction.
2188 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2189 MachineInstrBuilder MIB =
2190 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2191 .addReg(SrcReg, getKillRegState(SrcIsKill));
2193 MIB.addImm(TestBit);
2196 // Obtain the branch weight and add the TrueBB to the successor list.
2197 uint32_t BranchWeight = 0;
2199 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2200 TBB->getBasicBlock());
2201 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2202 fastEmitBranch(FBB, DbgLoc);
2207 bool AArch64FastISel::selectBranch(const Instruction *I) {
2208 const BranchInst *BI = cast<BranchInst>(I);
2209 if (BI->isUnconditional()) {
2210 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2211 fastEmitBranch(MSucc, BI->getDebugLoc());
2215 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2216 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2218 AArch64CC::CondCode CC = AArch64CC::NE;
2219 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2220 if (CI->hasOneUse() && isValueAvailable(CI)) {
2221 // Try to optimize or fold the cmp.
2222 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2223 switch (Predicate) {
2226 case CmpInst::FCMP_FALSE:
2227 fastEmitBranch(FBB, DbgLoc);
2229 case CmpInst::FCMP_TRUE:
2230 fastEmitBranch(TBB, DbgLoc);
2234 // Try to emit a combined compare-and-branch first.
2235 if (emitCompareAndBranch(BI))
2238 // Try to take advantage of fallthrough opportunities.
2239 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2240 std::swap(TBB, FBB);
2241 Predicate = CmpInst::getInversePredicate(Predicate);
2245 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2248 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2250 CC = getCompareCC(Predicate);
2251 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2252 switch (Predicate) {
2255 case CmpInst::FCMP_UEQ:
2256 ExtraCC = AArch64CC::EQ;
2259 case CmpInst::FCMP_ONE:
2260 ExtraCC = AArch64CC::MI;
2264 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2266 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2267 if (ExtraCC != AArch64CC::AL) {
2268 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2278 // Obtain the branch weight and add the TrueBB to the successor list.
2279 uint32_t BranchWeight = 0;
2281 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2282 TBB->getBasicBlock());
2283 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2285 fastEmitBranch(FBB, DbgLoc);
2288 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2290 if (TI->hasOneUse() && isValueAvailable(TI) &&
2291 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2292 unsigned CondReg = getRegForValue(TI->getOperand(0));
2295 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2297 // Issue an extract_subreg to get the lower 32-bits.
2298 if (SrcVT == MVT::i64) {
2299 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2304 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2305 assert(ANDReg && "Unexpected AND instruction emission failure.");
2306 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2308 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2309 std::swap(TBB, FBB);
2312 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2316 // Obtain the branch weight and add the TrueBB to the successor list.
2317 uint32_t BranchWeight = 0;
2319 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2320 TBB->getBasicBlock());
2321 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2323 fastEmitBranch(FBB, DbgLoc);
2326 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2327 uint64_t Imm = CI->getZExtValue();
2328 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2329 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2332 // Obtain the branch weight and add the target to the successor list.
2333 uint32_t BranchWeight = 0;
2335 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2336 Target->getBasicBlock());
2337 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2339 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2340 // Fake request the condition, otherwise the intrinsic might be completely
2342 unsigned CondReg = getRegForValue(BI->getCondition());
2347 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2351 // Obtain the branch weight and add the TrueBB to the successor list.
2352 uint32_t BranchWeight = 0;
2354 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2355 TBB->getBasicBlock());
2356 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2358 fastEmitBranch(FBB, DbgLoc);
2362 unsigned CondReg = getRegForValue(BI->getCondition());
2365 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2367 // We've been divorced from our compare! Our block was split, and
2368 // now our compare lives in a predecessor block. We musn't
2369 // re-compare here, as the children of the compare aren't guaranteed
2370 // live across the block boundary (we *could* check for this).
2371 // Regardless, the compare has been done in the predecessor block,
2372 // and it left a value for us in a virtual register. Ergo, we test
2373 // the one-bit value left in the virtual register.
2374 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2376 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2377 std::swap(TBB, FBB);
2381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2385 // Obtain the branch weight and add the TrueBB to the successor list.
2386 uint32_t BranchWeight = 0;
2388 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2389 TBB->getBasicBlock());
2390 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2392 fastEmitBranch(FBB, DbgLoc);
2396 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2397 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2398 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2402 // Emit the indirect branch.
2403 const MCInstrDesc &II = TII.get(AArch64::BR);
2404 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2405 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2407 // Make sure the CFG is up-to-date.
2408 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2409 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2414 bool AArch64FastISel::selectCmp(const Instruction *I) {
2415 const CmpInst *CI = cast<CmpInst>(I);
2417 // Try to optimize or fold the cmp.
2418 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2419 unsigned ResultReg = 0;
2420 switch (Predicate) {
2423 case CmpInst::FCMP_FALSE:
2424 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2425 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2426 TII.get(TargetOpcode::COPY), ResultReg)
2427 .addReg(AArch64::WZR, getKillRegState(true));
2429 case CmpInst::FCMP_TRUE:
2430 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2435 updateValueMap(I, ResultReg);
2440 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2443 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2445 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2446 // condition codes are inverted, because they are used by CSINC.
2447 static unsigned CondCodeTable[2][2] = {
2448 { AArch64CC::NE, AArch64CC::VC },
2449 { AArch64CC::PL, AArch64CC::LE }
2451 unsigned *CondCodes = nullptr;
2452 switch (Predicate) {
2455 case CmpInst::FCMP_UEQ:
2456 CondCodes = &CondCodeTable[0][0];
2458 case CmpInst::FCMP_ONE:
2459 CondCodes = &CondCodeTable[1][0];
2464 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
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(CondCodes[0]);
2470 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2472 .addReg(TmpReg1, getKillRegState(true))
2473 .addReg(AArch64::WZR, getKillRegState(true))
2474 .addImm(CondCodes[1]);
2476 updateValueMap(I, ResultReg);
2480 // Now set a register based on the comparison.
2481 AArch64CC::CondCode CC = getCompareCC(Predicate);
2482 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2483 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2484 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2486 .addReg(AArch64::WZR, getKillRegState(true))
2487 .addReg(AArch64::WZR, getKillRegState(true))
2488 .addImm(invertedCC);
2490 updateValueMap(I, ResultReg);
2494 bool AArch64FastISel::selectSelect(const Instruction *I) {
2495 const SelectInst *SI = cast<SelectInst>(I);
2497 EVT DestEVT = TLI.getValueType(SI->getType(), true);
2498 if (!DestEVT.isSimple())
2501 MVT DestVT = DestEVT.getSimpleVT();
2502 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
2507 const TargetRegisterClass *RC = nullptr;
2508 switch (DestVT.SimpleTy) {
2509 default: return false;
2511 SelectOpc = AArch64::CSELWr; RC = &AArch64::GPR32RegClass; break;
2513 SelectOpc = AArch64::CSELXr; RC = &AArch64::GPR64RegClass; break;
2515 SelectOpc = AArch64::FCSELSrrr; RC = &AArch64::FPR32RegClass; break;
2517 SelectOpc = AArch64::FCSELDrrr; RC = &AArch64::FPR64RegClass; break;
2520 const Value *Cond = SI->getCondition();
2521 bool NeedTest = true;
2522 AArch64CC::CondCode CC = AArch64CC::NE;
2523 if (foldXALUIntrinsic(CC, I, Cond))
2526 unsigned CondReg = getRegForValue(Cond);
2529 bool CondIsKill = hasTrivialKill(Cond);
2532 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2533 assert(ANDReg && "Unexpected AND instruction emission failure.");
2534 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2537 unsigned TrueReg = getRegForValue(SI->getTrueValue());
2538 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
2540 unsigned FalseReg = getRegForValue(SI->getFalseValue());
2541 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
2543 if (!TrueReg || !FalseReg)
2546 unsigned ResultReg = fastEmitInst_rri(SelectOpc, RC, TrueReg, TrueIsKill,
2547 FalseReg, FalseIsKill, CC);
2548 updateValueMap(I, ResultReg);
2552 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2553 Value *V = I->getOperand(0);
2554 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2557 unsigned Op = getRegForValue(V);
2561 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2563 ResultReg).addReg(Op);
2564 updateValueMap(I, ResultReg);
2568 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2569 Value *V = I->getOperand(0);
2570 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2573 unsigned Op = getRegForValue(V);
2577 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2578 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2579 ResultReg).addReg(Op);
2580 updateValueMap(I, ResultReg);
2584 // FPToUI and FPToSI
2585 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2587 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2590 unsigned SrcReg = getRegForValue(I->getOperand(0));
2594 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2595 if (SrcVT == MVT::f128)
2599 if (SrcVT == MVT::f64) {
2601 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2603 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2606 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2608 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2610 unsigned ResultReg = createResultReg(
2611 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2612 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2614 updateValueMap(I, ResultReg);
2618 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2620 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2622 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2623 "Unexpected value type.");
2625 unsigned SrcReg = getRegForValue(I->getOperand(0));
2628 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2630 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2632 // Handle sign-extension.
2633 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2635 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2642 if (SrcVT == MVT::i64) {
2644 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2646 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2649 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2651 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2654 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2656 updateValueMap(I, ResultReg);
2660 bool AArch64FastISel::fastLowerArguments() {
2661 if (!FuncInfo.CanLowerReturn)
2664 const Function *F = FuncInfo.Fn;
2668 CallingConv::ID CC = F->getCallingConv();
2669 if (CC != CallingConv::C)
2672 // Only handle simple cases of up to 8 GPR and FPR each.
2673 unsigned GPRCnt = 0;
2674 unsigned FPRCnt = 0;
2676 for (auto const &Arg : F->args()) {
2677 // The first argument is at index 1.
2679 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2680 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2681 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2682 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2685 Type *ArgTy = Arg.getType();
2686 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2689 EVT ArgVT = TLI.getValueType(ArgTy);
2690 if (!ArgVT.isSimple())
2693 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2694 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2697 if (VT.isVector() &&
2698 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2701 if (VT >= MVT::i1 && VT <= MVT::i64)
2703 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2704 VT.is128BitVector())
2709 if (GPRCnt > 8 || FPRCnt > 8)
2713 static const MCPhysReg Registers[6][8] = {
2714 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2715 AArch64::W5, AArch64::W6, AArch64::W7 },
2716 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2717 AArch64::X5, AArch64::X6, AArch64::X7 },
2718 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2719 AArch64::H5, AArch64::H6, AArch64::H7 },
2720 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2721 AArch64::S5, AArch64::S6, AArch64::S7 },
2722 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2723 AArch64::D5, AArch64::D6, AArch64::D7 },
2724 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2725 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2728 unsigned GPRIdx = 0;
2729 unsigned FPRIdx = 0;
2730 for (auto const &Arg : F->args()) {
2731 MVT VT = TLI.getSimpleValueType(Arg.getType());
2733 const TargetRegisterClass *RC;
2734 if (VT >= MVT::i1 && VT <= MVT::i32) {
2735 SrcReg = Registers[0][GPRIdx++];
2736 RC = &AArch64::GPR32RegClass;
2738 } else if (VT == MVT::i64) {
2739 SrcReg = Registers[1][GPRIdx++];
2740 RC = &AArch64::GPR64RegClass;
2741 } else if (VT == MVT::f16) {
2742 SrcReg = Registers[2][FPRIdx++];
2743 RC = &AArch64::FPR16RegClass;
2744 } else if (VT == MVT::f32) {
2745 SrcReg = Registers[3][FPRIdx++];
2746 RC = &AArch64::FPR32RegClass;
2747 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2748 SrcReg = Registers[4][FPRIdx++];
2749 RC = &AArch64::FPR64RegClass;
2750 } else if (VT.is128BitVector()) {
2751 SrcReg = Registers[5][FPRIdx++];
2752 RC = &AArch64::FPR128RegClass;
2754 llvm_unreachable("Unexpected value type.");
2756 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2757 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2758 // Without this, EmitLiveInCopies may eliminate the livein if its only
2759 // use is a bitcast (which isn't turned into an instruction).
2760 unsigned ResultReg = createResultReg(RC);
2761 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2762 TII.get(TargetOpcode::COPY), ResultReg)
2763 .addReg(DstReg, getKillRegState(true));
2764 updateValueMap(&Arg, ResultReg);
2769 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2770 SmallVectorImpl<MVT> &OutVTs,
2771 unsigned &NumBytes) {
2772 CallingConv::ID CC = CLI.CallConv;
2773 SmallVector<CCValAssign, 16> ArgLocs;
2774 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2775 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2777 // Get a count of how many bytes are to be pushed on the stack.
2778 NumBytes = CCInfo.getNextStackOffset();
2780 // Issue CALLSEQ_START
2781 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2782 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2785 // Process the args.
2786 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2787 CCValAssign &VA = ArgLocs[i];
2788 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2789 MVT ArgVT = OutVTs[VA.getValNo()];
2791 unsigned ArgReg = getRegForValue(ArgVal);
2795 // Handle arg promotion: SExt, ZExt, AExt.
2796 switch (VA.getLocInfo()) {
2797 case CCValAssign::Full:
2799 case CCValAssign::SExt: {
2800 MVT DestVT = VA.getLocVT();
2802 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2807 case CCValAssign::AExt:
2808 // Intentional fall-through.
2809 case CCValAssign::ZExt: {
2810 MVT DestVT = VA.getLocVT();
2812 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2818 llvm_unreachable("Unknown arg promotion!");
2821 // Now copy/store arg to correct locations.
2822 if (VA.isRegLoc() && !VA.needsCustom()) {
2823 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2824 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2825 CLI.OutRegs.push_back(VA.getLocReg());
2826 } else if (VA.needsCustom()) {
2827 // FIXME: Handle custom args.
2830 assert(VA.isMemLoc() && "Assuming store on stack.");
2832 // Don't emit stores for undef values.
2833 if (isa<UndefValue>(ArgVal))
2836 // Need to store on the stack.
2837 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2839 unsigned BEAlign = 0;
2840 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2841 BEAlign = 8 - ArgSize;
2844 Addr.setKind(Address::RegBase);
2845 Addr.setReg(AArch64::SP);
2846 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2848 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2849 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2850 MachinePointerInfo::getStack(Addr.getOffset()),
2851 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2853 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2860 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2861 unsigned NumBytes) {
2862 CallingConv::ID CC = CLI.CallConv;
2864 // Issue CALLSEQ_END
2865 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2866 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2867 .addImm(NumBytes).addImm(0);
2869 // Now the return value.
2870 if (RetVT != MVT::isVoid) {
2871 SmallVector<CCValAssign, 16> RVLocs;
2872 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2873 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
2875 // Only handle a single return value.
2876 if (RVLocs.size() != 1)
2879 // Copy all of the result registers out of their specified physreg.
2880 MVT CopyVT = RVLocs[0].getValVT();
2881 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
2882 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2883 TII.get(TargetOpcode::COPY), ResultReg)
2884 .addReg(RVLocs[0].getLocReg());
2885 CLI.InRegs.push_back(RVLocs[0].getLocReg());
2887 CLI.ResultReg = ResultReg;
2888 CLI.NumResultRegs = 1;
2894 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2895 CallingConv::ID CC = CLI.CallConv;
2896 bool IsTailCall = CLI.IsTailCall;
2897 bool IsVarArg = CLI.IsVarArg;
2898 const Value *Callee = CLI.Callee;
2899 const char *SymName = CLI.SymName;
2901 if (!Callee && !SymName)
2904 // Allow SelectionDAG isel to handle tail calls.
2908 CodeModel::Model CM = TM.getCodeModel();
2909 // Only support the small and large code model.
2910 if (CM != CodeModel::Small && CM != CodeModel::Large)
2913 // FIXME: Add large code model support for ELF.
2914 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
2917 // Let SDISel handle vararg functions.
2921 // FIXME: Only handle *simple* calls for now.
2923 if (CLI.RetTy->isVoidTy())
2924 RetVT = MVT::isVoid;
2925 else if (!isTypeLegal(CLI.RetTy, RetVT))
2928 for (auto Flag : CLI.OutFlags)
2929 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
2932 // Set up the argument vectors.
2933 SmallVector<MVT, 16> OutVTs;
2934 OutVTs.reserve(CLI.OutVals.size());
2936 for (auto *Val : CLI.OutVals) {
2938 if (!isTypeLegal(Val->getType(), VT) &&
2939 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
2942 // We don't handle vector parameters yet.
2943 if (VT.isVector() || VT.getSizeInBits() > 64)
2946 OutVTs.push_back(VT);
2950 if (Callee && !computeCallAddress(Callee, Addr))
2953 // Handle the arguments now that we've gotten them.
2955 if (!processCallArgs(CLI, OutVTs, NumBytes))
2959 MachineInstrBuilder MIB;
2960 if (CM == CodeModel::Small) {
2961 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
2962 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
2964 MIB.addExternalSymbol(SymName, 0);
2965 else if (Addr.getGlobalValue())
2966 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2967 else if (Addr.getReg()) {
2968 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
2973 unsigned CallReg = 0;
2975 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2978 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2980 CallReg = createResultReg(&AArch64::GPR64RegClass);
2981 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
2984 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
2986 } else if (Addr.getGlobalValue())
2987 CallReg = materializeGV(Addr.getGlobalValue());
2988 else if (Addr.getReg())
2989 CallReg = Addr.getReg();
2994 const MCInstrDesc &II = TII.get(AArch64::BLR);
2995 CallReg = constrainOperandRegClass(II, CallReg, 0);
2996 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
2999 // Add implicit physical register uses to the call.
3000 for (auto Reg : CLI.OutRegs)
3001 MIB.addReg(Reg, RegState::Implicit);
3003 // Add a register mask with the call-preserved registers.
3004 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3005 MIB.addRegMask(TRI.getCallPreservedMask(CC));
3009 // Finish off the call including any return values.
3010 return finishCall(CLI, RetVT, NumBytes);
3013 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3015 return Len / Alignment <= 4;
3020 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3021 uint64_t Len, unsigned Alignment) {
3022 // Make sure we don't bloat code by inlining very large memcpy's.
3023 if (!isMemCpySmall(Len, Alignment))
3026 int64_t UnscaledOffset = 0;
3027 Address OrigDest = Dest;
3028 Address OrigSrc = Src;
3032 if (!Alignment || Alignment >= 8) {
3043 // Bound based on alignment.
3044 if (Len >= 4 && Alignment == 4)
3046 else if (Len >= 2 && Alignment == 2)
3053 unsigned ResultReg = emitLoad(VT, VT, Src);
3057 if (!emitStore(VT, ResultReg, Dest))
3060 int64_t Size = VT.getSizeInBits() / 8;
3062 UnscaledOffset += Size;
3064 // We need to recompute the unscaled offset for each iteration.
3065 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3066 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3072 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3073 /// into the user. The condition code will only be updated on success.
3074 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3075 const Instruction *I,
3076 const Value *Cond) {
3077 if (!isa<ExtractValueInst>(Cond))
3080 const auto *EV = cast<ExtractValueInst>(Cond);
3081 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3084 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3086 const Function *Callee = II->getCalledFunction();
3088 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3089 if (!isTypeLegal(RetTy, RetVT))
3092 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3095 const Value *LHS = II->getArgOperand(0);
3096 const Value *RHS = II->getArgOperand(1);
3098 // Canonicalize immediate to the RHS.
3099 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3100 isCommutativeIntrinsic(II))
3101 std::swap(LHS, RHS);
3103 // Simplify multiplies.
3104 unsigned IID = II->getIntrinsicID();
3108 case Intrinsic::smul_with_overflow:
3109 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3110 if (C->getValue() == 2)
3111 IID = Intrinsic::sadd_with_overflow;
3113 case Intrinsic::umul_with_overflow:
3114 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3115 if (C->getValue() == 2)
3116 IID = Intrinsic::uadd_with_overflow;
3120 AArch64CC::CondCode TmpCC;
3124 case Intrinsic::sadd_with_overflow:
3125 case Intrinsic::ssub_with_overflow:
3126 TmpCC = AArch64CC::VS;
3128 case Intrinsic::uadd_with_overflow:
3129 TmpCC = AArch64CC::HS;
3131 case Intrinsic::usub_with_overflow:
3132 TmpCC = AArch64CC::LO;
3134 case Intrinsic::smul_with_overflow:
3135 case Intrinsic::umul_with_overflow:
3136 TmpCC = AArch64CC::NE;
3140 // Check if both instructions are in the same basic block.
3141 if (!isValueAvailable(II))
3144 // Make sure nothing is in the way
3145 BasicBlock::const_iterator Start = I;
3146 BasicBlock::const_iterator End = II;
3147 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3148 // We only expect extractvalue instructions between the intrinsic and the
3149 // instruction to be selected.
3150 if (!isa<ExtractValueInst>(Itr))
3153 // Check that the extractvalue operand comes from the intrinsic.
3154 const auto *EVI = cast<ExtractValueInst>(Itr);
3155 if (EVI->getAggregateOperand() != II)
3163 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3164 // FIXME: Handle more intrinsics.
3165 switch (II->getIntrinsicID()) {
3166 default: return false;
3167 case Intrinsic::frameaddress: {
3168 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3169 MFI->setFrameAddressIsTaken(true);
3171 const AArch64RegisterInfo *RegInfo =
3172 static_cast<const AArch64RegisterInfo *>(
3173 TM.getSubtargetImpl()->getRegisterInfo());
3174 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3175 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3176 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3177 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3178 // Recursively load frame address
3184 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3186 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3187 SrcReg, /*IsKill=*/true, 0);
3188 assert(DestReg && "Unexpected LDR instruction emission failure.");
3192 updateValueMap(II, SrcReg);
3195 case Intrinsic::memcpy:
3196 case Intrinsic::memmove: {
3197 const auto *MTI = cast<MemTransferInst>(II);
3198 // Don't handle volatile.
3199 if (MTI->isVolatile())
3202 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3203 // we would emit dead code because we don't currently handle memmoves.
3204 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3205 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3206 // Small memcpy's are common enough that we want to do them without a call
3208 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3209 unsigned Alignment = MTI->getAlignment();
3210 if (isMemCpySmall(Len, Alignment)) {
3212 if (!computeAddress(MTI->getRawDest(), Dest) ||
3213 !computeAddress(MTI->getRawSource(), Src))
3215 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3220 if (!MTI->getLength()->getType()->isIntegerTy(64))
3223 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3224 // Fast instruction selection doesn't support the special
3228 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3229 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3231 case Intrinsic::memset: {
3232 const MemSetInst *MSI = cast<MemSetInst>(II);
3233 // Don't handle volatile.
3234 if (MSI->isVolatile())
3237 if (!MSI->getLength()->getType()->isIntegerTy(64))
3240 if (MSI->getDestAddressSpace() > 255)
3241 // Fast instruction selection doesn't support the special
3245 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3247 case Intrinsic::sin:
3248 case Intrinsic::cos:
3249 case Intrinsic::pow: {
3251 if (!isTypeLegal(II->getType(), RetVT))
3254 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3257 static const RTLIB::Libcall LibCallTable[3][2] = {
3258 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3259 { RTLIB::COS_F32, RTLIB::COS_F64 },
3260 { RTLIB::POW_F32, RTLIB::POW_F64 }
3263 bool Is64Bit = RetVT == MVT::f64;
3264 switch (II->getIntrinsicID()) {
3266 llvm_unreachable("Unexpected intrinsic.");
3267 case Intrinsic::sin:
3268 LC = LibCallTable[0][Is64Bit];
3270 case Intrinsic::cos:
3271 LC = LibCallTable[1][Is64Bit];
3273 case Intrinsic::pow:
3274 LC = LibCallTable[2][Is64Bit];
3279 Args.reserve(II->getNumArgOperands());
3281 // Populate the argument list.
3282 for (auto &Arg : II->arg_operands()) {
3285 Entry.Ty = Arg->getType();
3286 Args.push_back(Entry);
3289 CallLoweringInfo CLI;
3290 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3291 TLI.getLibcallName(LC), std::move(Args));
3292 if (!lowerCallTo(CLI))
3294 updateValueMap(II, CLI.ResultReg);
3297 case Intrinsic::trap: {
3298 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3302 case Intrinsic::sqrt: {
3303 Type *RetTy = II->getCalledFunction()->getReturnType();
3306 if (!isTypeLegal(RetTy, VT))
3309 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3312 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3314 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3318 updateValueMap(II, ResultReg);
3321 case Intrinsic::sadd_with_overflow:
3322 case Intrinsic::uadd_with_overflow:
3323 case Intrinsic::ssub_with_overflow:
3324 case Intrinsic::usub_with_overflow:
3325 case Intrinsic::smul_with_overflow:
3326 case Intrinsic::umul_with_overflow: {
3327 // This implements the basic lowering of the xalu with overflow intrinsics.
3328 const Function *Callee = II->getCalledFunction();
3329 auto *Ty = cast<StructType>(Callee->getReturnType());
3330 Type *RetTy = Ty->getTypeAtIndex(0U);
3333 if (!isTypeLegal(RetTy, VT))
3336 if (VT != MVT::i32 && VT != MVT::i64)
3339 const Value *LHS = II->getArgOperand(0);
3340 const Value *RHS = II->getArgOperand(1);
3341 // Canonicalize immediate to the RHS.
3342 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3343 isCommutativeIntrinsic(II))
3344 std::swap(LHS, RHS);
3346 // Simplify multiplies.
3347 unsigned IID = II->getIntrinsicID();
3351 case Intrinsic::smul_with_overflow:
3352 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3353 if (C->getValue() == 2) {
3354 IID = Intrinsic::sadd_with_overflow;
3358 case Intrinsic::umul_with_overflow:
3359 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3360 if (C->getValue() == 2) {
3361 IID = Intrinsic::uadd_with_overflow;
3367 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3368 AArch64CC::CondCode CC = AArch64CC::Invalid;
3370 default: llvm_unreachable("Unexpected intrinsic!");
3371 case Intrinsic::sadd_with_overflow:
3372 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3375 case Intrinsic::uadd_with_overflow:
3376 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3379 case Intrinsic::ssub_with_overflow:
3380 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3383 case Intrinsic::usub_with_overflow:
3384 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3387 case Intrinsic::smul_with_overflow: {
3389 unsigned LHSReg = getRegForValue(LHS);
3392 bool LHSIsKill = hasTrivialKill(LHS);
3394 unsigned RHSReg = getRegForValue(RHS);
3397 bool RHSIsKill = hasTrivialKill(RHS);
3399 if (VT == MVT::i32) {
3400 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3401 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3402 /*IsKill=*/false, 32);
3403 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3405 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3407 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3408 AArch64_AM::ASR, 31, /*WantResult=*/false);
3410 assert(VT == MVT::i64 && "Unexpected value type.");
3411 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3412 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3414 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3415 AArch64_AM::ASR, 63, /*WantResult=*/false);
3419 case Intrinsic::umul_with_overflow: {
3421 unsigned LHSReg = getRegForValue(LHS);
3424 bool LHSIsKill = hasTrivialKill(LHS);
3426 unsigned RHSReg = getRegForValue(RHS);
3429 bool RHSIsKill = hasTrivialKill(RHS);
3431 if (VT == MVT::i32) {
3432 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3433 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3434 /*IsKill=*/false, AArch64_AM::LSR, 32,
3435 /*WantResult=*/false);
3436 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3439 assert(VT == MVT::i64 && "Unexpected value type.");
3440 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3441 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3443 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3444 /*IsKill=*/false, /*WantResult=*/false);
3451 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3452 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3453 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3456 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3457 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3458 /*IsKill=*/true, getInvertedCondCode(CC));
3460 assert((ResultReg1 + 1) == ResultReg2 &&
3461 "Nonconsecutive result registers.");
3462 updateValueMap(II, ResultReg1, 2);
3469 bool AArch64FastISel::selectRet(const Instruction *I) {
3470 const ReturnInst *Ret = cast<ReturnInst>(I);
3471 const Function &F = *I->getParent()->getParent();
3473 if (!FuncInfo.CanLowerReturn)
3479 // Build a list of return value registers.
3480 SmallVector<unsigned, 4> RetRegs;
3482 if (Ret->getNumOperands() > 0) {
3483 CallingConv::ID CC = F.getCallingConv();
3484 SmallVector<ISD::OutputArg, 4> Outs;
3485 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3487 // Analyze operands of the call, assigning locations to each operand.
3488 SmallVector<CCValAssign, 16> ValLocs;
3489 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3490 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3491 : RetCC_AArch64_AAPCS;
3492 CCInfo.AnalyzeReturn(Outs, RetCC);
3494 // Only handle a single return value for now.
3495 if (ValLocs.size() != 1)
3498 CCValAssign &VA = ValLocs[0];
3499 const Value *RV = Ret->getOperand(0);
3501 // Don't bother handling odd stuff for now.
3502 if ((VA.getLocInfo() != CCValAssign::Full) &&
3503 (VA.getLocInfo() != CCValAssign::BCvt))
3506 // Only handle register returns for now.
3510 unsigned Reg = getRegForValue(RV);
3514 unsigned SrcReg = Reg + VA.getValNo();
3515 unsigned DestReg = VA.getLocReg();
3516 // Avoid a cross-class copy. This is very unlikely.
3517 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3520 EVT RVEVT = TLI.getValueType(RV->getType());
3521 if (!RVEVT.isSimple())
3524 // Vectors (of > 1 lane) in big endian need tricky handling.
3525 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3526 !Subtarget->isLittleEndian())
3529 MVT RVVT = RVEVT.getSimpleVT();
3530 if (RVVT == MVT::f128)
3533 MVT DestVT = VA.getValVT();
3534 // Special handling for extended integers.
3535 if (RVVT != DestVT) {
3536 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3539 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3542 bool IsZExt = Outs[0].Flags.isZExt();
3543 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3549 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3550 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3552 // Add register to return instruction.
3553 RetRegs.push_back(VA.getLocReg());
3556 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3557 TII.get(AArch64::RET_ReallyLR));
3558 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3559 MIB.addReg(RetRegs[i], RegState::Implicit);
3563 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3564 Type *DestTy = I->getType();
3565 Value *Op = I->getOperand(0);
3566 Type *SrcTy = Op->getType();
3568 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3569 EVT DestEVT = TLI.getValueType(DestTy, true);
3570 if (!SrcEVT.isSimple())
3572 if (!DestEVT.isSimple())
3575 MVT SrcVT = SrcEVT.getSimpleVT();
3576 MVT DestVT = DestEVT.getSimpleVT();
3578 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3581 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3585 unsigned SrcReg = getRegForValue(Op);
3588 bool SrcIsKill = hasTrivialKill(Op);
3590 // If we're truncating from i64 to a smaller non-legal type then generate an
3591 // AND. Otherwise, we know the high bits are undefined and a truncate only
3592 // generate a COPY. We cannot mark the source register also as result
3593 // register, because this can incorrectly transfer the kill flag onto the
3596 if (SrcVT == MVT::i64) {
3598 switch (DestVT.SimpleTy) {
3600 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3612 // Issue an extract_subreg to get the lower 32-bits.
3613 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3615 // Create the AND instruction which performs the actual truncation.
3616 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3617 assert(ResultReg && "Unexpected AND instruction emission failure.");
3619 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3620 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3621 TII.get(TargetOpcode::COPY), ResultReg)
3622 .addReg(SrcReg, getKillRegState(SrcIsKill));
3625 updateValueMap(I, ResultReg);
3629 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3630 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3631 DestVT == MVT::i64) &&
3632 "Unexpected value type.");
3633 // Handle i8 and i16 as i32.
3634 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3638 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3639 assert(ResultReg && "Unexpected AND instruction emission failure.");
3640 if (DestVT == MVT::i64) {
3641 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3642 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3643 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3644 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3645 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3648 .addImm(AArch64::sub_32);
3653 if (DestVT == MVT::i64) {
3654 // FIXME: We're SExt i1 to i64.
3657 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3658 /*TODO:IsKill=*/false, 0, 0);
3662 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3663 unsigned Op1, bool Op1IsKill) {
3665 switch (RetVT.SimpleTy) {
3671 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3673 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3676 const TargetRegisterClass *RC =
3677 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3678 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3679 /*IsKill=*/ZReg, true);
3682 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3683 unsigned Op1, bool Op1IsKill) {
3684 if (RetVT != MVT::i64)
3687 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3688 Op0, Op0IsKill, Op1, Op1IsKill,
3689 AArch64::XZR, /*IsKill=*/true);
3692 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3693 unsigned Op1, bool Op1IsKill) {
3694 if (RetVT != MVT::i64)
3697 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3698 Op0, Op0IsKill, Op1, Op1IsKill,
3699 AArch64::XZR, /*IsKill=*/true);
3702 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3703 unsigned Op1Reg, bool Op1IsKill) {
3705 bool NeedTrunc = false;
3707 switch (RetVT.SimpleTy) {
3709 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3710 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3711 case MVT::i32: Opc = AArch64::LSLVWr; break;
3712 case MVT::i64: Opc = AArch64::LSLVXr; break;
3715 const TargetRegisterClass *RC =
3716 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3718 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3721 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3724 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3728 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3729 bool Op0IsKill, uint64_t Shift,
3731 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3732 "Unexpected source/return type pair.");
3733 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3734 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3735 "Unexpected source value type.");
3736 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3737 RetVT == MVT::i64) && "Unexpected return value type.");
3739 bool Is64Bit = (RetVT == MVT::i64);
3740 unsigned RegSize = Is64Bit ? 64 : 32;
3741 unsigned DstBits = RetVT.getSizeInBits();
3742 unsigned SrcBits = SrcVT.getSizeInBits();
3744 // Don't deal with undefined shifts.
3745 if (Shift >= DstBits)
3748 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3749 // {S|U}BFM Wd, Wn, #r, #s
3750 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3752 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3753 // %2 = shl i16 %1, 4
3754 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3755 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3756 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3757 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3759 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3760 // %2 = shl i16 %1, 8
3761 // Wd<32+7-24,32-24> = Wn<7:0>
3762 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3763 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3764 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3766 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3767 // %2 = shl i16 %1, 12
3768 // Wd<32+3-20,32-20> = Wn<3:0>
3769 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3770 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3771 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3773 unsigned ImmR = RegSize - Shift;
3774 // Limit the width to the length of the source type.
3775 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3776 static const unsigned OpcTable[2][2] = {
3777 {AArch64::SBFMWri, AArch64::SBFMXri},
3778 {AArch64::UBFMWri, AArch64::UBFMXri}
3780 unsigned Opc = OpcTable[IsZext][Is64Bit];
3781 const TargetRegisterClass *RC =
3782 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3783 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3784 unsigned TmpReg = MRI.createVirtualRegister(RC);
3785 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3786 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3788 .addReg(Op0, getKillRegState(Op0IsKill))
3789 .addImm(AArch64::sub_32);
3793 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3796 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3797 unsigned Op1Reg, bool Op1IsKill) {
3799 bool NeedTrunc = false;
3801 switch (RetVT.SimpleTy) {
3803 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3804 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3805 case MVT::i32: Opc = AArch64::LSRVWr; break;
3806 case MVT::i64: Opc = AArch64::LSRVXr; break;
3809 const TargetRegisterClass *RC =
3810 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3812 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3813 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3814 Op0IsKill = Op1IsKill = true;
3816 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3819 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3823 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3824 bool Op0IsKill, uint64_t Shift,
3826 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3827 "Unexpected source/return type pair.");
3828 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3829 SrcVT == MVT::i64) && "Unexpected source value type.");
3830 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3831 RetVT == MVT::i64) && "Unexpected return value type.");
3833 bool Is64Bit = (RetVT == MVT::i64);
3834 unsigned RegSize = Is64Bit ? 64 : 32;
3835 unsigned DstBits = RetVT.getSizeInBits();
3836 unsigned SrcBits = SrcVT.getSizeInBits();
3838 // Don't deal with undefined shifts.
3839 if (Shift >= DstBits)
3842 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3843 // {S|U}BFM Wd, Wn, #r, #s
3844 // Wd<s-r:0> = Wn<s:r> when r <= s
3846 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3847 // %2 = lshr i16 %1, 4
3848 // Wd<7-4:0> = Wn<7:4>
3849 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
3850 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3851 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3853 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3854 // %2 = lshr i16 %1, 8
3855 // Wd<7-7,0> = Wn<7:7>
3856 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
3857 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3858 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3860 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3861 // %2 = lshr i16 %1, 12
3862 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3863 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
3864 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3865 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3867 if (Shift >= SrcBits && IsZExt)
3868 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3870 // It is not possible to fold a sign-extend into the LShr instruction. In this
3871 // case emit a sign-extend.
3873 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3878 SrcBits = SrcVT.getSizeInBits();
3882 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3883 unsigned ImmS = SrcBits - 1;
3884 static const unsigned OpcTable[2][2] = {
3885 {AArch64::SBFMWri, AArch64::SBFMXri},
3886 {AArch64::UBFMWri, AArch64::UBFMXri}
3888 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3889 const TargetRegisterClass *RC =
3890 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3891 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3892 unsigned TmpReg = MRI.createVirtualRegister(RC);
3893 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3894 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3896 .addReg(Op0, getKillRegState(Op0IsKill))
3897 .addImm(AArch64::sub_32);
3901 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3904 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3905 unsigned Op1Reg, bool Op1IsKill) {
3907 bool NeedTrunc = false;
3909 switch (RetVT.SimpleTy) {
3911 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
3912 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
3913 case MVT::i32: Opc = AArch64::ASRVWr; break;
3914 case MVT::i64: Opc = AArch64::ASRVXr; break;
3917 const TargetRegisterClass *RC =
3918 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3920 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
3921 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3922 Op0IsKill = Op1IsKill = true;
3924 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3927 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3931 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3932 bool Op0IsKill, uint64_t Shift,
3934 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3935 "Unexpected source/return type pair.");
3936 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3937 SrcVT == MVT::i64) && "Unexpected source value type.");
3938 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3939 RetVT == MVT::i64) && "Unexpected return value type.");
3941 bool Is64Bit = (RetVT == MVT::i64);
3942 unsigned RegSize = Is64Bit ? 64 : 32;
3943 unsigned DstBits = RetVT.getSizeInBits();
3944 unsigned SrcBits = SrcVT.getSizeInBits();
3946 // Don't deal with undefined shifts.
3947 if (Shift >= DstBits)
3950 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3951 // {S|U}BFM Wd, Wn, #r, #s
3952 // Wd<s-r:0> = Wn<s:r> when r <= s
3954 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3955 // %2 = ashr i16 %1, 4
3956 // Wd<7-4:0> = Wn<7:4>
3957 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
3958 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3959 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3961 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3962 // %2 = ashr i16 %1, 8
3963 // Wd<7-7,0> = Wn<7:7>
3964 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3965 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3966 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3968 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3969 // %2 = ashr i16 %1, 12
3970 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3971 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3972 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3973 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3975 if (Shift >= SrcBits && IsZExt)
3976 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3978 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3979 unsigned ImmS = SrcBits - 1;
3980 static const unsigned OpcTable[2][2] = {
3981 {AArch64::SBFMWri, AArch64::SBFMXri},
3982 {AArch64::UBFMWri, AArch64::UBFMXri}
3984 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3985 const TargetRegisterClass *RC =
3986 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3987 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3988 unsigned TmpReg = MRI.createVirtualRegister(RC);
3989 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3990 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3992 .addReg(Op0, getKillRegState(Op0IsKill))
3993 .addImm(AArch64::sub_32);
3997 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4000 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
4002 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4004 // FastISel does not have plumbing to deal with extensions where the SrcVT or
4005 // DestVT are odd things, so test to make sure that they are both types we can
4006 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4007 // bail out to SelectionDAG.
4008 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4009 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4010 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
4011 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
4017 switch (SrcVT.SimpleTy) {
4021 return emiti1Ext(SrcReg, DestVT, IsZExt);
4023 if (DestVT == MVT::i64)
4024 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4026 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4030 if (DestVT == MVT::i64)
4031 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4033 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4037 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4038 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4043 // Handle i8 and i16 as i32.
4044 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4046 else if (DestVT == MVT::i64) {
4047 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4048 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4049 TII.get(AArch64::SUBREG_TO_REG), Src64)
4052 .addImm(AArch64::sub_32);
4056 const TargetRegisterClass *RC =
4057 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4058 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4061 static bool isZExtLoad(const MachineInstr *LI) {
4062 switch (LI->getOpcode()) {
4065 case AArch64::LDURBBi:
4066 case AArch64::LDURHHi:
4067 case AArch64::LDURWi:
4068 case AArch64::LDRBBui:
4069 case AArch64::LDRHHui:
4070 case AArch64::LDRWui:
4071 case AArch64::LDRBBroX:
4072 case AArch64::LDRHHroX:
4073 case AArch64::LDRWroX:
4074 case AArch64::LDRBBroW:
4075 case AArch64::LDRHHroW:
4076 case AArch64::LDRWroW:
4081 static bool isSExtLoad(const MachineInstr *LI) {
4082 switch (LI->getOpcode()) {
4085 case AArch64::LDURSBWi:
4086 case AArch64::LDURSHWi:
4087 case AArch64::LDURSBXi:
4088 case AArch64::LDURSHXi:
4089 case AArch64::LDURSWi:
4090 case AArch64::LDRSBWui:
4091 case AArch64::LDRSHWui:
4092 case AArch64::LDRSBXui:
4093 case AArch64::LDRSHXui:
4094 case AArch64::LDRSWui:
4095 case AArch64::LDRSBWroX:
4096 case AArch64::LDRSHWroX:
4097 case AArch64::LDRSBXroX:
4098 case AArch64::LDRSHXroX:
4099 case AArch64::LDRSWroX:
4100 case AArch64::LDRSBWroW:
4101 case AArch64::LDRSHWroW:
4102 case AArch64::LDRSBXroW:
4103 case AArch64::LDRSHXroW:
4104 case AArch64::LDRSWroW:
4109 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4111 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4112 if (!LI || !LI->hasOneUse())
4115 // Check if the load instruction has already been selected.
4116 unsigned Reg = lookUpRegForValue(LI);
4120 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4124 // Check if the correct load instruction has been emitted - SelectionDAG might
4125 // have emitted a zero-extending load, but we need a sign-extending load.
4126 bool IsZExt = isa<ZExtInst>(I);
4127 const auto *LoadMI = MI;
4128 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4129 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4130 unsigned LoadReg = MI->getOperand(1).getReg();
4131 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4132 assert(LoadMI && "Expected valid instruction");
4134 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4137 // Nothing to be done.
4138 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4139 updateValueMap(I, Reg);
4144 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4145 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4146 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4148 .addReg(Reg, getKillRegState(true))
4149 .addImm(AArch64::sub_32);
4152 assert((MI->getOpcode() == TargetOpcode::COPY &&
4153 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4154 "Expected copy instruction");
4155 Reg = MI->getOperand(1).getReg();
4156 MI->eraseFromParent();
4158 updateValueMap(I, Reg);
4162 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4163 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4164 "Unexpected integer extend instruction.");
4167 if (!isTypeSupported(I->getType(), RetVT))
4170 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4173 // Try to optimize already sign-/zero-extended values from load instructions.
4174 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4177 unsigned SrcReg = getRegForValue(I->getOperand(0));
4180 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4182 // Try to optimize already sign-/zero-extended values from function arguments.
4183 bool IsZExt = isa<ZExtInst>(I);
4184 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4185 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4186 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4187 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4188 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4189 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4191 .addReg(SrcReg, getKillRegState(SrcIsKill))
4192 .addImm(AArch64::sub_32);
4195 updateValueMap(I, SrcReg);
4200 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4204 updateValueMap(I, ResultReg);
4208 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4209 EVT DestEVT = TLI.getValueType(I->getType(), true);
4210 if (!DestEVT.isSimple())
4213 MVT DestVT = DestEVT.getSimpleVT();
4214 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4218 bool Is64bit = (DestVT == MVT::i64);
4219 switch (ISDOpcode) {
4223 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4226 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4229 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4230 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4233 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4235 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4238 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4240 const TargetRegisterClass *RC =
4241 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4242 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4243 Src1Reg, /*IsKill=*/false);
4244 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4245 // The remainder is computed as numerator - (quotient * denominator) using the
4246 // MSUB instruction.
4247 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4248 Src1Reg, Src1IsKill, Src0Reg,
4250 updateValueMap(I, ResultReg);
4254 bool AArch64FastISel::selectMul(const Instruction *I) {
4256 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4260 return selectBinaryOp(I, ISD::MUL);
4262 const Value *Src0 = I->getOperand(0);
4263 const Value *Src1 = I->getOperand(1);
4264 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4265 if (C->getValue().isPowerOf2())
4266 std::swap(Src0, Src1);
4268 // Try to simplify to a shift instruction.
4269 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4270 if (C->getValue().isPowerOf2()) {
4271 uint64_t ShiftVal = C->getValue().logBase2();
4274 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4275 if (!isIntExtFree(ZExt)) {
4277 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4280 Src0 = ZExt->getOperand(0);
4283 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4284 if (!isIntExtFree(SExt)) {
4286 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4289 Src0 = SExt->getOperand(0);
4294 unsigned Src0Reg = getRegForValue(Src0);
4297 bool Src0IsKill = hasTrivialKill(Src0);
4299 unsigned ResultReg =
4300 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4303 updateValueMap(I, ResultReg);
4308 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4311 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4313 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4316 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4318 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4323 updateValueMap(I, ResultReg);
4327 bool AArch64FastISel::selectShift(const Instruction *I) {
4329 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4332 if (RetVT.isVector())
4333 return selectOperator(I, I->getOpcode());
4335 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4336 unsigned ResultReg = 0;
4337 uint64_t ShiftVal = C->getZExtValue();
4339 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
4340 const Value *Op0 = I->getOperand(0);
4341 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4342 if (!isIntExtFree(ZExt)) {
4344 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4347 Op0 = ZExt->getOperand(0);
4350 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4351 if (!isIntExtFree(SExt)) {
4353 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4356 Op0 = SExt->getOperand(0);
4361 unsigned Op0Reg = getRegForValue(Op0);
4364 bool Op0IsKill = hasTrivialKill(Op0);
4366 switch (I->getOpcode()) {
4367 default: llvm_unreachable("Unexpected instruction.");
4368 case Instruction::Shl:
4369 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4371 case Instruction::AShr:
4372 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4374 case Instruction::LShr:
4375 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4381 updateValueMap(I, ResultReg);
4385 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4388 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4390 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4393 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4395 unsigned ResultReg = 0;
4396 switch (I->getOpcode()) {
4397 default: llvm_unreachable("Unexpected instruction.");
4398 case Instruction::Shl:
4399 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4401 case Instruction::AShr:
4402 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4404 case Instruction::LShr:
4405 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4412 updateValueMap(I, ResultReg);
4416 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4419 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4421 if (!isTypeLegal(I->getType(), RetVT))
4425 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4426 Opc = AArch64::FMOVWSr;
4427 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4428 Opc = AArch64::FMOVXDr;
4429 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4430 Opc = AArch64::FMOVSWr;
4431 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4432 Opc = AArch64::FMOVDXr;
4436 const TargetRegisterClass *RC = nullptr;
4437 switch (RetVT.SimpleTy) {
4438 default: llvm_unreachable("Unexpected value type.");
4439 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4440 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4441 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4442 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4444 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4447 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4448 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4453 updateValueMap(I, ResultReg);
4457 bool AArch64FastISel::selectFRem(const Instruction *I) {
4459 if (!isTypeLegal(I->getType(), RetVT))
4463 switch (RetVT.SimpleTy) {
4467 LC = RTLIB::REM_F32;
4470 LC = RTLIB::REM_F64;
4475 Args.reserve(I->getNumOperands());
4477 // Populate the argument list.
4478 for (auto &Arg : I->operands()) {
4481 Entry.Ty = Arg->getType();
4482 Args.push_back(Entry);
4485 CallLoweringInfo CLI;
4486 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4487 TLI.getLibcallName(LC), std::move(Args));
4488 if (!lowerCallTo(CLI))
4490 updateValueMap(I, CLI.ResultReg);
4494 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4496 if (!isTypeLegal(I->getType(), VT))
4499 if (!isa<ConstantInt>(I->getOperand(1)))
4500 return selectBinaryOp(I, ISD::SDIV);
4502 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4503 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4504 !(C.isPowerOf2() || (-C).isPowerOf2()))
4505 return selectBinaryOp(I, ISD::SDIV);
4507 unsigned Lg2 = C.countTrailingZeros();
4508 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4511 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4513 if (cast<BinaryOperator>(I)->isExact()) {
4514 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4517 updateValueMap(I, ResultReg);
4521 int64_t Pow2MinusOne = (1ULL << Lg2) - 1;
4522 unsigned AddReg = emitAdd_ri_(VT, Src0Reg, /*IsKill=*/false, Pow2MinusOne);
4526 // (Src0 < 0) ? Pow2 - 1 : 0;
4527 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4531 const TargetRegisterClass *RC;
4532 if (VT == MVT::i64) {
4533 SelectOpc = AArch64::CSELXr;
4534 RC = &AArch64::GPR64RegClass;
4536 SelectOpc = AArch64::CSELWr;
4537 RC = &AArch64::GPR32RegClass;
4539 unsigned SelectReg =
4540 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4541 Src0IsKill, AArch64CC::LT);
4545 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4546 // negate the result.
4547 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4550 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4551 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4553 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4558 updateValueMap(I, ResultReg);
4562 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4563 /// duplicate it for AArch64, because otherwise we would bail out even for
4564 /// simple cases. This is because the standard fastEmit functions don't cover
4565 /// MUL at all and ADD is lowered very inefficientily.
4566 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4567 unsigned N = getRegForValue(I->getOperand(0));
4570 bool NIsKill = hasTrivialKill(I->getOperand(0));
4572 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4573 // into a single N = N + TotalOffset.
4574 uint64_t TotalOffs = 0;
4575 Type *Ty = I->getOperand(0)->getType();
4576 MVT VT = TLI.getPointerTy();
4577 for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4578 const Value *Idx = *OI;
4579 if (auto *StTy = dyn_cast<StructType>(Ty)) {
4580 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4583 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4584 Ty = StTy->getElementType(Field);
4586 Ty = cast<SequentialType>(Ty)->getElementType();
4587 // If this is a constant subscript, handle it quickly.
4588 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4593 DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4597 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4604 // N = N + Idx * ElementSize;
4605 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4606 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4607 unsigned IdxN = Pair.first;
4608 bool IdxNIsKill = Pair.second;
4612 if (ElementSize != 1) {
4613 unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4616 IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4621 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4627 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4631 updateValueMap(I, N);
4635 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4636 switch (I->getOpcode()) {
4639 case Instruction::Add:
4640 case Instruction::Sub:
4641 return selectAddSub(I);
4642 case Instruction::Mul:
4643 return selectMul(I);
4644 case Instruction::SDiv:
4645 return selectSDiv(I);
4646 case Instruction::SRem:
4647 if (!selectBinaryOp(I, ISD::SREM))
4648 return selectRem(I, ISD::SREM);
4650 case Instruction::URem:
4651 if (!selectBinaryOp(I, ISD::UREM))
4652 return selectRem(I, ISD::UREM);
4654 case Instruction::Shl:
4655 case Instruction::LShr:
4656 case Instruction::AShr:
4657 return selectShift(I);
4658 case Instruction::And:
4659 case Instruction::Or:
4660 case Instruction::Xor:
4661 return selectLogicalOp(I);
4662 case Instruction::Br:
4663 return selectBranch(I);
4664 case Instruction::IndirectBr:
4665 return selectIndirectBr(I);
4666 case Instruction::BitCast:
4667 if (!FastISel::selectBitCast(I))
4668 return selectBitCast(I);
4670 case Instruction::FPToSI:
4671 if (!selectCast(I, ISD::FP_TO_SINT))
4672 return selectFPToInt(I, /*Signed=*/true);
4674 case Instruction::FPToUI:
4675 return selectFPToInt(I, /*Signed=*/false);
4676 case Instruction::ZExt:
4677 case Instruction::SExt:
4678 return selectIntExt(I);
4679 case Instruction::Trunc:
4680 if (!selectCast(I, ISD::TRUNCATE))
4681 return selectTrunc(I);
4683 case Instruction::FPExt:
4684 return selectFPExt(I);
4685 case Instruction::FPTrunc:
4686 return selectFPTrunc(I);
4687 case Instruction::SIToFP:
4688 if (!selectCast(I, ISD::SINT_TO_FP))
4689 return selectIntToFP(I, /*Signed=*/true);
4691 case Instruction::UIToFP:
4692 return selectIntToFP(I, /*Signed=*/false);
4693 case Instruction::Load:
4694 return selectLoad(I);
4695 case Instruction::Store:
4696 return selectStore(I);
4697 case Instruction::FCmp:
4698 case Instruction::ICmp:
4699 return selectCmp(I);
4700 case Instruction::Select:
4701 return selectSelect(I);
4702 case Instruction::Ret:
4703 return selectRet(I);
4704 case Instruction::FRem:
4705 return selectFRem(I);
4706 case Instruction::GetElementPtr:
4707 return selectGetElementPtr(I);
4710 // fall-back to target-independent instruction selection.
4711 return selectOperator(I, I->getOpcode());
4712 // Silence warnings.
4713 (void)&CC_AArch64_DarwinPCS_VarArg;
4717 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4718 const TargetLibraryInfo *LibInfo) {
4719 return new AArch64FastISel(FuncInfo, LibInfo);