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);
153 bool optimizeSelect(const SelectInst *SI);
154 std::pair<unsigned, bool> getRegForGEPIndex(const Value *Idx);
156 // Emit helper routines.
157 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
158 const Value *RHS, bool SetFlags = false,
159 bool WantResult = true, bool IsZExt = false);
160 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
161 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
162 bool SetFlags = false, bool WantResult = true);
163 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
164 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
165 bool WantResult = true);
166 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
167 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
168 AArch64_AM::ShiftExtendType ShiftType,
169 uint64_t ShiftImm, bool SetFlags = false,
170 bool WantResult = true);
171 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
172 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
173 AArch64_AM::ShiftExtendType ExtType,
174 uint64_t ShiftImm, bool SetFlags = false,
175 bool WantResult = true);
178 bool emitCompareAndBranch(const BranchInst *BI);
179 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
180 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
181 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
182 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
183 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
184 MachineMemOperand *MMO = nullptr);
185 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
186 MachineMemOperand *MMO = nullptr);
187 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
188 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
189 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
190 bool SetFlags = false, bool WantResult = true,
191 bool IsZExt = false);
192 unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
193 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
194 bool SetFlags = false, bool WantResult = true,
195 bool IsZExt = false);
196 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
197 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
198 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
199 unsigned RHSReg, bool RHSIsKill,
200 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
201 bool WantResult = true);
202 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
204 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
205 bool LHSIsKill, uint64_t Imm);
206 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
207 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
209 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
210 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
211 unsigned Op1, bool Op1IsKill);
212 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
213 unsigned Op1, bool Op1IsKill);
214 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
215 unsigned Op1, bool Op1IsKill);
216 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
217 unsigned Op1Reg, bool Op1IsKill);
218 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
219 uint64_t Imm, bool IsZExt = true);
220 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
221 unsigned Op1Reg, bool Op1IsKill);
222 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
223 uint64_t Imm, bool IsZExt = true);
224 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
225 unsigned Op1Reg, bool Op1IsKill);
226 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
227 uint64_t Imm, bool IsZExt = false);
229 unsigned materializeInt(const ConstantInt *CI, MVT VT);
230 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
231 unsigned materializeGV(const GlobalValue *GV);
233 // Call handling routines.
235 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
236 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
238 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
241 // Backend specific FastISel code.
242 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
243 unsigned fastMaterializeConstant(const Constant *C) override;
244 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
246 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
247 const TargetLibraryInfo *LibInfo)
248 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
249 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
250 Context = &FuncInfo.Fn->getContext();
253 bool fastSelectInstruction(const Instruction *I) override;
255 #include "AArch64GenFastISel.inc"
258 } // end anonymous namespace
260 #include "AArch64GenCallingConv.inc"
262 /// \brief Check if the sign-/zero-extend will be a noop.
263 static bool isIntExtFree(const Instruction *I) {
264 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
265 "Unexpected integer extend instruction.");
266 assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
267 "Unexpected value type.");
268 bool IsZExt = isa<ZExtInst>(I);
270 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
274 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
275 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
281 /// \brief Determine the implicit scale factor that is applied by a memory
282 /// operation for a given value type.
283 static unsigned getImplicitScaleFactor(MVT VT) {
284 switch (VT.SimpleTy) {
287 case MVT::i1: // fall-through
292 case MVT::i32: // fall-through
295 case MVT::i64: // fall-through
301 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
302 if (CC == CallingConv::WebKit_JS)
303 return CC_AArch64_WebKit_JS;
304 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
307 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
308 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
309 "Alloca should always return a pointer.");
311 // Don't handle dynamic allocas.
312 if (!FuncInfo.StaticAllocaMap.count(AI))
315 DenseMap<const AllocaInst *, int>::iterator SI =
316 FuncInfo.StaticAllocaMap.find(AI);
318 if (SI != FuncInfo.StaticAllocaMap.end()) {
319 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
322 .addFrameIndex(SI->second)
331 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
336 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
338 // Create a copy from the zero register to materialize a "0" value.
339 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
340 : &AArch64::GPR32RegClass;
341 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
342 unsigned ResultReg = createResultReg(RC);
343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
344 ResultReg).addReg(ZeroReg, getKillRegState(true));
348 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
349 // Positive zero (+0.0) has to be materialized with a fmov from the zero
350 // register, because the immediate version of fmov cannot encode zero.
351 if (CFP->isNullValue())
352 return fastMaterializeFloatZero(CFP);
354 if (VT != MVT::f32 && VT != MVT::f64)
357 const APFloat Val = CFP->getValueAPF();
358 bool Is64Bit = (VT == MVT::f64);
359 // This checks to see if we can use FMOV instructions to materialize
360 // a constant, otherwise we have to materialize via the constant pool.
361 if (TLI.isFPImmLegal(Val, VT)) {
363 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
364 assert((Imm != -1) && "Cannot encode floating-point constant.");
365 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
366 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
369 // Materialize via constant pool. MachineConstantPool wants an explicit
371 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
373 Align = DL.getTypeAllocSize(CFP->getType());
375 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
376 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
377 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
378 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
380 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
381 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
382 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
384 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
388 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
389 // We can't handle thread-local variables quickly yet.
390 if (GV->isThreadLocal())
393 // MachO still uses GOT for large code-model accesses, but ELF requires
394 // movz/movk sequences, which FastISel doesn't handle yet.
395 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
398 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
400 EVT DestEVT = TLI.getValueType(GV->getType(), true);
401 if (!DestEVT.isSimple())
404 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
407 if (OpFlags & AArch64II::MO_GOT) {
409 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
411 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
413 ResultReg = createResultReg(&AArch64::GPR64RegClass);
414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
417 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
419 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
420 // We can't handle addresses loaded from a constant pool quickly yet.
424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
426 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
428 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
429 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
432 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
438 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
439 EVT CEVT = TLI.getValueType(C->getType(), true);
441 // Only handle simple types.
442 if (!CEVT.isSimple())
444 MVT VT = CEVT.getSimpleVT();
446 if (const auto *CI = dyn_cast<ConstantInt>(C))
447 return materializeInt(CI, VT);
448 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
449 return materializeFP(CFP, VT);
450 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
451 return materializeGV(GV);
456 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
457 assert(CFP->isNullValue() &&
458 "Floating-point constant is not a positive zero.");
460 if (!isTypeLegal(CFP->getType(), VT))
463 if (VT != MVT::f32 && VT != MVT::f64)
466 bool Is64Bit = (VT == MVT::f64);
467 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
468 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
469 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
472 /// \brief Check if the multiply is by a power-of-2 constant.
473 static bool isMulPowOf2(const Value *I) {
474 if (const auto *MI = dyn_cast<MulOperator>(I)) {
475 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
476 if (C->getValue().isPowerOf2())
478 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
479 if (C->getValue().isPowerOf2())
485 // Computes the address to get to an object.
486 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
488 const User *U = nullptr;
489 unsigned Opcode = Instruction::UserOp1;
490 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
491 // Don't walk into other basic blocks unless the object is an alloca from
492 // another block, otherwise it may not have a virtual register assigned.
493 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
494 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
495 Opcode = I->getOpcode();
498 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
499 Opcode = C->getOpcode();
503 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
504 if (Ty->getAddressSpace() > 255)
505 // Fast instruction selection doesn't support the special
512 case Instruction::BitCast: {
513 // Look through bitcasts.
514 return computeAddress(U->getOperand(0), Addr, Ty);
516 case Instruction::IntToPtr: {
517 // Look past no-op inttoptrs.
518 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
519 return computeAddress(U->getOperand(0), Addr, Ty);
522 case Instruction::PtrToInt: {
523 // Look past no-op ptrtoints.
524 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
525 return computeAddress(U->getOperand(0), Addr, Ty);
528 case Instruction::GetElementPtr: {
529 Address SavedAddr = Addr;
530 uint64_t TmpOffset = Addr.getOffset();
532 // Iterate through the GEP folding the constants into offsets where
534 gep_type_iterator GTI = gep_type_begin(U);
535 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
537 const Value *Op = *i;
538 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
539 const StructLayout *SL = DL.getStructLayout(STy);
540 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
541 TmpOffset += SL->getElementOffset(Idx);
543 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
545 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
546 // Constant-offset addressing.
547 TmpOffset += CI->getSExtValue() * S;
550 if (canFoldAddIntoGEP(U, Op)) {
551 // A compatible add with a constant operand. Fold the constant.
553 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
554 TmpOffset += CI->getSExtValue() * S;
555 // Iterate on the other operand.
556 Op = cast<AddOperator>(Op)->getOperand(0);
560 goto unsupported_gep;
565 // Try to grab the base operand now.
566 Addr.setOffset(TmpOffset);
567 if (computeAddress(U->getOperand(0), Addr, Ty))
570 // We failed, restore everything and try the other options.
576 case Instruction::Alloca: {
577 const AllocaInst *AI = cast<AllocaInst>(Obj);
578 DenseMap<const AllocaInst *, int>::iterator SI =
579 FuncInfo.StaticAllocaMap.find(AI);
580 if (SI != FuncInfo.StaticAllocaMap.end()) {
581 Addr.setKind(Address::FrameIndexBase);
582 Addr.setFI(SI->second);
587 case Instruction::Add: {
588 // Adds of constants are common and easy enough.
589 const Value *LHS = U->getOperand(0);
590 const Value *RHS = U->getOperand(1);
592 if (isa<ConstantInt>(LHS))
595 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
596 Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
597 return computeAddress(LHS, Addr, Ty);
600 Address Backup = Addr;
601 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
607 case Instruction::Sub: {
608 // Subs of constants are common and easy enough.
609 const Value *LHS = U->getOperand(0);
610 const Value *RHS = U->getOperand(1);
612 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
613 Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
614 return computeAddress(LHS, Addr, Ty);
618 case Instruction::Shl: {
619 if (Addr.getOffsetReg())
622 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
626 unsigned Val = CI->getZExtValue();
627 if (Val < 1 || Val > 3)
630 uint64_t NumBytes = 0;
631 if (Ty && Ty->isSized()) {
632 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
633 NumBytes = NumBits / 8;
634 if (!isPowerOf2_64(NumBits))
638 if (NumBytes != (1ULL << Val))
642 Addr.setExtendType(AArch64_AM::LSL);
644 const Value *Src = U->getOperand(0);
645 if (const auto *I = dyn_cast<Instruction>(Src))
646 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
649 // Fold the zext or sext when it won't become a noop.
650 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
651 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
652 Addr.setExtendType(AArch64_AM::UXTW);
653 Src = ZE->getOperand(0);
655 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
656 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
657 Addr.setExtendType(AArch64_AM::SXTW);
658 Src = SE->getOperand(0);
662 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
663 if (AI->getOpcode() == Instruction::And) {
664 const Value *LHS = AI->getOperand(0);
665 const Value *RHS = AI->getOperand(1);
667 if (const auto *C = dyn_cast<ConstantInt>(LHS))
668 if (C->getValue() == 0xffffffff)
671 if (const auto *C = dyn_cast<ConstantInt>(RHS))
672 if (C->getValue() == 0xffffffff) {
673 Addr.setExtendType(AArch64_AM::UXTW);
674 unsigned Reg = getRegForValue(LHS);
677 bool RegIsKill = hasTrivialKill(LHS);
678 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
680 Addr.setOffsetReg(Reg);
685 unsigned Reg = getRegForValue(Src);
688 Addr.setOffsetReg(Reg);
691 case Instruction::Mul: {
692 if (Addr.getOffsetReg())
698 const Value *LHS = U->getOperand(0);
699 const Value *RHS = U->getOperand(1);
701 // Canonicalize power-of-2 value to the RHS.
702 if (const auto *C = dyn_cast<ConstantInt>(LHS))
703 if (C->getValue().isPowerOf2())
706 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
707 const auto *C = cast<ConstantInt>(RHS);
708 unsigned Val = C->getValue().logBase2();
709 if (Val < 1 || Val > 3)
712 uint64_t NumBytes = 0;
713 if (Ty && Ty->isSized()) {
714 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
715 NumBytes = NumBits / 8;
716 if (!isPowerOf2_64(NumBits))
720 if (NumBytes != (1ULL << Val))
724 Addr.setExtendType(AArch64_AM::LSL);
726 const Value *Src = LHS;
727 if (const auto *I = dyn_cast<Instruction>(Src))
728 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
732 // Fold the zext or sext when it won't become a noop.
733 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
734 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
735 Addr.setExtendType(AArch64_AM::UXTW);
736 Src = ZE->getOperand(0);
738 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
739 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
740 Addr.setExtendType(AArch64_AM::SXTW);
741 Src = SE->getOperand(0);
745 unsigned Reg = getRegForValue(Src);
748 Addr.setOffsetReg(Reg);
751 case Instruction::And: {
752 if (Addr.getOffsetReg())
755 if (DL.getTypeSizeInBits(Ty) != 8)
758 const Value *LHS = U->getOperand(0);
759 const Value *RHS = U->getOperand(1);
761 if (const auto *C = dyn_cast<ConstantInt>(LHS))
762 if (C->getValue() == 0xffffffff)
765 if (const auto *C = dyn_cast<ConstantInt>(RHS))
766 if (C->getValue() == 0xffffffff) {
768 Addr.setExtendType(AArch64_AM::LSL);
769 Addr.setExtendType(AArch64_AM::UXTW);
771 unsigned Reg = getRegForValue(LHS);
774 bool RegIsKill = hasTrivialKill(LHS);
775 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
777 Addr.setOffsetReg(Reg);
782 case Instruction::SExt:
783 case Instruction::ZExt: {
784 if (!Addr.getReg() || Addr.getOffsetReg())
787 const Value *Src = nullptr;
788 // Fold the zext or sext when it won't become a noop.
789 if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
790 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
791 Addr.setExtendType(AArch64_AM::UXTW);
792 Src = ZE->getOperand(0);
794 } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
795 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
796 Addr.setExtendType(AArch64_AM::SXTW);
797 Src = SE->getOperand(0);
805 unsigned Reg = getRegForValue(Src);
808 Addr.setOffsetReg(Reg);
813 if (Addr.isRegBase() && !Addr.getReg()) {
814 unsigned Reg = getRegForValue(Obj);
821 if (!Addr.getOffsetReg()) {
822 unsigned Reg = getRegForValue(Obj);
825 Addr.setOffsetReg(Reg);
832 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
833 const User *U = nullptr;
834 unsigned Opcode = Instruction::UserOp1;
837 if (const auto *I = dyn_cast<Instruction>(V)) {
838 Opcode = I->getOpcode();
840 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
841 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
842 Opcode = C->getOpcode();
848 case Instruction::BitCast:
849 // Look past bitcasts if its operand is in the same BB.
851 return computeCallAddress(U->getOperand(0), Addr);
853 case Instruction::IntToPtr:
854 // Look past no-op inttoptrs if its operand is in the same BB.
856 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
857 return computeCallAddress(U->getOperand(0), Addr);
859 case Instruction::PtrToInt:
860 // Look past no-op ptrtoints if its operand is in the same BB.
862 TLI.getValueType(U->getType()) == TLI.getPointerTy())
863 return computeCallAddress(U->getOperand(0), Addr);
867 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
868 Addr.setGlobalValue(GV);
872 // If all else fails, try to materialize the value in a register.
873 if (!Addr.getGlobalValue()) {
874 Addr.setReg(getRegForValue(V));
875 return Addr.getReg() != 0;
882 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
883 EVT evt = TLI.getValueType(Ty, true);
885 // Only handle simple types.
886 if (evt == MVT::Other || !evt.isSimple())
888 VT = evt.getSimpleVT();
890 // This is a legal type, but it's not something we handle in fast-isel.
894 // Handle all other legal types, i.e. a register that will directly hold this
896 return TLI.isTypeLegal(VT);
899 /// \brief Determine if the value type is supported by FastISel.
901 /// FastISel for AArch64 can handle more value types than are legal. This adds
902 /// simple value type such as i1, i8, and i16.
903 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
904 if (Ty->isVectorTy() && !IsVectorAllowed)
907 if (isTypeLegal(Ty, VT))
910 // If this is a type than can be sign or zero-extended to a basic operation
911 // go ahead and accept it now.
912 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
918 bool AArch64FastISel::isValueAvailable(const Value *V) const {
919 if (!isa<Instruction>(V))
922 const auto *I = cast<Instruction>(V);
923 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
929 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
930 unsigned ScaleFactor = getImplicitScaleFactor(VT);
934 bool ImmediateOffsetNeedsLowering = false;
935 bool RegisterOffsetNeedsLowering = false;
936 int64_t Offset = Addr.getOffset();
937 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
938 ImmediateOffsetNeedsLowering = true;
939 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
940 !isUInt<12>(Offset / ScaleFactor))
941 ImmediateOffsetNeedsLowering = true;
943 // Cannot encode an offset register and an immediate offset in the same
944 // instruction. Fold the immediate offset into the load/store instruction and
945 // emit an additonal add to take care of the offset register.
946 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.getOffsetReg())
947 RegisterOffsetNeedsLowering = true;
949 // Cannot encode zero register as base.
950 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
951 RegisterOffsetNeedsLowering = true;
953 // If this is a stack pointer and the offset needs to be simplified then put
954 // the alloca address into a register, set the base type back to register and
955 // continue. This should almost never happen.
956 if ((ImmediateOffsetNeedsLowering || Addr.getOffsetReg()) && Addr.isFIBase())
958 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
959 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
961 .addFrameIndex(Addr.getFI())
964 Addr.setKind(Address::RegBase);
965 Addr.setReg(ResultReg);
968 if (RegisterOffsetNeedsLowering) {
969 unsigned ResultReg = 0;
971 if (Addr.getExtendType() == AArch64_AM::SXTW ||
972 Addr.getExtendType() == AArch64_AM::UXTW )
973 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
974 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
975 /*TODO:IsKill=*/false, Addr.getExtendType(),
978 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
979 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
980 /*TODO:IsKill=*/false, AArch64_AM::LSL,
983 if (Addr.getExtendType() == AArch64_AM::UXTW)
984 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
985 /*Op0IsKill=*/false, Addr.getShift(),
987 else if (Addr.getExtendType() == AArch64_AM::SXTW)
988 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
989 /*Op0IsKill=*/false, Addr.getShift(),
992 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
993 /*Op0IsKill=*/false, Addr.getShift());
998 Addr.setReg(ResultReg);
999 Addr.setOffsetReg(0);
1001 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1004 // Since the offset is too large for the load/store instruction get the
1005 // reg+offset into a register.
1006 if (ImmediateOffsetNeedsLowering) {
1009 // Try to fold the immediate into the add instruction.
1010 ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1012 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1016 Addr.setReg(ResultReg);
1022 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1023 const MachineInstrBuilder &MIB,
1025 unsigned ScaleFactor,
1026 MachineMemOperand *MMO) {
1027 int64_t Offset = Addr.getOffset() / ScaleFactor;
1028 // Frame base works a bit differently. Handle it separately.
1029 if (Addr.isFIBase()) {
1030 int FI = Addr.getFI();
1031 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1032 // and alignment should be based on the VT.
1033 MMO = FuncInfo.MF->getMachineMemOperand(
1034 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1035 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1036 // Now add the rest of the operands.
1037 MIB.addFrameIndex(FI).addImm(Offset);
1039 assert(Addr.isRegBase() && "Unexpected address kind.");
1040 const MCInstrDesc &II = MIB->getDesc();
1041 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1043 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1045 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1046 if (Addr.getOffsetReg()) {
1047 assert(Addr.getOffset() == 0 && "Unexpected offset");
1048 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1049 Addr.getExtendType() == AArch64_AM::SXTX;
1050 MIB.addReg(Addr.getReg());
1051 MIB.addReg(Addr.getOffsetReg());
1052 MIB.addImm(IsSigned);
1053 MIB.addImm(Addr.getShift() != 0);
1055 MIB.addReg(Addr.getReg()).addImm(Offset);
1059 MIB.addMemOperand(MMO);
1062 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1063 const Value *RHS, bool SetFlags,
1064 bool WantResult, bool IsZExt) {
1065 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1066 bool NeedExtend = false;
1067 switch (RetVT.SimpleTy) {
1075 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1079 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1081 case MVT::i32: // fall-through
1086 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1088 // Canonicalize immediates to the RHS first.
1089 if (UseAdd && isa<Constant>(LHS) && !isa<Constant>(RHS))
1090 std::swap(LHS, RHS);
1092 // Canonicalize mul by power of 2 to the RHS.
1093 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1094 if (isMulPowOf2(LHS))
1095 std::swap(LHS, RHS);
1097 // Canonicalize shift immediate to the RHS.
1098 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1099 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1100 if (isa<ConstantInt>(SI->getOperand(1)))
1101 if (SI->getOpcode() == Instruction::Shl ||
1102 SI->getOpcode() == Instruction::LShr ||
1103 SI->getOpcode() == Instruction::AShr )
1104 std::swap(LHS, RHS);
1106 unsigned LHSReg = getRegForValue(LHS);
1109 bool LHSIsKill = hasTrivialKill(LHS);
1112 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1114 unsigned ResultReg = 0;
1115 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1116 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1117 if (C->isNegative())
1118 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1119 SetFlags, WantResult);
1121 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1123 } else if (const auto *C = dyn_cast<Constant>(RHS))
1124 if (C->isNullValue())
1125 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, 0, SetFlags,
1131 // Only extend the RHS within the instruction if there is a valid extend type.
1132 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1133 isValueAvailable(RHS)) {
1134 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1135 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1136 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1137 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1140 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1141 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1142 RHSIsKill, ExtendType, C->getZExtValue(),
1143 SetFlags, WantResult);
1145 unsigned RHSReg = getRegForValue(RHS);
1148 bool RHSIsKill = hasTrivialKill(RHS);
1149 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1150 ExtendType, 0, SetFlags, WantResult);
1153 // Check if the mul can be folded into the instruction.
1154 if (RHS->hasOneUse() && isValueAvailable(RHS))
1155 if (isMulPowOf2(RHS)) {
1156 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1157 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1159 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1160 if (C->getValue().isPowerOf2())
1161 std::swap(MulLHS, MulRHS);
1163 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1164 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1165 unsigned RHSReg = getRegForValue(MulLHS);
1168 bool RHSIsKill = hasTrivialKill(MulLHS);
1169 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1170 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1173 // Check if the shift can be folded into the instruction.
1174 if (RHS->hasOneUse() && isValueAvailable(RHS))
1175 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1176 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1177 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1178 switch (SI->getOpcode()) {
1180 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1181 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1182 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1184 uint64_t ShiftVal = C->getZExtValue();
1185 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1186 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1189 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1190 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1191 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1197 unsigned RHSReg = getRegForValue(RHS);
1200 bool RHSIsKill = hasTrivialKill(RHS);
1203 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1205 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1206 SetFlags, WantResult);
1209 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1210 bool LHSIsKill, unsigned RHSReg,
1211 bool RHSIsKill, bool SetFlags,
1213 assert(LHSReg && RHSReg && "Invalid register number.");
1215 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1218 static const unsigned OpcTable[2][2][2] = {
1219 { { AArch64::SUBWrr, AArch64::SUBXrr },
1220 { AArch64::ADDWrr, AArch64::ADDXrr } },
1221 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1222 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1224 bool Is64Bit = RetVT == MVT::i64;
1225 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1226 const TargetRegisterClass *RC =
1227 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1230 ResultReg = createResultReg(RC);
1232 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1234 const MCInstrDesc &II = TII.get(Opc);
1235 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1236 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1238 .addReg(LHSReg, getKillRegState(LHSIsKill))
1239 .addReg(RHSReg, getKillRegState(RHSIsKill));
1243 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1244 bool LHSIsKill, uint64_t Imm,
1245 bool SetFlags, bool WantResult) {
1246 assert(LHSReg && "Invalid register number.");
1248 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1252 if (isUInt<12>(Imm))
1254 else if ((Imm & 0xfff000) == Imm) {
1260 static const unsigned OpcTable[2][2][2] = {
1261 { { AArch64::SUBWri, AArch64::SUBXri },
1262 { AArch64::ADDWri, AArch64::ADDXri } },
1263 { { AArch64::SUBSWri, AArch64::SUBSXri },
1264 { AArch64::ADDSWri, AArch64::ADDSXri } }
1266 bool Is64Bit = RetVT == MVT::i64;
1267 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1268 const TargetRegisterClass *RC;
1270 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1272 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1275 ResultReg = createResultReg(RC);
1277 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1279 const MCInstrDesc &II = TII.get(Opc);
1280 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1282 .addReg(LHSReg, getKillRegState(LHSIsKill))
1284 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1288 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1289 bool LHSIsKill, unsigned RHSReg,
1291 AArch64_AM::ShiftExtendType ShiftType,
1292 uint64_t ShiftImm, bool SetFlags,
1294 assert(LHSReg && RHSReg && "Invalid register number.");
1296 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1299 static const unsigned OpcTable[2][2][2] = {
1300 { { AArch64::SUBWrs, AArch64::SUBXrs },
1301 { AArch64::ADDWrs, AArch64::ADDXrs } },
1302 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1303 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1305 bool Is64Bit = RetVT == MVT::i64;
1306 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1307 const TargetRegisterClass *RC =
1308 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1311 ResultReg = createResultReg(RC);
1313 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1315 const MCInstrDesc &II = TII.get(Opc);
1316 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1317 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1318 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1319 .addReg(LHSReg, getKillRegState(LHSIsKill))
1320 .addReg(RHSReg, getKillRegState(RHSIsKill))
1321 .addImm(getShifterImm(ShiftType, ShiftImm));
1325 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1326 bool LHSIsKill, unsigned RHSReg,
1328 AArch64_AM::ShiftExtendType ExtType,
1329 uint64_t ShiftImm, bool SetFlags,
1331 assert(LHSReg && RHSReg && "Invalid register number.");
1333 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1336 static const unsigned OpcTable[2][2][2] = {
1337 { { AArch64::SUBWrx, AArch64::SUBXrx },
1338 { AArch64::ADDWrx, AArch64::ADDXrx } },
1339 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1340 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1342 bool Is64Bit = RetVT == MVT::i64;
1343 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1344 const TargetRegisterClass *RC = nullptr;
1346 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1348 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1351 ResultReg = createResultReg(RC);
1353 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1355 const MCInstrDesc &II = TII.get(Opc);
1356 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1357 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1358 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1359 .addReg(LHSReg, getKillRegState(LHSIsKill))
1360 .addReg(RHSReg, getKillRegState(RHSIsKill))
1361 .addImm(getArithExtendImm(ExtType, ShiftImm));
1365 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1366 Type *Ty = LHS->getType();
1367 EVT EVT = TLI.getValueType(Ty, true);
1368 if (!EVT.isSimple())
1370 MVT VT = EVT.getSimpleVT();
1372 switch (VT.SimpleTy) {
1380 return emitICmp(VT, LHS, RHS, IsZExt);
1383 return emitFCmp(VT, LHS, RHS);
1387 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1389 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1393 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1395 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1396 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1399 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1400 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1403 // Check to see if the 2nd operand is a constant that we can encode directly
1405 bool UseImm = false;
1406 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1407 if (CFP->isZero() && !CFP->isNegative())
1410 unsigned LHSReg = getRegForValue(LHS);
1413 bool LHSIsKill = hasTrivialKill(LHS);
1416 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1417 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1418 .addReg(LHSReg, getKillRegState(LHSIsKill));
1422 unsigned RHSReg = getRegForValue(RHS);
1425 bool RHSIsKill = hasTrivialKill(RHS);
1427 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1429 .addReg(LHSReg, getKillRegState(LHSIsKill))
1430 .addReg(RHSReg, getKillRegState(RHSIsKill));
1434 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1435 bool SetFlags, bool WantResult, bool IsZExt) {
1436 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1440 /// \brief This method is a wrapper to simplify add emission.
1442 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1443 /// that fails, then try to materialize the immediate into a register and use
1444 /// emitAddSub_rr instead.
1445 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1449 ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1451 ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1456 unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1460 ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1464 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1465 bool SetFlags, bool WantResult, bool IsZExt) {
1466 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1470 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1471 bool LHSIsKill, unsigned RHSReg,
1472 bool RHSIsKill, bool WantResult) {
1473 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1474 RHSIsKill, /*SetFlags=*/true, WantResult);
1477 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1478 bool LHSIsKill, unsigned RHSReg,
1480 AArch64_AM::ShiftExtendType ShiftType,
1481 uint64_t ShiftImm, bool WantResult) {
1482 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1483 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1487 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1488 const Value *LHS, const Value *RHS) {
1489 // Canonicalize immediates to the RHS first.
1490 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1491 std::swap(LHS, RHS);
1493 // Canonicalize mul by power-of-2 to the RHS.
1494 if (LHS->hasOneUse() && isValueAvailable(LHS))
1495 if (isMulPowOf2(LHS))
1496 std::swap(LHS, RHS);
1498 // Canonicalize shift immediate to the RHS.
1499 if (LHS->hasOneUse() && isValueAvailable(LHS))
1500 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1501 if (isa<ConstantInt>(SI->getOperand(1)))
1502 std::swap(LHS, RHS);
1504 unsigned LHSReg = getRegForValue(LHS);
1507 bool LHSIsKill = hasTrivialKill(LHS);
1509 unsigned ResultReg = 0;
1510 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1511 uint64_t Imm = C->getZExtValue();
1512 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1517 // Check if the mul can be folded into the instruction.
1518 if (RHS->hasOneUse() && isValueAvailable(RHS))
1519 if (isMulPowOf2(RHS)) {
1520 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1521 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1523 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1524 if (C->getValue().isPowerOf2())
1525 std::swap(MulLHS, MulRHS);
1527 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1528 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1530 unsigned RHSReg = getRegForValue(MulLHS);
1533 bool RHSIsKill = hasTrivialKill(MulLHS);
1534 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1535 RHSIsKill, ShiftVal);
1538 // Check if the shift can be folded into the instruction.
1539 if (RHS->hasOneUse() && isValueAvailable(RHS))
1540 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1541 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1542 uint64_t ShiftVal = C->getZExtValue();
1543 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1546 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1547 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1548 RHSIsKill, ShiftVal);
1551 unsigned RHSReg = getRegForValue(RHS);
1554 bool RHSIsKill = hasTrivialKill(RHS);
1556 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1557 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1558 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1559 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1560 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1565 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1566 unsigned LHSReg, bool LHSIsKill,
1568 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1569 "ISD nodes are not consecutive!");
1570 static const unsigned OpcTable[3][2] = {
1571 { AArch64::ANDWri, AArch64::ANDXri },
1572 { AArch64::ORRWri, AArch64::ORRXri },
1573 { AArch64::EORWri, AArch64::EORXri }
1575 const TargetRegisterClass *RC;
1578 switch (RetVT.SimpleTy) {
1585 unsigned Idx = ISDOpc - ISD::AND;
1586 Opc = OpcTable[Idx][0];
1587 RC = &AArch64::GPR32spRegClass;
1592 Opc = OpcTable[ISDOpc - ISD::AND][1];
1593 RC = &AArch64::GPR64spRegClass;
1598 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1601 unsigned ResultReg =
1602 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1603 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1604 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1605 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1606 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1611 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1612 unsigned LHSReg, bool LHSIsKill,
1613 unsigned RHSReg, bool RHSIsKill,
1614 uint64_t ShiftImm) {
1615 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1616 "ISD nodes are not consecutive!");
1617 static const unsigned OpcTable[3][2] = {
1618 { AArch64::ANDWrs, AArch64::ANDXrs },
1619 { AArch64::ORRWrs, AArch64::ORRXrs },
1620 { AArch64::EORWrs, AArch64::EORXrs }
1622 const TargetRegisterClass *RC;
1624 switch (RetVT.SimpleTy) {
1631 Opc = OpcTable[ISDOpc - ISD::AND][0];
1632 RC = &AArch64::GPR32RegClass;
1635 Opc = OpcTable[ISDOpc - ISD::AND][1];
1636 RC = &AArch64::GPR64RegClass;
1639 unsigned ResultReg =
1640 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1641 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1642 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1643 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1644 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1649 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1651 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1654 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1655 bool WantZExt, MachineMemOperand *MMO) {
1656 // Simplify this down to something we can handle.
1657 if (!simplifyAddress(Addr, VT))
1660 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1662 llvm_unreachable("Unexpected value type.");
1664 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1665 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1666 bool UseScaled = true;
1667 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1672 static const unsigned GPOpcTable[2][8][4] = {
1674 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1676 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1678 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1680 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1682 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1684 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1686 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1688 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1692 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1694 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1696 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1698 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1700 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1702 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1704 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1706 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1711 static const unsigned FPOpcTable[4][2] = {
1712 { AArch64::LDURSi, AArch64::LDURDi },
1713 { AArch64::LDRSui, AArch64::LDRDui },
1714 { AArch64::LDRSroX, AArch64::LDRDroX },
1715 { AArch64::LDRSroW, AArch64::LDRDroW }
1719 const TargetRegisterClass *RC;
1720 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1721 Addr.getOffsetReg();
1722 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1723 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1724 Addr.getExtendType() == AArch64_AM::SXTW)
1727 bool IsRet64Bit = RetVT == MVT::i64;
1728 switch (VT.SimpleTy) {
1730 llvm_unreachable("Unexpected value type.");
1731 case MVT::i1: // Intentional fall-through.
1733 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1734 RC = (IsRet64Bit && !WantZExt) ?
1735 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1738 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1739 RC = (IsRet64Bit && !WantZExt) ?
1740 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1743 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1744 RC = (IsRet64Bit && !WantZExt) ?
1745 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1748 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1749 RC = &AArch64::GPR64RegClass;
1752 Opc = FPOpcTable[Idx][0];
1753 RC = &AArch64::FPR32RegClass;
1756 Opc = FPOpcTable[Idx][1];
1757 RC = &AArch64::FPR64RegClass;
1761 // Create the base instruction, then add the operands.
1762 unsigned ResultReg = createResultReg(RC);
1763 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1764 TII.get(Opc), ResultReg);
1765 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1767 // Loading an i1 requires special handling.
1768 if (VT == MVT::i1) {
1769 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1770 assert(ANDReg && "Unexpected AND instruction emission failure.");
1774 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1775 // the 32bit reg to a 64bit reg.
1776 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1777 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1778 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1779 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1781 .addReg(ResultReg, getKillRegState(true))
1782 .addImm(AArch64::sub_32);
1788 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1790 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1794 return selectOperator(I, I->getOpcode());
1797 switch (I->getOpcode()) {
1799 llvm_unreachable("Unexpected instruction.");
1800 case Instruction::Add:
1801 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1803 case Instruction::Sub:
1804 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1810 updateValueMap(I, ResultReg);
1814 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1816 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1820 return selectOperator(I, I->getOpcode());
1823 switch (I->getOpcode()) {
1825 llvm_unreachable("Unexpected instruction.");
1826 case Instruction::And:
1827 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1829 case Instruction::Or:
1830 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1832 case Instruction::Xor:
1833 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1839 updateValueMap(I, ResultReg);
1843 bool AArch64FastISel::selectLoad(const Instruction *I) {
1845 // Verify we have a legal type before going any further. Currently, we handle
1846 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1847 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1848 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1849 cast<LoadInst>(I)->isAtomic())
1852 // See if we can handle this address.
1854 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1857 // Fold the following sign-/zero-extend into the load instruction.
1858 bool WantZExt = true;
1860 const Value *IntExtVal = nullptr;
1861 if (I->hasOneUse()) {
1862 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1863 if (isTypeSupported(ZE->getType(), RetVT))
1867 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1868 if (isTypeSupported(SE->getType(), RetVT))
1876 unsigned ResultReg =
1877 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1881 // There are a few different cases we have to handle, because the load or the
1882 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1883 // SelectionDAG. There is also an ordering issue when both instructions are in
1884 // different basic blocks.
1885 // 1.) The load instruction is selected by FastISel, but the integer extend
1886 // not. This usually happens when the integer extend is in a different
1887 // basic block and SelectionDAG took over for that basic block.
1888 // 2.) The load instruction is selected before the integer extend. This only
1889 // happens when the integer extend is in a different basic block.
1890 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1891 // by FastISel. This happens if there are instructions between the load
1892 // and the integer extend that couldn't be selected by FastISel.
1894 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1895 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1896 // it when it selects the integer extend.
1897 unsigned Reg = lookUpRegForValue(IntExtVal);
1899 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1901 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1902 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1903 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1905 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1909 updateValueMap(I, ResultReg);
1913 // The integer extend has already been emitted - delete all the instructions
1914 // that have been emitted by the integer extend lowering code and use the
1915 // result from the load instruction directly.
1917 auto *MI = MRI.getUniqueVRegDef(Reg);
1921 for (auto &Opnd : MI->uses()) {
1923 Reg = Opnd.getReg();
1927 MI->eraseFromParent();
1929 updateValueMap(IntExtVal, ResultReg);
1933 updateValueMap(I, ResultReg);
1937 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1938 MachineMemOperand *MMO) {
1939 // Simplify this down to something we can handle.
1940 if (!simplifyAddress(Addr, VT))
1943 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1945 llvm_unreachable("Unexpected value type.");
1947 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1948 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1949 bool UseScaled = true;
1950 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1955 static const unsigned OpcTable[4][6] = {
1956 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1957 AArch64::STURSi, AArch64::STURDi },
1958 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1959 AArch64::STRSui, AArch64::STRDui },
1960 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1961 AArch64::STRSroX, AArch64::STRDroX },
1962 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1963 AArch64::STRSroW, AArch64::STRDroW }
1967 bool VTIsi1 = false;
1968 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1969 Addr.getOffsetReg();
1970 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1971 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1972 Addr.getExtendType() == AArch64_AM::SXTW)
1975 switch (VT.SimpleTy) {
1976 default: llvm_unreachable("Unexpected value type.");
1977 case MVT::i1: VTIsi1 = true;
1978 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1979 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1980 case MVT::i32: Opc = OpcTable[Idx][2]; break;
1981 case MVT::i64: Opc = OpcTable[Idx][3]; break;
1982 case MVT::f32: Opc = OpcTable[Idx][4]; break;
1983 case MVT::f64: Opc = OpcTable[Idx][5]; break;
1986 // Storing an i1 requires special handling.
1987 if (VTIsi1 && SrcReg != AArch64::WZR) {
1988 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1989 assert(ANDReg && "Unexpected AND instruction emission failure.");
1992 // Create the base instruction, then add the operands.
1993 const MCInstrDesc &II = TII.get(Opc);
1994 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
1995 MachineInstrBuilder MIB =
1996 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
1997 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
2002 bool AArch64FastISel::selectStore(const Instruction *I) {
2004 const Value *Op0 = I->getOperand(0);
2005 // Verify we have a legal type before going any further. Currently, we handle
2006 // simple types that will directly fit in a register (i32/f32/i64/f64) or
2007 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2008 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2009 cast<StoreInst>(I)->isAtomic())
2012 // Get the value to be stored into a register. Use the zero register directly
2013 // when possible to avoid an unnecessary copy and a wasted register.
2014 unsigned SrcReg = 0;
2015 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2017 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2018 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2019 if (CF->isZero() && !CF->isNegative()) {
2020 VT = MVT::getIntegerVT(VT.getSizeInBits());
2021 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2026 SrcReg = getRegForValue(Op0);
2031 // See if we can handle this address.
2033 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2036 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2041 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2043 case CmpInst::FCMP_ONE:
2044 case CmpInst::FCMP_UEQ:
2046 // AL is our "false" for now. The other two need more compares.
2047 return AArch64CC::AL;
2048 case CmpInst::ICMP_EQ:
2049 case CmpInst::FCMP_OEQ:
2050 return AArch64CC::EQ;
2051 case CmpInst::ICMP_SGT:
2052 case CmpInst::FCMP_OGT:
2053 return AArch64CC::GT;
2054 case CmpInst::ICMP_SGE:
2055 case CmpInst::FCMP_OGE:
2056 return AArch64CC::GE;
2057 case CmpInst::ICMP_UGT:
2058 case CmpInst::FCMP_UGT:
2059 return AArch64CC::HI;
2060 case CmpInst::FCMP_OLT:
2061 return AArch64CC::MI;
2062 case CmpInst::ICMP_ULE:
2063 case CmpInst::FCMP_OLE:
2064 return AArch64CC::LS;
2065 case CmpInst::FCMP_ORD:
2066 return AArch64CC::VC;
2067 case CmpInst::FCMP_UNO:
2068 return AArch64CC::VS;
2069 case CmpInst::FCMP_UGE:
2070 return AArch64CC::PL;
2071 case CmpInst::ICMP_SLT:
2072 case CmpInst::FCMP_ULT:
2073 return AArch64CC::LT;
2074 case CmpInst::ICMP_SLE:
2075 case CmpInst::FCMP_ULE:
2076 return AArch64CC::LE;
2077 case CmpInst::FCMP_UNE:
2078 case CmpInst::ICMP_NE:
2079 return AArch64CC::NE;
2080 case CmpInst::ICMP_UGE:
2081 return AArch64CC::HS;
2082 case CmpInst::ICMP_ULT:
2083 return AArch64CC::LO;
2087 /// \brief Try to emit a combined compare-and-branch instruction.
2088 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2089 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2090 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2091 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2093 const Value *LHS = CI->getOperand(0);
2094 const Value *RHS = CI->getOperand(1);
2097 if (!isTypeSupported(LHS->getType(), VT))
2100 unsigned BW = VT.getSizeInBits();
2104 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2105 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2107 // Try to take advantage of fallthrough opportunities.
2108 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2109 std::swap(TBB, FBB);
2110 Predicate = CmpInst::getInversePredicate(Predicate);
2115 switch (Predicate) {
2118 case CmpInst::ICMP_EQ:
2119 case CmpInst::ICMP_NE:
2120 if (isa<Constant>(LHS) && cast<Constant>(LHS)->isNullValue())
2121 std::swap(LHS, RHS);
2123 if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2126 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2127 if (AI->getOpcode() == Instruction::And && isValueAvailable(AI)) {
2128 const Value *AndLHS = AI->getOperand(0);
2129 const Value *AndRHS = AI->getOperand(1);
2131 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2132 if (C->getValue().isPowerOf2())
2133 std::swap(AndLHS, AndRHS);
2135 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2136 if (C->getValue().isPowerOf2()) {
2137 TestBit = C->getValue().logBase2();
2145 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2147 case CmpInst::ICMP_SLT:
2148 case CmpInst::ICMP_SGE:
2149 if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2153 IsCmpNE = Predicate == CmpInst::ICMP_SLT;
2155 case CmpInst::ICMP_SGT:
2156 case CmpInst::ICMP_SLE:
2157 if (!isa<ConstantInt>(RHS))
2160 if (cast<ConstantInt>(RHS)->getValue() != APInt(BW, -1, true))
2164 IsCmpNE = Predicate == CmpInst::ICMP_SLE;
2168 static const unsigned OpcTable[2][2][2] = {
2169 { {AArch64::CBZW, AArch64::CBZX },
2170 {AArch64::CBNZW, AArch64::CBNZX} },
2171 { {AArch64::TBZW, AArch64::TBZX },
2172 {AArch64::TBNZW, AArch64::TBNZX} }
2175 bool IsBitTest = TestBit != -1;
2176 bool Is64Bit = BW == 64;
2177 if (TestBit < 32 && TestBit >= 0)
2180 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2181 const MCInstrDesc &II = TII.get(Opc);
2183 unsigned SrcReg = getRegForValue(LHS);
2186 bool SrcIsKill = hasTrivialKill(LHS);
2188 if (BW == 64 && !Is64Bit)
2189 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2192 if ((BW < 32) && !IsBitTest)
2193 SrcReg = emitIntExt(VT, SrcReg, MVT::i32, /*IsZExt=*/true);
2195 // Emit the combined compare and branch instruction.
2196 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2197 MachineInstrBuilder MIB =
2198 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2199 .addReg(SrcReg, getKillRegState(SrcIsKill));
2201 MIB.addImm(TestBit);
2204 // Obtain the branch weight and add the TrueBB to the successor list.
2205 uint32_t BranchWeight = 0;
2207 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2208 TBB->getBasicBlock());
2209 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2210 fastEmitBranch(FBB, DbgLoc);
2215 bool AArch64FastISel::selectBranch(const Instruction *I) {
2216 const BranchInst *BI = cast<BranchInst>(I);
2217 if (BI->isUnconditional()) {
2218 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2219 fastEmitBranch(MSucc, BI->getDebugLoc());
2223 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2224 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2226 AArch64CC::CondCode CC = AArch64CC::NE;
2227 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2228 if (CI->hasOneUse() && isValueAvailable(CI)) {
2229 // Try to optimize or fold the cmp.
2230 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2231 switch (Predicate) {
2234 case CmpInst::FCMP_FALSE:
2235 fastEmitBranch(FBB, DbgLoc);
2237 case CmpInst::FCMP_TRUE:
2238 fastEmitBranch(TBB, DbgLoc);
2242 // Try to emit a combined compare-and-branch first.
2243 if (emitCompareAndBranch(BI))
2246 // Try to take advantage of fallthrough opportunities.
2247 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2248 std::swap(TBB, FBB);
2249 Predicate = CmpInst::getInversePredicate(Predicate);
2253 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2256 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2258 CC = getCompareCC(Predicate);
2259 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2260 switch (Predicate) {
2263 case CmpInst::FCMP_UEQ:
2264 ExtraCC = AArch64CC::EQ;
2267 case CmpInst::FCMP_ONE:
2268 ExtraCC = AArch64CC::MI;
2272 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2274 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2275 if (ExtraCC != AArch64CC::AL) {
2276 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2282 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2286 // Obtain the branch weight and add the TrueBB to the successor list.
2287 uint32_t BranchWeight = 0;
2289 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2290 TBB->getBasicBlock());
2291 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2293 fastEmitBranch(FBB, DbgLoc);
2296 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2298 if (TI->hasOneUse() && isValueAvailable(TI) &&
2299 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2300 unsigned CondReg = getRegForValue(TI->getOperand(0));
2303 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2305 // Issue an extract_subreg to get the lower 32-bits.
2306 if (SrcVT == MVT::i64) {
2307 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2312 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2313 assert(ANDReg && "Unexpected AND instruction emission failure.");
2314 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2316 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2317 std::swap(TBB, FBB);
2320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2324 // Obtain the branch weight and add the TrueBB to the successor list.
2325 uint32_t BranchWeight = 0;
2327 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2328 TBB->getBasicBlock());
2329 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2331 fastEmitBranch(FBB, DbgLoc);
2334 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2335 uint64_t Imm = CI->getZExtValue();
2336 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2337 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2340 // Obtain the branch weight and add the target to the successor list.
2341 uint32_t BranchWeight = 0;
2343 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2344 Target->getBasicBlock());
2345 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2347 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2348 // Fake request the condition, otherwise the intrinsic might be completely
2350 unsigned CondReg = getRegForValue(BI->getCondition());
2355 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2359 // Obtain the branch weight and add the TrueBB to the successor list.
2360 uint32_t BranchWeight = 0;
2362 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2363 TBB->getBasicBlock());
2364 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2366 fastEmitBranch(FBB, DbgLoc);
2370 unsigned CondReg = getRegForValue(BI->getCondition());
2373 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2375 // We've been divorced from our compare! Our block was split, and
2376 // now our compare lives in a predecessor block. We musn't
2377 // re-compare here, as the children of the compare aren't guaranteed
2378 // live across the block boundary (we *could* check for this).
2379 // Regardless, the compare has been done in the predecessor block,
2380 // and it left a value for us in a virtual register. Ergo, we test
2381 // the one-bit value left in the virtual register.
2382 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2384 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2385 std::swap(TBB, FBB);
2389 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2393 // Obtain the branch weight and add the TrueBB to the successor list.
2394 uint32_t BranchWeight = 0;
2396 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2397 TBB->getBasicBlock());
2398 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2400 fastEmitBranch(FBB, DbgLoc);
2404 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2405 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2406 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2410 // Emit the indirect branch.
2411 const MCInstrDesc &II = TII.get(AArch64::BR);
2412 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2413 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2415 // Make sure the CFG is up-to-date.
2416 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2417 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2422 bool AArch64FastISel::selectCmp(const Instruction *I) {
2423 const CmpInst *CI = cast<CmpInst>(I);
2425 // Try to optimize or fold the cmp.
2426 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2427 unsigned ResultReg = 0;
2428 switch (Predicate) {
2431 case CmpInst::FCMP_FALSE:
2432 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2434 TII.get(TargetOpcode::COPY), ResultReg)
2435 .addReg(AArch64::WZR, getKillRegState(true));
2437 case CmpInst::FCMP_TRUE:
2438 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2443 updateValueMap(I, ResultReg);
2448 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2451 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2453 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2454 // condition codes are inverted, because they are used by CSINC.
2455 static unsigned CondCodeTable[2][2] = {
2456 { AArch64CC::NE, AArch64CC::VC },
2457 { AArch64CC::PL, AArch64CC::LE }
2459 unsigned *CondCodes = nullptr;
2460 switch (Predicate) {
2463 case CmpInst::FCMP_UEQ:
2464 CondCodes = &CondCodeTable[0][0];
2466 case CmpInst::FCMP_ONE:
2467 CondCodes = &CondCodeTable[1][0];
2472 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2473 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2475 .addReg(AArch64::WZR, getKillRegState(true))
2476 .addReg(AArch64::WZR, getKillRegState(true))
2477 .addImm(CondCodes[0]);
2478 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2480 .addReg(TmpReg1, getKillRegState(true))
2481 .addReg(AArch64::WZR, getKillRegState(true))
2482 .addImm(CondCodes[1]);
2484 updateValueMap(I, ResultReg);
2488 // Now set a register based on the comparison.
2489 AArch64CC::CondCode CC = getCompareCC(Predicate);
2490 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2491 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2492 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2494 .addReg(AArch64::WZR, getKillRegState(true))
2495 .addReg(AArch64::WZR, getKillRegState(true))
2496 .addImm(invertedCC);
2498 updateValueMap(I, ResultReg);
2502 /// \brief Optimize selects of i1 if one of the operands has a 'true' or 'false'
2504 bool AArch64FastISel::optimizeSelect(const SelectInst *SI) {
2505 if (!SI->getType()->isIntegerTy(1))
2508 const Value *Src1Val, *Src2Val;
2510 bool NeedExtraOp = false;
2511 if (auto *CI = dyn_cast<ConstantInt>(SI->getTrueValue())) {
2513 Src1Val = SI->getCondition();
2514 Src2Val = SI->getFalseValue();
2515 Opc = AArch64::ORRWrr;
2517 assert(CI->isZero());
2518 Src1Val = SI->getFalseValue();
2519 Src2Val = SI->getCondition();
2520 Opc = AArch64::BICWrr;
2522 } else if (auto *CI = dyn_cast<ConstantInt>(SI->getFalseValue())) {
2524 Src1Val = SI->getCondition();
2525 Src2Val = SI->getTrueValue();
2526 Opc = AArch64::ORRWrr;
2529 assert(CI->isZero());
2530 Src1Val = SI->getCondition();
2531 Src2Val = SI->getTrueValue();
2532 Opc = AArch64::ANDWrr;
2539 unsigned Src1Reg = getRegForValue(Src1Val);
2542 bool Src1IsKill = hasTrivialKill(Src1Val);
2544 unsigned Src2Reg = getRegForValue(Src2Val);
2547 bool Src2IsKill = hasTrivialKill(Src2Val);
2550 Src1Reg = emitLogicalOp_ri(ISD::XOR, MVT::i32, Src1Reg, Src1IsKill, 1);
2553 unsigned ResultReg = fastEmitInst_rr(Opc, &AArch64::GPR32spRegClass, Src1Reg,
2554 Src1IsKill, Src2Reg, Src2IsKill);
2555 updateValueMap(SI, ResultReg);
2559 bool AArch64FastISel::selectSelect(const Instruction *I) {
2560 assert(isa<SelectInst>(I) && "Expected a select instruction.");
2562 if (!isTypeSupported(I->getType(), VT))
2566 const TargetRegisterClass *RC;
2567 switch (VT.SimpleTy) {
2574 Opc = AArch64::CSELWr;
2575 RC = &AArch64::GPR32RegClass;
2578 Opc = AArch64::CSELXr;
2579 RC = &AArch64::GPR64RegClass;
2582 Opc = AArch64::FCSELSrrr;
2583 RC = &AArch64::FPR32RegClass;
2586 Opc = AArch64::FCSELDrrr;
2587 RC = &AArch64::FPR64RegClass;
2591 const SelectInst *SI = cast<SelectInst>(I);
2592 const Value *Cond = SI->getCondition();
2593 AArch64CC::CondCode CC = AArch64CC::NE;
2594 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2596 if (optimizeSelect(SI))
2599 // Try to pickup the flags, so we don't have to emit another compare.
2600 if (foldXALUIntrinsic(CC, I, Cond)) {
2601 // Fake request the condition to force emission of the XALU intrinsic.
2602 unsigned CondReg = getRegForValue(Cond);
2605 } else if (isa<CmpInst>(Cond) && cast<CmpInst>(Cond)->hasOneUse() &&
2606 isValueAvailable(Cond)) {
2607 const auto *Cmp = cast<CmpInst>(Cond);
2608 // Try to optimize or fold the cmp.
2609 CmpInst::Predicate Predicate = optimizeCmpPredicate(Cmp);
2610 const Value *FoldSelect = nullptr;
2611 switch (Predicate) {
2614 case CmpInst::FCMP_FALSE:
2615 FoldSelect = SI->getFalseValue();
2617 case CmpInst::FCMP_TRUE:
2618 FoldSelect = SI->getTrueValue();
2623 unsigned SrcReg = getRegForValue(FoldSelect);
2626 unsigned UseReg = lookUpRegForValue(SI);
2628 MRI.clearKillFlags(UseReg);
2630 updateValueMap(I, SrcReg);
2635 if (!emitCmp(Cmp->getOperand(0), Cmp->getOperand(1), Cmp->isUnsigned()))
2638 // FCMP_UEQ and FCMP_ONE cannot be checked with a single select instruction.
2639 CC = getCompareCC(Predicate);
2640 switch (Predicate) {
2643 case CmpInst::FCMP_UEQ:
2644 ExtraCC = AArch64CC::EQ;
2647 case CmpInst::FCMP_ONE:
2648 ExtraCC = AArch64CC::MI;
2652 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2654 unsigned CondReg = getRegForValue(Cond);
2657 bool CondIsKill = hasTrivialKill(Cond);
2659 // Emit a TST instruction (ANDS wzr, reg, #imm).
2660 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDSWri),
2662 .addReg(CondReg, getKillRegState(CondIsKill))
2663 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2666 unsigned Src1Reg = getRegForValue(SI->getTrueValue());
2667 bool Src1IsKill = hasTrivialKill(SI->getTrueValue());
2669 unsigned Src2Reg = getRegForValue(SI->getFalseValue());
2670 bool Src2IsKill = hasTrivialKill(SI->getFalseValue());
2672 if (!Src1Reg || !Src2Reg)
2675 if (ExtraCC != AArch64CC::AL) {
2676 Src2Reg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2677 Src2IsKill, ExtraCC);
2680 unsigned ResultReg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2682 updateValueMap(I, ResultReg);
2686 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2687 Value *V = I->getOperand(0);
2688 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2691 unsigned Op = getRegForValue(V);
2695 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2696 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2697 ResultReg).addReg(Op);
2698 updateValueMap(I, ResultReg);
2702 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2703 Value *V = I->getOperand(0);
2704 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2707 unsigned Op = getRegForValue(V);
2711 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2712 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2713 ResultReg).addReg(Op);
2714 updateValueMap(I, ResultReg);
2718 // FPToUI and FPToSI
2719 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2721 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2724 unsigned SrcReg = getRegForValue(I->getOperand(0));
2728 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2729 if (SrcVT == MVT::f128)
2733 if (SrcVT == MVT::f64) {
2735 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2737 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2740 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2742 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2744 unsigned ResultReg = createResultReg(
2745 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2746 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2748 updateValueMap(I, ResultReg);
2752 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2754 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2756 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2757 "Unexpected value type.");
2759 unsigned SrcReg = getRegForValue(I->getOperand(0));
2762 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2764 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2766 // Handle sign-extension.
2767 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2769 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2776 if (SrcVT == MVT::i64) {
2778 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2780 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2783 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2785 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2788 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2790 updateValueMap(I, ResultReg);
2794 bool AArch64FastISel::fastLowerArguments() {
2795 if (!FuncInfo.CanLowerReturn)
2798 const Function *F = FuncInfo.Fn;
2802 CallingConv::ID CC = F->getCallingConv();
2803 if (CC != CallingConv::C)
2806 // Only handle simple cases of up to 8 GPR and FPR each.
2807 unsigned GPRCnt = 0;
2808 unsigned FPRCnt = 0;
2810 for (auto const &Arg : F->args()) {
2811 // The first argument is at index 1.
2813 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2814 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2815 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2816 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2819 Type *ArgTy = Arg.getType();
2820 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2823 EVT ArgVT = TLI.getValueType(ArgTy);
2824 if (!ArgVT.isSimple())
2827 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2828 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2831 if (VT.isVector() &&
2832 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2835 if (VT >= MVT::i1 && VT <= MVT::i64)
2837 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2838 VT.is128BitVector())
2843 if (GPRCnt > 8 || FPRCnt > 8)
2847 static const MCPhysReg Registers[6][8] = {
2848 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2849 AArch64::W5, AArch64::W6, AArch64::W7 },
2850 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2851 AArch64::X5, AArch64::X6, AArch64::X7 },
2852 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2853 AArch64::H5, AArch64::H6, AArch64::H7 },
2854 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2855 AArch64::S5, AArch64::S6, AArch64::S7 },
2856 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2857 AArch64::D5, AArch64::D6, AArch64::D7 },
2858 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2859 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2862 unsigned GPRIdx = 0;
2863 unsigned FPRIdx = 0;
2864 for (auto const &Arg : F->args()) {
2865 MVT VT = TLI.getSimpleValueType(Arg.getType());
2867 const TargetRegisterClass *RC;
2868 if (VT >= MVT::i1 && VT <= MVT::i32) {
2869 SrcReg = Registers[0][GPRIdx++];
2870 RC = &AArch64::GPR32RegClass;
2872 } else if (VT == MVT::i64) {
2873 SrcReg = Registers[1][GPRIdx++];
2874 RC = &AArch64::GPR64RegClass;
2875 } else if (VT == MVT::f16) {
2876 SrcReg = Registers[2][FPRIdx++];
2877 RC = &AArch64::FPR16RegClass;
2878 } else if (VT == MVT::f32) {
2879 SrcReg = Registers[3][FPRIdx++];
2880 RC = &AArch64::FPR32RegClass;
2881 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2882 SrcReg = Registers[4][FPRIdx++];
2883 RC = &AArch64::FPR64RegClass;
2884 } else if (VT.is128BitVector()) {
2885 SrcReg = Registers[5][FPRIdx++];
2886 RC = &AArch64::FPR128RegClass;
2888 llvm_unreachable("Unexpected value type.");
2890 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2891 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2892 // Without this, EmitLiveInCopies may eliminate the livein if its only
2893 // use is a bitcast (which isn't turned into an instruction).
2894 unsigned ResultReg = createResultReg(RC);
2895 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2896 TII.get(TargetOpcode::COPY), ResultReg)
2897 .addReg(DstReg, getKillRegState(true));
2898 updateValueMap(&Arg, ResultReg);
2903 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2904 SmallVectorImpl<MVT> &OutVTs,
2905 unsigned &NumBytes) {
2906 CallingConv::ID CC = CLI.CallConv;
2907 SmallVector<CCValAssign, 16> ArgLocs;
2908 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2909 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2911 // Get a count of how many bytes are to be pushed on the stack.
2912 NumBytes = CCInfo.getNextStackOffset();
2914 // Issue CALLSEQ_START
2915 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2916 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2919 // Process the args.
2920 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2921 CCValAssign &VA = ArgLocs[i];
2922 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2923 MVT ArgVT = OutVTs[VA.getValNo()];
2925 unsigned ArgReg = getRegForValue(ArgVal);
2929 // Handle arg promotion: SExt, ZExt, AExt.
2930 switch (VA.getLocInfo()) {
2931 case CCValAssign::Full:
2933 case CCValAssign::SExt: {
2934 MVT DestVT = VA.getLocVT();
2936 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2941 case CCValAssign::AExt:
2942 // Intentional fall-through.
2943 case CCValAssign::ZExt: {
2944 MVT DestVT = VA.getLocVT();
2946 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2952 llvm_unreachable("Unknown arg promotion!");
2955 // Now copy/store arg to correct locations.
2956 if (VA.isRegLoc() && !VA.needsCustom()) {
2957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2958 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2959 CLI.OutRegs.push_back(VA.getLocReg());
2960 } else if (VA.needsCustom()) {
2961 // FIXME: Handle custom args.
2964 assert(VA.isMemLoc() && "Assuming store on stack.");
2966 // Don't emit stores for undef values.
2967 if (isa<UndefValue>(ArgVal))
2970 // Need to store on the stack.
2971 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2973 unsigned BEAlign = 0;
2974 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2975 BEAlign = 8 - ArgSize;
2978 Addr.setKind(Address::RegBase);
2979 Addr.setReg(AArch64::SP);
2980 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2982 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2983 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2984 MachinePointerInfo::getStack(Addr.getOffset()),
2985 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2987 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2994 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2995 unsigned NumBytes) {
2996 CallingConv::ID CC = CLI.CallConv;
2998 // Issue CALLSEQ_END
2999 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3000 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3001 .addImm(NumBytes).addImm(0);
3003 // Now the return value.
3004 if (RetVT != MVT::isVoid) {
3005 SmallVector<CCValAssign, 16> RVLocs;
3006 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
3007 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
3009 // Only handle a single return value.
3010 if (RVLocs.size() != 1)
3013 // Copy all of the result registers out of their specified physreg.
3014 MVT CopyVT = RVLocs[0].getValVT();
3015 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
3016 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3017 TII.get(TargetOpcode::COPY), ResultReg)
3018 .addReg(RVLocs[0].getLocReg());
3019 CLI.InRegs.push_back(RVLocs[0].getLocReg());
3021 CLI.ResultReg = ResultReg;
3022 CLI.NumResultRegs = 1;
3028 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3029 CallingConv::ID CC = CLI.CallConv;
3030 bool IsTailCall = CLI.IsTailCall;
3031 bool IsVarArg = CLI.IsVarArg;
3032 const Value *Callee = CLI.Callee;
3033 const char *SymName = CLI.SymName;
3035 if (!Callee && !SymName)
3038 // Allow SelectionDAG isel to handle tail calls.
3042 CodeModel::Model CM = TM.getCodeModel();
3043 // Only support the small and large code model.
3044 if (CM != CodeModel::Small && CM != CodeModel::Large)
3047 // FIXME: Add large code model support for ELF.
3048 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
3051 // Let SDISel handle vararg functions.
3055 // FIXME: Only handle *simple* calls for now.
3057 if (CLI.RetTy->isVoidTy())
3058 RetVT = MVT::isVoid;
3059 else if (!isTypeLegal(CLI.RetTy, RetVT))
3062 for (auto Flag : CLI.OutFlags)
3063 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
3066 // Set up the argument vectors.
3067 SmallVector<MVT, 16> OutVTs;
3068 OutVTs.reserve(CLI.OutVals.size());
3070 for (auto *Val : CLI.OutVals) {
3072 if (!isTypeLegal(Val->getType(), VT) &&
3073 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
3076 // We don't handle vector parameters yet.
3077 if (VT.isVector() || VT.getSizeInBits() > 64)
3080 OutVTs.push_back(VT);
3084 if (Callee && !computeCallAddress(Callee, Addr))
3087 // Handle the arguments now that we've gotten them.
3089 if (!processCallArgs(CLI, OutVTs, NumBytes))
3093 MachineInstrBuilder MIB;
3094 if (CM == CodeModel::Small) {
3095 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
3096 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
3098 MIB.addExternalSymbol(SymName, 0);
3099 else if (Addr.getGlobalValue())
3100 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
3101 else if (Addr.getReg()) {
3102 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
3107 unsigned CallReg = 0;
3109 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
3110 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
3112 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
3114 CallReg = createResultReg(&AArch64::GPR64RegClass);
3115 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
3118 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
3120 } else if (Addr.getGlobalValue())
3121 CallReg = materializeGV(Addr.getGlobalValue());
3122 else if (Addr.getReg())
3123 CallReg = Addr.getReg();
3128 const MCInstrDesc &II = TII.get(AArch64::BLR);
3129 CallReg = constrainOperandRegClass(II, CallReg, 0);
3130 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
3133 // Add implicit physical register uses to the call.
3134 for (auto Reg : CLI.OutRegs)
3135 MIB.addReg(Reg, RegState::Implicit);
3137 // Add a register mask with the call-preserved registers.
3138 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3139 MIB.addRegMask(TRI.getCallPreservedMask(CC));
3143 // Finish off the call including any return values.
3144 return finishCall(CLI, RetVT, NumBytes);
3147 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3149 return Len / Alignment <= 4;
3154 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3155 uint64_t Len, unsigned Alignment) {
3156 // Make sure we don't bloat code by inlining very large memcpy's.
3157 if (!isMemCpySmall(Len, Alignment))
3160 int64_t UnscaledOffset = 0;
3161 Address OrigDest = Dest;
3162 Address OrigSrc = Src;
3166 if (!Alignment || Alignment >= 8) {
3177 // Bound based on alignment.
3178 if (Len >= 4 && Alignment == 4)
3180 else if (Len >= 2 && Alignment == 2)
3187 unsigned ResultReg = emitLoad(VT, VT, Src);
3191 if (!emitStore(VT, ResultReg, Dest))
3194 int64_t Size = VT.getSizeInBits() / 8;
3196 UnscaledOffset += Size;
3198 // We need to recompute the unscaled offset for each iteration.
3199 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3200 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3206 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3207 /// into the user. The condition code will only be updated on success.
3208 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3209 const Instruction *I,
3210 const Value *Cond) {
3211 if (!isa<ExtractValueInst>(Cond))
3214 const auto *EV = cast<ExtractValueInst>(Cond);
3215 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3218 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3220 const Function *Callee = II->getCalledFunction();
3222 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3223 if (!isTypeLegal(RetTy, RetVT))
3226 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3229 const Value *LHS = II->getArgOperand(0);
3230 const Value *RHS = II->getArgOperand(1);
3232 // Canonicalize immediate to the RHS.
3233 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3234 isCommutativeIntrinsic(II))
3235 std::swap(LHS, RHS);
3237 // Simplify multiplies.
3238 unsigned IID = II->getIntrinsicID();
3242 case Intrinsic::smul_with_overflow:
3243 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3244 if (C->getValue() == 2)
3245 IID = Intrinsic::sadd_with_overflow;
3247 case Intrinsic::umul_with_overflow:
3248 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3249 if (C->getValue() == 2)
3250 IID = Intrinsic::uadd_with_overflow;
3254 AArch64CC::CondCode TmpCC;
3258 case Intrinsic::sadd_with_overflow:
3259 case Intrinsic::ssub_with_overflow:
3260 TmpCC = AArch64CC::VS;
3262 case Intrinsic::uadd_with_overflow:
3263 TmpCC = AArch64CC::HS;
3265 case Intrinsic::usub_with_overflow:
3266 TmpCC = AArch64CC::LO;
3268 case Intrinsic::smul_with_overflow:
3269 case Intrinsic::umul_with_overflow:
3270 TmpCC = AArch64CC::NE;
3274 // Check if both instructions are in the same basic block.
3275 if (!isValueAvailable(II))
3278 // Make sure nothing is in the way
3279 BasicBlock::const_iterator Start = I;
3280 BasicBlock::const_iterator End = II;
3281 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3282 // We only expect extractvalue instructions between the intrinsic and the
3283 // instruction to be selected.
3284 if (!isa<ExtractValueInst>(Itr))
3287 // Check that the extractvalue operand comes from the intrinsic.
3288 const auto *EVI = cast<ExtractValueInst>(Itr);
3289 if (EVI->getAggregateOperand() != II)
3297 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3298 // FIXME: Handle more intrinsics.
3299 switch (II->getIntrinsicID()) {
3300 default: return false;
3301 case Intrinsic::frameaddress: {
3302 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3303 MFI->setFrameAddressIsTaken(true);
3305 const AArch64RegisterInfo *RegInfo =
3306 static_cast<const AArch64RegisterInfo *>(
3307 TM.getSubtargetImpl()->getRegisterInfo());
3308 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3309 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3310 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3311 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3312 // Recursively load frame address
3318 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3320 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3321 SrcReg, /*IsKill=*/true, 0);
3322 assert(DestReg && "Unexpected LDR instruction emission failure.");
3326 updateValueMap(II, SrcReg);
3329 case Intrinsic::memcpy:
3330 case Intrinsic::memmove: {
3331 const auto *MTI = cast<MemTransferInst>(II);
3332 // Don't handle volatile.
3333 if (MTI->isVolatile())
3336 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3337 // we would emit dead code because we don't currently handle memmoves.
3338 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3339 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3340 // Small memcpy's are common enough that we want to do them without a call
3342 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3343 unsigned Alignment = MTI->getAlignment();
3344 if (isMemCpySmall(Len, Alignment)) {
3346 if (!computeAddress(MTI->getRawDest(), Dest) ||
3347 !computeAddress(MTI->getRawSource(), Src))
3349 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3354 if (!MTI->getLength()->getType()->isIntegerTy(64))
3357 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3358 // Fast instruction selection doesn't support the special
3362 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3363 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3365 case Intrinsic::memset: {
3366 const MemSetInst *MSI = cast<MemSetInst>(II);
3367 // Don't handle volatile.
3368 if (MSI->isVolatile())
3371 if (!MSI->getLength()->getType()->isIntegerTy(64))
3374 if (MSI->getDestAddressSpace() > 255)
3375 // Fast instruction selection doesn't support the special
3379 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3381 case Intrinsic::sin:
3382 case Intrinsic::cos:
3383 case Intrinsic::pow: {
3385 if (!isTypeLegal(II->getType(), RetVT))
3388 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3391 static const RTLIB::Libcall LibCallTable[3][2] = {
3392 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3393 { RTLIB::COS_F32, RTLIB::COS_F64 },
3394 { RTLIB::POW_F32, RTLIB::POW_F64 }
3397 bool Is64Bit = RetVT == MVT::f64;
3398 switch (II->getIntrinsicID()) {
3400 llvm_unreachable("Unexpected intrinsic.");
3401 case Intrinsic::sin:
3402 LC = LibCallTable[0][Is64Bit];
3404 case Intrinsic::cos:
3405 LC = LibCallTable[1][Is64Bit];
3407 case Intrinsic::pow:
3408 LC = LibCallTable[2][Is64Bit];
3413 Args.reserve(II->getNumArgOperands());
3415 // Populate the argument list.
3416 for (auto &Arg : II->arg_operands()) {
3419 Entry.Ty = Arg->getType();
3420 Args.push_back(Entry);
3423 CallLoweringInfo CLI;
3424 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3425 TLI.getLibcallName(LC), std::move(Args));
3426 if (!lowerCallTo(CLI))
3428 updateValueMap(II, CLI.ResultReg);
3431 case Intrinsic::fabs: {
3433 if (!isTypeLegal(II->getType(), VT))
3437 switch (VT.SimpleTy) {
3441 Opc = AArch64::FABSSr;
3444 Opc = AArch64::FABSDr;
3447 unsigned SrcReg = getRegForValue(II->getOperand(0));
3450 bool SrcRegIsKill = hasTrivialKill(II->getOperand(0));
3451 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3452 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3453 .addReg(SrcReg, getKillRegState(SrcRegIsKill));
3454 updateValueMap(II, ResultReg);
3457 case Intrinsic::trap: {
3458 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3462 case Intrinsic::sqrt: {
3463 Type *RetTy = II->getCalledFunction()->getReturnType();
3466 if (!isTypeLegal(RetTy, VT))
3469 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3472 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3474 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3478 updateValueMap(II, ResultReg);
3481 case Intrinsic::sadd_with_overflow:
3482 case Intrinsic::uadd_with_overflow:
3483 case Intrinsic::ssub_with_overflow:
3484 case Intrinsic::usub_with_overflow:
3485 case Intrinsic::smul_with_overflow:
3486 case Intrinsic::umul_with_overflow: {
3487 // This implements the basic lowering of the xalu with overflow intrinsics.
3488 const Function *Callee = II->getCalledFunction();
3489 auto *Ty = cast<StructType>(Callee->getReturnType());
3490 Type *RetTy = Ty->getTypeAtIndex(0U);
3493 if (!isTypeLegal(RetTy, VT))
3496 if (VT != MVT::i32 && VT != MVT::i64)
3499 const Value *LHS = II->getArgOperand(0);
3500 const Value *RHS = II->getArgOperand(1);
3501 // Canonicalize immediate to the RHS.
3502 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3503 isCommutativeIntrinsic(II))
3504 std::swap(LHS, RHS);
3506 // Simplify multiplies.
3507 unsigned IID = II->getIntrinsicID();
3511 case Intrinsic::smul_with_overflow:
3512 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3513 if (C->getValue() == 2) {
3514 IID = Intrinsic::sadd_with_overflow;
3518 case Intrinsic::umul_with_overflow:
3519 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3520 if (C->getValue() == 2) {
3521 IID = Intrinsic::uadd_with_overflow;
3527 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3528 AArch64CC::CondCode CC = AArch64CC::Invalid;
3530 default: llvm_unreachable("Unexpected intrinsic!");
3531 case Intrinsic::sadd_with_overflow:
3532 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3535 case Intrinsic::uadd_with_overflow:
3536 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3539 case Intrinsic::ssub_with_overflow:
3540 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3543 case Intrinsic::usub_with_overflow:
3544 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3547 case Intrinsic::smul_with_overflow: {
3549 unsigned LHSReg = getRegForValue(LHS);
3552 bool LHSIsKill = hasTrivialKill(LHS);
3554 unsigned RHSReg = getRegForValue(RHS);
3557 bool RHSIsKill = hasTrivialKill(RHS);
3559 if (VT == MVT::i32) {
3560 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3561 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3562 /*IsKill=*/false, 32);
3563 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3565 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3567 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3568 AArch64_AM::ASR, 31, /*WantResult=*/false);
3570 assert(VT == MVT::i64 && "Unexpected value type.");
3571 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3572 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3574 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3575 AArch64_AM::ASR, 63, /*WantResult=*/false);
3579 case Intrinsic::umul_with_overflow: {
3581 unsigned LHSReg = getRegForValue(LHS);
3584 bool LHSIsKill = hasTrivialKill(LHS);
3586 unsigned RHSReg = getRegForValue(RHS);
3589 bool RHSIsKill = hasTrivialKill(RHS);
3591 if (VT == MVT::i32) {
3592 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3593 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3594 /*IsKill=*/false, AArch64_AM::LSR, 32,
3595 /*WantResult=*/false);
3596 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3599 assert(VT == MVT::i64 && "Unexpected value type.");
3600 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3601 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3603 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3604 /*IsKill=*/false, /*WantResult=*/false);
3611 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3612 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3613 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3616 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3617 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3618 /*IsKill=*/true, getInvertedCondCode(CC));
3620 assert((ResultReg1 + 1) == ResultReg2 &&
3621 "Nonconsecutive result registers.");
3622 updateValueMap(II, ResultReg1, 2);
3629 bool AArch64FastISel::selectRet(const Instruction *I) {
3630 const ReturnInst *Ret = cast<ReturnInst>(I);
3631 const Function &F = *I->getParent()->getParent();
3633 if (!FuncInfo.CanLowerReturn)
3639 // Build a list of return value registers.
3640 SmallVector<unsigned, 4> RetRegs;
3642 if (Ret->getNumOperands() > 0) {
3643 CallingConv::ID CC = F.getCallingConv();
3644 SmallVector<ISD::OutputArg, 4> Outs;
3645 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3647 // Analyze operands of the call, assigning locations to each operand.
3648 SmallVector<CCValAssign, 16> ValLocs;
3649 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3650 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3651 : RetCC_AArch64_AAPCS;
3652 CCInfo.AnalyzeReturn(Outs, RetCC);
3654 // Only handle a single return value for now.
3655 if (ValLocs.size() != 1)
3658 CCValAssign &VA = ValLocs[0];
3659 const Value *RV = Ret->getOperand(0);
3661 // Don't bother handling odd stuff for now.
3662 if ((VA.getLocInfo() != CCValAssign::Full) &&
3663 (VA.getLocInfo() != CCValAssign::BCvt))
3666 // Only handle register returns for now.
3670 unsigned Reg = getRegForValue(RV);
3674 unsigned SrcReg = Reg + VA.getValNo();
3675 unsigned DestReg = VA.getLocReg();
3676 // Avoid a cross-class copy. This is very unlikely.
3677 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3680 EVT RVEVT = TLI.getValueType(RV->getType());
3681 if (!RVEVT.isSimple())
3684 // Vectors (of > 1 lane) in big endian need tricky handling.
3685 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3686 !Subtarget->isLittleEndian())
3689 MVT RVVT = RVEVT.getSimpleVT();
3690 if (RVVT == MVT::f128)
3693 MVT DestVT = VA.getValVT();
3694 // Special handling for extended integers.
3695 if (RVVT != DestVT) {
3696 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3699 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3702 bool IsZExt = Outs[0].Flags.isZExt();
3703 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3709 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3710 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3712 // Add register to return instruction.
3713 RetRegs.push_back(VA.getLocReg());
3716 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3717 TII.get(AArch64::RET_ReallyLR));
3718 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3719 MIB.addReg(RetRegs[i], RegState::Implicit);
3723 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3724 Type *DestTy = I->getType();
3725 Value *Op = I->getOperand(0);
3726 Type *SrcTy = Op->getType();
3728 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3729 EVT DestEVT = TLI.getValueType(DestTy, true);
3730 if (!SrcEVT.isSimple())
3732 if (!DestEVT.isSimple())
3735 MVT SrcVT = SrcEVT.getSimpleVT();
3736 MVT DestVT = DestEVT.getSimpleVT();
3738 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3741 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3745 unsigned SrcReg = getRegForValue(Op);
3748 bool SrcIsKill = hasTrivialKill(Op);
3750 // If we're truncating from i64 to a smaller non-legal type then generate an
3751 // AND. Otherwise, we know the high bits are undefined and a truncate only
3752 // generate a COPY. We cannot mark the source register also as result
3753 // register, because this can incorrectly transfer the kill flag onto the
3756 if (SrcVT == MVT::i64) {
3758 switch (DestVT.SimpleTy) {
3760 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3772 // Issue an extract_subreg to get the lower 32-bits.
3773 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3775 // Create the AND instruction which performs the actual truncation.
3776 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3777 assert(ResultReg && "Unexpected AND instruction emission failure.");
3779 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3780 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3781 TII.get(TargetOpcode::COPY), ResultReg)
3782 .addReg(SrcReg, getKillRegState(SrcIsKill));
3785 updateValueMap(I, ResultReg);
3789 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3790 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3791 DestVT == MVT::i64) &&
3792 "Unexpected value type.");
3793 // Handle i8 and i16 as i32.
3794 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3798 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3799 assert(ResultReg && "Unexpected AND instruction emission failure.");
3800 if (DestVT == MVT::i64) {
3801 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3802 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3803 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3804 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3805 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3808 .addImm(AArch64::sub_32);
3813 if (DestVT == MVT::i64) {
3814 // FIXME: We're SExt i1 to i64.
3817 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3818 /*TODO:IsKill=*/false, 0, 0);
3822 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3823 unsigned Op1, bool Op1IsKill) {
3825 switch (RetVT.SimpleTy) {
3831 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3833 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3836 const TargetRegisterClass *RC =
3837 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3838 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3839 /*IsKill=*/ZReg, true);
3842 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3843 unsigned Op1, bool Op1IsKill) {
3844 if (RetVT != MVT::i64)
3847 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3848 Op0, Op0IsKill, Op1, Op1IsKill,
3849 AArch64::XZR, /*IsKill=*/true);
3852 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3853 unsigned Op1, bool Op1IsKill) {
3854 if (RetVT != MVT::i64)
3857 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3858 Op0, Op0IsKill, Op1, Op1IsKill,
3859 AArch64::XZR, /*IsKill=*/true);
3862 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3863 unsigned Op1Reg, bool Op1IsKill) {
3865 bool NeedTrunc = false;
3867 switch (RetVT.SimpleTy) {
3869 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3870 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3871 case MVT::i32: Opc = AArch64::LSLVWr; break;
3872 case MVT::i64: Opc = AArch64::LSLVXr; break;
3875 const TargetRegisterClass *RC =
3876 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3878 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3881 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3884 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3888 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3889 bool Op0IsKill, uint64_t Shift,
3891 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3892 "Unexpected source/return type pair.");
3893 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3894 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3895 "Unexpected source value type.");
3896 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3897 RetVT == MVT::i64) && "Unexpected return value type.");
3899 bool Is64Bit = (RetVT == MVT::i64);
3900 unsigned RegSize = Is64Bit ? 64 : 32;
3901 unsigned DstBits = RetVT.getSizeInBits();
3902 unsigned SrcBits = SrcVT.getSizeInBits();
3903 const TargetRegisterClass *RC =
3904 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3906 // Just emit a copy for "zero" shifts.
3908 if (RetVT == SrcVT) {
3909 unsigned ResultReg = createResultReg(RC);
3910 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3911 TII.get(TargetOpcode::COPY), ResultReg)
3912 .addReg(Op0, getKillRegState(Op0IsKill));
3915 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3918 // Don't deal with undefined shifts.
3919 if (Shift >= DstBits)
3922 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3923 // {S|U}BFM Wd, Wn, #r, #s
3924 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3926 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3927 // %2 = shl i16 %1, 4
3928 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3929 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3930 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3931 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3933 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3934 // %2 = shl i16 %1, 8
3935 // Wd<32+7-24,32-24> = Wn<7:0>
3936 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3937 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3938 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3940 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3941 // %2 = shl i16 %1, 12
3942 // Wd<32+3-20,32-20> = Wn<3:0>
3943 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3944 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3945 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3947 unsigned ImmR = RegSize - Shift;
3948 // Limit the width to the length of the source type.
3949 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3950 static const unsigned OpcTable[2][2] = {
3951 {AArch64::SBFMWri, AArch64::SBFMXri},
3952 {AArch64::UBFMWri, AArch64::UBFMXri}
3954 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3955 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3956 unsigned TmpReg = MRI.createVirtualRegister(RC);
3957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3958 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3960 .addReg(Op0, getKillRegState(Op0IsKill))
3961 .addImm(AArch64::sub_32);
3965 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3968 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3969 unsigned Op1Reg, bool Op1IsKill) {
3971 bool NeedTrunc = false;
3973 switch (RetVT.SimpleTy) {
3975 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3976 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3977 case MVT::i32: Opc = AArch64::LSRVWr; break;
3978 case MVT::i64: Opc = AArch64::LSRVXr; break;
3981 const TargetRegisterClass *RC =
3982 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3984 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3985 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3986 Op0IsKill = Op1IsKill = true;
3988 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3991 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3995 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3996 bool Op0IsKill, uint64_t Shift,
3998 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3999 "Unexpected source/return type pair.");
4000 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4001 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4002 "Unexpected source value type.");
4003 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4004 RetVT == MVT::i64) && "Unexpected return value type.");
4006 bool Is64Bit = (RetVT == MVT::i64);
4007 unsigned RegSize = Is64Bit ? 64 : 32;
4008 unsigned DstBits = RetVT.getSizeInBits();
4009 unsigned SrcBits = SrcVT.getSizeInBits();
4010 const TargetRegisterClass *RC =
4011 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4013 // Just emit a copy for "zero" shifts.
4015 if (RetVT == SrcVT) {
4016 unsigned ResultReg = createResultReg(RC);
4017 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4018 TII.get(TargetOpcode::COPY), ResultReg)
4019 .addReg(Op0, getKillRegState(Op0IsKill));
4022 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4025 // Don't deal with undefined shifts.
4026 if (Shift >= DstBits)
4029 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4030 // {S|U}BFM Wd, Wn, #r, #s
4031 // Wd<s-r:0> = Wn<s:r> when r <= s
4033 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4034 // %2 = lshr i16 %1, 4
4035 // Wd<7-4:0> = Wn<7:4>
4036 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
4037 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4038 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4040 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4041 // %2 = lshr i16 %1, 8
4042 // Wd<7-7,0> = Wn<7:7>
4043 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
4044 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4045 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4047 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4048 // %2 = lshr i16 %1, 12
4049 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4050 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
4051 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4052 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4054 if (Shift >= SrcBits && IsZExt)
4055 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4057 // It is not possible to fold a sign-extend into the LShr instruction. In this
4058 // case emit a sign-extend.
4060 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4065 SrcBits = SrcVT.getSizeInBits();
4069 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4070 unsigned ImmS = SrcBits - 1;
4071 static const unsigned OpcTable[2][2] = {
4072 {AArch64::SBFMWri, AArch64::SBFMXri},
4073 {AArch64::UBFMWri, AArch64::UBFMXri}
4075 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4076 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4077 unsigned TmpReg = MRI.createVirtualRegister(RC);
4078 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4079 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4081 .addReg(Op0, getKillRegState(Op0IsKill))
4082 .addImm(AArch64::sub_32);
4086 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4089 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4090 unsigned Op1Reg, bool Op1IsKill) {
4092 bool NeedTrunc = false;
4094 switch (RetVT.SimpleTy) {
4096 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
4097 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
4098 case MVT::i32: Opc = AArch64::ASRVWr; break;
4099 case MVT::i64: Opc = AArch64::ASRVXr; break;
4102 const TargetRegisterClass *RC =
4103 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4105 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
4106 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4107 Op0IsKill = Op1IsKill = true;
4109 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4112 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4116 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4117 bool Op0IsKill, uint64_t Shift,
4119 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4120 "Unexpected source/return type pair.");
4121 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4122 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4123 "Unexpected source value type.");
4124 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4125 RetVT == MVT::i64) && "Unexpected return value type.");
4127 bool Is64Bit = (RetVT == MVT::i64);
4128 unsigned RegSize = Is64Bit ? 64 : 32;
4129 unsigned DstBits = RetVT.getSizeInBits();
4130 unsigned SrcBits = SrcVT.getSizeInBits();
4131 const TargetRegisterClass *RC =
4132 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4134 // Just emit a copy for "zero" shifts.
4136 if (RetVT == SrcVT) {
4137 unsigned ResultReg = createResultReg(RC);
4138 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4139 TII.get(TargetOpcode::COPY), ResultReg)
4140 .addReg(Op0, getKillRegState(Op0IsKill));
4143 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4146 // Don't deal with undefined shifts.
4147 if (Shift >= DstBits)
4150 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4151 // {S|U}BFM Wd, Wn, #r, #s
4152 // Wd<s-r:0> = Wn<s:r> when r <= s
4154 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4155 // %2 = ashr i16 %1, 4
4156 // Wd<7-4:0> = Wn<7:4>
4157 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
4158 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4159 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4161 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4162 // %2 = ashr i16 %1, 8
4163 // Wd<7-7,0> = Wn<7:7>
4164 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4165 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4166 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4168 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4169 // %2 = ashr i16 %1, 12
4170 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4171 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4172 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4173 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4175 if (Shift >= SrcBits && IsZExt)
4176 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4178 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4179 unsigned ImmS = SrcBits - 1;
4180 static const unsigned OpcTable[2][2] = {
4181 {AArch64::SBFMWri, AArch64::SBFMXri},
4182 {AArch64::UBFMWri, AArch64::UBFMXri}
4184 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4185 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4186 unsigned TmpReg = MRI.createVirtualRegister(RC);
4187 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4188 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4190 .addReg(Op0, getKillRegState(Op0IsKill))
4191 .addImm(AArch64::sub_32);
4195 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4198 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
4200 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4202 // FastISel does not have plumbing to deal with extensions where the SrcVT or
4203 // DestVT are odd things, so test to make sure that they are both types we can
4204 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4205 // bail out to SelectionDAG.
4206 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4207 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4208 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
4209 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
4215 switch (SrcVT.SimpleTy) {
4219 return emiti1Ext(SrcReg, DestVT, IsZExt);
4221 if (DestVT == MVT::i64)
4222 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4224 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4228 if (DestVT == MVT::i64)
4229 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4231 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4235 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4236 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4241 // Handle i8 and i16 as i32.
4242 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4244 else if (DestVT == MVT::i64) {
4245 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4246 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4247 TII.get(AArch64::SUBREG_TO_REG), Src64)
4250 .addImm(AArch64::sub_32);
4254 const TargetRegisterClass *RC =
4255 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4256 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4259 static bool isZExtLoad(const MachineInstr *LI) {
4260 switch (LI->getOpcode()) {
4263 case AArch64::LDURBBi:
4264 case AArch64::LDURHHi:
4265 case AArch64::LDURWi:
4266 case AArch64::LDRBBui:
4267 case AArch64::LDRHHui:
4268 case AArch64::LDRWui:
4269 case AArch64::LDRBBroX:
4270 case AArch64::LDRHHroX:
4271 case AArch64::LDRWroX:
4272 case AArch64::LDRBBroW:
4273 case AArch64::LDRHHroW:
4274 case AArch64::LDRWroW:
4279 static bool isSExtLoad(const MachineInstr *LI) {
4280 switch (LI->getOpcode()) {
4283 case AArch64::LDURSBWi:
4284 case AArch64::LDURSHWi:
4285 case AArch64::LDURSBXi:
4286 case AArch64::LDURSHXi:
4287 case AArch64::LDURSWi:
4288 case AArch64::LDRSBWui:
4289 case AArch64::LDRSHWui:
4290 case AArch64::LDRSBXui:
4291 case AArch64::LDRSHXui:
4292 case AArch64::LDRSWui:
4293 case AArch64::LDRSBWroX:
4294 case AArch64::LDRSHWroX:
4295 case AArch64::LDRSBXroX:
4296 case AArch64::LDRSHXroX:
4297 case AArch64::LDRSWroX:
4298 case AArch64::LDRSBWroW:
4299 case AArch64::LDRSHWroW:
4300 case AArch64::LDRSBXroW:
4301 case AArch64::LDRSHXroW:
4302 case AArch64::LDRSWroW:
4307 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4309 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4310 if (!LI || !LI->hasOneUse())
4313 // Check if the load instruction has already been selected.
4314 unsigned Reg = lookUpRegForValue(LI);
4318 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4322 // Check if the correct load instruction has been emitted - SelectionDAG might
4323 // have emitted a zero-extending load, but we need a sign-extending load.
4324 bool IsZExt = isa<ZExtInst>(I);
4325 const auto *LoadMI = MI;
4326 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4327 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4328 unsigned LoadReg = MI->getOperand(1).getReg();
4329 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4330 assert(LoadMI && "Expected valid instruction");
4332 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4335 // Nothing to be done.
4336 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4337 updateValueMap(I, Reg);
4342 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4344 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4346 .addReg(Reg, getKillRegState(true))
4347 .addImm(AArch64::sub_32);
4350 assert((MI->getOpcode() == TargetOpcode::COPY &&
4351 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4352 "Expected copy instruction");
4353 Reg = MI->getOperand(1).getReg();
4354 MI->eraseFromParent();
4356 updateValueMap(I, Reg);
4360 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4361 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4362 "Unexpected integer extend instruction.");
4365 if (!isTypeSupported(I->getType(), RetVT))
4368 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4371 // Try to optimize already sign-/zero-extended values from load instructions.
4372 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4375 unsigned SrcReg = getRegForValue(I->getOperand(0));
4378 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4380 // Try to optimize already sign-/zero-extended values from function arguments.
4381 bool IsZExt = isa<ZExtInst>(I);
4382 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4383 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4384 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4385 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4386 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4387 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4389 .addReg(SrcReg, getKillRegState(SrcIsKill))
4390 .addImm(AArch64::sub_32);
4393 // Conservatively clear all kill flags from all uses, because we are
4394 // replacing a sign-/zero-extend instruction at IR level with a nop at MI
4395 // level. The result of the instruction at IR level might have been
4396 // trivially dead, which is now not longer true.
4397 unsigned UseReg = lookUpRegForValue(I);
4399 MRI.clearKillFlags(UseReg);
4401 updateValueMap(I, SrcReg);
4406 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4410 updateValueMap(I, ResultReg);
4414 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4415 EVT DestEVT = TLI.getValueType(I->getType(), true);
4416 if (!DestEVT.isSimple())
4419 MVT DestVT = DestEVT.getSimpleVT();
4420 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4424 bool Is64bit = (DestVT == MVT::i64);
4425 switch (ISDOpcode) {
4429 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4432 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4435 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4436 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4439 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4441 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4444 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4446 const TargetRegisterClass *RC =
4447 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4448 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4449 Src1Reg, /*IsKill=*/false);
4450 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4451 // The remainder is computed as numerator - (quotient * denominator) using the
4452 // MSUB instruction.
4453 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4454 Src1Reg, Src1IsKill, Src0Reg,
4456 updateValueMap(I, ResultReg);
4460 bool AArch64FastISel::selectMul(const Instruction *I) {
4462 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4466 return selectBinaryOp(I, ISD::MUL);
4468 const Value *Src0 = I->getOperand(0);
4469 const Value *Src1 = I->getOperand(1);
4470 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4471 if (C->getValue().isPowerOf2())
4472 std::swap(Src0, Src1);
4474 // Try to simplify to a shift instruction.
4475 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4476 if (C->getValue().isPowerOf2()) {
4477 uint64_t ShiftVal = C->getValue().logBase2();
4480 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4481 if (!isIntExtFree(ZExt)) {
4483 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4486 Src0 = ZExt->getOperand(0);
4489 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4490 if (!isIntExtFree(SExt)) {
4492 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4495 Src0 = SExt->getOperand(0);
4500 unsigned Src0Reg = getRegForValue(Src0);
4503 bool Src0IsKill = hasTrivialKill(Src0);
4505 unsigned ResultReg =
4506 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4509 updateValueMap(I, ResultReg);
4514 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4517 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4519 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4522 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4524 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4529 updateValueMap(I, ResultReg);
4533 bool AArch64FastISel::selectShift(const Instruction *I) {
4535 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4538 if (RetVT.isVector())
4539 return selectOperator(I, I->getOpcode());
4541 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4542 unsigned ResultReg = 0;
4543 uint64_t ShiftVal = C->getZExtValue();
4545 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
4546 const Value *Op0 = I->getOperand(0);
4547 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4548 if (!isIntExtFree(ZExt)) {
4550 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4553 Op0 = ZExt->getOperand(0);
4556 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4557 if (!isIntExtFree(SExt)) {
4559 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4562 Op0 = SExt->getOperand(0);
4567 unsigned Op0Reg = getRegForValue(Op0);
4570 bool Op0IsKill = hasTrivialKill(Op0);
4572 switch (I->getOpcode()) {
4573 default: llvm_unreachable("Unexpected instruction.");
4574 case Instruction::Shl:
4575 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4577 case Instruction::AShr:
4578 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4580 case Instruction::LShr:
4581 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4587 updateValueMap(I, ResultReg);
4591 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4594 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4596 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4599 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4601 unsigned ResultReg = 0;
4602 switch (I->getOpcode()) {
4603 default: llvm_unreachable("Unexpected instruction.");
4604 case Instruction::Shl:
4605 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4607 case Instruction::AShr:
4608 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4610 case Instruction::LShr:
4611 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4618 updateValueMap(I, ResultReg);
4622 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4625 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4627 if (!isTypeLegal(I->getType(), RetVT))
4631 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4632 Opc = AArch64::FMOVWSr;
4633 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4634 Opc = AArch64::FMOVXDr;
4635 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4636 Opc = AArch64::FMOVSWr;
4637 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4638 Opc = AArch64::FMOVDXr;
4642 const TargetRegisterClass *RC = nullptr;
4643 switch (RetVT.SimpleTy) {
4644 default: llvm_unreachable("Unexpected value type.");
4645 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4646 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4647 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4648 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4650 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4653 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4654 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4659 updateValueMap(I, ResultReg);
4663 bool AArch64FastISel::selectFRem(const Instruction *I) {
4665 if (!isTypeLegal(I->getType(), RetVT))
4669 switch (RetVT.SimpleTy) {
4673 LC = RTLIB::REM_F32;
4676 LC = RTLIB::REM_F64;
4681 Args.reserve(I->getNumOperands());
4683 // Populate the argument list.
4684 for (auto &Arg : I->operands()) {
4687 Entry.Ty = Arg->getType();
4688 Args.push_back(Entry);
4691 CallLoweringInfo CLI;
4692 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4693 TLI.getLibcallName(LC), std::move(Args));
4694 if (!lowerCallTo(CLI))
4696 updateValueMap(I, CLI.ResultReg);
4700 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4702 if (!isTypeLegal(I->getType(), VT))
4705 if (!isa<ConstantInt>(I->getOperand(1)))
4706 return selectBinaryOp(I, ISD::SDIV);
4708 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4709 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4710 !(C.isPowerOf2() || (-C).isPowerOf2()))
4711 return selectBinaryOp(I, ISD::SDIV);
4713 unsigned Lg2 = C.countTrailingZeros();
4714 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4717 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4719 if (cast<BinaryOperator>(I)->isExact()) {
4720 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4723 updateValueMap(I, ResultReg);
4727 int64_t Pow2MinusOne = (1ULL << Lg2) - 1;
4728 unsigned AddReg = emitAdd_ri_(VT, Src0Reg, /*IsKill=*/false, Pow2MinusOne);
4732 // (Src0 < 0) ? Pow2 - 1 : 0;
4733 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4737 const TargetRegisterClass *RC;
4738 if (VT == MVT::i64) {
4739 SelectOpc = AArch64::CSELXr;
4740 RC = &AArch64::GPR64RegClass;
4742 SelectOpc = AArch64::CSELWr;
4743 RC = &AArch64::GPR32RegClass;
4745 unsigned SelectReg =
4746 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4747 Src0IsKill, AArch64CC::LT);
4751 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4752 // negate the result.
4753 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4756 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4757 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4759 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4764 updateValueMap(I, ResultReg);
4768 /// This is mostly a copy of the existing FastISel getRegForGEPIndex code. We
4769 /// have to duplicate it for AArch64, because otherwise we would fail during the
4770 /// sign-extend emission.
4771 std::pair<unsigned, bool> AArch64FastISel::getRegForGEPIndex(const Value *Idx) {
4772 unsigned IdxN = getRegForValue(Idx);
4774 // Unhandled operand. Halt "fast" selection and bail.
4775 return std::pair<unsigned, bool>(0, false);
4777 bool IdxNIsKill = hasTrivialKill(Idx);
4779 // If the index is smaller or larger than intptr_t, truncate or extend it.
4780 MVT PtrVT = TLI.getPointerTy();
4781 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
4782 if (IdxVT.bitsLT(PtrVT)) {
4783 IdxN = emitIntExt(IdxVT.getSimpleVT(), IdxN, PtrVT, /*IsZExt=*/false);
4785 } else if (IdxVT.bitsGT(PtrVT))
4786 llvm_unreachable("AArch64 FastISel doesn't support types larger than i64");
4787 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
4790 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4791 /// duplicate it for AArch64, because otherwise we would bail out even for
4792 /// simple cases. This is because the standard fastEmit functions don't cover
4793 /// MUL at all and ADD is lowered very inefficientily.
4794 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4795 unsigned N = getRegForValue(I->getOperand(0));
4798 bool NIsKill = hasTrivialKill(I->getOperand(0));
4800 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4801 // into a single N = N + TotalOffset.
4802 uint64_t TotalOffs = 0;
4803 Type *Ty = I->getOperand(0)->getType();
4804 MVT VT = TLI.getPointerTy();
4805 for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4806 const Value *Idx = *OI;
4807 if (auto *StTy = dyn_cast<StructType>(Ty)) {
4808 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4811 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4812 Ty = StTy->getElementType(Field);
4814 Ty = cast<SequentialType>(Ty)->getElementType();
4815 // If this is a constant subscript, handle it quickly.
4816 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4821 DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4825 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4832 // N = N + Idx * ElementSize;
4833 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4834 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4835 unsigned IdxN = Pair.first;
4836 bool IdxNIsKill = Pair.second;
4840 if (ElementSize != 1) {
4841 unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4844 IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4849 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4855 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4859 updateValueMap(I, N);
4863 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4864 switch (I->getOpcode()) {
4867 case Instruction::Add:
4868 case Instruction::Sub:
4869 return selectAddSub(I);
4870 case Instruction::Mul:
4871 return selectMul(I);
4872 case Instruction::SDiv:
4873 return selectSDiv(I);
4874 case Instruction::SRem:
4875 if (!selectBinaryOp(I, ISD::SREM))
4876 return selectRem(I, ISD::SREM);
4878 case Instruction::URem:
4879 if (!selectBinaryOp(I, ISD::UREM))
4880 return selectRem(I, ISD::UREM);
4882 case Instruction::Shl:
4883 case Instruction::LShr:
4884 case Instruction::AShr:
4885 return selectShift(I);
4886 case Instruction::And:
4887 case Instruction::Or:
4888 case Instruction::Xor:
4889 return selectLogicalOp(I);
4890 case Instruction::Br:
4891 return selectBranch(I);
4892 case Instruction::IndirectBr:
4893 return selectIndirectBr(I);
4894 case Instruction::BitCast:
4895 if (!FastISel::selectBitCast(I))
4896 return selectBitCast(I);
4898 case Instruction::FPToSI:
4899 if (!selectCast(I, ISD::FP_TO_SINT))
4900 return selectFPToInt(I, /*Signed=*/true);
4902 case Instruction::FPToUI:
4903 return selectFPToInt(I, /*Signed=*/false);
4904 case Instruction::ZExt:
4905 case Instruction::SExt:
4906 return selectIntExt(I);
4907 case Instruction::Trunc:
4908 if (!selectCast(I, ISD::TRUNCATE))
4909 return selectTrunc(I);
4911 case Instruction::FPExt:
4912 return selectFPExt(I);
4913 case Instruction::FPTrunc:
4914 return selectFPTrunc(I);
4915 case Instruction::SIToFP:
4916 if (!selectCast(I, ISD::SINT_TO_FP))
4917 return selectIntToFP(I, /*Signed=*/true);
4919 case Instruction::UIToFP:
4920 return selectIntToFP(I, /*Signed=*/false);
4921 case Instruction::Load:
4922 return selectLoad(I);
4923 case Instruction::Store:
4924 return selectStore(I);
4925 case Instruction::FCmp:
4926 case Instruction::ICmp:
4927 return selectCmp(I);
4928 case Instruction::Select:
4929 return selectSelect(I);
4930 case Instruction::Ret:
4931 return selectRet(I);
4932 case Instruction::FRem:
4933 return selectFRem(I);
4934 case Instruction::GetElementPtr:
4935 return selectGetElementPtr(I);
4938 // fall-back to target-independent instruction selection.
4939 return selectOperator(I, I->getOpcode());
4940 // Silence warnings.
4941 (void)&CC_AArch64_DarwinPCS_VarArg;
4945 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4946 const TargetLibraryInfo *LibInfo) {
4947 return new AArch64FastISel(FuncInfo, LibInfo);