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 "AArch64CallingConvention.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GetElementPtrTypeIterator.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/Support/CommandLine.h"
44 class AArch64FastISel final : public FastISel {
54 AArch64_AM::ShiftExtendType ExtType;
62 const GlobalValue *GV;
65 Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
66 OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
67 void setKind(BaseKind K) { Kind = K; }
68 BaseKind getKind() const { return Kind; }
69 void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
70 AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
71 bool isRegBase() const { return Kind == RegBase; }
72 bool isFIBase() const { return Kind == FrameIndexBase; }
73 void setReg(unsigned Reg) {
74 assert(isRegBase() && "Invalid base register access!");
77 unsigned getReg() const {
78 assert(isRegBase() && "Invalid base register access!");
81 void setOffsetReg(unsigned Reg) {
84 unsigned getOffsetReg() const {
87 void setFI(unsigned FI) {
88 assert(isFIBase() && "Invalid base frame index access!");
91 unsigned getFI() const {
92 assert(isFIBase() && "Invalid base frame index access!");
95 void setOffset(int64_t O) { Offset = O; }
96 int64_t getOffset() { return Offset; }
97 void setShift(unsigned S) { Shift = S; }
98 unsigned getShift() { return Shift; }
100 void setGlobalValue(const GlobalValue *G) { GV = G; }
101 const GlobalValue *getGlobalValue() { return GV; }
104 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
105 /// make the right decision when generating code for different targets.
106 const AArch64Subtarget *Subtarget;
107 LLVMContext *Context;
109 bool fastLowerArguments() override;
110 bool fastLowerCall(CallLoweringInfo &CLI) override;
111 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
114 // Selection routines.
115 bool selectAddSub(const Instruction *I);
116 bool selectLogicalOp(const Instruction *I);
117 bool selectLoad(const Instruction *I);
118 bool selectStore(const Instruction *I);
119 bool selectBranch(const Instruction *I);
120 bool selectIndirectBr(const Instruction *I);
121 bool selectCmp(const Instruction *I);
122 bool selectSelect(const Instruction *I);
123 bool selectFPExt(const Instruction *I);
124 bool selectFPTrunc(const Instruction *I);
125 bool selectFPToInt(const Instruction *I, bool Signed);
126 bool selectIntToFP(const Instruction *I, bool Signed);
127 bool selectRem(const Instruction *I, unsigned ISDOpcode);
128 bool selectRet(const Instruction *I);
129 bool selectTrunc(const Instruction *I);
130 bool selectIntExt(const Instruction *I);
131 bool selectMul(const Instruction *I);
132 bool selectShift(const Instruction *I);
133 bool selectBitCast(const Instruction *I);
134 bool selectFRem(const Instruction *I);
135 bool selectSDiv(const Instruction *I);
136 bool selectGetElementPtr(const Instruction *I);
138 // Utility helper routines.
139 bool isTypeLegal(Type *Ty, MVT &VT);
140 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
141 bool isValueAvailable(const Value *V) const;
142 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
143 bool computeCallAddress(const Value *V, Address &Addr);
144 bool simplifyAddress(Address &Addr, MVT VT);
145 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
146 unsigned Flags, unsigned ScaleFactor,
147 MachineMemOperand *MMO);
148 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
149 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
151 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
153 bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
154 bool optimizeSelect(const SelectInst *SI);
155 std::pair<unsigned, bool> getRegForGEPIndex(const Value *Idx);
157 // Emit helper routines.
158 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
159 const Value *RHS, bool SetFlags = false,
160 bool WantResult = true, bool IsZExt = false);
161 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
162 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
163 bool SetFlags = false, bool WantResult = true);
164 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
165 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
166 bool WantResult = true);
167 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
168 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
169 AArch64_AM::ShiftExtendType ShiftType,
170 uint64_t ShiftImm, bool SetFlags = false,
171 bool WantResult = true);
172 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
173 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
174 AArch64_AM::ShiftExtendType ExtType,
175 uint64_t ShiftImm, bool SetFlags = false,
176 bool WantResult = true);
179 bool emitCompareAndBranch(const BranchInst *BI);
180 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
181 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
182 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
183 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
184 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
185 MachineMemOperand *MMO = nullptr);
186 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
187 MachineMemOperand *MMO = nullptr);
188 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
189 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
190 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
191 bool SetFlags = false, bool WantResult = true,
192 bool IsZExt = false);
193 unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
194 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
195 bool SetFlags = false, bool WantResult = true,
196 bool IsZExt = false);
197 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
198 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
199 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
200 unsigned RHSReg, bool RHSIsKill,
201 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
202 bool WantResult = true);
203 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
205 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
206 bool LHSIsKill, uint64_t Imm);
207 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
208 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
210 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
211 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
212 unsigned Op1, bool Op1IsKill);
213 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
214 unsigned Op1, bool Op1IsKill);
215 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
216 unsigned Op1, bool Op1IsKill);
217 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
218 unsigned Op1Reg, bool Op1IsKill);
219 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
220 uint64_t Imm, bool IsZExt = true);
221 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
222 unsigned Op1Reg, bool Op1IsKill);
223 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
224 uint64_t Imm, bool IsZExt = true);
225 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
226 unsigned Op1Reg, bool Op1IsKill);
227 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
228 uint64_t Imm, bool IsZExt = false);
230 unsigned materializeInt(const ConstantInt *CI, MVT VT);
231 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
232 unsigned materializeGV(const GlobalValue *GV);
234 // Call handling routines.
236 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
237 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
239 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
242 // Backend specific FastISel code.
243 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
244 unsigned fastMaterializeConstant(const Constant *C) override;
245 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
247 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
248 const TargetLibraryInfo *LibInfo)
249 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
251 &static_cast<const AArch64Subtarget &>(FuncInfo.MF->getSubtarget());
252 Context = &FuncInfo.Fn->getContext();
255 bool fastSelectInstruction(const Instruction *I) override;
257 #include "AArch64GenFastISel.inc"
260 } // end anonymous namespace
262 #include "AArch64GenCallingConv.inc"
264 /// \brief Check if the sign-/zero-extend will be a noop.
265 static bool isIntExtFree(const Instruction *I) {
266 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
267 "Unexpected integer extend instruction.");
268 assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
269 "Unexpected value type.");
270 bool IsZExt = isa<ZExtInst>(I);
272 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
276 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
277 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
283 /// \brief Determine the implicit scale factor that is applied by a memory
284 /// operation for a given value type.
285 static unsigned getImplicitScaleFactor(MVT VT) {
286 switch (VT.SimpleTy) {
289 case MVT::i1: // fall-through
294 case MVT::i32: // fall-through
297 case MVT::i64: // fall-through
303 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
304 if (CC == CallingConv::WebKit_JS)
305 return CC_AArch64_WebKit_JS;
306 if (CC == CallingConv::GHC)
307 return CC_AArch64_GHC;
308 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
311 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
312 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
313 "Alloca should always return a pointer.");
315 // Don't handle dynamic allocas.
316 if (!FuncInfo.StaticAllocaMap.count(AI))
319 DenseMap<const AllocaInst *, int>::iterator SI =
320 FuncInfo.StaticAllocaMap.find(AI);
322 if (SI != FuncInfo.StaticAllocaMap.end()) {
323 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
324 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
326 .addFrameIndex(SI->second)
335 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
340 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
342 // Create a copy from the zero register to materialize a "0" value.
343 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
344 : &AArch64::GPR32RegClass;
345 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
346 unsigned ResultReg = createResultReg(RC);
347 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
348 ResultReg).addReg(ZeroReg, getKillRegState(true));
352 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
353 // Positive zero (+0.0) has to be materialized with a fmov from the zero
354 // register, because the immediate version of fmov cannot encode zero.
355 if (CFP->isNullValue())
356 return fastMaterializeFloatZero(CFP);
358 if (VT != MVT::f32 && VT != MVT::f64)
361 const APFloat Val = CFP->getValueAPF();
362 bool Is64Bit = (VT == MVT::f64);
363 // This checks to see if we can use FMOV instructions to materialize
364 // a constant, otherwise we have to materialize via the constant pool.
365 if (TLI.isFPImmLegal(Val, VT)) {
367 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
368 assert((Imm != -1) && "Cannot encode floating-point constant.");
369 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
370 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
373 // For the MachO large code model materialize the FP constant in code.
374 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
375 unsigned Opc1 = Is64Bit ? AArch64::MOVi64imm : AArch64::MOVi32imm;
376 const TargetRegisterClass *RC = Is64Bit ?
377 &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
379 unsigned TmpReg = createResultReg(RC);
380 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc1), TmpReg)
381 .addImm(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
383 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
384 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
385 TII.get(TargetOpcode::COPY), ResultReg)
386 .addReg(TmpReg, getKillRegState(true));
391 // Materialize via constant pool. MachineConstantPool wants an explicit
393 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
395 Align = DL.getTypeAllocSize(CFP->getType());
397 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
398 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
399 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
400 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
402 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
403 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
406 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
410 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
411 // We can't handle thread-local variables quickly yet.
412 if (GV->isThreadLocal())
415 // MachO still uses GOT for large code-model accesses, but ELF requires
416 // movz/movk sequences, which FastISel doesn't handle yet.
417 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
420 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
422 EVT DestEVT = TLI.getValueType(GV->getType(), true);
423 if (!DestEVT.isSimple())
426 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
429 if (OpFlags & AArch64II::MO_GOT) {
431 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
433 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
435 ResultReg = createResultReg(&AArch64::GPR64RegClass);
436 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
439 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
441 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
442 // We can't handle addresses loaded from a constant pool quickly yet.
446 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
448 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
450 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
454 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
460 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
461 EVT CEVT = TLI.getValueType(C->getType(), true);
463 // Only handle simple types.
464 if (!CEVT.isSimple())
466 MVT VT = CEVT.getSimpleVT();
468 if (const auto *CI = dyn_cast<ConstantInt>(C))
469 return materializeInt(CI, VT);
470 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
471 return materializeFP(CFP, VT);
472 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
473 return materializeGV(GV);
478 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
479 assert(CFP->isNullValue() &&
480 "Floating-point constant is not a positive zero.");
482 if (!isTypeLegal(CFP->getType(), VT))
485 if (VT != MVT::f32 && VT != MVT::f64)
488 bool Is64Bit = (VT == MVT::f64);
489 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
490 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
491 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
494 /// \brief Check if the multiply is by a power-of-2 constant.
495 static bool isMulPowOf2(const Value *I) {
496 if (const auto *MI = dyn_cast<MulOperator>(I)) {
497 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
498 if (C->getValue().isPowerOf2())
500 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
501 if (C->getValue().isPowerOf2())
507 // Computes the address to get to an object.
508 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
510 const User *U = nullptr;
511 unsigned Opcode = Instruction::UserOp1;
512 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
513 // Don't walk into other basic blocks unless the object is an alloca from
514 // another block, otherwise it may not have a virtual register assigned.
515 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
516 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
517 Opcode = I->getOpcode();
520 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
521 Opcode = C->getOpcode();
525 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
526 if (Ty->getAddressSpace() > 255)
527 // Fast instruction selection doesn't support the special
534 case Instruction::BitCast: {
535 // Look through bitcasts.
536 return computeAddress(U->getOperand(0), Addr, Ty);
538 case Instruction::IntToPtr: {
539 // Look past no-op inttoptrs.
540 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
541 return computeAddress(U->getOperand(0), Addr, Ty);
544 case Instruction::PtrToInt: {
545 // Look past no-op ptrtoints.
546 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
547 return computeAddress(U->getOperand(0), Addr, Ty);
550 case Instruction::GetElementPtr: {
551 Address SavedAddr = Addr;
552 uint64_t TmpOffset = Addr.getOffset();
554 // Iterate through the GEP folding the constants into offsets where
556 gep_type_iterator GTI = gep_type_begin(U);
557 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
559 const Value *Op = *i;
560 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
561 const StructLayout *SL = DL.getStructLayout(STy);
562 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
563 TmpOffset += SL->getElementOffset(Idx);
565 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
567 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
568 // Constant-offset addressing.
569 TmpOffset += CI->getSExtValue() * S;
572 if (canFoldAddIntoGEP(U, Op)) {
573 // A compatible add with a constant operand. Fold the constant.
575 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
576 TmpOffset += CI->getSExtValue() * S;
577 // Iterate on the other operand.
578 Op = cast<AddOperator>(Op)->getOperand(0);
582 goto unsupported_gep;
587 // Try to grab the base operand now.
588 Addr.setOffset(TmpOffset);
589 if (computeAddress(U->getOperand(0), Addr, Ty))
592 // We failed, restore everything and try the other options.
598 case Instruction::Alloca: {
599 const AllocaInst *AI = cast<AllocaInst>(Obj);
600 DenseMap<const AllocaInst *, int>::iterator SI =
601 FuncInfo.StaticAllocaMap.find(AI);
602 if (SI != FuncInfo.StaticAllocaMap.end()) {
603 Addr.setKind(Address::FrameIndexBase);
604 Addr.setFI(SI->second);
609 case Instruction::Add: {
610 // Adds of constants are common and easy enough.
611 const Value *LHS = U->getOperand(0);
612 const Value *RHS = U->getOperand(1);
614 if (isa<ConstantInt>(LHS))
617 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
618 Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
619 return computeAddress(LHS, Addr, Ty);
622 Address Backup = Addr;
623 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
629 case Instruction::Sub: {
630 // Subs of constants are common and easy enough.
631 const Value *LHS = U->getOperand(0);
632 const Value *RHS = U->getOperand(1);
634 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
635 Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
636 return computeAddress(LHS, Addr, Ty);
640 case Instruction::Shl: {
641 if (Addr.getOffsetReg())
644 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
648 unsigned Val = CI->getZExtValue();
649 if (Val < 1 || Val > 3)
652 uint64_t NumBytes = 0;
653 if (Ty && Ty->isSized()) {
654 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
655 NumBytes = NumBits / 8;
656 if (!isPowerOf2_64(NumBits))
660 if (NumBytes != (1ULL << Val))
664 Addr.setExtendType(AArch64_AM::LSL);
666 const Value *Src = U->getOperand(0);
667 if (const auto *I = dyn_cast<Instruction>(Src))
668 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
671 // Fold the zext or sext when it won't become a noop.
672 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
673 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
674 Addr.setExtendType(AArch64_AM::UXTW);
675 Src = ZE->getOperand(0);
677 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
678 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
679 Addr.setExtendType(AArch64_AM::SXTW);
680 Src = SE->getOperand(0);
684 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
685 if (AI->getOpcode() == Instruction::And) {
686 const Value *LHS = AI->getOperand(0);
687 const Value *RHS = AI->getOperand(1);
689 if (const auto *C = dyn_cast<ConstantInt>(LHS))
690 if (C->getValue() == 0xffffffff)
693 if (const auto *C = dyn_cast<ConstantInt>(RHS))
694 if (C->getValue() == 0xffffffff) {
695 Addr.setExtendType(AArch64_AM::UXTW);
696 unsigned Reg = getRegForValue(LHS);
699 bool RegIsKill = hasTrivialKill(LHS);
700 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
702 Addr.setOffsetReg(Reg);
707 unsigned Reg = getRegForValue(Src);
710 Addr.setOffsetReg(Reg);
713 case Instruction::Mul: {
714 if (Addr.getOffsetReg())
720 const Value *LHS = U->getOperand(0);
721 const Value *RHS = U->getOperand(1);
723 // Canonicalize power-of-2 value to the RHS.
724 if (const auto *C = dyn_cast<ConstantInt>(LHS))
725 if (C->getValue().isPowerOf2())
728 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
729 const auto *C = cast<ConstantInt>(RHS);
730 unsigned Val = C->getValue().logBase2();
731 if (Val < 1 || Val > 3)
734 uint64_t NumBytes = 0;
735 if (Ty && Ty->isSized()) {
736 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
737 NumBytes = NumBits / 8;
738 if (!isPowerOf2_64(NumBits))
742 if (NumBytes != (1ULL << Val))
746 Addr.setExtendType(AArch64_AM::LSL);
748 const Value *Src = LHS;
749 if (const auto *I = dyn_cast<Instruction>(Src))
750 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
754 // Fold the zext or sext when it won't become a noop.
755 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
756 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
757 Addr.setExtendType(AArch64_AM::UXTW);
758 Src = ZE->getOperand(0);
760 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
761 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
762 Addr.setExtendType(AArch64_AM::SXTW);
763 Src = SE->getOperand(0);
767 unsigned Reg = getRegForValue(Src);
770 Addr.setOffsetReg(Reg);
773 case Instruction::And: {
774 if (Addr.getOffsetReg())
777 if (!Ty || DL.getTypeSizeInBits(Ty) != 8)
780 const Value *LHS = U->getOperand(0);
781 const Value *RHS = U->getOperand(1);
783 if (const auto *C = dyn_cast<ConstantInt>(LHS))
784 if (C->getValue() == 0xffffffff)
787 if (const auto *C = dyn_cast<ConstantInt>(RHS))
788 if (C->getValue() == 0xffffffff) {
790 Addr.setExtendType(AArch64_AM::LSL);
791 Addr.setExtendType(AArch64_AM::UXTW);
793 unsigned Reg = getRegForValue(LHS);
796 bool RegIsKill = hasTrivialKill(LHS);
797 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
799 Addr.setOffsetReg(Reg);
804 case Instruction::SExt:
805 case Instruction::ZExt: {
806 if (!Addr.getReg() || Addr.getOffsetReg())
809 const Value *Src = nullptr;
810 // Fold the zext or sext when it won't become a noop.
811 if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
812 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
813 Addr.setExtendType(AArch64_AM::UXTW);
814 Src = ZE->getOperand(0);
816 } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
817 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
818 Addr.setExtendType(AArch64_AM::SXTW);
819 Src = SE->getOperand(0);
827 unsigned Reg = getRegForValue(Src);
830 Addr.setOffsetReg(Reg);
835 if (Addr.isRegBase() && !Addr.getReg()) {
836 unsigned Reg = getRegForValue(Obj);
843 if (!Addr.getOffsetReg()) {
844 unsigned Reg = getRegForValue(Obj);
847 Addr.setOffsetReg(Reg);
854 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
855 const User *U = nullptr;
856 unsigned Opcode = Instruction::UserOp1;
859 if (const auto *I = dyn_cast<Instruction>(V)) {
860 Opcode = I->getOpcode();
862 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
863 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
864 Opcode = C->getOpcode();
870 case Instruction::BitCast:
871 // Look past bitcasts if its operand is in the same BB.
873 return computeCallAddress(U->getOperand(0), Addr);
875 case Instruction::IntToPtr:
876 // Look past no-op inttoptrs if its operand is in the same BB.
878 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
879 return computeCallAddress(U->getOperand(0), Addr);
881 case Instruction::PtrToInt:
882 // Look past no-op ptrtoints if its operand is in the same BB.
884 TLI.getValueType(U->getType()) == TLI.getPointerTy())
885 return computeCallAddress(U->getOperand(0), Addr);
889 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
890 Addr.setGlobalValue(GV);
894 // If all else fails, try to materialize the value in a register.
895 if (!Addr.getGlobalValue()) {
896 Addr.setReg(getRegForValue(V));
897 return Addr.getReg() != 0;
904 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
905 EVT evt = TLI.getValueType(Ty, true);
907 // Only handle simple types.
908 if (evt == MVT::Other || !evt.isSimple())
910 VT = evt.getSimpleVT();
912 // This is a legal type, but it's not something we handle in fast-isel.
916 // Handle all other legal types, i.e. a register that will directly hold this
918 return TLI.isTypeLegal(VT);
921 /// \brief Determine if the value type is supported by FastISel.
923 /// FastISel for AArch64 can handle more value types than are legal. This adds
924 /// simple value type such as i1, i8, and i16.
925 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
926 if (Ty->isVectorTy() && !IsVectorAllowed)
929 if (isTypeLegal(Ty, VT))
932 // If this is a type than can be sign or zero-extended to a basic operation
933 // go ahead and accept it now.
934 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
940 bool AArch64FastISel::isValueAvailable(const Value *V) const {
941 if (!isa<Instruction>(V))
944 const auto *I = cast<Instruction>(V);
945 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
951 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
952 unsigned ScaleFactor = getImplicitScaleFactor(VT);
956 bool ImmediateOffsetNeedsLowering = false;
957 bool RegisterOffsetNeedsLowering = false;
958 int64_t Offset = Addr.getOffset();
959 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
960 ImmediateOffsetNeedsLowering = true;
961 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
962 !isUInt<12>(Offset / ScaleFactor))
963 ImmediateOffsetNeedsLowering = true;
965 // Cannot encode an offset register and an immediate offset in the same
966 // instruction. Fold the immediate offset into the load/store instruction and
967 // emit an additonal add to take care of the offset register.
968 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.getOffsetReg())
969 RegisterOffsetNeedsLowering = true;
971 // Cannot encode zero register as base.
972 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
973 RegisterOffsetNeedsLowering = true;
975 // If this is a stack pointer and the offset needs to be simplified then put
976 // the alloca address into a register, set the base type back to register and
977 // continue. This should almost never happen.
978 if ((ImmediateOffsetNeedsLowering || Addr.getOffsetReg()) && Addr.isFIBase())
980 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
981 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
983 .addFrameIndex(Addr.getFI())
986 Addr.setKind(Address::RegBase);
987 Addr.setReg(ResultReg);
990 if (RegisterOffsetNeedsLowering) {
991 unsigned ResultReg = 0;
993 if (Addr.getExtendType() == AArch64_AM::SXTW ||
994 Addr.getExtendType() == AArch64_AM::UXTW )
995 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
996 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
997 /*TODO:IsKill=*/false, Addr.getExtendType(),
1000 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
1001 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
1002 /*TODO:IsKill=*/false, AArch64_AM::LSL,
1005 if (Addr.getExtendType() == AArch64_AM::UXTW)
1006 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1007 /*Op0IsKill=*/false, Addr.getShift(),
1009 else if (Addr.getExtendType() == AArch64_AM::SXTW)
1010 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1011 /*Op0IsKill=*/false, Addr.getShift(),
1014 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
1015 /*Op0IsKill=*/false, Addr.getShift());
1020 Addr.setReg(ResultReg);
1021 Addr.setOffsetReg(0);
1023 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1026 // Since the offset is too large for the load/store instruction get the
1027 // reg+offset into a register.
1028 if (ImmediateOffsetNeedsLowering) {
1031 // Try to fold the immediate into the add instruction.
1032 ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1034 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1038 Addr.setReg(ResultReg);
1044 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1045 const MachineInstrBuilder &MIB,
1047 unsigned ScaleFactor,
1048 MachineMemOperand *MMO) {
1049 int64_t Offset = Addr.getOffset() / ScaleFactor;
1050 // Frame base works a bit differently. Handle it separately.
1051 if (Addr.isFIBase()) {
1052 int FI = Addr.getFI();
1053 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1054 // and alignment should be based on the VT.
1055 MMO = FuncInfo.MF->getMachineMemOperand(
1056 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1057 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1058 // Now add the rest of the operands.
1059 MIB.addFrameIndex(FI).addImm(Offset);
1061 assert(Addr.isRegBase() && "Unexpected address kind.");
1062 const MCInstrDesc &II = MIB->getDesc();
1063 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1065 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1067 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1068 if (Addr.getOffsetReg()) {
1069 assert(Addr.getOffset() == 0 && "Unexpected offset");
1070 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1071 Addr.getExtendType() == AArch64_AM::SXTX;
1072 MIB.addReg(Addr.getReg());
1073 MIB.addReg(Addr.getOffsetReg());
1074 MIB.addImm(IsSigned);
1075 MIB.addImm(Addr.getShift() != 0);
1077 MIB.addReg(Addr.getReg()).addImm(Offset);
1081 MIB.addMemOperand(MMO);
1084 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1085 const Value *RHS, bool SetFlags,
1086 bool WantResult, bool IsZExt) {
1087 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1088 bool NeedExtend = false;
1089 switch (RetVT.SimpleTy) {
1097 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1101 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1103 case MVT::i32: // fall-through
1108 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1110 // Canonicalize immediates to the RHS first.
1111 if (UseAdd && isa<Constant>(LHS) && !isa<Constant>(RHS))
1112 std::swap(LHS, RHS);
1114 // Canonicalize mul by power of 2 to the RHS.
1115 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1116 if (isMulPowOf2(LHS))
1117 std::swap(LHS, RHS);
1119 // Canonicalize shift immediate to the RHS.
1120 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1121 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1122 if (isa<ConstantInt>(SI->getOperand(1)))
1123 if (SI->getOpcode() == Instruction::Shl ||
1124 SI->getOpcode() == Instruction::LShr ||
1125 SI->getOpcode() == Instruction::AShr )
1126 std::swap(LHS, RHS);
1128 unsigned LHSReg = getRegForValue(LHS);
1131 bool LHSIsKill = hasTrivialKill(LHS);
1134 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1136 unsigned ResultReg = 0;
1137 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1138 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1139 if (C->isNegative())
1140 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1141 SetFlags, WantResult);
1143 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1145 } else if (const auto *C = dyn_cast<Constant>(RHS))
1146 if (C->isNullValue())
1147 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, 0, SetFlags,
1153 // Only extend the RHS within the instruction if there is a valid extend type.
1154 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1155 isValueAvailable(RHS)) {
1156 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1157 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1158 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1159 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1162 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1163 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1164 RHSIsKill, ExtendType, C->getZExtValue(),
1165 SetFlags, WantResult);
1167 unsigned RHSReg = getRegForValue(RHS);
1170 bool RHSIsKill = hasTrivialKill(RHS);
1171 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1172 ExtendType, 0, SetFlags, WantResult);
1175 // Check if the mul can be folded into the instruction.
1176 if (RHS->hasOneUse() && isValueAvailable(RHS))
1177 if (isMulPowOf2(RHS)) {
1178 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1179 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1181 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1182 if (C->getValue().isPowerOf2())
1183 std::swap(MulLHS, MulRHS);
1185 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1186 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1187 unsigned RHSReg = getRegForValue(MulLHS);
1190 bool RHSIsKill = hasTrivialKill(MulLHS);
1191 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1192 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1195 // Check if the shift can be folded into the instruction.
1196 if (RHS->hasOneUse() && isValueAvailable(RHS))
1197 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1198 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1199 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1200 switch (SI->getOpcode()) {
1202 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1203 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1204 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1206 uint64_t ShiftVal = C->getZExtValue();
1207 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1208 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1211 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1212 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1213 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1219 unsigned RHSReg = getRegForValue(RHS);
1222 bool RHSIsKill = hasTrivialKill(RHS);
1225 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1227 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1228 SetFlags, WantResult);
1231 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1232 bool LHSIsKill, unsigned RHSReg,
1233 bool RHSIsKill, bool SetFlags,
1235 assert(LHSReg && RHSReg && "Invalid register number.");
1237 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1240 static const unsigned OpcTable[2][2][2] = {
1241 { { AArch64::SUBWrr, AArch64::SUBXrr },
1242 { AArch64::ADDWrr, AArch64::ADDXrr } },
1243 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1244 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1246 bool Is64Bit = RetVT == MVT::i64;
1247 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1248 const TargetRegisterClass *RC =
1249 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1252 ResultReg = createResultReg(RC);
1254 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1256 const MCInstrDesc &II = TII.get(Opc);
1257 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1258 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1259 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1260 .addReg(LHSReg, getKillRegState(LHSIsKill))
1261 .addReg(RHSReg, getKillRegState(RHSIsKill));
1265 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1266 bool LHSIsKill, uint64_t Imm,
1267 bool SetFlags, bool WantResult) {
1268 assert(LHSReg && "Invalid register number.");
1270 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1274 if (isUInt<12>(Imm))
1276 else if ((Imm & 0xfff000) == Imm) {
1282 static const unsigned OpcTable[2][2][2] = {
1283 { { AArch64::SUBWri, AArch64::SUBXri },
1284 { AArch64::ADDWri, AArch64::ADDXri } },
1285 { { AArch64::SUBSWri, AArch64::SUBSXri },
1286 { AArch64::ADDSWri, AArch64::ADDSXri } }
1288 bool Is64Bit = RetVT == MVT::i64;
1289 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1290 const TargetRegisterClass *RC;
1292 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1294 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1297 ResultReg = createResultReg(RC);
1299 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1301 const MCInstrDesc &II = TII.get(Opc);
1302 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1303 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1304 .addReg(LHSReg, getKillRegState(LHSIsKill))
1306 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1310 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1311 bool LHSIsKill, unsigned RHSReg,
1313 AArch64_AM::ShiftExtendType ShiftType,
1314 uint64_t ShiftImm, bool SetFlags,
1316 assert(LHSReg && RHSReg && "Invalid register number.");
1318 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1321 static const unsigned OpcTable[2][2][2] = {
1322 { { AArch64::SUBWrs, AArch64::SUBXrs },
1323 { AArch64::ADDWrs, AArch64::ADDXrs } },
1324 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1325 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1327 bool Is64Bit = RetVT == MVT::i64;
1328 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1329 const TargetRegisterClass *RC =
1330 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1333 ResultReg = createResultReg(RC);
1335 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1337 const MCInstrDesc &II = TII.get(Opc);
1338 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1339 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1340 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1341 .addReg(LHSReg, getKillRegState(LHSIsKill))
1342 .addReg(RHSReg, getKillRegState(RHSIsKill))
1343 .addImm(getShifterImm(ShiftType, ShiftImm));
1347 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1348 bool LHSIsKill, unsigned RHSReg,
1350 AArch64_AM::ShiftExtendType ExtType,
1351 uint64_t ShiftImm, bool SetFlags,
1353 assert(LHSReg && RHSReg && "Invalid register number.");
1355 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1358 static const unsigned OpcTable[2][2][2] = {
1359 { { AArch64::SUBWrx, AArch64::SUBXrx },
1360 { AArch64::ADDWrx, AArch64::ADDXrx } },
1361 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1362 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1364 bool Is64Bit = RetVT == MVT::i64;
1365 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1366 const TargetRegisterClass *RC = nullptr;
1368 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1370 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1373 ResultReg = createResultReg(RC);
1375 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1377 const MCInstrDesc &II = TII.get(Opc);
1378 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1379 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1380 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1381 .addReg(LHSReg, getKillRegState(LHSIsKill))
1382 .addReg(RHSReg, getKillRegState(RHSIsKill))
1383 .addImm(getArithExtendImm(ExtType, ShiftImm));
1387 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1388 Type *Ty = LHS->getType();
1389 EVT EVT = TLI.getValueType(Ty, true);
1390 if (!EVT.isSimple())
1392 MVT VT = EVT.getSimpleVT();
1394 switch (VT.SimpleTy) {
1402 return emitICmp(VT, LHS, RHS, IsZExt);
1405 return emitFCmp(VT, LHS, RHS);
1409 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1411 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1415 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1417 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1418 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1421 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1422 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1425 // Check to see if the 2nd operand is a constant that we can encode directly
1427 bool UseImm = false;
1428 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1429 if (CFP->isZero() && !CFP->isNegative())
1432 unsigned LHSReg = getRegForValue(LHS);
1435 bool LHSIsKill = hasTrivialKill(LHS);
1438 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1439 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1440 .addReg(LHSReg, getKillRegState(LHSIsKill));
1444 unsigned RHSReg = getRegForValue(RHS);
1447 bool RHSIsKill = hasTrivialKill(RHS);
1449 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1450 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1451 .addReg(LHSReg, getKillRegState(LHSIsKill))
1452 .addReg(RHSReg, getKillRegState(RHSIsKill));
1456 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1457 bool SetFlags, bool WantResult, bool IsZExt) {
1458 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1462 /// \brief This method is a wrapper to simplify add emission.
1464 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1465 /// that fails, then try to materialize the immediate into a register and use
1466 /// emitAddSub_rr instead.
1467 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1471 ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1473 ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1478 unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1482 ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1486 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1487 bool SetFlags, bool WantResult, bool IsZExt) {
1488 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1492 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1493 bool LHSIsKill, unsigned RHSReg,
1494 bool RHSIsKill, bool WantResult) {
1495 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1496 RHSIsKill, /*SetFlags=*/true, WantResult);
1499 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1500 bool LHSIsKill, unsigned RHSReg,
1502 AArch64_AM::ShiftExtendType ShiftType,
1503 uint64_t ShiftImm, bool WantResult) {
1504 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1505 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1509 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1510 const Value *LHS, const Value *RHS) {
1511 // Canonicalize immediates to the RHS first.
1512 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1513 std::swap(LHS, RHS);
1515 // Canonicalize mul by power-of-2 to the RHS.
1516 if (LHS->hasOneUse() && isValueAvailable(LHS))
1517 if (isMulPowOf2(LHS))
1518 std::swap(LHS, RHS);
1520 // Canonicalize shift immediate to the RHS.
1521 if (LHS->hasOneUse() && isValueAvailable(LHS))
1522 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1523 if (isa<ConstantInt>(SI->getOperand(1)))
1524 std::swap(LHS, RHS);
1526 unsigned LHSReg = getRegForValue(LHS);
1529 bool LHSIsKill = hasTrivialKill(LHS);
1531 unsigned ResultReg = 0;
1532 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1533 uint64_t Imm = C->getZExtValue();
1534 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1539 // Check if the mul can be folded into the instruction.
1540 if (RHS->hasOneUse() && isValueAvailable(RHS))
1541 if (isMulPowOf2(RHS)) {
1542 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1543 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1545 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1546 if (C->getValue().isPowerOf2())
1547 std::swap(MulLHS, MulRHS);
1549 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1550 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1552 unsigned RHSReg = getRegForValue(MulLHS);
1555 bool RHSIsKill = hasTrivialKill(MulLHS);
1556 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1557 RHSIsKill, ShiftVal);
1560 // Check if the shift can be folded into the instruction.
1561 if (RHS->hasOneUse() && isValueAvailable(RHS))
1562 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1563 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1564 uint64_t ShiftVal = C->getZExtValue();
1565 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1568 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1569 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1570 RHSIsKill, ShiftVal);
1573 unsigned RHSReg = getRegForValue(RHS);
1576 bool RHSIsKill = hasTrivialKill(RHS);
1578 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1579 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1580 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1581 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1582 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1587 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1588 unsigned LHSReg, bool LHSIsKill,
1590 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1591 "ISD nodes are not consecutive!");
1592 static const unsigned OpcTable[3][2] = {
1593 { AArch64::ANDWri, AArch64::ANDXri },
1594 { AArch64::ORRWri, AArch64::ORRXri },
1595 { AArch64::EORWri, AArch64::EORXri }
1597 const TargetRegisterClass *RC;
1600 switch (RetVT.SimpleTy) {
1607 unsigned Idx = ISDOpc - ISD::AND;
1608 Opc = OpcTable[Idx][0];
1609 RC = &AArch64::GPR32spRegClass;
1614 Opc = OpcTable[ISDOpc - ISD::AND][1];
1615 RC = &AArch64::GPR64spRegClass;
1620 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1623 unsigned ResultReg =
1624 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1625 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1626 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1627 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1628 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1633 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1634 unsigned LHSReg, bool LHSIsKill,
1635 unsigned RHSReg, bool RHSIsKill,
1636 uint64_t ShiftImm) {
1637 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1638 "ISD nodes are not consecutive!");
1639 static const unsigned OpcTable[3][2] = {
1640 { AArch64::ANDWrs, AArch64::ANDXrs },
1641 { AArch64::ORRWrs, AArch64::ORRXrs },
1642 { AArch64::EORWrs, AArch64::EORXrs }
1644 const TargetRegisterClass *RC;
1646 switch (RetVT.SimpleTy) {
1653 Opc = OpcTable[ISDOpc - ISD::AND][0];
1654 RC = &AArch64::GPR32RegClass;
1657 Opc = OpcTable[ISDOpc - ISD::AND][1];
1658 RC = &AArch64::GPR64RegClass;
1661 unsigned ResultReg =
1662 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1663 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1664 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1665 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1666 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1671 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1673 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1676 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1677 bool WantZExt, MachineMemOperand *MMO) {
1678 // Simplify this down to something we can handle.
1679 if (!simplifyAddress(Addr, VT))
1682 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1684 llvm_unreachable("Unexpected value type.");
1686 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1687 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1688 bool UseScaled = true;
1689 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1694 static const unsigned GPOpcTable[2][8][4] = {
1696 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1698 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1700 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1702 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1704 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1706 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1708 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1710 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1714 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1716 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1718 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1720 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1722 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1724 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1726 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1728 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1733 static const unsigned FPOpcTable[4][2] = {
1734 { AArch64::LDURSi, AArch64::LDURDi },
1735 { AArch64::LDRSui, AArch64::LDRDui },
1736 { AArch64::LDRSroX, AArch64::LDRDroX },
1737 { AArch64::LDRSroW, AArch64::LDRDroW }
1741 const TargetRegisterClass *RC;
1742 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1743 Addr.getOffsetReg();
1744 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1745 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1746 Addr.getExtendType() == AArch64_AM::SXTW)
1749 bool IsRet64Bit = RetVT == MVT::i64;
1750 switch (VT.SimpleTy) {
1752 llvm_unreachable("Unexpected value type.");
1753 case MVT::i1: // Intentional fall-through.
1755 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1756 RC = (IsRet64Bit && !WantZExt) ?
1757 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1760 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1761 RC = (IsRet64Bit && !WantZExt) ?
1762 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1765 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1766 RC = (IsRet64Bit && !WantZExt) ?
1767 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1770 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1771 RC = &AArch64::GPR64RegClass;
1774 Opc = FPOpcTable[Idx][0];
1775 RC = &AArch64::FPR32RegClass;
1778 Opc = FPOpcTable[Idx][1];
1779 RC = &AArch64::FPR64RegClass;
1783 // Create the base instruction, then add the operands.
1784 unsigned ResultReg = createResultReg(RC);
1785 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1786 TII.get(Opc), ResultReg);
1787 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1789 // Loading an i1 requires special handling.
1790 if (VT == MVT::i1) {
1791 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1792 assert(ANDReg && "Unexpected AND instruction emission failure.");
1796 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1797 // the 32bit reg to a 64bit reg.
1798 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1799 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1800 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1801 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1803 .addReg(ResultReg, getKillRegState(true))
1804 .addImm(AArch64::sub_32);
1810 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1812 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1816 return selectOperator(I, I->getOpcode());
1819 switch (I->getOpcode()) {
1821 llvm_unreachable("Unexpected instruction.");
1822 case Instruction::Add:
1823 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1825 case Instruction::Sub:
1826 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1832 updateValueMap(I, ResultReg);
1836 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1838 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1842 return selectOperator(I, I->getOpcode());
1845 switch (I->getOpcode()) {
1847 llvm_unreachable("Unexpected instruction.");
1848 case Instruction::And:
1849 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1851 case Instruction::Or:
1852 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1854 case Instruction::Xor:
1855 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1861 updateValueMap(I, ResultReg);
1865 bool AArch64FastISel::selectLoad(const Instruction *I) {
1867 // Verify we have a legal type before going any further. Currently, we handle
1868 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1869 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1870 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1871 cast<LoadInst>(I)->isAtomic())
1874 // See if we can handle this address.
1876 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1879 // Fold the following sign-/zero-extend into the load instruction.
1880 bool WantZExt = true;
1882 const Value *IntExtVal = nullptr;
1883 if (I->hasOneUse()) {
1884 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1885 if (isTypeSupported(ZE->getType(), RetVT))
1889 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1890 if (isTypeSupported(SE->getType(), RetVT))
1898 unsigned ResultReg =
1899 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1903 // There are a few different cases we have to handle, because the load or the
1904 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1905 // SelectionDAG. There is also an ordering issue when both instructions are in
1906 // different basic blocks.
1907 // 1.) The load instruction is selected by FastISel, but the integer extend
1908 // not. This usually happens when the integer extend is in a different
1909 // basic block and SelectionDAG took over for that basic block.
1910 // 2.) The load instruction is selected before the integer extend. This only
1911 // happens when the integer extend is in a different basic block.
1912 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1913 // by FastISel. This happens if there are instructions between the load
1914 // and the integer extend that couldn't be selected by FastISel.
1916 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1917 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1918 // it when it selects the integer extend.
1919 unsigned Reg = lookUpRegForValue(IntExtVal);
1921 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1923 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1924 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1925 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1927 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1931 updateValueMap(I, ResultReg);
1935 // The integer extend has already been emitted - delete all the instructions
1936 // that have been emitted by the integer extend lowering code and use the
1937 // result from the load instruction directly.
1939 auto *MI = MRI.getUniqueVRegDef(Reg);
1943 for (auto &Opnd : MI->uses()) {
1945 Reg = Opnd.getReg();
1949 MI->eraseFromParent();
1951 updateValueMap(IntExtVal, ResultReg);
1955 updateValueMap(I, ResultReg);
1959 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1960 MachineMemOperand *MMO) {
1961 // Simplify this down to something we can handle.
1962 if (!simplifyAddress(Addr, VT))
1965 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1967 llvm_unreachable("Unexpected value type.");
1969 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1970 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1971 bool UseScaled = true;
1972 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1977 static const unsigned OpcTable[4][6] = {
1978 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1979 AArch64::STURSi, AArch64::STURDi },
1980 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1981 AArch64::STRSui, AArch64::STRDui },
1982 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1983 AArch64::STRSroX, AArch64::STRDroX },
1984 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1985 AArch64::STRSroW, AArch64::STRDroW }
1989 bool VTIsi1 = false;
1990 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1991 Addr.getOffsetReg();
1992 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1993 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1994 Addr.getExtendType() == AArch64_AM::SXTW)
1997 switch (VT.SimpleTy) {
1998 default: llvm_unreachable("Unexpected value type.");
1999 case MVT::i1: VTIsi1 = true;
2000 case MVT::i8: Opc = OpcTable[Idx][0]; break;
2001 case MVT::i16: Opc = OpcTable[Idx][1]; break;
2002 case MVT::i32: Opc = OpcTable[Idx][2]; break;
2003 case MVT::i64: Opc = OpcTable[Idx][3]; break;
2004 case MVT::f32: Opc = OpcTable[Idx][4]; break;
2005 case MVT::f64: Opc = OpcTable[Idx][5]; break;
2008 // Storing an i1 requires special handling.
2009 if (VTIsi1 && SrcReg != AArch64::WZR) {
2010 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
2011 assert(ANDReg && "Unexpected AND instruction emission failure.");
2014 // Create the base instruction, then add the operands.
2015 const MCInstrDesc &II = TII.get(Opc);
2016 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2017 MachineInstrBuilder MIB =
2018 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
2019 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
2024 bool AArch64FastISel::selectStore(const Instruction *I) {
2026 const Value *Op0 = I->getOperand(0);
2027 // Verify we have a legal type before going any further. Currently, we handle
2028 // simple types that will directly fit in a register (i32/f32/i64/f64) or
2029 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2030 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2031 cast<StoreInst>(I)->isAtomic())
2034 // Get the value to be stored into a register. Use the zero register directly
2035 // when possible to avoid an unnecessary copy and a wasted register.
2036 unsigned SrcReg = 0;
2037 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2039 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2040 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2041 if (CF->isZero() && !CF->isNegative()) {
2042 VT = MVT::getIntegerVT(VT.getSizeInBits());
2043 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2048 SrcReg = getRegForValue(Op0);
2053 // See if we can handle this address.
2055 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2058 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2063 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2065 case CmpInst::FCMP_ONE:
2066 case CmpInst::FCMP_UEQ:
2068 // AL is our "false" for now. The other two need more compares.
2069 return AArch64CC::AL;
2070 case CmpInst::ICMP_EQ:
2071 case CmpInst::FCMP_OEQ:
2072 return AArch64CC::EQ;
2073 case CmpInst::ICMP_SGT:
2074 case CmpInst::FCMP_OGT:
2075 return AArch64CC::GT;
2076 case CmpInst::ICMP_SGE:
2077 case CmpInst::FCMP_OGE:
2078 return AArch64CC::GE;
2079 case CmpInst::ICMP_UGT:
2080 case CmpInst::FCMP_UGT:
2081 return AArch64CC::HI;
2082 case CmpInst::FCMP_OLT:
2083 return AArch64CC::MI;
2084 case CmpInst::ICMP_ULE:
2085 case CmpInst::FCMP_OLE:
2086 return AArch64CC::LS;
2087 case CmpInst::FCMP_ORD:
2088 return AArch64CC::VC;
2089 case CmpInst::FCMP_UNO:
2090 return AArch64CC::VS;
2091 case CmpInst::FCMP_UGE:
2092 return AArch64CC::PL;
2093 case CmpInst::ICMP_SLT:
2094 case CmpInst::FCMP_ULT:
2095 return AArch64CC::LT;
2096 case CmpInst::ICMP_SLE:
2097 case CmpInst::FCMP_ULE:
2098 return AArch64CC::LE;
2099 case CmpInst::FCMP_UNE:
2100 case CmpInst::ICMP_NE:
2101 return AArch64CC::NE;
2102 case CmpInst::ICMP_UGE:
2103 return AArch64CC::HS;
2104 case CmpInst::ICMP_ULT:
2105 return AArch64CC::LO;
2109 /// \brief Try to emit a combined compare-and-branch instruction.
2110 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2111 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2112 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2113 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2115 const Value *LHS = CI->getOperand(0);
2116 const Value *RHS = CI->getOperand(1);
2119 if (!isTypeSupported(LHS->getType(), VT))
2122 unsigned BW = VT.getSizeInBits();
2126 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2127 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2129 // Try to take advantage of fallthrough opportunities.
2130 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2131 std::swap(TBB, FBB);
2132 Predicate = CmpInst::getInversePredicate(Predicate);
2137 switch (Predicate) {
2140 case CmpInst::ICMP_EQ:
2141 case CmpInst::ICMP_NE:
2142 if (isa<Constant>(LHS) && cast<Constant>(LHS)->isNullValue())
2143 std::swap(LHS, RHS);
2145 if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2148 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2149 if (AI->getOpcode() == Instruction::And && isValueAvailable(AI)) {
2150 const Value *AndLHS = AI->getOperand(0);
2151 const Value *AndRHS = AI->getOperand(1);
2153 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2154 if (C->getValue().isPowerOf2())
2155 std::swap(AndLHS, AndRHS);
2157 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2158 if (C->getValue().isPowerOf2()) {
2159 TestBit = C->getValue().logBase2();
2167 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2169 case CmpInst::ICMP_SLT:
2170 case CmpInst::ICMP_SGE:
2171 if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2175 IsCmpNE = Predicate == CmpInst::ICMP_SLT;
2177 case CmpInst::ICMP_SGT:
2178 case CmpInst::ICMP_SLE:
2179 if (!isa<ConstantInt>(RHS))
2182 if (cast<ConstantInt>(RHS)->getValue() != APInt(BW, -1, true))
2186 IsCmpNE = Predicate == CmpInst::ICMP_SLE;
2190 static const unsigned OpcTable[2][2][2] = {
2191 { {AArch64::CBZW, AArch64::CBZX },
2192 {AArch64::CBNZW, AArch64::CBNZX} },
2193 { {AArch64::TBZW, AArch64::TBZX },
2194 {AArch64::TBNZW, AArch64::TBNZX} }
2197 bool IsBitTest = TestBit != -1;
2198 bool Is64Bit = BW == 64;
2199 if (TestBit < 32 && TestBit >= 0)
2202 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2203 const MCInstrDesc &II = TII.get(Opc);
2205 unsigned SrcReg = getRegForValue(LHS);
2208 bool SrcIsKill = hasTrivialKill(LHS);
2210 if (BW == 64 && !Is64Bit)
2211 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2214 if ((BW < 32) && !IsBitTest)
2215 SrcReg = emitIntExt(VT, SrcReg, MVT::i32, /*IsZExt=*/true);
2217 // Emit the combined compare and branch instruction.
2218 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2219 MachineInstrBuilder MIB =
2220 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2221 .addReg(SrcReg, getKillRegState(SrcIsKill));
2223 MIB.addImm(TestBit);
2226 // Obtain the branch weight and add the TrueBB to the successor list.
2227 uint32_t BranchWeight = 0;
2229 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2230 TBB->getBasicBlock());
2231 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2232 fastEmitBranch(FBB, DbgLoc);
2237 bool AArch64FastISel::selectBranch(const Instruction *I) {
2238 const BranchInst *BI = cast<BranchInst>(I);
2239 if (BI->isUnconditional()) {
2240 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2241 fastEmitBranch(MSucc, BI->getDebugLoc());
2245 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2246 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2248 AArch64CC::CondCode CC = AArch64CC::NE;
2249 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2250 if (CI->hasOneUse() && isValueAvailable(CI)) {
2251 // Try to optimize or fold the cmp.
2252 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2253 switch (Predicate) {
2256 case CmpInst::FCMP_FALSE:
2257 fastEmitBranch(FBB, DbgLoc);
2259 case CmpInst::FCMP_TRUE:
2260 fastEmitBranch(TBB, DbgLoc);
2264 // Try to emit a combined compare-and-branch first.
2265 if (emitCompareAndBranch(BI))
2268 // Try to take advantage of fallthrough opportunities.
2269 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2270 std::swap(TBB, FBB);
2271 Predicate = CmpInst::getInversePredicate(Predicate);
2275 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2278 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2280 CC = getCompareCC(Predicate);
2281 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2282 switch (Predicate) {
2285 case CmpInst::FCMP_UEQ:
2286 ExtraCC = AArch64CC::EQ;
2289 case CmpInst::FCMP_ONE:
2290 ExtraCC = AArch64CC::MI;
2294 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2296 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2297 if (ExtraCC != AArch64CC::AL) {
2298 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2304 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2308 // Obtain the branch weight and add the TrueBB to the successor list.
2309 uint32_t BranchWeight = 0;
2311 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2312 TBB->getBasicBlock());
2313 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2315 fastEmitBranch(FBB, DbgLoc);
2318 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2320 if (TI->hasOneUse() && isValueAvailable(TI) &&
2321 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2322 unsigned CondReg = getRegForValue(TI->getOperand(0));
2325 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2327 // Issue an extract_subreg to get the lower 32-bits.
2328 if (SrcVT == MVT::i64) {
2329 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2334 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2335 assert(ANDReg && "Unexpected AND instruction emission failure.");
2336 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2338 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2339 std::swap(TBB, FBB);
2342 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2346 // Obtain the branch weight and add the TrueBB to the successor list.
2347 uint32_t BranchWeight = 0;
2349 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2350 TBB->getBasicBlock());
2351 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2353 fastEmitBranch(FBB, DbgLoc);
2356 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2357 uint64_t Imm = CI->getZExtValue();
2358 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2359 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2362 // Obtain the branch weight and add the target to the successor list.
2363 uint32_t BranchWeight = 0;
2365 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2366 Target->getBasicBlock());
2367 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2369 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2370 // Fake request the condition, otherwise the intrinsic might be completely
2372 unsigned CondReg = getRegForValue(BI->getCondition());
2377 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2381 // Obtain the branch weight and add the TrueBB to the successor list.
2382 uint32_t BranchWeight = 0;
2384 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2385 TBB->getBasicBlock());
2386 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2388 fastEmitBranch(FBB, DbgLoc);
2392 unsigned CondReg = getRegForValue(BI->getCondition());
2395 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2397 // We've been divorced from our compare! Our block was split, and
2398 // now our compare lives in a predecessor block. We musn't
2399 // re-compare here, as the children of the compare aren't guaranteed
2400 // live across the block boundary (we *could* check for this).
2401 // Regardless, the compare has been done in the predecessor block,
2402 // and it left a value for us in a virtual register. Ergo, we test
2403 // the one-bit value left in the virtual register.
2404 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2406 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2407 std::swap(TBB, FBB);
2411 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2415 // Obtain the branch weight and add the TrueBB to the successor list.
2416 uint32_t BranchWeight = 0;
2418 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2419 TBB->getBasicBlock());
2420 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2422 fastEmitBranch(FBB, DbgLoc);
2426 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2427 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2428 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2432 // Emit the indirect branch.
2433 const MCInstrDesc &II = TII.get(AArch64::BR);
2434 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2435 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2437 // Make sure the CFG is up-to-date.
2438 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2439 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2444 bool AArch64FastISel::selectCmp(const Instruction *I) {
2445 const CmpInst *CI = cast<CmpInst>(I);
2447 // Try to optimize or fold the cmp.
2448 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2449 unsigned ResultReg = 0;
2450 switch (Predicate) {
2453 case CmpInst::FCMP_FALSE:
2454 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2455 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2456 TII.get(TargetOpcode::COPY), ResultReg)
2457 .addReg(AArch64::WZR, getKillRegState(true));
2459 case CmpInst::FCMP_TRUE:
2460 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2465 updateValueMap(I, ResultReg);
2470 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2473 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2475 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2476 // condition codes are inverted, because they are used by CSINC.
2477 static unsigned CondCodeTable[2][2] = {
2478 { AArch64CC::NE, AArch64CC::VC },
2479 { AArch64CC::PL, AArch64CC::LE }
2481 unsigned *CondCodes = nullptr;
2482 switch (Predicate) {
2485 case CmpInst::FCMP_UEQ:
2486 CondCodes = &CondCodeTable[0][0];
2488 case CmpInst::FCMP_ONE:
2489 CondCodes = &CondCodeTable[1][0];
2494 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2495 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2497 .addReg(AArch64::WZR, getKillRegState(true))
2498 .addReg(AArch64::WZR, getKillRegState(true))
2499 .addImm(CondCodes[0]);
2500 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2502 .addReg(TmpReg1, getKillRegState(true))
2503 .addReg(AArch64::WZR, getKillRegState(true))
2504 .addImm(CondCodes[1]);
2506 updateValueMap(I, ResultReg);
2510 // Now set a register based on the comparison.
2511 AArch64CC::CondCode CC = getCompareCC(Predicate);
2512 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2513 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2514 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2516 .addReg(AArch64::WZR, getKillRegState(true))
2517 .addReg(AArch64::WZR, getKillRegState(true))
2518 .addImm(invertedCC);
2520 updateValueMap(I, ResultReg);
2524 /// \brief Optimize selects of i1 if one of the operands has a 'true' or 'false'
2526 bool AArch64FastISel::optimizeSelect(const SelectInst *SI) {
2527 if (!SI->getType()->isIntegerTy(1))
2530 const Value *Src1Val, *Src2Val;
2532 bool NeedExtraOp = false;
2533 if (auto *CI = dyn_cast<ConstantInt>(SI->getTrueValue())) {
2535 Src1Val = SI->getCondition();
2536 Src2Val = SI->getFalseValue();
2537 Opc = AArch64::ORRWrr;
2539 assert(CI->isZero());
2540 Src1Val = SI->getFalseValue();
2541 Src2Val = SI->getCondition();
2542 Opc = AArch64::BICWrr;
2544 } else if (auto *CI = dyn_cast<ConstantInt>(SI->getFalseValue())) {
2546 Src1Val = SI->getCondition();
2547 Src2Val = SI->getTrueValue();
2548 Opc = AArch64::ORRWrr;
2551 assert(CI->isZero());
2552 Src1Val = SI->getCondition();
2553 Src2Val = SI->getTrueValue();
2554 Opc = AArch64::ANDWrr;
2561 unsigned Src1Reg = getRegForValue(Src1Val);
2564 bool Src1IsKill = hasTrivialKill(Src1Val);
2566 unsigned Src2Reg = getRegForValue(Src2Val);
2569 bool Src2IsKill = hasTrivialKill(Src2Val);
2572 Src1Reg = emitLogicalOp_ri(ISD::XOR, MVT::i32, Src1Reg, Src1IsKill, 1);
2575 unsigned ResultReg = fastEmitInst_rr(Opc, &AArch64::GPR32spRegClass, Src1Reg,
2576 Src1IsKill, Src2Reg, Src2IsKill);
2577 updateValueMap(SI, ResultReg);
2581 bool AArch64FastISel::selectSelect(const Instruction *I) {
2582 assert(isa<SelectInst>(I) && "Expected a select instruction.");
2584 if (!isTypeSupported(I->getType(), VT))
2588 const TargetRegisterClass *RC;
2589 switch (VT.SimpleTy) {
2596 Opc = AArch64::CSELWr;
2597 RC = &AArch64::GPR32RegClass;
2600 Opc = AArch64::CSELXr;
2601 RC = &AArch64::GPR64RegClass;
2604 Opc = AArch64::FCSELSrrr;
2605 RC = &AArch64::FPR32RegClass;
2608 Opc = AArch64::FCSELDrrr;
2609 RC = &AArch64::FPR64RegClass;
2613 const SelectInst *SI = cast<SelectInst>(I);
2614 const Value *Cond = SI->getCondition();
2615 AArch64CC::CondCode CC = AArch64CC::NE;
2616 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2618 if (optimizeSelect(SI))
2621 // Try to pickup the flags, so we don't have to emit another compare.
2622 if (foldXALUIntrinsic(CC, I, Cond)) {
2623 // Fake request the condition to force emission of the XALU intrinsic.
2624 unsigned CondReg = getRegForValue(Cond);
2627 } else if (isa<CmpInst>(Cond) && cast<CmpInst>(Cond)->hasOneUse() &&
2628 isValueAvailable(Cond)) {
2629 const auto *Cmp = cast<CmpInst>(Cond);
2630 // Try to optimize or fold the cmp.
2631 CmpInst::Predicate Predicate = optimizeCmpPredicate(Cmp);
2632 const Value *FoldSelect = nullptr;
2633 switch (Predicate) {
2636 case CmpInst::FCMP_FALSE:
2637 FoldSelect = SI->getFalseValue();
2639 case CmpInst::FCMP_TRUE:
2640 FoldSelect = SI->getTrueValue();
2645 unsigned SrcReg = getRegForValue(FoldSelect);
2648 unsigned UseReg = lookUpRegForValue(SI);
2650 MRI.clearKillFlags(UseReg);
2652 updateValueMap(I, SrcReg);
2657 if (!emitCmp(Cmp->getOperand(0), Cmp->getOperand(1), Cmp->isUnsigned()))
2660 // FCMP_UEQ and FCMP_ONE cannot be checked with a single select instruction.
2661 CC = getCompareCC(Predicate);
2662 switch (Predicate) {
2665 case CmpInst::FCMP_UEQ:
2666 ExtraCC = AArch64CC::EQ;
2669 case CmpInst::FCMP_ONE:
2670 ExtraCC = AArch64CC::MI;
2674 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2676 unsigned CondReg = getRegForValue(Cond);
2679 bool CondIsKill = hasTrivialKill(Cond);
2681 // Emit a TST instruction (ANDS wzr, reg, #imm).
2682 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDSWri),
2684 .addReg(CondReg, getKillRegState(CondIsKill))
2685 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2688 unsigned Src1Reg = getRegForValue(SI->getTrueValue());
2689 bool Src1IsKill = hasTrivialKill(SI->getTrueValue());
2691 unsigned Src2Reg = getRegForValue(SI->getFalseValue());
2692 bool Src2IsKill = hasTrivialKill(SI->getFalseValue());
2694 if (!Src1Reg || !Src2Reg)
2697 if (ExtraCC != AArch64CC::AL) {
2698 Src2Reg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2699 Src2IsKill, ExtraCC);
2702 unsigned ResultReg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2704 updateValueMap(I, ResultReg);
2708 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2709 Value *V = I->getOperand(0);
2710 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2713 unsigned Op = getRegForValue(V);
2717 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2718 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2719 ResultReg).addReg(Op);
2720 updateValueMap(I, ResultReg);
2724 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2725 Value *V = I->getOperand(0);
2726 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2729 unsigned Op = getRegForValue(V);
2733 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2734 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2735 ResultReg).addReg(Op);
2736 updateValueMap(I, ResultReg);
2740 // FPToUI and FPToSI
2741 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2743 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2746 unsigned SrcReg = getRegForValue(I->getOperand(0));
2750 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2751 if (SrcVT == MVT::f128)
2755 if (SrcVT == MVT::f64) {
2757 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2759 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2762 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2764 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2766 unsigned ResultReg = createResultReg(
2767 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2768 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2770 updateValueMap(I, ResultReg);
2774 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2776 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2778 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2779 "Unexpected value type.");
2781 unsigned SrcReg = getRegForValue(I->getOperand(0));
2784 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2786 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2788 // Handle sign-extension.
2789 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2791 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2798 if (SrcVT == MVT::i64) {
2800 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2802 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2805 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2807 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2810 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2812 updateValueMap(I, ResultReg);
2816 bool AArch64FastISel::fastLowerArguments() {
2817 if (!FuncInfo.CanLowerReturn)
2820 const Function *F = FuncInfo.Fn;
2824 CallingConv::ID CC = F->getCallingConv();
2825 if (CC != CallingConv::C)
2828 // Only handle simple cases of up to 8 GPR and FPR each.
2829 unsigned GPRCnt = 0;
2830 unsigned FPRCnt = 0;
2832 for (auto const &Arg : F->args()) {
2833 // The first argument is at index 1.
2835 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2836 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2837 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2838 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2841 Type *ArgTy = Arg.getType();
2842 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2845 EVT ArgVT = TLI.getValueType(ArgTy);
2846 if (!ArgVT.isSimple())
2849 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2850 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2853 if (VT.isVector() &&
2854 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2857 if (VT >= MVT::i1 && VT <= MVT::i64)
2859 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2860 VT.is128BitVector())
2865 if (GPRCnt > 8 || FPRCnt > 8)
2869 static const MCPhysReg Registers[6][8] = {
2870 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2871 AArch64::W5, AArch64::W6, AArch64::W7 },
2872 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2873 AArch64::X5, AArch64::X6, AArch64::X7 },
2874 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2875 AArch64::H5, AArch64::H6, AArch64::H7 },
2876 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2877 AArch64::S5, AArch64::S6, AArch64::S7 },
2878 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2879 AArch64::D5, AArch64::D6, AArch64::D7 },
2880 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2881 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2884 unsigned GPRIdx = 0;
2885 unsigned FPRIdx = 0;
2886 for (auto const &Arg : F->args()) {
2887 MVT VT = TLI.getSimpleValueType(Arg.getType());
2889 const TargetRegisterClass *RC;
2890 if (VT >= MVT::i1 && VT <= MVT::i32) {
2891 SrcReg = Registers[0][GPRIdx++];
2892 RC = &AArch64::GPR32RegClass;
2894 } else if (VT == MVT::i64) {
2895 SrcReg = Registers[1][GPRIdx++];
2896 RC = &AArch64::GPR64RegClass;
2897 } else if (VT == MVT::f16) {
2898 SrcReg = Registers[2][FPRIdx++];
2899 RC = &AArch64::FPR16RegClass;
2900 } else if (VT == MVT::f32) {
2901 SrcReg = Registers[3][FPRIdx++];
2902 RC = &AArch64::FPR32RegClass;
2903 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2904 SrcReg = Registers[4][FPRIdx++];
2905 RC = &AArch64::FPR64RegClass;
2906 } else if (VT.is128BitVector()) {
2907 SrcReg = Registers[5][FPRIdx++];
2908 RC = &AArch64::FPR128RegClass;
2910 llvm_unreachable("Unexpected value type.");
2912 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2913 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2914 // Without this, EmitLiveInCopies may eliminate the livein if its only
2915 // use is a bitcast (which isn't turned into an instruction).
2916 unsigned ResultReg = createResultReg(RC);
2917 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2918 TII.get(TargetOpcode::COPY), ResultReg)
2919 .addReg(DstReg, getKillRegState(true));
2920 updateValueMap(&Arg, ResultReg);
2925 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2926 SmallVectorImpl<MVT> &OutVTs,
2927 unsigned &NumBytes) {
2928 CallingConv::ID CC = CLI.CallConv;
2929 SmallVector<CCValAssign, 16> ArgLocs;
2930 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2931 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2933 // Get a count of how many bytes are to be pushed on the stack.
2934 NumBytes = CCInfo.getNextStackOffset();
2936 // Issue CALLSEQ_START
2937 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2938 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2941 // Process the args.
2942 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2943 CCValAssign &VA = ArgLocs[i];
2944 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2945 MVT ArgVT = OutVTs[VA.getValNo()];
2947 unsigned ArgReg = getRegForValue(ArgVal);
2951 // Handle arg promotion: SExt, ZExt, AExt.
2952 switch (VA.getLocInfo()) {
2953 case CCValAssign::Full:
2955 case CCValAssign::SExt: {
2956 MVT DestVT = VA.getLocVT();
2958 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2963 case CCValAssign::AExt:
2964 // Intentional fall-through.
2965 case CCValAssign::ZExt: {
2966 MVT DestVT = VA.getLocVT();
2968 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2974 llvm_unreachable("Unknown arg promotion!");
2977 // Now copy/store arg to correct locations.
2978 if (VA.isRegLoc() && !VA.needsCustom()) {
2979 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2980 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2981 CLI.OutRegs.push_back(VA.getLocReg());
2982 } else if (VA.needsCustom()) {
2983 // FIXME: Handle custom args.
2986 assert(VA.isMemLoc() && "Assuming store on stack.");
2988 // Don't emit stores for undef values.
2989 if (isa<UndefValue>(ArgVal))
2992 // Need to store on the stack.
2993 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2995 unsigned BEAlign = 0;
2996 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2997 BEAlign = 8 - ArgSize;
3000 Addr.setKind(Address::RegBase);
3001 Addr.setReg(AArch64::SP);
3002 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
3004 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3005 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3006 MachinePointerInfo::getStack(Addr.getOffset()),
3007 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3009 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
3016 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
3017 unsigned NumBytes) {
3018 CallingConv::ID CC = CLI.CallConv;
3020 // Issue CALLSEQ_END
3021 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3022 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3023 .addImm(NumBytes).addImm(0);
3025 // Now the return value.
3026 if (RetVT != MVT::isVoid) {
3027 SmallVector<CCValAssign, 16> RVLocs;
3028 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
3029 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
3031 // Only handle a single return value.
3032 if (RVLocs.size() != 1)
3035 // Copy all of the result registers out of their specified physreg.
3036 MVT CopyVT = RVLocs[0].getValVT();
3037 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
3038 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3039 TII.get(TargetOpcode::COPY), ResultReg)
3040 .addReg(RVLocs[0].getLocReg());
3041 CLI.InRegs.push_back(RVLocs[0].getLocReg());
3043 CLI.ResultReg = ResultReg;
3044 CLI.NumResultRegs = 1;
3050 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3051 CallingConv::ID CC = CLI.CallConv;
3052 bool IsTailCall = CLI.IsTailCall;
3053 bool IsVarArg = CLI.IsVarArg;
3054 const Value *Callee = CLI.Callee;
3055 const char *SymName = CLI.SymName;
3057 if (!Callee && !SymName)
3060 // Allow SelectionDAG isel to handle tail calls.
3064 CodeModel::Model CM = TM.getCodeModel();
3065 // Only support the small and large code model.
3066 if (CM != CodeModel::Small && CM != CodeModel::Large)
3069 // FIXME: Add large code model support for ELF.
3070 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
3073 // Let SDISel handle vararg functions.
3077 // FIXME: Only handle *simple* calls for now.
3079 if (CLI.RetTy->isVoidTy())
3080 RetVT = MVT::isVoid;
3081 else if (!isTypeLegal(CLI.RetTy, RetVT))
3084 for (auto Flag : CLI.OutFlags)
3085 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
3088 // Set up the argument vectors.
3089 SmallVector<MVT, 16> OutVTs;
3090 OutVTs.reserve(CLI.OutVals.size());
3092 for (auto *Val : CLI.OutVals) {
3094 if (!isTypeLegal(Val->getType(), VT) &&
3095 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
3098 // We don't handle vector parameters yet.
3099 if (VT.isVector() || VT.getSizeInBits() > 64)
3102 OutVTs.push_back(VT);
3106 if (Callee && !computeCallAddress(Callee, Addr))
3109 // Handle the arguments now that we've gotten them.
3111 if (!processCallArgs(CLI, OutVTs, NumBytes))
3115 MachineInstrBuilder MIB;
3116 if (CM == CodeModel::Small) {
3117 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
3118 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
3120 MIB.addExternalSymbol(SymName, 0);
3121 else if (Addr.getGlobalValue())
3122 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
3123 else if (Addr.getReg()) {
3124 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
3129 unsigned CallReg = 0;
3131 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
3132 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
3134 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
3136 CallReg = createResultReg(&AArch64::GPR64RegClass);
3137 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
3140 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
3142 } else if (Addr.getGlobalValue())
3143 CallReg = materializeGV(Addr.getGlobalValue());
3144 else if (Addr.getReg())
3145 CallReg = Addr.getReg();
3150 const MCInstrDesc &II = TII.get(AArch64::BLR);
3151 CallReg = constrainOperandRegClass(II, CallReg, 0);
3152 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
3155 // Add implicit physical register uses to the call.
3156 for (auto Reg : CLI.OutRegs)
3157 MIB.addReg(Reg, RegState::Implicit);
3159 // Add a register mask with the call-preserved registers.
3160 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3161 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3165 // Finish off the call including any return values.
3166 return finishCall(CLI, RetVT, NumBytes);
3169 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3171 return Len / Alignment <= 4;
3176 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3177 uint64_t Len, unsigned Alignment) {
3178 // Make sure we don't bloat code by inlining very large memcpy's.
3179 if (!isMemCpySmall(Len, Alignment))
3182 int64_t UnscaledOffset = 0;
3183 Address OrigDest = Dest;
3184 Address OrigSrc = Src;
3188 if (!Alignment || Alignment >= 8) {
3199 // Bound based on alignment.
3200 if (Len >= 4 && Alignment == 4)
3202 else if (Len >= 2 && Alignment == 2)
3209 unsigned ResultReg = emitLoad(VT, VT, Src);
3213 if (!emitStore(VT, ResultReg, Dest))
3216 int64_t Size = VT.getSizeInBits() / 8;
3218 UnscaledOffset += Size;
3220 // We need to recompute the unscaled offset for each iteration.
3221 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3222 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3228 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3229 /// into the user. The condition code will only be updated on success.
3230 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3231 const Instruction *I,
3232 const Value *Cond) {
3233 if (!isa<ExtractValueInst>(Cond))
3236 const auto *EV = cast<ExtractValueInst>(Cond);
3237 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3240 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3242 const Function *Callee = II->getCalledFunction();
3244 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3245 if (!isTypeLegal(RetTy, RetVT))
3248 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3251 const Value *LHS = II->getArgOperand(0);
3252 const Value *RHS = II->getArgOperand(1);
3254 // Canonicalize immediate to the RHS.
3255 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3256 isCommutativeIntrinsic(II))
3257 std::swap(LHS, RHS);
3259 // Simplify multiplies.
3260 unsigned IID = II->getIntrinsicID();
3264 case Intrinsic::smul_with_overflow:
3265 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3266 if (C->getValue() == 2)
3267 IID = Intrinsic::sadd_with_overflow;
3269 case Intrinsic::umul_with_overflow:
3270 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3271 if (C->getValue() == 2)
3272 IID = Intrinsic::uadd_with_overflow;
3276 AArch64CC::CondCode TmpCC;
3280 case Intrinsic::sadd_with_overflow:
3281 case Intrinsic::ssub_with_overflow:
3282 TmpCC = AArch64CC::VS;
3284 case Intrinsic::uadd_with_overflow:
3285 TmpCC = AArch64CC::HS;
3287 case Intrinsic::usub_with_overflow:
3288 TmpCC = AArch64CC::LO;
3290 case Intrinsic::smul_with_overflow:
3291 case Intrinsic::umul_with_overflow:
3292 TmpCC = AArch64CC::NE;
3296 // Check if both instructions are in the same basic block.
3297 if (!isValueAvailable(II))
3300 // Make sure nothing is in the way
3301 BasicBlock::const_iterator Start = I;
3302 BasicBlock::const_iterator End = II;
3303 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3304 // We only expect extractvalue instructions between the intrinsic and the
3305 // instruction to be selected.
3306 if (!isa<ExtractValueInst>(Itr))
3309 // Check that the extractvalue operand comes from the intrinsic.
3310 const auto *EVI = cast<ExtractValueInst>(Itr);
3311 if (EVI->getAggregateOperand() != II)
3319 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3320 // FIXME: Handle more intrinsics.
3321 switch (II->getIntrinsicID()) {
3322 default: return false;
3323 case Intrinsic::frameaddress: {
3324 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3325 MFI->setFrameAddressIsTaken(true);
3327 const AArch64RegisterInfo *RegInfo =
3328 static_cast<const AArch64RegisterInfo *>(Subtarget->getRegisterInfo());
3329 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3330 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3331 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3332 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3333 // Recursively load frame address
3339 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3341 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3342 SrcReg, /*IsKill=*/true, 0);
3343 assert(DestReg && "Unexpected LDR instruction emission failure.");
3347 updateValueMap(II, SrcReg);
3350 case Intrinsic::memcpy:
3351 case Intrinsic::memmove: {
3352 const auto *MTI = cast<MemTransferInst>(II);
3353 // Don't handle volatile.
3354 if (MTI->isVolatile())
3357 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3358 // we would emit dead code because we don't currently handle memmoves.
3359 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3360 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3361 // Small memcpy's are common enough that we want to do them without a call
3363 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3364 unsigned Alignment = MTI->getAlignment();
3365 if (isMemCpySmall(Len, Alignment)) {
3367 if (!computeAddress(MTI->getRawDest(), Dest) ||
3368 !computeAddress(MTI->getRawSource(), Src))
3370 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3375 if (!MTI->getLength()->getType()->isIntegerTy(64))
3378 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3379 // Fast instruction selection doesn't support the special
3383 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3384 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3386 case Intrinsic::memset: {
3387 const MemSetInst *MSI = cast<MemSetInst>(II);
3388 // Don't handle volatile.
3389 if (MSI->isVolatile())
3392 if (!MSI->getLength()->getType()->isIntegerTy(64))
3395 if (MSI->getDestAddressSpace() > 255)
3396 // Fast instruction selection doesn't support the special
3400 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3402 case Intrinsic::sin:
3403 case Intrinsic::cos:
3404 case Intrinsic::pow: {
3406 if (!isTypeLegal(II->getType(), RetVT))
3409 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3412 static const RTLIB::Libcall LibCallTable[3][2] = {
3413 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3414 { RTLIB::COS_F32, RTLIB::COS_F64 },
3415 { RTLIB::POW_F32, RTLIB::POW_F64 }
3418 bool Is64Bit = RetVT == MVT::f64;
3419 switch (II->getIntrinsicID()) {
3421 llvm_unreachable("Unexpected intrinsic.");
3422 case Intrinsic::sin:
3423 LC = LibCallTable[0][Is64Bit];
3425 case Intrinsic::cos:
3426 LC = LibCallTable[1][Is64Bit];
3428 case Intrinsic::pow:
3429 LC = LibCallTable[2][Is64Bit];
3434 Args.reserve(II->getNumArgOperands());
3436 // Populate the argument list.
3437 for (auto &Arg : II->arg_operands()) {
3440 Entry.Ty = Arg->getType();
3441 Args.push_back(Entry);
3444 CallLoweringInfo CLI;
3445 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3446 TLI.getLibcallName(LC), std::move(Args));
3447 if (!lowerCallTo(CLI))
3449 updateValueMap(II, CLI.ResultReg);
3452 case Intrinsic::fabs: {
3454 if (!isTypeLegal(II->getType(), VT))
3458 switch (VT.SimpleTy) {
3462 Opc = AArch64::FABSSr;
3465 Opc = AArch64::FABSDr;
3468 unsigned SrcReg = getRegForValue(II->getOperand(0));
3471 bool SrcRegIsKill = hasTrivialKill(II->getOperand(0));
3472 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3473 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3474 .addReg(SrcReg, getKillRegState(SrcRegIsKill));
3475 updateValueMap(II, ResultReg);
3478 case Intrinsic::trap: {
3479 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3483 case Intrinsic::sqrt: {
3484 Type *RetTy = II->getCalledFunction()->getReturnType();
3487 if (!isTypeLegal(RetTy, VT))
3490 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3493 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3495 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3499 updateValueMap(II, ResultReg);
3502 case Intrinsic::sadd_with_overflow:
3503 case Intrinsic::uadd_with_overflow:
3504 case Intrinsic::ssub_with_overflow:
3505 case Intrinsic::usub_with_overflow:
3506 case Intrinsic::smul_with_overflow:
3507 case Intrinsic::umul_with_overflow: {
3508 // This implements the basic lowering of the xalu with overflow intrinsics.
3509 const Function *Callee = II->getCalledFunction();
3510 auto *Ty = cast<StructType>(Callee->getReturnType());
3511 Type *RetTy = Ty->getTypeAtIndex(0U);
3514 if (!isTypeLegal(RetTy, VT))
3517 if (VT != MVT::i32 && VT != MVT::i64)
3520 const Value *LHS = II->getArgOperand(0);
3521 const Value *RHS = II->getArgOperand(1);
3522 // Canonicalize immediate to the RHS.
3523 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3524 isCommutativeIntrinsic(II))
3525 std::swap(LHS, RHS);
3527 // Simplify multiplies.
3528 unsigned IID = II->getIntrinsicID();
3532 case Intrinsic::smul_with_overflow:
3533 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3534 if (C->getValue() == 2) {
3535 IID = Intrinsic::sadd_with_overflow;
3539 case Intrinsic::umul_with_overflow:
3540 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3541 if (C->getValue() == 2) {
3542 IID = Intrinsic::uadd_with_overflow;
3548 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3549 AArch64CC::CondCode CC = AArch64CC::Invalid;
3551 default: llvm_unreachable("Unexpected intrinsic!");
3552 case Intrinsic::sadd_with_overflow:
3553 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3556 case Intrinsic::uadd_with_overflow:
3557 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3560 case Intrinsic::ssub_with_overflow:
3561 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3564 case Intrinsic::usub_with_overflow:
3565 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3568 case Intrinsic::smul_with_overflow: {
3570 unsigned LHSReg = getRegForValue(LHS);
3573 bool LHSIsKill = hasTrivialKill(LHS);
3575 unsigned RHSReg = getRegForValue(RHS);
3578 bool RHSIsKill = hasTrivialKill(RHS);
3580 if (VT == MVT::i32) {
3581 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3582 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3583 /*IsKill=*/false, 32);
3584 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3586 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3588 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3589 AArch64_AM::ASR, 31, /*WantResult=*/false);
3591 assert(VT == MVT::i64 && "Unexpected value type.");
3592 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3593 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3595 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3596 AArch64_AM::ASR, 63, /*WantResult=*/false);
3600 case Intrinsic::umul_with_overflow: {
3602 unsigned LHSReg = getRegForValue(LHS);
3605 bool LHSIsKill = hasTrivialKill(LHS);
3607 unsigned RHSReg = getRegForValue(RHS);
3610 bool RHSIsKill = hasTrivialKill(RHS);
3612 if (VT == MVT::i32) {
3613 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3614 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3615 /*IsKill=*/false, AArch64_AM::LSR, 32,
3616 /*WantResult=*/false);
3617 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3620 assert(VT == MVT::i64 && "Unexpected value type.");
3621 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3622 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3624 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3625 /*IsKill=*/false, /*WantResult=*/false);
3632 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3633 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3634 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3637 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3638 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3639 /*IsKill=*/true, getInvertedCondCode(CC));
3641 assert((ResultReg1 + 1) == ResultReg2 &&
3642 "Nonconsecutive result registers.");
3643 updateValueMap(II, ResultReg1, 2);
3650 bool AArch64FastISel::selectRet(const Instruction *I) {
3651 const ReturnInst *Ret = cast<ReturnInst>(I);
3652 const Function &F = *I->getParent()->getParent();
3654 if (!FuncInfo.CanLowerReturn)
3660 // Build a list of return value registers.
3661 SmallVector<unsigned, 4> RetRegs;
3663 if (Ret->getNumOperands() > 0) {
3664 CallingConv::ID CC = F.getCallingConv();
3665 SmallVector<ISD::OutputArg, 4> Outs;
3666 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3668 // Analyze operands of the call, assigning locations to each operand.
3669 SmallVector<CCValAssign, 16> ValLocs;
3670 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3671 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3672 : RetCC_AArch64_AAPCS;
3673 CCInfo.AnalyzeReturn(Outs, RetCC);
3675 // Only handle a single return value for now.
3676 if (ValLocs.size() != 1)
3679 CCValAssign &VA = ValLocs[0];
3680 const Value *RV = Ret->getOperand(0);
3682 // Don't bother handling odd stuff for now.
3683 if ((VA.getLocInfo() != CCValAssign::Full) &&
3684 (VA.getLocInfo() != CCValAssign::BCvt))
3687 // Only handle register returns for now.
3691 unsigned Reg = getRegForValue(RV);
3695 unsigned SrcReg = Reg + VA.getValNo();
3696 unsigned DestReg = VA.getLocReg();
3697 // Avoid a cross-class copy. This is very unlikely.
3698 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3701 EVT RVEVT = TLI.getValueType(RV->getType());
3702 if (!RVEVT.isSimple())
3705 // Vectors (of > 1 lane) in big endian need tricky handling.
3706 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3707 !Subtarget->isLittleEndian())
3710 MVT RVVT = RVEVT.getSimpleVT();
3711 if (RVVT == MVT::f128)
3714 MVT DestVT = VA.getValVT();
3715 // Special handling for extended integers.
3716 if (RVVT != DestVT) {
3717 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3720 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3723 bool IsZExt = Outs[0].Flags.isZExt();
3724 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3730 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3731 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3733 // Add register to return instruction.
3734 RetRegs.push_back(VA.getLocReg());
3737 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3738 TII.get(AArch64::RET_ReallyLR));
3739 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3740 MIB.addReg(RetRegs[i], RegState::Implicit);
3744 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3745 Type *DestTy = I->getType();
3746 Value *Op = I->getOperand(0);
3747 Type *SrcTy = Op->getType();
3749 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3750 EVT DestEVT = TLI.getValueType(DestTy, true);
3751 if (!SrcEVT.isSimple())
3753 if (!DestEVT.isSimple())
3756 MVT SrcVT = SrcEVT.getSimpleVT();
3757 MVT DestVT = DestEVT.getSimpleVT();
3759 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3762 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3766 unsigned SrcReg = getRegForValue(Op);
3769 bool SrcIsKill = hasTrivialKill(Op);
3771 // If we're truncating from i64 to a smaller non-legal type then generate an
3772 // AND. Otherwise, we know the high bits are undefined and a truncate only
3773 // generate a COPY. We cannot mark the source register also as result
3774 // register, because this can incorrectly transfer the kill flag onto the
3777 if (SrcVT == MVT::i64) {
3779 switch (DestVT.SimpleTy) {
3781 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3793 // Issue an extract_subreg to get the lower 32-bits.
3794 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3796 // Create the AND instruction which performs the actual truncation.
3797 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3798 assert(ResultReg && "Unexpected AND instruction emission failure.");
3800 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3801 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3802 TII.get(TargetOpcode::COPY), ResultReg)
3803 .addReg(SrcReg, getKillRegState(SrcIsKill));
3806 updateValueMap(I, ResultReg);
3810 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3811 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3812 DestVT == MVT::i64) &&
3813 "Unexpected value type.");
3814 // Handle i8 and i16 as i32.
3815 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3819 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3820 assert(ResultReg && "Unexpected AND instruction emission failure.");
3821 if (DestVT == MVT::i64) {
3822 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3823 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3824 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3825 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3826 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3829 .addImm(AArch64::sub_32);
3834 if (DestVT == MVT::i64) {
3835 // FIXME: We're SExt i1 to i64.
3838 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3839 /*TODO:IsKill=*/false, 0, 0);
3843 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3844 unsigned Op1, bool Op1IsKill) {
3846 switch (RetVT.SimpleTy) {
3852 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3854 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3857 const TargetRegisterClass *RC =
3858 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3859 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3860 /*IsKill=*/ZReg, true);
3863 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3864 unsigned Op1, bool Op1IsKill) {
3865 if (RetVT != MVT::i64)
3868 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3869 Op0, Op0IsKill, Op1, Op1IsKill,
3870 AArch64::XZR, /*IsKill=*/true);
3873 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3874 unsigned Op1, bool Op1IsKill) {
3875 if (RetVT != MVT::i64)
3878 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3879 Op0, Op0IsKill, Op1, Op1IsKill,
3880 AArch64::XZR, /*IsKill=*/true);
3883 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3884 unsigned Op1Reg, bool Op1IsKill) {
3886 bool NeedTrunc = false;
3888 switch (RetVT.SimpleTy) {
3890 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3891 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3892 case MVT::i32: Opc = AArch64::LSLVWr; break;
3893 case MVT::i64: Opc = AArch64::LSLVXr; break;
3896 const TargetRegisterClass *RC =
3897 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3899 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3902 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3905 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3909 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3910 bool Op0IsKill, uint64_t Shift,
3912 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3913 "Unexpected source/return type pair.");
3914 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3915 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3916 "Unexpected source value type.");
3917 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3918 RetVT == MVT::i64) && "Unexpected return value type.");
3920 bool Is64Bit = (RetVT == MVT::i64);
3921 unsigned RegSize = Is64Bit ? 64 : 32;
3922 unsigned DstBits = RetVT.getSizeInBits();
3923 unsigned SrcBits = SrcVT.getSizeInBits();
3924 const TargetRegisterClass *RC =
3925 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3927 // Just emit a copy for "zero" shifts.
3929 if (RetVT == SrcVT) {
3930 unsigned ResultReg = createResultReg(RC);
3931 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3932 TII.get(TargetOpcode::COPY), ResultReg)
3933 .addReg(Op0, getKillRegState(Op0IsKill));
3936 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3939 // Don't deal with undefined shifts.
3940 if (Shift >= DstBits)
3943 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3944 // {S|U}BFM Wd, Wn, #r, #s
3945 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3947 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3948 // %2 = shl i16 %1, 4
3949 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3950 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3951 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3952 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3954 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3955 // %2 = shl i16 %1, 8
3956 // Wd<32+7-24,32-24> = Wn<7:0>
3957 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3958 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3959 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3961 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3962 // %2 = shl i16 %1, 12
3963 // Wd<32+3-20,32-20> = Wn<3:0>
3964 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3965 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3966 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3968 unsigned ImmR = RegSize - Shift;
3969 // Limit the width to the length of the source type.
3970 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3971 static const unsigned OpcTable[2][2] = {
3972 {AArch64::SBFMWri, AArch64::SBFMXri},
3973 {AArch64::UBFMWri, AArch64::UBFMXri}
3975 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3976 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3977 unsigned TmpReg = MRI.createVirtualRegister(RC);
3978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3979 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3981 .addReg(Op0, getKillRegState(Op0IsKill))
3982 .addImm(AArch64::sub_32);
3986 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3989 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3990 unsigned Op1Reg, bool Op1IsKill) {
3992 bool NeedTrunc = false;
3994 switch (RetVT.SimpleTy) {
3996 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3997 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3998 case MVT::i32: Opc = AArch64::LSRVWr; break;
3999 case MVT::i64: Opc = AArch64::LSRVXr; break;
4002 const TargetRegisterClass *RC =
4003 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4005 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
4006 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4007 Op0IsKill = Op1IsKill = true;
4009 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4012 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4016 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4017 bool Op0IsKill, uint64_t Shift,
4019 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4020 "Unexpected source/return type pair.");
4021 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4022 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4023 "Unexpected source value type.");
4024 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4025 RetVT == MVT::i64) && "Unexpected return value type.");
4027 bool Is64Bit = (RetVT == MVT::i64);
4028 unsigned RegSize = Is64Bit ? 64 : 32;
4029 unsigned DstBits = RetVT.getSizeInBits();
4030 unsigned SrcBits = SrcVT.getSizeInBits();
4031 const TargetRegisterClass *RC =
4032 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4034 // Just emit a copy for "zero" shifts.
4036 if (RetVT == SrcVT) {
4037 unsigned ResultReg = createResultReg(RC);
4038 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4039 TII.get(TargetOpcode::COPY), ResultReg)
4040 .addReg(Op0, getKillRegState(Op0IsKill));
4043 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4046 // Don't deal with undefined shifts.
4047 if (Shift >= DstBits)
4050 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4051 // {S|U}BFM Wd, Wn, #r, #s
4052 // Wd<s-r:0> = Wn<s:r> when r <= s
4054 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4055 // %2 = lshr i16 %1, 4
4056 // Wd<7-4:0> = Wn<7:4>
4057 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
4058 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4059 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4061 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4062 // %2 = lshr i16 %1, 8
4063 // Wd<7-7,0> = Wn<7:7>
4064 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
4065 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4066 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4068 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4069 // %2 = lshr i16 %1, 12
4070 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4071 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
4072 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4073 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4075 if (Shift >= SrcBits && IsZExt)
4076 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4078 // It is not possible to fold a sign-extend into the LShr instruction. In this
4079 // case emit a sign-extend.
4081 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4086 SrcBits = SrcVT.getSizeInBits();
4090 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4091 unsigned ImmS = SrcBits - 1;
4092 static const unsigned OpcTable[2][2] = {
4093 {AArch64::SBFMWri, AArch64::SBFMXri},
4094 {AArch64::UBFMWri, AArch64::UBFMXri}
4096 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4097 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4098 unsigned TmpReg = MRI.createVirtualRegister(RC);
4099 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4100 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4102 .addReg(Op0, getKillRegState(Op0IsKill))
4103 .addImm(AArch64::sub_32);
4107 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4110 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4111 unsigned Op1Reg, bool Op1IsKill) {
4113 bool NeedTrunc = false;
4115 switch (RetVT.SimpleTy) {
4117 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
4118 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
4119 case MVT::i32: Opc = AArch64::ASRVWr; break;
4120 case MVT::i64: Opc = AArch64::ASRVXr; break;
4123 const TargetRegisterClass *RC =
4124 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4126 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
4127 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4128 Op0IsKill = Op1IsKill = true;
4130 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4133 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4137 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4138 bool Op0IsKill, uint64_t Shift,
4140 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4141 "Unexpected source/return type pair.");
4142 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4143 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4144 "Unexpected source value type.");
4145 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4146 RetVT == MVT::i64) && "Unexpected return value type.");
4148 bool Is64Bit = (RetVT == MVT::i64);
4149 unsigned RegSize = Is64Bit ? 64 : 32;
4150 unsigned DstBits = RetVT.getSizeInBits();
4151 unsigned SrcBits = SrcVT.getSizeInBits();
4152 const TargetRegisterClass *RC =
4153 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4155 // Just emit a copy for "zero" shifts.
4157 if (RetVT == SrcVT) {
4158 unsigned ResultReg = createResultReg(RC);
4159 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4160 TII.get(TargetOpcode::COPY), ResultReg)
4161 .addReg(Op0, getKillRegState(Op0IsKill));
4164 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4167 // Don't deal with undefined shifts.
4168 if (Shift >= DstBits)
4171 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4172 // {S|U}BFM Wd, Wn, #r, #s
4173 // Wd<s-r:0> = Wn<s:r> when r <= s
4175 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4176 // %2 = ashr i16 %1, 4
4177 // Wd<7-4:0> = Wn<7:4>
4178 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
4179 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4180 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4182 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4183 // %2 = ashr i16 %1, 8
4184 // Wd<7-7,0> = Wn<7:7>
4185 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4186 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4187 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4189 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4190 // %2 = ashr i16 %1, 12
4191 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4192 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4193 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4194 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4196 if (Shift >= SrcBits && IsZExt)
4197 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4199 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4200 unsigned ImmS = SrcBits - 1;
4201 static const unsigned OpcTable[2][2] = {
4202 {AArch64::SBFMWri, AArch64::SBFMXri},
4203 {AArch64::UBFMWri, AArch64::UBFMXri}
4205 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4206 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4207 unsigned TmpReg = MRI.createVirtualRegister(RC);
4208 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4209 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4211 .addReg(Op0, getKillRegState(Op0IsKill))
4212 .addImm(AArch64::sub_32);
4216 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4219 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
4221 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4223 // FastISel does not have plumbing to deal with extensions where the SrcVT or
4224 // DestVT are odd things, so test to make sure that they are both types we can
4225 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4226 // bail out to SelectionDAG.
4227 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4228 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4229 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
4230 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
4236 switch (SrcVT.SimpleTy) {
4240 return emiti1Ext(SrcReg, DestVT, IsZExt);
4242 if (DestVT == MVT::i64)
4243 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4245 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4249 if (DestVT == MVT::i64)
4250 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4252 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4256 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4257 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4262 // Handle i8 and i16 as i32.
4263 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4265 else if (DestVT == MVT::i64) {
4266 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4267 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4268 TII.get(AArch64::SUBREG_TO_REG), Src64)
4271 .addImm(AArch64::sub_32);
4275 const TargetRegisterClass *RC =
4276 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4277 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4280 static bool isZExtLoad(const MachineInstr *LI) {
4281 switch (LI->getOpcode()) {
4284 case AArch64::LDURBBi:
4285 case AArch64::LDURHHi:
4286 case AArch64::LDURWi:
4287 case AArch64::LDRBBui:
4288 case AArch64::LDRHHui:
4289 case AArch64::LDRWui:
4290 case AArch64::LDRBBroX:
4291 case AArch64::LDRHHroX:
4292 case AArch64::LDRWroX:
4293 case AArch64::LDRBBroW:
4294 case AArch64::LDRHHroW:
4295 case AArch64::LDRWroW:
4300 static bool isSExtLoad(const MachineInstr *LI) {
4301 switch (LI->getOpcode()) {
4304 case AArch64::LDURSBWi:
4305 case AArch64::LDURSHWi:
4306 case AArch64::LDURSBXi:
4307 case AArch64::LDURSHXi:
4308 case AArch64::LDURSWi:
4309 case AArch64::LDRSBWui:
4310 case AArch64::LDRSHWui:
4311 case AArch64::LDRSBXui:
4312 case AArch64::LDRSHXui:
4313 case AArch64::LDRSWui:
4314 case AArch64::LDRSBWroX:
4315 case AArch64::LDRSHWroX:
4316 case AArch64::LDRSBXroX:
4317 case AArch64::LDRSHXroX:
4318 case AArch64::LDRSWroX:
4319 case AArch64::LDRSBWroW:
4320 case AArch64::LDRSHWroW:
4321 case AArch64::LDRSBXroW:
4322 case AArch64::LDRSHXroW:
4323 case AArch64::LDRSWroW:
4328 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4330 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4331 if (!LI || !LI->hasOneUse())
4334 // Check if the load instruction has already been selected.
4335 unsigned Reg = lookUpRegForValue(LI);
4339 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4343 // Check if the correct load instruction has been emitted - SelectionDAG might
4344 // have emitted a zero-extending load, but we need a sign-extending load.
4345 bool IsZExt = isa<ZExtInst>(I);
4346 const auto *LoadMI = MI;
4347 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4348 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4349 unsigned LoadReg = MI->getOperand(1).getReg();
4350 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4351 assert(LoadMI && "Expected valid instruction");
4353 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4356 // Nothing to be done.
4357 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4358 updateValueMap(I, Reg);
4363 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4364 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4365 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4367 .addReg(Reg, getKillRegState(true))
4368 .addImm(AArch64::sub_32);
4371 assert((MI->getOpcode() == TargetOpcode::COPY &&
4372 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4373 "Expected copy instruction");
4374 Reg = MI->getOperand(1).getReg();
4375 MI->eraseFromParent();
4377 updateValueMap(I, Reg);
4381 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4382 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4383 "Unexpected integer extend instruction.");
4386 if (!isTypeSupported(I->getType(), RetVT))
4389 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4392 // Try to optimize already sign-/zero-extended values from load instructions.
4393 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4396 unsigned SrcReg = getRegForValue(I->getOperand(0));
4399 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4401 // Try to optimize already sign-/zero-extended values from function arguments.
4402 bool IsZExt = isa<ZExtInst>(I);
4403 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4404 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4405 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4406 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4408 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4410 .addReg(SrcReg, getKillRegState(SrcIsKill))
4411 .addImm(AArch64::sub_32);
4414 // Conservatively clear all kill flags from all uses, because we are
4415 // replacing a sign-/zero-extend instruction at IR level with a nop at MI
4416 // level. The result of the instruction at IR level might have been
4417 // trivially dead, which is now not longer true.
4418 unsigned UseReg = lookUpRegForValue(I);
4420 MRI.clearKillFlags(UseReg);
4422 updateValueMap(I, SrcReg);
4427 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4431 updateValueMap(I, ResultReg);
4435 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4436 EVT DestEVT = TLI.getValueType(I->getType(), true);
4437 if (!DestEVT.isSimple())
4440 MVT DestVT = DestEVT.getSimpleVT();
4441 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4445 bool Is64bit = (DestVT == MVT::i64);
4446 switch (ISDOpcode) {
4450 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4453 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4456 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4457 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4460 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4462 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4465 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4467 const TargetRegisterClass *RC =
4468 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4469 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4470 Src1Reg, /*IsKill=*/false);
4471 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4472 // The remainder is computed as numerator - (quotient * denominator) using the
4473 // MSUB instruction.
4474 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4475 Src1Reg, Src1IsKill, Src0Reg,
4477 updateValueMap(I, ResultReg);
4481 bool AArch64FastISel::selectMul(const Instruction *I) {
4483 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4487 return selectBinaryOp(I, ISD::MUL);
4489 const Value *Src0 = I->getOperand(0);
4490 const Value *Src1 = I->getOperand(1);
4491 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4492 if (C->getValue().isPowerOf2())
4493 std::swap(Src0, Src1);
4495 // Try to simplify to a shift instruction.
4496 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4497 if (C->getValue().isPowerOf2()) {
4498 uint64_t ShiftVal = C->getValue().logBase2();
4501 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4502 if (!isIntExtFree(ZExt)) {
4504 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4507 Src0 = ZExt->getOperand(0);
4510 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4511 if (!isIntExtFree(SExt)) {
4513 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4516 Src0 = SExt->getOperand(0);
4521 unsigned Src0Reg = getRegForValue(Src0);
4524 bool Src0IsKill = hasTrivialKill(Src0);
4526 unsigned ResultReg =
4527 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4530 updateValueMap(I, ResultReg);
4535 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4538 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4540 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4543 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4545 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4550 updateValueMap(I, ResultReg);
4554 bool AArch64FastISel::selectShift(const Instruction *I) {
4556 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4559 if (RetVT.isVector())
4560 return selectOperator(I, I->getOpcode());
4562 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4563 unsigned ResultReg = 0;
4564 uint64_t ShiftVal = C->getZExtValue();
4566 bool IsZExt = I->getOpcode() != Instruction::AShr;
4567 const Value *Op0 = I->getOperand(0);
4568 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4569 if (!isIntExtFree(ZExt)) {
4571 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4574 Op0 = ZExt->getOperand(0);
4577 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4578 if (!isIntExtFree(SExt)) {
4580 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4583 Op0 = SExt->getOperand(0);
4588 unsigned Op0Reg = getRegForValue(Op0);
4591 bool Op0IsKill = hasTrivialKill(Op0);
4593 switch (I->getOpcode()) {
4594 default: llvm_unreachable("Unexpected instruction.");
4595 case Instruction::Shl:
4596 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4598 case Instruction::AShr:
4599 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4601 case Instruction::LShr:
4602 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4608 updateValueMap(I, ResultReg);
4612 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4615 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4617 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4620 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4622 unsigned ResultReg = 0;
4623 switch (I->getOpcode()) {
4624 default: llvm_unreachable("Unexpected instruction.");
4625 case Instruction::Shl:
4626 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4628 case Instruction::AShr:
4629 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4631 case Instruction::LShr:
4632 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4639 updateValueMap(I, ResultReg);
4643 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4646 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4648 if (!isTypeLegal(I->getType(), RetVT))
4652 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4653 Opc = AArch64::FMOVWSr;
4654 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4655 Opc = AArch64::FMOVXDr;
4656 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4657 Opc = AArch64::FMOVSWr;
4658 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4659 Opc = AArch64::FMOVDXr;
4663 const TargetRegisterClass *RC = nullptr;
4664 switch (RetVT.SimpleTy) {
4665 default: llvm_unreachable("Unexpected value type.");
4666 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4667 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4668 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4669 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4671 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4674 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4675 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4680 updateValueMap(I, ResultReg);
4684 bool AArch64FastISel::selectFRem(const Instruction *I) {
4686 if (!isTypeLegal(I->getType(), RetVT))
4690 switch (RetVT.SimpleTy) {
4694 LC = RTLIB::REM_F32;
4697 LC = RTLIB::REM_F64;
4702 Args.reserve(I->getNumOperands());
4704 // Populate the argument list.
4705 for (auto &Arg : I->operands()) {
4708 Entry.Ty = Arg->getType();
4709 Args.push_back(Entry);
4712 CallLoweringInfo CLI;
4713 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4714 TLI.getLibcallName(LC), std::move(Args));
4715 if (!lowerCallTo(CLI))
4717 updateValueMap(I, CLI.ResultReg);
4721 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4723 if (!isTypeLegal(I->getType(), VT))
4726 if (!isa<ConstantInt>(I->getOperand(1)))
4727 return selectBinaryOp(I, ISD::SDIV);
4729 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4730 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4731 !(C.isPowerOf2() || (-C).isPowerOf2()))
4732 return selectBinaryOp(I, ISD::SDIV);
4734 unsigned Lg2 = C.countTrailingZeros();
4735 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4738 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4740 if (cast<BinaryOperator>(I)->isExact()) {
4741 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4744 updateValueMap(I, ResultReg);
4748 int64_t Pow2MinusOne = (1ULL << Lg2) - 1;
4749 unsigned AddReg = emitAdd_ri_(VT, Src0Reg, /*IsKill=*/false, Pow2MinusOne);
4753 // (Src0 < 0) ? Pow2 - 1 : 0;
4754 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4758 const TargetRegisterClass *RC;
4759 if (VT == MVT::i64) {
4760 SelectOpc = AArch64::CSELXr;
4761 RC = &AArch64::GPR64RegClass;
4763 SelectOpc = AArch64::CSELWr;
4764 RC = &AArch64::GPR32RegClass;
4766 unsigned SelectReg =
4767 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4768 Src0IsKill, AArch64CC::LT);
4772 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4773 // negate the result.
4774 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4777 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4778 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4780 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4785 updateValueMap(I, ResultReg);
4789 /// This is mostly a copy of the existing FastISel getRegForGEPIndex code. We
4790 /// have to duplicate it for AArch64, because otherwise we would fail during the
4791 /// sign-extend emission.
4792 std::pair<unsigned, bool> AArch64FastISel::getRegForGEPIndex(const Value *Idx) {
4793 unsigned IdxN = getRegForValue(Idx);
4795 // Unhandled operand. Halt "fast" selection and bail.
4796 return std::pair<unsigned, bool>(0, false);
4798 bool IdxNIsKill = hasTrivialKill(Idx);
4800 // If the index is smaller or larger than intptr_t, truncate or extend it.
4801 MVT PtrVT = TLI.getPointerTy();
4802 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
4803 if (IdxVT.bitsLT(PtrVT)) {
4804 IdxN = emitIntExt(IdxVT.getSimpleVT(), IdxN, PtrVT, /*IsZExt=*/false);
4806 } else if (IdxVT.bitsGT(PtrVT))
4807 llvm_unreachable("AArch64 FastISel doesn't support types larger than i64");
4808 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
4811 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4812 /// duplicate it for AArch64, because otherwise we would bail out even for
4813 /// simple cases. This is because the standard fastEmit functions don't cover
4814 /// MUL at all and ADD is lowered very inefficientily.
4815 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4816 unsigned N = getRegForValue(I->getOperand(0));
4819 bool NIsKill = hasTrivialKill(I->getOperand(0));
4821 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4822 // into a single N = N + TotalOffset.
4823 uint64_t TotalOffs = 0;
4824 Type *Ty = I->getOperand(0)->getType();
4825 MVT VT = TLI.getPointerTy();
4826 for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4827 const Value *Idx = *OI;
4828 if (auto *StTy = dyn_cast<StructType>(Ty)) {
4829 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4832 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4833 Ty = StTy->getElementType(Field);
4835 Ty = cast<SequentialType>(Ty)->getElementType();
4836 // If this is a constant subscript, handle it quickly.
4837 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4842 DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4846 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4853 // N = N + Idx * ElementSize;
4854 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4855 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4856 unsigned IdxN = Pair.first;
4857 bool IdxNIsKill = Pair.second;
4861 if (ElementSize != 1) {
4862 unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4865 IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4870 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4876 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4880 updateValueMap(I, N);
4884 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4885 switch (I->getOpcode()) {
4888 case Instruction::Add:
4889 case Instruction::Sub:
4890 return selectAddSub(I);
4891 case Instruction::Mul:
4892 return selectMul(I);
4893 case Instruction::SDiv:
4894 return selectSDiv(I);
4895 case Instruction::SRem:
4896 if (!selectBinaryOp(I, ISD::SREM))
4897 return selectRem(I, ISD::SREM);
4899 case Instruction::URem:
4900 if (!selectBinaryOp(I, ISD::UREM))
4901 return selectRem(I, ISD::UREM);
4903 case Instruction::Shl:
4904 case Instruction::LShr:
4905 case Instruction::AShr:
4906 return selectShift(I);
4907 case Instruction::And:
4908 case Instruction::Or:
4909 case Instruction::Xor:
4910 return selectLogicalOp(I);
4911 case Instruction::Br:
4912 return selectBranch(I);
4913 case Instruction::IndirectBr:
4914 return selectIndirectBr(I);
4915 case Instruction::BitCast:
4916 if (!FastISel::selectBitCast(I))
4917 return selectBitCast(I);
4919 case Instruction::FPToSI:
4920 if (!selectCast(I, ISD::FP_TO_SINT))
4921 return selectFPToInt(I, /*Signed=*/true);
4923 case Instruction::FPToUI:
4924 return selectFPToInt(I, /*Signed=*/false);
4925 case Instruction::ZExt:
4926 case Instruction::SExt:
4927 return selectIntExt(I);
4928 case Instruction::Trunc:
4929 if (!selectCast(I, ISD::TRUNCATE))
4930 return selectTrunc(I);
4932 case Instruction::FPExt:
4933 return selectFPExt(I);
4934 case Instruction::FPTrunc:
4935 return selectFPTrunc(I);
4936 case Instruction::SIToFP:
4937 if (!selectCast(I, ISD::SINT_TO_FP))
4938 return selectIntToFP(I, /*Signed=*/true);
4940 case Instruction::UIToFP:
4941 return selectIntToFP(I, /*Signed=*/false);
4942 case Instruction::Load:
4943 return selectLoad(I);
4944 case Instruction::Store:
4945 return selectStore(I);
4946 case Instruction::FCmp:
4947 case Instruction::ICmp:
4948 return selectCmp(I);
4949 case Instruction::Select:
4950 return selectSelect(I);
4951 case Instruction::Ret:
4952 return selectRet(I);
4953 case Instruction::FRem:
4954 return selectFRem(I);
4955 case Instruction::GetElementPtr:
4956 return selectGetElementPtr(I);
4959 // fall-back to target-independent instruction selection.
4960 return selectOperator(I, I->getOpcode());
4961 // Silence warnings.
4962 (void)&CC_AArch64_DarwinPCS_VarArg;
4966 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4967 const TargetLibraryInfo *LibInfo) {
4968 return new AArch64FastISel(FuncInfo, LibInfo);