1 //===-- AArch6464FastISel.cpp - AArch64 FastISel implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the AArch64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // AArch64GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "MCTargetDesc/AArch64AddressingModes.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/FastISel.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Support/CommandLine.h"
43 class AArch64FastISel : public FastISel {
53 AArch64_AM::ShiftExtendType ExtType;
61 const GlobalValue *GV;
64 Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
65 OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
66 void setKind(BaseKind K) { Kind = K; }
67 BaseKind getKind() const { return Kind; }
68 void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
69 AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
70 bool isRegBase() const { return Kind == RegBase; }
71 bool isFIBase() const { return Kind == FrameIndexBase; }
72 void setReg(unsigned Reg) {
73 assert(isRegBase() && "Invalid base register access!");
76 unsigned getReg() const {
77 assert(isRegBase() && "Invalid base register access!");
80 void setOffsetReg(unsigned Reg) {
81 assert(isRegBase() && "Invalid offset register access!");
84 unsigned getOffsetReg() const {
85 assert(isRegBase() && "Invalid offset register access!");
88 void setFI(unsigned FI) {
89 assert(isFIBase() && "Invalid base frame index access!");
92 unsigned getFI() const {
93 assert(isFIBase() && "Invalid base frame index access!");
96 void setOffset(int64_t O) { Offset = O; }
97 int64_t getOffset() { return Offset; }
98 void setShift(unsigned S) { Shift = S; }
99 unsigned getShift() { return Shift; }
101 void setGlobalValue(const GlobalValue *G) { GV = G; }
102 const GlobalValue *getGlobalValue() { return GV; }
105 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
106 /// make the right decision when generating code for different targets.
107 const AArch64Subtarget *Subtarget;
108 LLVMContext *Context;
110 bool FastLowerArguments() override;
111 bool FastLowerCall(CallLoweringInfo &CLI) override;
112 bool FastLowerIntrinsicCall(const IntrinsicInst *II) override;
115 // Selection routines.
116 bool SelectLoad(const Instruction *I);
117 bool SelectStore(const Instruction *I);
118 bool SelectBranch(const Instruction *I);
119 bool SelectIndirectBr(const Instruction *I);
120 bool SelectCmp(const Instruction *I);
121 bool SelectSelect(const Instruction *I);
122 bool SelectFPExt(const Instruction *I);
123 bool SelectFPTrunc(const Instruction *I);
124 bool SelectFPToInt(const Instruction *I, bool Signed);
125 bool SelectIntToFP(const Instruction *I, bool Signed);
126 bool SelectRem(const Instruction *I, unsigned ISDOpcode);
127 bool SelectRet(const Instruction *I);
128 bool SelectTrunc(const Instruction *I);
129 bool SelectIntExt(const Instruction *I);
130 bool SelectMul(const Instruction *I);
131 bool SelectShift(const Instruction *I, bool IsLeftShift, bool IsArithmetic);
132 bool SelectBitCast(const Instruction *I);
134 // Utility helper routines.
135 bool isTypeLegal(Type *Ty, MVT &VT);
136 bool isLoadStoreTypeLegal(Type *Ty, MVT &VT);
137 bool ComputeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
138 bool ComputeCallAddress(const Value *V, Address &Addr);
139 bool SimplifyAddress(Address &Addr, MVT VT);
140 void AddLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
141 unsigned Flags, unsigned ScaleFactor,
142 MachineMemOperand *MMO);
143 bool IsMemCpySmall(uint64_t Len, unsigned Alignment);
144 bool TryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
146 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
149 // Emit helper routines.
150 unsigned emitAddsSubs(bool UseAdds, MVT RetVT, const Value *LHS,
151 const Value *RHS, bool IsZExt = false,
152 bool WantResult = true);
153 unsigned emitAddsSubs_rr(bool UseAdds, MVT RetVT, unsigned LHSReg,
154 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
155 bool WantResult = true);
156 unsigned emitAddsSubs_ri(bool UseAdds, MVT RetVT, unsigned LHSReg,
157 bool LHSIsKill, uint64_t Imm,
158 bool WantResult = true);
159 unsigned emitAddsSubs_rs(bool UseAdds, MVT RetVT, unsigned LHSReg,
160 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
161 AArch64_AM::ShiftExtendType ShiftType,
162 uint64_t ShiftImm, bool WantResult = true);
163 unsigned emitAddsSubs_rx(bool UseAdds, MVT RetVT, unsigned LHSReg,
164 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
165 AArch64_AM::ShiftExtendType ExtType,
166 uint64_t ShiftImm, bool WantResult = true);
169 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
170 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
171 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
172 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
173 bool EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
174 MachineMemOperand *MMO = nullptr);
175 bool EmitStore(MVT VT, unsigned SrcReg, Address Addr,
176 MachineMemOperand *MMO = nullptr);
177 unsigned EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
178 unsigned Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
179 unsigned emitAdds(MVT RetVT, const Value *LHS, const Value *RHS,
180 bool IsZExt = false, bool WantResult = true);
181 unsigned emitSubs(MVT RetVT, const Value *LHS, const Value *RHS,
182 bool IsZExt = false, bool WantResult = true);
183 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
184 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
185 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
186 unsigned RHSReg, bool RHSIsKill,
187 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
188 bool WantResult = true);
189 unsigned emitAND_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
190 unsigned Emit_MUL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
191 unsigned Op1, bool Op1IsKill);
192 unsigned Emit_SMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
193 unsigned Op1, bool Op1IsKill);
194 unsigned Emit_UMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
195 unsigned Op1, bool Op1IsKill);
196 unsigned Emit_LSL_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
197 unsigned Emit_LSR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
198 unsigned Emit_ASR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
200 unsigned AArch64MaterializeInt(const ConstantInt *CI, MVT VT);
201 unsigned AArch64MaterializeFP(const ConstantFP *CFP, MVT VT);
202 unsigned AArch64MaterializeGV(const GlobalValue *GV);
204 // Call handling routines.
206 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
207 bool ProcessCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
209 bool FinishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
212 // Backend specific FastISel code.
213 unsigned TargetMaterializeAlloca(const AllocaInst *AI) override;
214 unsigned TargetMaterializeConstant(const Constant *C) override;
216 explicit AArch64FastISel(FunctionLoweringInfo &funcInfo,
217 const TargetLibraryInfo *libInfo)
218 : FastISel(funcInfo, libInfo) {
219 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
220 Context = &funcInfo.Fn->getContext();
223 bool TargetSelectInstruction(const Instruction *I) override;
225 #include "AArch64GenFastISel.inc"
228 } // end anonymous namespace
230 #include "AArch64GenCallingConv.inc"
232 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
233 if (CC == CallingConv::WebKit_JS)
234 return CC_AArch64_WebKit_JS;
235 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
238 unsigned AArch64FastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
239 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
240 "Alloca should always return a pointer.");
242 // Don't handle dynamic allocas.
243 if (!FuncInfo.StaticAllocaMap.count(AI))
246 DenseMap<const AllocaInst *, int>::iterator SI =
247 FuncInfo.StaticAllocaMap.find(AI);
249 if (SI != FuncInfo.StaticAllocaMap.end()) {
250 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
253 .addFrameIndex(SI->second)
262 unsigned AArch64FastISel::AArch64MaterializeInt(const ConstantInt *CI, MVT VT) {
267 return FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
269 // Create a copy from the zero register to materialize a "0" value.
270 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
271 : &AArch64::GPR32RegClass;
272 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
273 unsigned ResultReg = createResultReg(RC);
274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
275 TII.get(TargetOpcode::COPY), ResultReg)
276 .addReg(ZeroReg, getKillRegState(true));
280 unsigned AArch64FastISel::AArch64MaterializeFP(const ConstantFP *CFP, MVT VT) {
281 if (VT != MVT::f32 && VT != MVT::f64)
284 const APFloat Val = CFP->getValueAPF();
285 bool Is64Bit = (VT == MVT::f64);
287 // This checks to see if we can use FMOV instructions to materialize
288 // a constant, otherwise we have to materialize via the constant pool.
289 if (TLI.isFPImmLegal(Val, VT)) {
290 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
291 // Positive zero (+0.0) has to be materialized with a fmov from the zero
292 // register, because the immediate version of fmov cannot encode zero.
293 if (Val.isPosZero()) {
294 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
295 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
296 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
297 .addReg(ZReg, getKillRegState(true));
300 int Imm = Is64Bit ? AArch64_AM::getFP64Imm(Val)
301 : AArch64_AM::getFP32Imm(Val);
302 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
303 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
308 // Materialize via constant pool. MachineConstantPool wants an explicit
310 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
312 Align = DL.getTypeAllocSize(CFP->getType());
314 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
315 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
316 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
318 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
320 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
321 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
322 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
324 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
328 unsigned AArch64FastISel::AArch64MaterializeGV(const GlobalValue *GV) {
329 // We can't handle thread-local variables quickly yet.
330 if (GV->isThreadLocal())
333 // MachO still uses GOT for large code-model accesses, but ELF requires
334 // movz/movk sequences, which FastISel doesn't handle yet.
335 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
338 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
340 EVT DestEVT = TLI.getValueType(GV->getType(), true);
341 if (!DestEVT.isSimple())
344 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
347 if (OpFlags & AArch64II::MO_GOT) {
349 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
351 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
353 ResultReg = createResultReg(&AArch64::GPR64RegClass);
354 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
357 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
361 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
363 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
365 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
366 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
369 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
375 unsigned AArch64FastISel::TargetMaterializeConstant(const Constant *C) {
376 EVT CEVT = TLI.getValueType(C->getType(), true);
378 // Only handle simple types.
379 if (!CEVT.isSimple())
381 MVT VT = CEVT.getSimpleVT();
383 if (const auto *CI = dyn_cast<ConstantInt>(C))
384 return AArch64MaterializeInt(CI, VT);
385 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
386 return AArch64MaterializeFP(CFP, VT);
387 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
388 return AArch64MaterializeGV(GV);
393 // Computes the address to get to an object.
394 bool AArch64FastISel::ComputeAddress(const Value *Obj, Address &Addr, Type *Ty)
396 const User *U = nullptr;
397 unsigned Opcode = Instruction::UserOp1;
398 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
399 // Don't walk into other basic blocks unless the object is an alloca from
400 // another block, otherwise it may not have a virtual register assigned.
401 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
402 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
403 Opcode = I->getOpcode();
406 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
407 Opcode = C->getOpcode();
411 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
412 if (Ty->getAddressSpace() > 255)
413 // Fast instruction selection doesn't support the special
420 case Instruction::BitCast: {
421 // Look through bitcasts.
422 return ComputeAddress(U->getOperand(0), Addr, Ty);
424 case Instruction::IntToPtr: {
425 // Look past no-op inttoptrs.
426 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
427 return ComputeAddress(U->getOperand(0), Addr, Ty);
430 case Instruction::PtrToInt: {
431 // Look past no-op ptrtoints.
432 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
433 return ComputeAddress(U->getOperand(0), Addr, Ty);
436 case Instruction::GetElementPtr: {
437 Address SavedAddr = Addr;
438 uint64_t TmpOffset = Addr.getOffset();
440 // Iterate through the GEP folding the constants into offsets where
442 gep_type_iterator GTI = gep_type_begin(U);
443 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
445 const Value *Op = *i;
446 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
447 const StructLayout *SL = DL.getStructLayout(STy);
448 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
449 TmpOffset += SL->getElementOffset(Idx);
451 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
453 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
454 // Constant-offset addressing.
455 TmpOffset += CI->getSExtValue() * S;
458 if (canFoldAddIntoGEP(U, Op)) {
459 // A compatible add with a constant operand. Fold the constant.
461 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
462 TmpOffset += CI->getSExtValue() * S;
463 // Iterate on the other operand.
464 Op = cast<AddOperator>(Op)->getOperand(0);
468 goto unsupported_gep;
473 // Try to grab the base operand now.
474 Addr.setOffset(TmpOffset);
475 if (ComputeAddress(U->getOperand(0), Addr, Ty))
478 // We failed, restore everything and try the other options.
484 case Instruction::Alloca: {
485 const AllocaInst *AI = cast<AllocaInst>(Obj);
486 DenseMap<const AllocaInst *, int>::iterator SI =
487 FuncInfo.StaticAllocaMap.find(AI);
488 if (SI != FuncInfo.StaticAllocaMap.end()) {
489 Addr.setKind(Address::FrameIndexBase);
490 Addr.setFI(SI->second);
495 case Instruction::Add: {
496 // Adds of constants are common and easy enough.
497 const Value *LHS = U->getOperand(0);
498 const Value *RHS = U->getOperand(1);
500 if (isa<ConstantInt>(LHS))
503 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
504 Addr.setOffset(Addr.getOffset() + (uint64_t)CI->getSExtValue());
505 return ComputeAddress(LHS, Addr, Ty);
508 Address Backup = Addr;
509 if (ComputeAddress(LHS, Addr, Ty) && ComputeAddress(RHS, Addr, Ty))
515 case Instruction::Shl:
516 if (Addr.getOffsetReg())
519 if (const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
520 unsigned Val = CI->getZExtValue();
521 if (Val < 1 || Val > 3)
524 uint64_t NumBytes = 0;
525 if (Ty && Ty->isSized()) {
526 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
527 NumBytes = NumBits / 8;
528 if (!isPowerOf2_64(NumBits))
532 if (NumBytes != (1ULL << Val))
536 Addr.setExtendType(AArch64_AM::LSL);
538 if (const auto *I = dyn_cast<Instruction>(U->getOperand(0)))
539 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
542 if (const auto *ZE = dyn_cast<ZExtInst>(U))
543 if (ZE->getOperand(0)->getType()->isIntegerTy(32))
544 Addr.setExtendType(AArch64_AM::UXTW);
546 if (const auto *SE = dyn_cast<SExtInst>(U))
547 if (SE->getOperand(0)->getType()->isIntegerTy(32))
548 Addr.setExtendType(AArch64_AM::SXTW);
550 unsigned Reg = getRegForValue(U->getOperand(0));
553 Addr.setOffsetReg(Reg);
560 if (!Addr.getOffsetReg()) {
561 unsigned Reg = getRegForValue(Obj);
564 Addr.setOffsetReg(Reg);
570 unsigned Reg = getRegForValue(Obj);
577 bool AArch64FastISel::ComputeCallAddress(const Value *V, Address &Addr) {
578 const User *U = nullptr;
579 unsigned Opcode = Instruction::UserOp1;
582 if (const auto *I = dyn_cast<Instruction>(V)) {
583 Opcode = I->getOpcode();
585 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
586 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
587 Opcode = C->getOpcode();
593 case Instruction::BitCast:
594 // Look past bitcasts if its operand is in the same BB.
596 return ComputeCallAddress(U->getOperand(0), Addr);
598 case Instruction::IntToPtr:
599 // Look past no-op inttoptrs if its operand is in the same BB.
601 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
602 return ComputeCallAddress(U->getOperand(0), Addr);
604 case Instruction::PtrToInt:
605 // Look past no-op ptrtoints if its operand is in the same BB.
607 TLI.getValueType(U->getType()) == TLI.getPointerTy())
608 return ComputeCallAddress(U->getOperand(0), Addr);
612 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
613 Addr.setGlobalValue(GV);
617 // If all else fails, try to materialize the value in a register.
618 if (!Addr.getGlobalValue()) {
619 Addr.setReg(getRegForValue(V));
620 return Addr.getReg() != 0;
627 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
628 EVT evt = TLI.getValueType(Ty, true);
630 // Only handle simple types.
631 if (evt == MVT::Other || !evt.isSimple())
633 VT = evt.getSimpleVT();
635 // This is a legal type, but it's not something we handle in fast-isel.
639 // Handle all other legal types, i.e. a register that will directly hold this
641 return TLI.isTypeLegal(VT);
644 bool AArch64FastISel::isLoadStoreTypeLegal(Type *Ty, MVT &VT) {
645 if (isTypeLegal(Ty, VT))
648 // If this is a type than can be sign or zero-extended to a basic operation
649 // go ahead and accept it now. For stores, this reflects truncation.
650 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
656 bool AArch64FastISel::SimplifyAddress(Address &Addr, MVT VT) {
657 unsigned ScaleFactor;
658 switch (VT.SimpleTy) {
659 default: return false;
660 case MVT::i1: // fall-through
661 case MVT::i8: ScaleFactor = 1; break;
662 case MVT::i16: ScaleFactor = 2; break;
663 case MVT::i32: // fall-through
664 case MVT::f32: ScaleFactor = 4; break;
665 case MVT::i64: // fall-through
666 case MVT::f64: ScaleFactor = 8; break;
669 bool ImmediateOffsetNeedsLowering = false;
670 bool RegisterOffsetNeedsLowering = false;
671 int64_t Offset = Addr.getOffset();
672 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
673 ImmediateOffsetNeedsLowering = true;
674 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
675 !isUInt<12>(Offset / ScaleFactor))
676 ImmediateOffsetNeedsLowering = true;
678 // Cannot encode an offset register and an immediate offset in the same
679 // instruction. Fold the immediate offset into the load/store instruction and
680 // emit an additonal add to take care of the offset register.
681 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.isRegBase() &&
683 RegisterOffsetNeedsLowering = true;
685 // If this is a stack pointer and the offset needs to be simplified then put
686 // the alloca address into a register, set the base type back to register and
687 // continue. This should almost never happen.
688 if (ImmediateOffsetNeedsLowering && Addr.isFIBase()) {
689 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
690 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
692 .addFrameIndex(Addr.getFI())
695 Addr.setKind(Address::RegBase);
696 Addr.setReg(ResultReg);
699 if (RegisterOffsetNeedsLowering) {
700 unsigned ResultReg = 0;
702 ResultReg = createResultReg(&AArch64::GPR64RegClass);
703 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
704 TII.get(AArch64::ADDXrs), ResultReg)
705 .addReg(Addr.getReg())
706 .addReg(Addr.getOffsetReg())
707 .addImm(Addr.getShift());
709 ResultReg = Emit_LSL_ri(MVT::i64, Addr.getOffsetReg(),
710 /*Op0IsKill=*/false, Addr.getShift());
714 Addr.setReg(ResultReg);
715 Addr.setOffsetReg(0);
719 // Since the offset is too large for the load/store instruction get the
720 // reg+offset into a register.
721 if (ImmediateOffsetNeedsLowering) {
722 unsigned ResultReg = 0;
724 ResultReg = FastEmit_ri_(MVT::i64, ISD::ADD, Addr.getReg(),
725 /*IsKill=*/false, Offset, MVT::i64);
727 ResultReg = FastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
731 Addr.setReg(ResultReg);
737 void AArch64FastISel::AddLoadStoreOperands(Address &Addr,
738 const MachineInstrBuilder &MIB,
740 unsigned ScaleFactor,
741 MachineMemOperand *MMO) {
742 int64_t Offset = Addr.getOffset() / ScaleFactor;
743 // Frame base works a bit differently. Handle it separately.
744 if (Addr.isFIBase()) {
745 int FI = Addr.getFI();
746 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
747 // and alignment should be based on the VT.
748 MMO = FuncInfo.MF->getMachineMemOperand(
749 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
750 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
751 // Now add the rest of the operands.
752 MIB.addFrameIndex(FI).addImm(Offset);
754 assert(Addr.isRegBase() && "Unexpected address kind.");
755 if (Addr.getOffsetReg()) {
756 assert(Addr.getOffset() == 0 && "Unexpected offset");
757 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
758 Addr.getExtendType() == AArch64_AM::SXTX;
759 MIB.addReg(Addr.getReg());
760 MIB.addReg(Addr.getOffsetReg());
761 MIB.addImm(IsSigned);
762 MIB.addImm(Addr.getShift() != 0);
764 MIB.addReg(Addr.getReg());
770 MIB.addMemOperand(MMO);
773 unsigned AArch64FastISel::emitAddsSubs(bool UseAdds, MVT RetVT,
774 const Value *LHS, const Value *RHS,
775 bool IsZExt, bool WantResult) {
776 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
777 bool NeedExtend = false;
778 switch (RetVT.SimpleTy) {
786 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
790 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
792 case MVT::i32: // fall-through
797 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
799 // Canonicalize immediates to the RHS first.
800 if (UseAdds && isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
803 // Canonicalize shift immediate to the RHS.
805 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
806 if (isa<ConstantInt>(SI->getOperand(1)))
807 if (SI->getOpcode() == Instruction::Shl ||
808 SI->getOpcode() == Instruction::LShr ||
809 SI->getOpcode() == Instruction::AShr )
812 unsigned LHSReg = getRegForValue(LHS);
815 bool LHSIsKill = hasTrivialKill(LHS);
818 LHSReg = EmitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
820 unsigned ResultReg = 0;
821 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
822 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
825 emitAddsSubs_ri(!UseAdds, RetVT, LHSReg, LHSIsKill, -Imm, WantResult);
828 emitAddsSubs_ri(UseAdds, RetVT, LHSReg, LHSIsKill, Imm, WantResult);
833 // Only extend the RHS within the instruction if there is a valid extend type.
834 if (ExtendType != AArch64_AM::InvalidShiftExtend) {
835 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
836 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
837 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
838 unsigned RHSReg = getRegForValue(SI->getOperand(0));
841 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
842 return emitAddsSubs_rx(UseAdds, RetVT, LHSReg, LHSIsKill, RHSReg,
843 RHSIsKill, ExtendType, C->getZExtValue(),
846 unsigned RHSReg = getRegForValue(RHS);
849 bool RHSIsKill = hasTrivialKill(RHS);
850 return emitAddsSubs_rx(UseAdds, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
851 ExtendType, 0, WantResult);
854 // Check if the shift can be folded into the instruction.
855 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
856 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
857 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
858 switch (SI->getOpcode()) {
860 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
861 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
862 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
864 uint64_t ShiftVal = C->getZExtValue();
865 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
866 unsigned RHSReg = getRegForValue(SI->getOperand(0));
869 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
870 return emitAddsSubs_rs(UseAdds, RetVT, LHSReg, LHSIsKill, RHSReg,
871 RHSIsKill, ShiftType, ShiftVal, WantResult);
876 unsigned RHSReg = getRegForValue(RHS);
879 bool RHSIsKill = hasTrivialKill(RHS);
882 RHSReg = EmitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
884 return emitAddsSubs_rr(UseAdds, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
888 unsigned AArch64FastISel::emitAddsSubs_rr(bool UseAdds, MVT RetVT,
889 unsigned LHSReg, bool LHSIsKill,
890 unsigned RHSReg, bool RHSIsKill,
892 assert(LHSReg && RHSReg && "Invalid register number.");
894 if (RetVT != MVT::i32 && RetVT != MVT::i64)
897 static const unsigned OpcTable[2][2] = {
898 { AArch64::ADDSWrr, AArch64::ADDSXrr },
899 { AArch64::SUBSWrr, AArch64::SUBSXrr }
901 unsigned Opc = OpcTable[!UseAdds][(RetVT == MVT::i64)];
904 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
906 ResultReg = (RetVT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
908 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
909 .addReg(LHSReg, getKillRegState(LHSIsKill))
910 .addReg(RHSReg, getKillRegState(RHSIsKill));
915 unsigned AArch64FastISel::emitAddsSubs_ri(bool UseAdds, MVT RetVT,
916 unsigned LHSReg, bool LHSIsKill,
917 uint64_t Imm, bool WantResult) {
918 assert(LHSReg && "Invalid register number.");
920 if (RetVT != MVT::i32 && RetVT != MVT::i64)
926 else if ((Imm & 0xfff000) == Imm) {
932 static const unsigned OpcTable[2][2] = {
933 { AArch64::ADDSWri, AArch64::ADDSXri },
934 { AArch64::SUBSWri, AArch64::SUBSXri }
936 unsigned Opc = OpcTable[!UseAdds][(RetVT == MVT::i64)];
939 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
941 ResultReg = (RetVT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
943 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
944 .addReg(LHSReg, getKillRegState(LHSIsKill))
946 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
951 unsigned AArch64FastISel::emitAddsSubs_rs(bool UseAdds, MVT RetVT,
952 unsigned LHSReg, bool LHSIsKill,
953 unsigned RHSReg, bool RHSIsKill,
954 AArch64_AM::ShiftExtendType ShiftType,
955 uint64_t ShiftImm, bool WantResult) {
956 assert(LHSReg && RHSReg && "Invalid register number.");
958 if (RetVT != MVT::i32 && RetVT != MVT::i64)
961 static const unsigned OpcTable[2][2] = {
962 { AArch64::ADDSWrs, AArch64::ADDSXrs },
963 { AArch64::SUBSWrs, AArch64::SUBSXrs }
965 unsigned Opc = OpcTable[!UseAdds][(RetVT == MVT::i64)];
968 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
970 ResultReg = (RetVT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
972 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
973 .addReg(LHSReg, getKillRegState(LHSIsKill))
974 .addReg(RHSReg, getKillRegState(RHSIsKill))
975 .addImm(getShifterImm(ShiftType, ShiftImm));
980 unsigned AArch64FastISel::emitAddsSubs_rx(bool UseAdds, MVT RetVT,
981 unsigned LHSReg, bool LHSIsKill,
982 unsigned RHSReg, bool RHSIsKill,
983 AArch64_AM::ShiftExtendType ExtType,
984 uint64_t ShiftImm, bool WantResult) {
985 assert(LHSReg && RHSReg && "Invalid register number.");
987 if (RetVT != MVT::i32 && RetVT != MVT::i64)
990 static const unsigned OpcTable[2][2] = {
991 { AArch64::ADDSWrx, AArch64::ADDSXrx },
992 { AArch64::SUBSWrx, AArch64::SUBSXrx }
994 unsigned Opc = OpcTable[!UseAdds][(RetVT == MVT::i64)];
997 ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
999 ResultReg = (RetVT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
1001 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1002 .addReg(LHSReg, getKillRegState(LHSIsKill))
1003 .addReg(RHSReg, getKillRegState(RHSIsKill))
1004 .addImm(getArithExtendImm(ExtType, ShiftImm));
1009 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1010 Type *Ty = LHS->getType();
1011 EVT EVT = TLI.getValueType(Ty, true);
1012 if (!EVT.isSimple())
1014 MVT VT = EVT.getSimpleVT();
1016 switch (VT.SimpleTy) {
1024 return emitICmp(VT, LHS, RHS, IsZExt);
1027 return emitFCmp(VT, LHS, RHS);
1031 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1033 return emitSubs(RetVT, LHS, RHS, IsZExt, /*WantResult=*/false) != 0;
1036 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1038 return emitAddsSubs_ri(false, RetVT, LHSReg, LHSIsKill, Imm,
1039 /*WantResult=*/false) != 0;
1042 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1043 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1046 // Check to see if the 2nd operand is a constant that we can encode directly
1048 bool UseImm = false;
1049 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1050 if (CFP->isZero() && !CFP->isNegative())
1053 unsigned LHSReg = getRegForValue(LHS);
1056 bool LHSIsKill = hasTrivialKill(LHS);
1059 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1060 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1061 .addReg(LHSReg, getKillRegState(LHSIsKill));
1065 unsigned RHSReg = getRegForValue(RHS);
1068 bool RHSIsKill = hasTrivialKill(RHS);
1070 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1071 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1072 .addReg(LHSReg, getKillRegState(LHSIsKill))
1073 .addReg(RHSReg, getKillRegState(RHSIsKill));
1077 unsigned AArch64FastISel::emitAdds(MVT RetVT, const Value *LHS,
1078 const Value *RHS, bool IsZExt,
1080 return emitAddsSubs(true, RetVT, LHS, RHS, IsZExt, WantResult);
1083 unsigned AArch64FastISel::emitSubs(MVT RetVT, const Value *LHS,
1084 const Value *RHS, bool IsZExt,
1086 return emitAddsSubs(false, RetVT, LHS, RHS, IsZExt, WantResult);
1089 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1090 bool LHSIsKill, unsigned RHSReg,
1091 bool RHSIsKill, bool WantResult) {
1092 return emitAddsSubs_rr(false, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1096 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1097 bool LHSIsKill, unsigned RHSReg,
1099 AArch64_AM::ShiftExtendType ShiftType,
1100 uint64_t ShiftImm, bool WantResult) {
1101 return emitAddsSubs_rs(false, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1102 ShiftType, ShiftImm, WantResult);
1105 // FIXME: This should be eventually generated automatically by tblgen.
1106 unsigned AArch64FastISel::emitAND_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1108 const TargetRegisterClass *RC = nullptr;
1110 unsigned RegSize = 0;
1111 switch (RetVT.SimpleTy) {
1115 Opc = AArch64::ANDWri;
1116 RC = &AArch64::GPR32spRegClass;
1120 Opc = AArch64::ANDXri;
1121 RC = &AArch64::GPR64spRegClass;
1126 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1129 return FastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1130 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1133 bool AArch64FastISel::EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
1134 MachineMemOperand *MMO) {
1135 // Simplify this down to something we can handle.
1136 if (!SimplifyAddress(Addr, VT))
1139 unsigned ScaleFactor;
1140 switch (VT.SimpleTy) {
1141 default: llvm_unreachable("Unexpected value type.");
1142 case MVT::i1: // fall-through
1143 case MVT::i8: ScaleFactor = 1; break;
1144 case MVT::i16: ScaleFactor = 2; break;
1145 case MVT::i32: // fall-through
1146 case MVT::f32: ScaleFactor = 4; break;
1147 case MVT::i64: // fall-through
1148 case MVT::f64: ScaleFactor = 8; break;
1151 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1152 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1153 bool UseScaled = true;
1154 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1159 static const unsigned OpcTable[4][6] = {
1160 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi, AArch64::LDURXi,
1161 AArch64::LDURSi, AArch64::LDURDi },
1162 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui, AArch64::LDRXui,
1163 AArch64::LDRSui, AArch64::LDRDui },
1164 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX, AArch64::LDRXroX,
1165 AArch64::LDRSroX, AArch64::LDRDroX },
1166 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW, AArch64::LDRXroW,
1167 AArch64::LDRSroW, AArch64::LDRDroW }
1171 const TargetRegisterClass *RC;
1172 bool VTIsi1 = false;
1173 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1174 Addr.getOffsetReg();
1175 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1176 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1177 Addr.getExtendType() == AArch64_AM::SXTW)
1180 switch (VT.SimpleTy) {
1181 default: llvm_unreachable("Unexpected value type.");
1182 case MVT::i1: VTIsi1 = true; // Intentional fall-through.
1183 case MVT::i8: Opc = OpcTable[Idx][0]; RC = &AArch64::GPR32RegClass; break;
1184 case MVT::i16: Opc = OpcTable[Idx][1]; RC = &AArch64::GPR32RegClass; break;
1185 case MVT::i32: Opc = OpcTable[Idx][2]; RC = &AArch64::GPR32RegClass; break;
1186 case MVT::i64: Opc = OpcTable[Idx][3]; RC = &AArch64::GPR64RegClass; break;
1187 case MVT::f32: Opc = OpcTable[Idx][4]; RC = &AArch64::FPR32RegClass; break;
1188 case MVT::f64: Opc = OpcTable[Idx][5]; RC = &AArch64::FPR64RegClass; break;
1191 // Create the base instruction, then add the operands.
1192 ResultReg = createResultReg(RC);
1193 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1194 TII.get(Opc), ResultReg);
1195 AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1197 // Loading an i1 requires special handling.
1199 unsigned ANDReg = emitAND_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1200 assert(ANDReg && "Unexpected AND instruction emission failure.");
1206 bool AArch64FastISel::SelectLoad(const Instruction *I) {
1208 // Verify we have a legal type before going any further. Currently, we handle
1209 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1210 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1211 if (!isLoadStoreTypeLegal(I->getType(), VT) || cast<LoadInst>(I)->isAtomic())
1214 // See if we can handle this address.
1216 if (!ComputeAddress(I->getOperand(0), Addr, I->getType()))
1220 if (!EmitLoad(VT, ResultReg, Addr, createMachineMemOperandFor(I)))
1223 UpdateValueMap(I, ResultReg);
1227 bool AArch64FastISel::EmitStore(MVT VT, unsigned SrcReg, Address Addr,
1228 MachineMemOperand *MMO) {
1229 // Simplify this down to something we can handle.
1230 if (!SimplifyAddress(Addr, VT))
1233 unsigned ScaleFactor;
1234 switch (VT.SimpleTy) {
1235 default: llvm_unreachable("Unexpected value type.");
1236 case MVT::i1: // fall-through
1237 case MVT::i8: ScaleFactor = 1; break;
1238 case MVT::i16: ScaleFactor = 2; break;
1239 case MVT::i32: // fall-through
1240 case MVT::f32: ScaleFactor = 4; break;
1241 case MVT::i64: // fall-through
1242 case MVT::f64: ScaleFactor = 8; break;
1245 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1246 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1247 bool UseScaled = true;
1248 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1254 static const unsigned OpcTable[4][6] = {
1255 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1256 AArch64::STURSi, AArch64::STURDi },
1257 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1258 AArch64::STRSui, AArch64::STRDui },
1259 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1260 AArch64::STRSroX, AArch64::STRDroX },
1261 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1262 AArch64::STRSroW, AArch64::STRDroW }
1267 bool VTIsi1 = false;
1268 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1269 Addr.getOffsetReg();
1270 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1271 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1272 Addr.getExtendType() == AArch64_AM::SXTW)
1275 switch (VT.SimpleTy) {
1276 default: llvm_unreachable("Unexpected value type.");
1277 case MVT::i1: VTIsi1 = true;
1278 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1279 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1280 case MVT::i32: Opc = OpcTable[Idx][2]; break;
1281 case MVT::i64: Opc = OpcTable[Idx][3]; break;
1282 case MVT::f32: Opc = OpcTable[Idx][4]; break;
1283 case MVT::f64: Opc = OpcTable[Idx][5]; break;
1286 // Storing an i1 requires special handling.
1288 unsigned ANDReg = emitAND_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1289 assert(ANDReg && "Unexpected AND instruction emission failure.");
1292 // Create the base instruction, then add the operands.
1293 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1296 AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
1301 bool AArch64FastISel::SelectStore(const Instruction *I) {
1303 Value *Op0 = I->getOperand(0);
1304 // Verify we have a legal type before going any further. Currently, we handle
1305 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1306 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1307 if (!isLoadStoreTypeLegal(Op0->getType(), VT) ||
1308 cast<StoreInst>(I)->isAtomic())
1311 // Get the value to be stored into a register.
1312 unsigned SrcReg = getRegForValue(Op0);
1316 // See if we can handle this address.
1318 if (!ComputeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
1321 if (!EmitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
1326 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
1328 case CmpInst::FCMP_ONE:
1329 case CmpInst::FCMP_UEQ:
1331 // AL is our "false" for now. The other two need more compares.
1332 return AArch64CC::AL;
1333 case CmpInst::ICMP_EQ:
1334 case CmpInst::FCMP_OEQ:
1335 return AArch64CC::EQ;
1336 case CmpInst::ICMP_SGT:
1337 case CmpInst::FCMP_OGT:
1338 return AArch64CC::GT;
1339 case CmpInst::ICMP_SGE:
1340 case CmpInst::FCMP_OGE:
1341 return AArch64CC::GE;
1342 case CmpInst::ICMP_UGT:
1343 case CmpInst::FCMP_UGT:
1344 return AArch64CC::HI;
1345 case CmpInst::FCMP_OLT:
1346 return AArch64CC::MI;
1347 case CmpInst::ICMP_ULE:
1348 case CmpInst::FCMP_OLE:
1349 return AArch64CC::LS;
1350 case CmpInst::FCMP_ORD:
1351 return AArch64CC::VC;
1352 case CmpInst::FCMP_UNO:
1353 return AArch64CC::VS;
1354 case CmpInst::FCMP_UGE:
1355 return AArch64CC::PL;
1356 case CmpInst::ICMP_SLT:
1357 case CmpInst::FCMP_ULT:
1358 return AArch64CC::LT;
1359 case CmpInst::ICMP_SLE:
1360 case CmpInst::FCMP_ULE:
1361 return AArch64CC::LE;
1362 case CmpInst::FCMP_UNE:
1363 case CmpInst::ICMP_NE:
1364 return AArch64CC::NE;
1365 case CmpInst::ICMP_UGE:
1366 return AArch64CC::HS;
1367 case CmpInst::ICMP_ULT:
1368 return AArch64CC::LO;
1372 bool AArch64FastISel::SelectBranch(const Instruction *I) {
1373 const BranchInst *BI = cast<BranchInst>(I);
1374 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1375 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1377 AArch64CC::CondCode CC = AArch64CC::NE;
1378 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1379 if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
1380 // We may not handle every CC for now.
1381 CC = getCompareCC(CI->getPredicate());
1382 if (CC == AArch64CC::AL)
1386 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1390 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1394 // Obtain the branch weight and add the TrueBB to the successor list.
1395 uint32_t BranchWeight = 0;
1397 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1398 TBB->getBasicBlock());
1399 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1401 FastEmitBranch(FBB, DbgLoc);
1404 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1406 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1407 (isLoadStoreTypeLegal(TI->getOperand(0)->getType(), SrcVT))) {
1408 unsigned CondReg = getRegForValue(TI->getOperand(0));
1411 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
1413 // Issue an extract_subreg to get the lower 32-bits.
1414 if (SrcVT == MVT::i64) {
1415 CondReg = FastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
1420 unsigned ANDReg = emitAND_ri(MVT::i32, CondReg, CondIsKill, 1);
1421 assert(ANDReg && "Unexpected AND instruction emission failure.");
1422 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
1424 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1425 std::swap(TBB, FBB);
1428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1432 // Obtain the branch weight and add the TrueBB to the successor list.
1433 uint32_t BranchWeight = 0;
1435 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1436 TBB->getBasicBlock());
1437 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1439 FastEmitBranch(FBB, DbgLoc);
1442 } else if (const ConstantInt *CI =
1443 dyn_cast<ConstantInt>(BI->getCondition())) {
1444 uint64_t Imm = CI->getZExtValue();
1445 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1446 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
1449 // Obtain the branch weight and add the target to the successor list.
1450 uint32_t BranchWeight = 0;
1452 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1453 Target->getBasicBlock());
1454 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
1456 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
1457 // Fake request the condition, otherwise the intrinsic might be completely
1459 unsigned CondReg = getRegForValue(BI->getCondition());
1464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1468 // Obtain the branch weight and add the TrueBB to the successor list.
1469 uint32_t BranchWeight = 0;
1471 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1472 TBB->getBasicBlock());
1473 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1475 FastEmitBranch(FBB, DbgLoc);
1479 unsigned CondReg = getRegForValue(BI->getCondition());
1482 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
1484 // We've been divorced from our compare! Our block was split, and
1485 // now our compare lives in a predecessor block. We musn't
1486 // re-compare here, as the children of the compare aren't guaranteed
1487 // live across the block boundary (we *could* check for this).
1488 // Regardless, the compare has been done in the predecessor block,
1489 // and it left a value for us in a virtual register. Ergo, we test
1490 // the one-bit value left in the virtual register.
1491 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
1493 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1494 std::swap(TBB, FBB);
1498 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1502 // Obtain the branch weight and add the TrueBB to the successor list.
1503 uint32_t BranchWeight = 0;
1505 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1506 TBB->getBasicBlock());
1507 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1509 FastEmitBranch(FBB, DbgLoc);
1513 bool AArch64FastISel::SelectIndirectBr(const Instruction *I) {
1514 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
1515 unsigned AddrReg = getRegForValue(BI->getOperand(0));
1519 // Emit the indirect branch.
1520 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BR))
1523 // Make sure the CFG is up-to-date.
1524 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
1525 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
1530 bool AArch64FastISel::SelectCmp(const Instruction *I) {
1531 const CmpInst *CI = cast<CmpInst>(I);
1533 // We may not handle every CC for now.
1534 AArch64CC::CondCode CC = getCompareCC(CI->getPredicate());
1535 if (CC == AArch64CC::AL)
1539 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1542 // Now set a register based on the comparison.
1543 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
1544 unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
1545 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
1547 .addReg(AArch64::WZR)
1548 .addReg(AArch64::WZR)
1549 .addImm(invertedCC);
1551 UpdateValueMap(I, ResultReg);
1555 bool AArch64FastISel::SelectSelect(const Instruction *I) {
1556 const SelectInst *SI = cast<SelectInst>(I);
1558 EVT DestEVT = TLI.getValueType(SI->getType(), true);
1559 if (!DestEVT.isSimple())
1562 MVT DestVT = DestEVT.getSimpleVT();
1563 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
1568 switch (DestVT.SimpleTy) {
1569 default: return false;
1570 case MVT::i32: SelectOpc = AArch64::CSELWr; break;
1571 case MVT::i64: SelectOpc = AArch64::CSELXr; break;
1572 case MVT::f32: SelectOpc = AArch64::FCSELSrrr; break;
1573 case MVT::f64: SelectOpc = AArch64::FCSELDrrr; break;
1576 const Value *Cond = SI->getCondition();
1577 bool NeedTest = true;
1578 AArch64CC::CondCode CC = AArch64CC::NE;
1579 if (foldXALUIntrinsic(CC, I, Cond))
1582 unsigned CondReg = getRegForValue(Cond);
1585 bool CondIsKill = hasTrivialKill(Cond);
1588 unsigned ANDReg = emitAND_ri(MVT::i32, CondReg, CondIsKill, 1);
1589 assert(ANDReg && "Unexpected AND instruction emission failure.");
1590 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
1593 unsigned TrueReg = getRegForValue(SI->getTrueValue());
1594 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
1596 unsigned FalseReg = getRegForValue(SI->getFalseValue());
1597 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
1599 if (!TrueReg || !FalseReg)
1602 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1603 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SelectOpc),
1605 .addReg(TrueReg, getKillRegState(TrueIsKill))
1606 .addReg(FalseReg, getKillRegState(FalseIsKill))
1609 UpdateValueMap(I, ResultReg);
1613 bool AArch64FastISel::SelectFPExt(const Instruction *I) {
1614 Value *V = I->getOperand(0);
1615 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
1618 unsigned Op = getRegForValue(V);
1622 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
1623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
1624 ResultReg).addReg(Op);
1625 UpdateValueMap(I, ResultReg);
1629 bool AArch64FastISel::SelectFPTrunc(const Instruction *I) {
1630 Value *V = I->getOperand(0);
1631 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
1634 unsigned Op = getRegForValue(V);
1638 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
1639 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
1640 ResultReg).addReg(Op);
1641 UpdateValueMap(I, ResultReg);
1645 // FPToUI and FPToSI
1646 bool AArch64FastISel::SelectFPToInt(const Instruction *I, bool Signed) {
1648 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1651 unsigned SrcReg = getRegForValue(I->getOperand(0));
1655 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1656 if (SrcVT == MVT::f128)
1660 if (SrcVT == MVT::f64) {
1662 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
1664 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
1667 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
1669 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
1671 unsigned ResultReg = createResultReg(
1672 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
1673 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1675 UpdateValueMap(I, ResultReg);
1679 bool AArch64FastISel::SelectIntToFP(const Instruction *I, bool Signed) {
1681 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1683 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
1684 "Unexpected value type.");
1686 unsigned SrcReg = getRegForValue(I->getOperand(0));
1690 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1692 // Handle sign-extension.
1693 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1695 EmitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
1700 MRI.constrainRegClass(SrcReg, SrcVT == MVT::i64 ? &AArch64::GPR64RegClass
1701 : &AArch64::GPR32RegClass);
1704 if (SrcVT == MVT::i64) {
1706 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
1708 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
1711 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
1713 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
1716 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1717 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1719 UpdateValueMap(I, ResultReg);
1723 bool AArch64FastISel::FastLowerArguments() {
1724 if (!FuncInfo.CanLowerReturn)
1727 const Function *F = FuncInfo.Fn;
1731 CallingConv::ID CC = F->getCallingConv();
1732 if (CC != CallingConv::C)
1735 // Only handle simple cases like i1/i8/i16/i32/i64/f32/f64 of up to 8 GPR and
1737 unsigned GPRCnt = 0;
1738 unsigned FPRCnt = 0;
1740 for (auto const &Arg : F->args()) {
1741 // The first argument is at index 1.
1743 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1744 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1745 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1746 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1749 Type *ArgTy = Arg.getType();
1750 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1753 EVT ArgVT = TLI.getValueType(ArgTy);
1754 if (!ArgVT.isSimple()) return false;
1755 switch (ArgVT.getSimpleVT().SimpleTy) {
1756 default: return false;
1771 if (GPRCnt > 8 || FPRCnt > 8)
1775 static const MCPhysReg Registers[5][8] = {
1776 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
1777 AArch64::W5, AArch64::W6, AArch64::W7 },
1778 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
1779 AArch64::X5, AArch64::X6, AArch64::X7 },
1780 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
1781 AArch64::H5, AArch64::H6, AArch64::H7 },
1782 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
1783 AArch64::S5, AArch64::S6, AArch64::S7 },
1784 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
1785 AArch64::D5, AArch64::D6, AArch64::D7 }
1788 unsigned GPRIdx = 0;
1789 unsigned FPRIdx = 0;
1790 for (auto const &Arg : F->args()) {
1791 MVT VT = TLI.getSimpleValueType(Arg.getType());
1793 switch (VT.SimpleTy) {
1794 default: llvm_unreachable("Unexpected value type.");
1797 case MVT::i16: VT = MVT::i32; // fall-through
1798 case MVT::i32: SrcReg = Registers[0][GPRIdx++]; break;
1799 case MVT::i64: SrcReg = Registers[1][GPRIdx++]; break;
1800 case MVT::f16: SrcReg = Registers[2][FPRIdx++]; break;
1801 case MVT::f32: SrcReg = Registers[3][FPRIdx++]; break;
1802 case MVT::f64: SrcReg = Registers[4][FPRIdx++]; break;
1805 // Skip unused arguments.
1806 if (Arg.use_empty()) {
1807 UpdateValueMap(&Arg, 0);
1811 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1812 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1813 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1814 // Without this, EmitLiveInCopies may eliminate the livein if its only
1815 // use is a bitcast (which isn't turned into an instruction).
1816 unsigned ResultReg = createResultReg(RC);
1817 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1818 TII.get(TargetOpcode::COPY), ResultReg)
1819 .addReg(DstReg, getKillRegState(true));
1820 UpdateValueMap(&Arg, ResultReg);
1825 bool AArch64FastISel::ProcessCallArgs(CallLoweringInfo &CLI,
1826 SmallVectorImpl<MVT> &OutVTs,
1827 unsigned &NumBytes) {
1828 CallingConv::ID CC = CLI.CallConv;
1829 SmallVector<CCValAssign, 16> ArgLocs;
1830 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
1831 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
1833 // Get a count of how many bytes are to be pushed on the stack.
1834 NumBytes = CCInfo.getNextStackOffset();
1836 // Issue CALLSEQ_START
1837 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1838 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
1841 // Process the args.
1842 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1843 CCValAssign &VA = ArgLocs[i];
1844 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
1845 MVT ArgVT = OutVTs[VA.getValNo()];
1847 unsigned ArgReg = getRegForValue(ArgVal);
1851 // Handle arg promotion: SExt, ZExt, AExt.
1852 switch (VA.getLocInfo()) {
1853 case CCValAssign::Full:
1855 case CCValAssign::SExt: {
1856 MVT DestVT = VA.getLocVT();
1858 ArgReg = EmitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
1863 case CCValAssign::AExt:
1864 // Intentional fall-through.
1865 case CCValAssign::ZExt: {
1866 MVT DestVT = VA.getLocVT();
1868 ArgReg = EmitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
1874 llvm_unreachable("Unknown arg promotion!");
1877 // Now copy/store arg to correct locations.
1878 if (VA.isRegLoc() && !VA.needsCustom()) {
1879 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1880 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
1881 CLI.OutRegs.push_back(VA.getLocReg());
1882 } else if (VA.needsCustom()) {
1883 // FIXME: Handle custom args.
1886 assert(VA.isMemLoc() && "Assuming store on stack.");
1888 // Don't emit stores for undef values.
1889 if (isa<UndefValue>(ArgVal))
1892 // Need to store on the stack.
1893 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
1895 unsigned BEAlign = 0;
1896 if (ArgSize < 8 && !Subtarget->isLittleEndian())
1897 BEAlign = 8 - ArgSize;
1900 Addr.setKind(Address::RegBase);
1901 Addr.setReg(AArch64::SP);
1902 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
1904 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
1905 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
1906 MachinePointerInfo::getStack(Addr.getOffset()),
1907 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
1909 if (!EmitStore(ArgVT, ArgReg, Addr, MMO))
1916 bool AArch64FastISel::FinishCall(CallLoweringInfo &CLI, MVT RetVT,
1917 unsigned NumBytes) {
1918 CallingConv::ID CC = CLI.CallConv;
1920 // Issue CALLSEQ_END
1921 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1922 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
1923 .addImm(NumBytes).addImm(0);
1925 // Now the return value.
1926 if (RetVT != MVT::isVoid) {
1927 SmallVector<CCValAssign, 16> RVLocs;
1928 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
1929 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
1931 // Only handle a single return value.
1932 if (RVLocs.size() != 1)
1935 // Copy all of the result registers out of their specified physreg.
1936 MVT CopyVT = RVLocs[0].getValVT();
1937 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
1938 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1939 TII.get(TargetOpcode::COPY), ResultReg)
1940 .addReg(RVLocs[0].getLocReg());
1941 CLI.InRegs.push_back(RVLocs[0].getLocReg());
1943 CLI.ResultReg = ResultReg;
1944 CLI.NumResultRegs = 1;
1950 bool AArch64FastISel::FastLowerCall(CallLoweringInfo &CLI) {
1951 CallingConv::ID CC = CLI.CallConv;
1952 bool IsTailCall = CLI.IsTailCall;
1953 bool IsVarArg = CLI.IsVarArg;
1954 const Value *Callee = CLI.Callee;
1955 const char *SymName = CLI.SymName;
1957 // Allow SelectionDAG isel to handle tail calls.
1961 CodeModel::Model CM = TM.getCodeModel();
1962 // Only support the small and large code model.
1963 if (CM != CodeModel::Small && CM != CodeModel::Large)
1966 // FIXME: Add large code model support for ELF.
1967 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
1970 // Let SDISel handle vararg functions.
1974 // FIXME: Only handle *simple* calls for now.
1976 if (CLI.RetTy->isVoidTy())
1977 RetVT = MVT::isVoid;
1978 else if (!isTypeLegal(CLI.RetTy, RetVT))
1981 for (auto Flag : CLI.OutFlags)
1982 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
1985 // Set up the argument vectors.
1986 SmallVector<MVT, 16> OutVTs;
1987 OutVTs.reserve(CLI.OutVals.size());
1989 for (auto *Val : CLI.OutVals) {
1991 if (!isTypeLegal(Val->getType(), VT) &&
1992 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
1995 // We don't handle vector parameters yet.
1996 if (VT.isVector() || VT.getSizeInBits() > 64)
1999 OutVTs.push_back(VT);
2003 if (!ComputeCallAddress(Callee, Addr))
2006 // Handle the arguments now that we've gotten them.
2008 if (!ProcessCallArgs(CLI, OutVTs, NumBytes))
2012 MachineInstrBuilder MIB;
2013 if (CM == CodeModel::Small) {
2014 unsigned CallOpc = Addr.getReg() ? AArch64::BLR : AArch64::BL;
2015 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2017 MIB.addExternalSymbol(SymName, 0);
2018 else if (Addr.getGlobalValue())
2019 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2020 else if (Addr.getReg())
2021 MIB.addReg(Addr.getReg());
2025 unsigned CallReg = 0;
2027 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2028 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2030 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2032 CallReg = createResultReg(&AArch64::GPR64RegClass);
2033 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
2036 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
2038 } else if (Addr.getGlobalValue()) {
2039 CallReg = AArch64MaterializeGV(Addr.getGlobalValue());
2040 } else if (Addr.getReg())
2041 CallReg = Addr.getReg();
2046 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2047 TII.get(AArch64::BLR)).addReg(CallReg);
2050 // Add implicit physical register uses to the call.
2051 for (auto Reg : CLI.OutRegs)
2052 MIB.addReg(Reg, RegState::Implicit);
2054 // Add a register mask with the call-preserved registers.
2055 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2056 MIB.addRegMask(TRI.getCallPreservedMask(CC));
2060 // Finish off the call including any return values.
2061 return FinishCall(CLI, RetVT, NumBytes);
2064 bool AArch64FastISel::IsMemCpySmall(uint64_t Len, unsigned Alignment) {
2066 return Len / Alignment <= 4;
2071 bool AArch64FastISel::TryEmitSmallMemCpy(Address Dest, Address Src,
2072 uint64_t Len, unsigned Alignment) {
2073 // Make sure we don't bloat code by inlining very large memcpy's.
2074 if (!IsMemCpySmall(Len, Alignment))
2077 int64_t UnscaledOffset = 0;
2078 Address OrigDest = Dest;
2079 Address OrigSrc = Src;
2083 if (!Alignment || Alignment >= 8) {
2094 // Bound based on alignment.
2095 if (Len >= 4 && Alignment == 4)
2097 else if (Len >= 2 && Alignment == 2)
2106 RV = EmitLoad(VT, ResultReg, Src);
2110 RV = EmitStore(VT, ResultReg, Dest);
2114 int64_t Size = VT.getSizeInBits() / 8;
2116 UnscaledOffset += Size;
2118 // We need to recompute the unscaled offset for each iteration.
2119 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
2120 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
2126 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
2127 /// into the user. The condition code will only be updated on success.
2128 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
2129 const Instruction *I,
2130 const Value *Cond) {
2131 if (!isa<ExtractValueInst>(Cond))
2134 const auto *EV = cast<ExtractValueInst>(Cond);
2135 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
2138 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
2140 const Function *Callee = II->getCalledFunction();
2142 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
2143 if (!isTypeLegal(RetTy, RetVT))
2146 if (RetVT != MVT::i32 && RetVT != MVT::i64)
2149 AArch64CC::CondCode TmpCC;
2150 switch (II->getIntrinsicID()) {
2151 default: return false;
2152 case Intrinsic::sadd_with_overflow:
2153 case Intrinsic::ssub_with_overflow: TmpCC = AArch64CC::VS; break;
2154 case Intrinsic::uadd_with_overflow: TmpCC = AArch64CC::HS; break;
2155 case Intrinsic::usub_with_overflow: TmpCC = AArch64CC::LO; break;
2156 case Intrinsic::smul_with_overflow:
2157 case Intrinsic::umul_with_overflow: TmpCC = AArch64CC::NE; break;
2160 // Check if both instructions are in the same basic block.
2161 if (II->getParent() != I->getParent())
2164 // Make sure nothing is in the way
2165 BasicBlock::const_iterator Start = I;
2166 BasicBlock::const_iterator End = II;
2167 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
2168 // We only expect extractvalue instructions between the intrinsic and the
2169 // instruction to be selected.
2170 if (!isa<ExtractValueInst>(Itr))
2173 // Check that the extractvalue operand comes from the intrinsic.
2174 const auto *EVI = cast<ExtractValueInst>(Itr);
2175 if (EVI->getAggregateOperand() != II)
2183 bool AArch64FastISel::FastLowerIntrinsicCall(const IntrinsicInst *II) {
2184 // FIXME: Handle more intrinsics.
2185 switch (II->getIntrinsicID()) {
2186 default: return false;
2187 case Intrinsic::frameaddress: {
2188 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2189 MFI->setFrameAddressIsTaken(true);
2191 const AArch64RegisterInfo *RegInfo =
2192 static_cast<const AArch64RegisterInfo *>(
2193 TM.getSubtargetImpl()->getRegisterInfo());
2194 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
2195 unsigned SrcReg = FramePtr;
2197 // Recursively load frame address
2203 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2205 DestReg = createResultReg(&AArch64::GPR64RegClass);
2206 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2207 TII.get(AArch64::LDRXui), DestReg)
2208 .addReg(SrcReg).addImm(0);
2212 UpdateValueMap(II, SrcReg);
2215 case Intrinsic::memcpy:
2216 case Intrinsic::memmove: {
2217 const auto *MTI = cast<MemTransferInst>(II);
2218 // Don't handle volatile.
2219 if (MTI->isVolatile())
2222 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
2223 // we would emit dead code because we don't currently handle memmoves.
2224 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
2225 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
2226 // Small memcpy's are common enough that we want to do them without a call
2228 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
2229 unsigned Alignment = MTI->getAlignment();
2230 if (IsMemCpySmall(Len, Alignment)) {
2232 if (!ComputeAddress(MTI->getRawDest(), Dest) ||
2233 !ComputeAddress(MTI->getRawSource(), Src))
2235 if (TryEmitSmallMemCpy(Dest, Src, Len, Alignment))
2240 if (!MTI->getLength()->getType()->isIntegerTy(64))
2243 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
2244 // Fast instruction selection doesn't support the special
2248 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
2249 return LowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
2251 case Intrinsic::memset: {
2252 const MemSetInst *MSI = cast<MemSetInst>(II);
2253 // Don't handle volatile.
2254 if (MSI->isVolatile())
2257 if (!MSI->getLength()->getType()->isIntegerTy(64))
2260 if (MSI->getDestAddressSpace() > 255)
2261 // Fast instruction selection doesn't support the special
2265 return LowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2267 case Intrinsic::trap: {
2268 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
2272 case Intrinsic::sqrt: {
2273 Type *RetTy = II->getCalledFunction()->getReturnType();
2276 if (!isTypeLegal(RetTy, VT))
2279 unsigned Op0Reg = getRegForValue(II->getOperand(0));
2282 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
2284 unsigned ResultReg = FastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
2288 UpdateValueMap(II, ResultReg);
2291 case Intrinsic::sadd_with_overflow:
2292 case Intrinsic::uadd_with_overflow:
2293 case Intrinsic::ssub_with_overflow:
2294 case Intrinsic::usub_with_overflow:
2295 case Intrinsic::smul_with_overflow:
2296 case Intrinsic::umul_with_overflow: {
2297 // This implements the basic lowering of the xalu with overflow intrinsics.
2298 const Function *Callee = II->getCalledFunction();
2299 auto *Ty = cast<StructType>(Callee->getReturnType());
2300 Type *RetTy = Ty->getTypeAtIndex(0U);
2301 Type *CondTy = Ty->getTypeAtIndex(1);
2304 if (!isTypeLegal(RetTy, VT))
2307 if (VT != MVT::i32 && VT != MVT::i64)
2310 const Value *LHS = II->getArgOperand(0);
2311 const Value *RHS = II->getArgOperand(1);
2312 // Canonicalize immediate to the RHS.
2313 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2314 isCommutativeIntrinsic(II))
2315 std::swap(LHS, RHS);
2317 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
2318 AArch64CC::CondCode CC = AArch64CC::Invalid;
2319 switch (II->getIntrinsicID()) {
2320 default: llvm_unreachable("Unexpected intrinsic!");
2321 case Intrinsic::sadd_with_overflow:
2322 ResultReg1 = emitAdds(VT, LHS, RHS); CC = AArch64CC::VS; break;
2323 case Intrinsic::uadd_with_overflow:
2324 ResultReg1 = emitAdds(VT, LHS, RHS); CC = AArch64CC::HS; break;
2325 case Intrinsic::ssub_with_overflow:
2326 ResultReg1 = emitSubs(VT, LHS, RHS); CC = AArch64CC::VS; break;
2327 case Intrinsic::usub_with_overflow:
2328 ResultReg1 = emitSubs(VT, LHS, RHS); CC = AArch64CC::LO; break;
2329 case Intrinsic::smul_with_overflow: {
2331 unsigned LHSReg = getRegForValue(LHS);
2334 bool LHSIsKill = hasTrivialKill(LHS);
2336 unsigned RHSReg = getRegForValue(RHS);
2339 bool RHSIsKill = hasTrivialKill(RHS);
2341 if (VT == MVT::i32) {
2342 MulReg = Emit_SMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2343 unsigned ShiftReg = Emit_LSR_ri(MVT::i64, MulReg, false, 32);
2344 MulReg = FastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
2346 ShiftReg = FastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
2348 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
2349 AArch64_AM::ASR, 31, /*WantResult=*/false);
2351 assert(VT == MVT::i64 && "Unexpected value type.");
2352 MulReg = Emit_MUL_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2353 unsigned SMULHReg = FastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
2355 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
2356 AArch64_AM::ASR, 63, /*WantResult=*/false);
2360 case Intrinsic::umul_with_overflow: {
2362 unsigned LHSReg = getRegForValue(LHS);
2365 bool LHSIsKill = hasTrivialKill(LHS);
2367 unsigned RHSReg = getRegForValue(RHS);
2370 bool RHSIsKill = hasTrivialKill(RHS);
2372 if (VT == MVT::i32) {
2373 MulReg = Emit_UMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2374 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
2375 /*IsKill=*/false, AArch64_AM::LSR, 32,
2376 /*WantResult=*/false);
2377 MulReg = FastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
2380 assert(VT == MVT::i64 && "Unexpected value type.");
2381 MulReg = Emit_MUL_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2382 unsigned UMULHReg = FastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
2384 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
2385 /*IsKill=*/false, /*WantResult=*/false);
2392 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
2393 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2394 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
2397 ResultReg2 = FuncInfo.CreateRegs(CondTy);
2398 assert((ResultReg1 + 1) == ResultReg2 &&
2399 "Nonconsecutive result registers.");
2400 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2402 .addReg(AArch64::WZR, getKillRegState(true))
2403 .addReg(AArch64::WZR, getKillRegState(true))
2404 .addImm(getInvertedCondCode(CC));
2406 UpdateValueMap(II, ResultReg1, 2);
2413 bool AArch64FastISel::SelectRet(const Instruction *I) {
2414 const ReturnInst *Ret = cast<ReturnInst>(I);
2415 const Function &F = *I->getParent()->getParent();
2417 if (!FuncInfo.CanLowerReturn)
2423 // Build a list of return value registers.
2424 SmallVector<unsigned, 4> RetRegs;
2426 if (Ret->getNumOperands() > 0) {
2427 CallingConv::ID CC = F.getCallingConv();
2428 SmallVector<ISD::OutputArg, 4> Outs;
2429 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
2431 // Analyze operands of the call, assigning locations to each operand.
2432 SmallVector<CCValAssign, 16> ValLocs;
2433 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
2434 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2435 : RetCC_AArch64_AAPCS;
2436 CCInfo.AnalyzeReturn(Outs, RetCC);
2438 // Only handle a single return value for now.
2439 if (ValLocs.size() != 1)
2442 CCValAssign &VA = ValLocs[0];
2443 const Value *RV = Ret->getOperand(0);
2445 // Don't bother handling odd stuff for now.
2446 if (VA.getLocInfo() != CCValAssign::Full)
2448 // Only handle register returns for now.
2451 unsigned Reg = getRegForValue(RV);
2455 unsigned SrcReg = Reg + VA.getValNo();
2456 unsigned DestReg = VA.getLocReg();
2457 // Avoid a cross-class copy. This is very unlikely.
2458 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
2461 EVT RVEVT = TLI.getValueType(RV->getType());
2462 if (!RVEVT.isSimple())
2465 // Vectors (of > 1 lane) in big endian need tricky handling.
2466 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1)
2469 MVT RVVT = RVEVT.getSimpleVT();
2470 if (RVVT == MVT::f128)
2472 MVT DestVT = VA.getValVT();
2473 // Special handling for extended integers.
2474 if (RVVT != DestVT) {
2475 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
2478 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
2481 bool isZExt = Outs[0].Flags.isZExt();
2482 SrcReg = EmitIntExt(RVVT, SrcReg, DestVT, isZExt);
2488 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2489 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
2491 // Add register to return instruction.
2492 RetRegs.push_back(VA.getLocReg());
2495 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2496 TII.get(AArch64::RET_ReallyLR));
2497 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
2498 MIB.addReg(RetRegs[i], RegState::Implicit);
2502 bool AArch64FastISel::SelectTrunc(const Instruction *I) {
2503 Type *DestTy = I->getType();
2504 Value *Op = I->getOperand(0);
2505 Type *SrcTy = Op->getType();
2507 EVT SrcEVT = TLI.getValueType(SrcTy, true);
2508 EVT DestEVT = TLI.getValueType(DestTy, true);
2509 if (!SrcEVT.isSimple())
2511 if (!DestEVT.isSimple())
2514 MVT SrcVT = SrcEVT.getSimpleVT();
2515 MVT DestVT = DestEVT.getSimpleVT();
2517 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
2520 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
2524 unsigned SrcReg = getRegForValue(Op);
2527 bool SrcIsKill = hasTrivialKill(Op);
2529 // If we're truncating from i64 to a smaller non-legal type then generate an
2530 // AND. Otherwise, we know the high bits are undefined and a truncate doesn't
2531 // generate any code.
2532 if (SrcVT == MVT::i64) {
2534 switch (DestVT.SimpleTy) {
2536 // Trunc i64 to i32 is handled by the target-independent fast-isel.
2548 // Issue an extract_subreg to get the lower 32-bits.
2549 unsigned Reg32 = FastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2551 // Create the AND instruction which performs the actual truncation.
2552 unsigned ANDReg = emitAND_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
2553 assert(ANDReg && "Unexpected AND instruction emission failure.");
2557 UpdateValueMap(I, SrcReg);
2561 unsigned AArch64FastISel::Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt) {
2562 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
2563 DestVT == MVT::i64) &&
2564 "Unexpected value type.");
2565 // Handle i8 and i16 as i32.
2566 if (DestVT == MVT::i8 || DestVT == MVT::i16)
2570 unsigned ResultReg = emitAND_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
2571 assert(ResultReg && "Unexpected AND instruction emission failure.");
2572 if (DestVT == MVT::i64) {
2573 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
2574 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
2575 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2576 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2577 TII.get(AArch64::SUBREG_TO_REG), Reg64)
2580 .addImm(AArch64::sub_32);
2585 if (DestVT == MVT::i64) {
2586 // FIXME: We're SExt i1 to i64.
2589 unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
2590 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SBFMWri),
2599 unsigned AArch64FastISel::Emit_MUL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2600 unsigned Op1, bool Op1IsKill) {
2602 switch (RetVT.SimpleTy) {
2608 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
2610 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
2613 // Create the base instruction, then add the operands.
2614 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
2615 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2616 .addReg(Op0, getKillRegState(Op0IsKill))
2617 .addReg(Op1, getKillRegState(Op1IsKill))
2618 .addReg(ZReg, getKillRegState(true));
2623 unsigned AArch64FastISel::Emit_SMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2624 unsigned Op1, bool Op1IsKill) {
2625 if (RetVT != MVT::i64)
2628 // Create the base instruction, then add the operands.
2629 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
2630 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SMADDLrrr),
2632 .addReg(Op0, getKillRegState(Op0IsKill))
2633 .addReg(Op1, getKillRegState(Op1IsKill))
2634 .addReg(AArch64::XZR, getKillRegState(true));
2639 unsigned AArch64FastISel::Emit_UMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2640 unsigned Op1, bool Op1IsKill) {
2641 if (RetVT != MVT::i64)
2644 // Create the base instruction, then add the operands.
2645 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
2646 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::UMADDLrrr),
2648 .addReg(Op0, getKillRegState(Op0IsKill))
2649 .addReg(Op1, getKillRegState(Op1IsKill))
2650 .addReg(AArch64::XZR, getKillRegState(true));
2655 unsigned AArch64FastISel::Emit_LSL_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2657 unsigned Opc, ImmR, ImmS;
2658 switch (RetVT.SimpleTy) {
2661 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 7 - Shift; break;
2663 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 15 - Shift; break;
2665 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 31 - Shift; break;
2667 Opc = AArch64::UBFMXri; ImmR = -Shift % 64; ImmS = 63 - Shift; break;
2670 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2671 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, ImmR,
2675 unsigned AArch64FastISel::Emit_LSR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2678 switch (RetVT.SimpleTy) {
2680 case MVT::i8: Opc = AArch64::UBFMWri; ImmS = 7; break;
2681 case MVT::i16: Opc = AArch64::UBFMWri; ImmS = 15; break;
2682 case MVT::i32: Opc = AArch64::UBFMWri; ImmS = 31; break;
2683 case MVT::i64: Opc = AArch64::UBFMXri; ImmS = 63; break;
2686 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2687 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, Shift,
2691 unsigned AArch64FastISel::Emit_ASR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2694 switch (RetVT.SimpleTy) {
2696 case MVT::i8: Opc = AArch64::SBFMWri; ImmS = 7; break;
2697 case MVT::i16: Opc = AArch64::SBFMWri; ImmS = 15; break;
2698 case MVT::i32: Opc = AArch64::SBFMWri; ImmS = 31; break;
2699 case MVT::i64: Opc = AArch64::SBFMXri; ImmS = 63; break;
2702 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2703 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, Shift,
2707 unsigned AArch64FastISel::EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
2709 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
2711 // FastISel does not have plumbing to deal with extensions where the SrcVT or
2712 // DestVT are odd things, so test to make sure that they are both types we can
2713 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
2714 // bail out to SelectionDAG.
2715 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
2716 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
2717 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
2718 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
2724 switch (SrcVT.SimpleTy) {
2728 return Emiti1Ext(SrcReg, DestVT, isZExt);
2730 if (DestVT == MVT::i64)
2731 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2733 Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
2737 if (DestVT == MVT::i64)
2738 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2740 Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
2744 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
2745 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2750 // Handle i8 and i16 as i32.
2751 if (DestVT == MVT::i8 || DestVT == MVT::i16)
2753 else if (DestVT == MVT::i64) {
2754 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2755 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2756 TII.get(AArch64::SUBREG_TO_REG), Src64)
2759 .addImm(AArch64::sub_32);
2763 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2764 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2772 bool AArch64FastISel::SelectIntExt(const Instruction *I) {
2773 // On ARM, in general, integer casts don't involve legal types; this code
2774 // handles promotable integers. The high bits for a type smaller than
2775 // the register size are assumed to be undefined.
2776 Type *DestTy = I->getType();
2777 Value *Src = I->getOperand(0);
2778 Type *SrcTy = Src->getType();
2780 bool isZExt = isa<ZExtInst>(I);
2781 unsigned SrcReg = getRegForValue(Src);
2785 EVT SrcEVT = TLI.getValueType(SrcTy, true);
2786 EVT DestEVT = TLI.getValueType(DestTy, true);
2787 if (!SrcEVT.isSimple())
2789 if (!DestEVT.isSimple())
2792 MVT SrcVT = SrcEVT.getSimpleVT();
2793 MVT DestVT = DestEVT.getSimpleVT();
2794 unsigned ResultReg = 0;
2796 // Check if it is an argument and if it is already zero/sign-extended.
2797 if (const auto *Arg = dyn_cast<Argument>(Src)) {
2798 if ((isZExt && Arg->hasZExtAttr()) || (!isZExt && Arg->hasSExtAttr())) {
2799 if (DestVT == MVT::i64) {
2800 ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2801 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2802 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
2805 .addImm(AArch64::sub_32);
2812 ResultReg = EmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2817 UpdateValueMap(I, ResultReg);
2821 bool AArch64FastISel::SelectRem(const Instruction *I, unsigned ISDOpcode) {
2822 EVT DestEVT = TLI.getValueType(I->getType(), true);
2823 if (!DestEVT.isSimple())
2826 MVT DestVT = DestEVT.getSimpleVT();
2827 if (DestVT != MVT::i64 && DestVT != MVT::i32)
2831 bool is64bit = (DestVT == MVT::i64);
2832 switch (ISDOpcode) {
2836 DivOpc = is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
2839 DivOpc = is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
2842 unsigned MSubOpc = is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
2843 unsigned Src0Reg = getRegForValue(I->getOperand(0));
2847 unsigned Src1Reg = getRegForValue(I->getOperand(1));
2851 unsigned QuotReg = createResultReg(TLI.getRegClassFor(DestVT));
2852 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(DivOpc), QuotReg)
2855 // The remainder is computed as numerator - (quotient * denominator) using the
2856 // MSUB instruction.
2857 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2858 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MSubOpc), ResultReg)
2862 UpdateValueMap(I, ResultReg);
2866 bool AArch64FastISel::SelectMul(const Instruction *I) {
2867 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2868 if (!SrcEVT.isSimple())
2870 MVT SrcVT = SrcEVT.getSimpleVT();
2872 // Must be simple value type. Don't handle vectors.
2873 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
2877 unsigned Src0Reg = getRegForValue(I->getOperand(0));
2880 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
2882 unsigned Src1Reg = getRegForValue(I->getOperand(1));
2885 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
2887 unsigned ResultReg =
2888 Emit_MUL_rr(SrcVT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
2893 UpdateValueMap(I, ResultReg);
2897 bool AArch64FastISel::SelectShift(const Instruction *I, bool IsLeftShift,
2898 bool IsArithmetic) {
2899 EVT RetEVT = TLI.getValueType(I->getType(), true);
2900 if (!RetEVT.isSimple())
2902 MVT RetVT = RetEVT.getSimpleVT();
2904 if (!isa<ConstantInt>(I->getOperand(1)))
2907 unsigned Op0Reg = getRegForValue(I->getOperand(0));
2910 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
2912 uint64_t ShiftVal = cast<ConstantInt>(I->getOperand(1))->getZExtValue();
2916 ResultReg = Emit_LSL_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2919 ResultReg = Emit_ASR_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2921 ResultReg = Emit_LSR_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2927 UpdateValueMap(I, ResultReg);
2931 bool AArch64FastISel::SelectBitCast(const Instruction *I) {
2934 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
2936 if (!isTypeLegal(I->getType(), RetVT))
2940 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
2941 Opc = AArch64::FMOVWSr;
2942 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
2943 Opc = AArch64::FMOVXDr;
2944 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
2945 Opc = AArch64::FMOVSWr;
2946 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
2947 Opc = AArch64::FMOVDXr;
2951 unsigned Op0Reg = getRegForValue(I->getOperand(0));
2954 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
2955 unsigned ResultReg = FastEmitInst_r(Opc, TLI.getRegClassFor(RetVT),
2961 UpdateValueMap(I, ResultReg);
2965 bool AArch64FastISel::TargetSelectInstruction(const Instruction *I) {
2966 switch (I->getOpcode()) {
2969 case Instruction::Load:
2970 return SelectLoad(I);
2971 case Instruction::Store:
2972 return SelectStore(I);
2973 case Instruction::Br:
2974 return SelectBranch(I);
2975 case Instruction::IndirectBr:
2976 return SelectIndirectBr(I);
2977 case Instruction::FCmp:
2978 case Instruction::ICmp:
2979 return SelectCmp(I);
2980 case Instruction::Select:
2981 return SelectSelect(I);
2982 case Instruction::FPExt:
2983 return SelectFPExt(I);
2984 case Instruction::FPTrunc:
2985 return SelectFPTrunc(I);
2986 case Instruction::FPToSI:
2987 return SelectFPToInt(I, /*Signed=*/true);
2988 case Instruction::FPToUI:
2989 return SelectFPToInt(I, /*Signed=*/false);
2990 case Instruction::SIToFP:
2991 return SelectIntToFP(I, /*Signed=*/true);
2992 case Instruction::UIToFP:
2993 return SelectIntToFP(I, /*Signed=*/false);
2994 case Instruction::SRem:
2995 return SelectRem(I, ISD::SREM);
2996 case Instruction::URem:
2997 return SelectRem(I, ISD::UREM);
2998 case Instruction::Ret:
2999 return SelectRet(I);
3000 case Instruction::Trunc:
3001 return SelectTrunc(I);
3002 case Instruction::ZExt:
3003 case Instruction::SExt:
3004 return SelectIntExt(I);
3006 // FIXME: All of these should really be handled by the target-independent
3007 // selector -> improve FastISel tblgen.
3008 case Instruction::Mul:
3009 return SelectMul(I);
3010 case Instruction::Shl:
3011 return SelectShift(I, /*IsLeftShift=*/true, /*IsArithmetic=*/false);
3012 case Instruction::LShr:
3013 return SelectShift(I, /*IsLeftShift=*/false, /*IsArithmetic=*/false);
3014 case Instruction::AShr:
3015 return SelectShift(I, /*IsLeftShift=*/false, /*IsArithmetic=*/true);
3016 case Instruction::BitCast:
3017 return SelectBitCast(I);
3020 // Silence warnings.
3021 (void)&CC_AArch64_DarwinPCS_VarArg;
3025 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &funcInfo,
3026 const TargetLibraryInfo *libInfo) {
3027 return new AArch64FastISel(funcInfo, libInfo);