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 {
59 const GlobalValue *GV;
62 Address() : Kind(RegBase), Offset(0), GV(nullptr) { Base.Reg = 0; }
63 void setKind(BaseKind K) { Kind = K; }
64 BaseKind getKind() const { return Kind; }
65 bool isRegBase() const { return Kind == RegBase; }
66 bool isFIBase() const { return Kind == FrameIndexBase; }
67 void setReg(unsigned Reg) {
68 assert(isRegBase() && "Invalid base register access!");
71 unsigned getReg() const {
72 assert(isRegBase() && "Invalid base register access!");
75 void setFI(unsigned FI) {
76 assert(isFIBase() && "Invalid base frame index access!");
79 unsigned getFI() const {
80 assert(isFIBase() && "Invalid base frame index access!");
83 void setOffset(int64_t O) { Offset = O; }
84 int64_t getOffset() { return Offset; }
86 void setGlobalValue(const GlobalValue *G) { GV = G; }
87 const GlobalValue *getGlobalValue() { return GV; }
89 bool isValid() { return isFIBase() || (isRegBase() && getReg() != 0); }
92 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
93 /// make the right decision when generating code for different targets.
94 const AArch64Subtarget *Subtarget;
97 bool FastLowerArguments() override;
98 bool FastLowerCall(CallLoweringInfo &CLI) override;
99 bool FastLowerIntrinsicCall(const IntrinsicInst *II) override;
102 // Selection routines.
103 bool SelectLoad(const Instruction *I);
104 bool SelectStore(const Instruction *I);
105 bool SelectBranch(const Instruction *I);
106 bool SelectIndirectBr(const Instruction *I);
107 bool SelectCmp(const Instruction *I);
108 bool SelectSelect(const Instruction *I);
109 bool SelectFPExt(const Instruction *I);
110 bool SelectFPTrunc(const Instruction *I);
111 bool SelectFPToInt(const Instruction *I, bool Signed);
112 bool SelectIntToFP(const Instruction *I, bool Signed);
113 bool SelectRem(const Instruction *I, unsigned ISDOpcode);
114 bool SelectRet(const Instruction *I);
115 bool SelectTrunc(const Instruction *I);
116 bool SelectIntExt(const Instruction *I);
117 bool SelectMul(const Instruction *I);
118 bool SelectShift(const Instruction *I, bool IsLeftShift, bool IsArithmetic);
119 bool SelectBitCast(const Instruction *I);
121 // Utility helper routines.
122 bool isTypeLegal(Type *Ty, MVT &VT);
123 bool isLoadStoreTypeLegal(Type *Ty, MVT &VT);
124 bool ComputeAddress(const Value *Obj, Address &Addr);
125 bool ComputeCallAddress(const Value *V, Address &Addr);
126 bool SimplifyAddress(Address &Addr, MVT VT, int64_t ScaleFactor,
128 void AddLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
129 unsigned Flags, MachineMemOperand *MMO,
131 bool IsMemCpySmall(uint64_t Len, unsigned Alignment);
132 bool TryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
134 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
138 bool EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt);
139 bool EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
140 MachineMemOperand *MMO = nullptr, bool UseUnscaled = false);
141 bool EmitStore(MVT VT, unsigned SrcReg, Address Addr,
142 MachineMemOperand *MMO = nullptr, bool UseUnscaled = false);
143 unsigned EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
144 unsigned Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
145 unsigned Emit_MUL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
146 unsigned Op1, bool Op1IsKill);
147 unsigned Emit_SMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
148 unsigned Op1, bool Op1IsKill);
149 unsigned Emit_UMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
150 unsigned Op1, bool Op1IsKill);
151 unsigned Emit_LSL_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
152 unsigned Emit_LSR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
153 unsigned Emit_ASR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
155 unsigned AArch64MaterializeInt(const ConstantInt *CI, MVT VT);
156 unsigned AArch64MaterializeFP(const ConstantFP *CFP, MVT VT);
157 unsigned AArch64MaterializeGV(const GlobalValue *GV);
159 // Call handling routines.
161 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
162 bool ProcessCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
164 bool FinishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
167 // Backend specific FastISel code.
168 unsigned TargetMaterializeAlloca(const AllocaInst *AI) override;
169 unsigned TargetMaterializeConstant(const Constant *C) override;
171 explicit AArch64FastISel(FunctionLoweringInfo &funcInfo,
172 const TargetLibraryInfo *libInfo)
173 : FastISel(funcInfo, libInfo) {
174 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
175 Context = &funcInfo.Fn->getContext();
178 bool TargetSelectInstruction(const Instruction *I) override;
180 #include "AArch64GenFastISel.inc"
183 } // end anonymous namespace
185 #include "AArch64GenCallingConv.inc"
187 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
188 if (CC == CallingConv::WebKit_JS)
189 return CC_AArch64_WebKit_JS;
190 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
193 unsigned AArch64FastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
194 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
195 "Alloca should always return a pointer.");
197 // Don't handle dynamic allocas.
198 if (!FuncInfo.StaticAllocaMap.count(AI))
201 DenseMap<const AllocaInst *, int>::iterator SI =
202 FuncInfo.StaticAllocaMap.find(AI);
204 if (SI != FuncInfo.StaticAllocaMap.end()) {
205 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
206 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
208 .addFrameIndex(SI->second)
217 unsigned AArch64FastISel::AArch64MaterializeInt(const ConstantInt *CI, MVT VT) {
220 return FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
223 unsigned AArch64FastISel::AArch64MaterializeFP(const ConstantFP *CFP, MVT VT) {
224 if (VT != MVT::f32 && VT != MVT::f64)
227 const APFloat Val = CFP->getValueAPF();
228 bool Is64Bit = (VT == MVT::f64);
230 // This checks to see if we can use FMOV instructions to materialize
231 // a constant, otherwise we have to materialize via the constant pool.
232 if (TLI.isFPImmLegal(Val, VT)) {
233 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
234 // Positive zero (+0.0) has to be materialized with a fmov from the zero
235 // register, because the immediate version of fmov cannot encode zero.
236 if (Val.isPosZero()) {
237 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
238 unsigned Opc = Is64Bit ? AArch64::FMOVDr : AArch64::FMOVSr;
239 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
240 .addReg(ZReg, getKillRegState(true));
243 int Imm = Is64Bit ? AArch64_AM::getFP64Imm(Val)
244 : AArch64_AM::getFP32Imm(Val);
245 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
246 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
251 // Materialize via constant pool. MachineConstantPool wants an explicit
253 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
255 Align = DL.getTypeAllocSize(CFP->getType());
257 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
258 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
259 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
261 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
263 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
264 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
265 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
267 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
271 unsigned AArch64FastISel::AArch64MaterializeGV(const GlobalValue *GV) {
272 // We can't handle thread-local variables quickly yet.
273 if (GV->isThreadLocal())
276 // MachO still uses GOT for large code-model accesses, but ELF requires
277 // movz/movk sequences, which FastISel doesn't handle yet.
278 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
281 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
283 EVT DestEVT = TLI.getValueType(GV->getType(), true);
284 if (!DestEVT.isSimple())
287 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
290 if (OpFlags & AArch64II::MO_GOT) {
292 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
294 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
296 ResultReg = createResultReg(&AArch64::GPR64RegClass);
297 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
300 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
304 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
306 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
308 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
309 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
312 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
318 unsigned AArch64FastISel::TargetMaterializeConstant(const Constant *C) {
319 EVT CEVT = TLI.getValueType(C->getType(), true);
321 // Only handle simple types.
322 if (!CEVT.isSimple())
324 MVT VT = CEVT.getSimpleVT();
326 if (const auto *CI = dyn_cast<ConstantInt>(C))
327 return AArch64MaterializeInt(CI, VT);
328 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
329 return AArch64MaterializeFP(CFP, VT);
330 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
331 return AArch64MaterializeGV(GV);
336 // Computes the address to get to an object.
337 bool AArch64FastISel::ComputeAddress(const Value *Obj, Address &Addr) {
338 const User *U = nullptr;
339 unsigned Opcode = Instruction::UserOp1;
340 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
341 // Don't walk into other basic blocks unless the object is an alloca from
342 // another block, otherwise it may not have a virtual register assigned.
343 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
344 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
345 Opcode = I->getOpcode();
348 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
349 Opcode = C->getOpcode();
353 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
354 if (Ty->getAddressSpace() > 255)
355 // Fast instruction selection doesn't support the special
362 case Instruction::BitCast: {
363 // Look through bitcasts.
364 return ComputeAddress(U->getOperand(0), Addr);
366 case Instruction::IntToPtr: {
367 // Look past no-op inttoptrs.
368 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
369 return ComputeAddress(U->getOperand(0), Addr);
372 case Instruction::PtrToInt: {
373 // Look past no-op ptrtoints.
374 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
375 return ComputeAddress(U->getOperand(0), Addr);
378 case Instruction::GetElementPtr: {
379 Address SavedAddr = Addr;
380 uint64_t TmpOffset = Addr.getOffset();
382 // Iterate through the GEP folding the constants into offsets where
384 gep_type_iterator GTI = gep_type_begin(U);
385 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
387 const Value *Op = *i;
388 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
389 const StructLayout *SL = DL.getStructLayout(STy);
390 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
391 TmpOffset += SL->getElementOffset(Idx);
393 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
395 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
396 // Constant-offset addressing.
397 TmpOffset += CI->getSExtValue() * S;
400 if (canFoldAddIntoGEP(U, Op)) {
401 // A compatible add with a constant operand. Fold the constant.
403 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
404 TmpOffset += CI->getSExtValue() * S;
405 // Iterate on the other operand.
406 Op = cast<AddOperator>(Op)->getOperand(0);
410 goto unsupported_gep;
415 // Try to grab the base operand now.
416 Addr.setOffset(TmpOffset);
417 if (ComputeAddress(U->getOperand(0), Addr))
420 // We failed, restore everything and try the other options.
426 case Instruction::Alloca: {
427 const AllocaInst *AI = cast<AllocaInst>(Obj);
428 DenseMap<const AllocaInst *, int>::iterator SI =
429 FuncInfo.StaticAllocaMap.find(AI);
430 if (SI != FuncInfo.StaticAllocaMap.end()) {
431 Addr.setKind(Address::FrameIndexBase);
432 Addr.setFI(SI->second);
437 case Instruction::Add:
438 // Adds of constants are common and easy enough.
439 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
440 Addr.setOffset(Addr.getOffset() + (uint64_t)CI->getSExtValue());
441 return ComputeAddress(U->getOperand(0), Addr);
446 // Try to get this in a register if nothing else has worked.
448 Addr.setReg(getRegForValue(Obj));
449 return Addr.isValid();
452 bool AArch64FastISel::ComputeCallAddress(const Value *V, Address &Addr) {
453 const User *U = nullptr;
454 unsigned Opcode = Instruction::UserOp1;
457 if (const auto *I = dyn_cast<Instruction>(V)) {
458 Opcode = I->getOpcode();
460 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
461 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
462 Opcode = C->getOpcode();
468 case Instruction::BitCast:
469 // Look past bitcasts if its operand is in the same BB.
471 return ComputeCallAddress(U->getOperand(0), Addr);
473 case Instruction::IntToPtr:
474 // Look past no-op inttoptrs if its operand is in the same BB.
476 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
477 return ComputeCallAddress(U->getOperand(0), Addr);
479 case Instruction::PtrToInt:
480 // Look past no-op ptrtoints if its operand is in the same BB.
482 TLI.getValueType(U->getType()) == TLI.getPointerTy())
483 return ComputeCallAddress(U->getOperand(0), Addr);
487 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
488 Addr.setGlobalValue(GV);
492 // If all else fails, try to materialize the value in a register.
493 if (!Addr.getGlobalValue()) {
494 Addr.setReg(getRegForValue(V));
495 return Addr.getReg() != 0;
502 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
503 EVT evt = TLI.getValueType(Ty, true);
505 // Only handle simple types.
506 if (evt == MVT::Other || !evt.isSimple())
508 VT = evt.getSimpleVT();
510 // This is a legal type, but it's not something we handle in fast-isel.
514 // Handle all other legal types, i.e. a register that will directly hold this
516 return TLI.isTypeLegal(VT);
519 bool AArch64FastISel::isLoadStoreTypeLegal(Type *Ty, MVT &VT) {
520 if (isTypeLegal(Ty, VT))
523 // If this is a type than can be sign or zero-extended to a basic operation
524 // go ahead and accept it now. For stores, this reflects truncation.
525 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
531 bool AArch64FastISel::SimplifyAddress(Address &Addr, MVT VT,
532 int64_t ScaleFactor, bool UseUnscaled) {
533 bool needsLowering = false;
534 int64_t Offset = Addr.getOffset();
535 switch (VT.SimpleTy) {
546 // Using scaled, 12-bit, unsigned immediate offsets.
547 needsLowering = ((Offset & 0xfff) != Offset);
549 // Using unscaled, 9-bit, signed immediate offsets.
550 needsLowering = (Offset > 256 || Offset < -256);
554 //If this is a stack pointer and the offset needs to be simplified then put
555 // the alloca address into a register, set the base type back to register and
556 // continue. This should almost never happen.
557 if (needsLowering && Addr.getKind() == Address::FrameIndexBase) {
558 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
559 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
561 .addFrameIndex(Addr.getFI())
564 Addr.setKind(Address::RegBase);
565 Addr.setReg(ResultReg);
568 // Since the offset is too large for the load/store instruction get the
569 // reg+offset into a register.
571 uint64_t UnscaledOffset = Addr.getOffset() * ScaleFactor;
572 unsigned ResultReg = FastEmit_ri_(MVT::i64, ISD::ADD, Addr.getReg(), false,
573 UnscaledOffset, MVT::i64);
576 Addr.setReg(ResultReg);
582 void AArch64FastISel::AddLoadStoreOperands(Address &Addr,
583 const MachineInstrBuilder &MIB,
585 MachineMemOperand *MMO,
587 int64_t Offset = Addr.getOffset();
588 // Frame base works a bit differently. Handle it separately.
589 if (Addr.getKind() == Address::FrameIndexBase) {
590 int FI = Addr.getFI();
591 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
592 // and alignment should be based on the VT.
593 MMO = FuncInfo.MF->getMachineMemOperand(
594 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
595 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
596 // Now add the rest of the operands.
597 MIB.addFrameIndex(FI).addImm(Offset);
599 // Now add the rest of the operands.
600 MIB.addReg(Addr.getReg());
605 MIB.addMemOperand(MMO);
608 bool AArch64FastISel::EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
609 MachineMemOperand *MMO, bool UseUnscaled) {
610 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
611 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
612 if (!UseUnscaled && Addr.getOffset() < 0)
616 const TargetRegisterClass *RC;
618 int64_t ScaleFactor = 0;
619 switch (VT.SimpleTy) {
624 // Intentional fall-through.
626 Opc = UseUnscaled ? AArch64::LDURBBi : AArch64::LDRBBui;
627 RC = &AArch64::GPR32RegClass;
631 Opc = UseUnscaled ? AArch64::LDURHHi : AArch64::LDRHHui;
632 RC = &AArch64::GPR32RegClass;
636 Opc = UseUnscaled ? AArch64::LDURWi : AArch64::LDRWui;
637 RC = &AArch64::GPR32RegClass;
641 Opc = UseUnscaled ? AArch64::LDURXi : AArch64::LDRXui;
642 RC = &AArch64::GPR64RegClass;
646 Opc = UseUnscaled ? AArch64::LDURSi : AArch64::LDRSui;
647 RC = TLI.getRegClassFor(VT);
651 Opc = UseUnscaled ? AArch64::LDURDi : AArch64::LDRDui;
652 RC = TLI.getRegClassFor(VT);
658 int64_t Offset = Addr.getOffset();
659 if (Offset & (ScaleFactor - 1))
660 // Retry using an unscaled, 9-bit, signed immediate offset.
661 return EmitLoad(VT, ResultReg, Addr, MMO, /*UseUnscaled*/ true);
663 Addr.setOffset(Offset / ScaleFactor);
666 // Simplify this down to something we can handle.
667 if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
670 // Create the base instruction, then add the operands.
671 ResultReg = createResultReg(RC);
672 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
673 TII.get(Opc), ResultReg);
674 AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, MMO, UseUnscaled);
676 // Loading an i1 requires special handling.
678 MRI.constrainRegClass(ResultReg, &AArch64::GPR32RegClass);
679 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
680 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
683 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
689 bool AArch64FastISel::SelectLoad(const Instruction *I) {
691 // Verify we have a legal type before going any further. Currently, we handle
692 // simple types that will directly fit in a register (i32/f32/i64/f64) or
693 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
694 if (!isLoadStoreTypeLegal(I->getType(), VT) || cast<LoadInst>(I)->isAtomic())
697 // See if we can handle this address.
699 if (!ComputeAddress(I->getOperand(0), Addr))
703 if (!EmitLoad(VT, ResultReg, Addr, createMachineMemOperandFor(I)))
706 UpdateValueMap(I, ResultReg);
710 bool AArch64FastISel::EmitStore(MVT VT, unsigned SrcReg, Address Addr,
711 MachineMemOperand *MMO, bool UseUnscaled) {
712 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
713 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
714 if (!UseUnscaled && Addr.getOffset() < 0)
719 int64_t ScaleFactor = 0;
720 // Using scaled, 12-bit, unsigned immediate offsets.
721 switch (VT.SimpleTy) {
727 StrOpc = UseUnscaled ? AArch64::STURBBi : AArch64::STRBBui;
731 StrOpc = UseUnscaled ? AArch64::STURHHi : AArch64::STRHHui;
735 StrOpc = UseUnscaled ? AArch64::STURWi : AArch64::STRWui;
739 StrOpc = UseUnscaled ? AArch64::STURXi : AArch64::STRXui;
743 StrOpc = UseUnscaled ? AArch64::STURSi : AArch64::STRSui;
747 StrOpc = UseUnscaled ? AArch64::STURDi : AArch64::STRDui;
753 int64_t Offset = Addr.getOffset();
754 if (Offset & (ScaleFactor - 1))
755 // Retry using an unscaled, 9-bit, signed immediate offset.
756 return EmitStore(VT, SrcReg, Addr, MMO, /*UseUnscaled*/ true);
758 Addr.setOffset(Offset / ScaleFactor);
761 // Simplify this down to something we can handle.
762 if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
765 // Storing an i1 requires special handling.
767 MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
768 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
769 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
772 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
775 // Create the base instruction, then add the operands.
776 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
777 TII.get(StrOpc)).addReg(SrcReg);
778 AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, MMO, UseUnscaled);
783 bool AArch64FastISel::SelectStore(const Instruction *I) {
785 Value *Op0 = I->getOperand(0);
786 // Verify we have a legal type before going any further. Currently, we handle
787 // simple types that will directly fit in a register (i32/f32/i64/f64) or
788 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
789 if (!isLoadStoreTypeLegal(Op0->getType(), VT) ||
790 cast<StoreInst>(I)->isAtomic())
793 // Get the value to be stored into a register.
794 unsigned SrcReg = getRegForValue(Op0);
798 // See if we can handle this address.
800 if (!ComputeAddress(I->getOperand(1), Addr))
803 if (!EmitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
808 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
810 case CmpInst::FCMP_ONE:
811 case CmpInst::FCMP_UEQ:
813 // AL is our "false" for now. The other two need more compares.
814 return AArch64CC::AL;
815 case CmpInst::ICMP_EQ:
816 case CmpInst::FCMP_OEQ:
817 return AArch64CC::EQ;
818 case CmpInst::ICMP_SGT:
819 case CmpInst::FCMP_OGT:
820 return AArch64CC::GT;
821 case CmpInst::ICMP_SGE:
822 case CmpInst::FCMP_OGE:
823 return AArch64CC::GE;
824 case CmpInst::ICMP_UGT:
825 case CmpInst::FCMP_UGT:
826 return AArch64CC::HI;
827 case CmpInst::FCMP_OLT:
828 return AArch64CC::MI;
829 case CmpInst::ICMP_ULE:
830 case CmpInst::FCMP_OLE:
831 return AArch64CC::LS;
832 case CmpInst::FCMP_ORD:
833 return AArch64CC::VC;
834 case CmpInst::FCMP_UNO:
835 return AArch64CC::VS;
836 case CmpInst::FCMP_UGE:
837 return AArch64CC::PL;
838 case CmpInst::ICMP_SLT:
839 case CmpInst::FCMP_ULT:
840 return AArch64CC::LT;
841 case CmpInst::ICMP_SLE:
842 case CmpInst::FCMP_ULE:
843 return AArch64CC::LE;
844 case CmpInst::FCMP_UNE:
845 case CmpInst::ICMP_NE:
846 return AArch64CC::NE;
847 case CmpInst::ICMP_UGE:
848 return AArch64CC::HS;
849 case CmpInst::ICMP_ULT:
850 return AArch64CC::LO;
854 bool AArch64FastISel::SelectBranch(const Instruction *I) {
855 const BranchInst *BI = cast<BranchInst>(I);
856 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
857 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
859 AArch64CC::CondCode CC = AArch64CC::NE;
860 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
861 if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
862 // We may not handle every CC for now.
863 CC = getCompareCC(CI->getPredicate());
864 if (CC == AArch64CC::AL)
868 if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
872 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
876 // Obtain the branch weight and add the TrueBB to the successor list.
877 uint32_t BranchWeight = 0;
879 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
880 TBB->getBasicBlock());
881 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
883 FastEmitBranch(FBB, DbgLoc);
886 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
888 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
889 (isLoadStoreTypeLegal(TI->getOperand(0)->getType(), SrcVT))) {
890 unsigned CondReg = getRegForValue(TI->getOperand(0));
894 // Issue an extract_subreg to get the lower 32-bits.
895 if (SrcVT == MVT::i64)
896 CondReg = FastEmitInst_extractsubreg(MVT::i32, CondReg, /*Kill=*/true,
899 MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
900 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
901 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
902 TII.get(AArch64::ANDWri), ANDReg)
904 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
905 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
906 TII.get(AArch64::SUBSWri), AArch64::WZR)
911 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
915 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
919 // Obtain the branch weight and add the TrueBB to the successor list.
920 uint32_t BranchWeight = 0;
922 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
923 TBB->getBasicBlock());
924 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
926 FastEmitBranch(FBB, DbgLoc);
929 } else if (const ConstantInt *CI =
930 dyn_cast<ConstantInt>(BI->getCondition())) {
931 uint64_t Imm = CI->getZExtValue();
932 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
933 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
936 // Obtain the branch weight and add the target to the successor list.
937 uint32_t BranchWeight = 0;
939 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
940 Target->getBasicBlock());
941 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
943 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
944 // Fake request the condition, otherwise the intrinsic might be completely
946 unsigned CondReg = getRegForValue(BI->getCondition());
951 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
955 // Obtain the branch weight and add the TrueBB to the successor list.
956 uint32_t BranchWeight = 0;
958 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
959 TBB->getBasicBlock());
960 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
962 FastEmitBranch(FBB, DbgLoc);
966 unsigned CondReg = getRegForValue(BI->getCondition());
970 // We've been divorced from our compare! Our block was split, and
971 // now our compare lives in a predecessor block. We musn't
972 // re-compare here, as the children of the compare aren't guaranteed
973 // live across the block boundary (we *could* check for this).
974 // Regardless, the compare has been done in the predecessor block,
975 // and it left a value for us in a virtual register. Ergo, we test
976 // the one-bit value left in the virtual register.
977 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri),
983 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
988 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
992 // Obtain the branch weight and add the TrueBB to the successor list.
993 uint32_t BranchWeight = 0;
995 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
996 TBB->getBasicBlock());
997 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
999 FastEmitBranch(FBB, DbgLoc);
1003 bool AArch64FastISel::SelectIndirectBr(const Instruction *I) {
1004 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
1005 unsigned AddrReg = getRegForValue(BI->getOperand(0));
1009 // Emit the indirect branch.
1010 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BR))
1013 // Make sure the CFG is up-to-date.
1014 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
1015 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
1020 bool AArch64FastISel::EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt) {
1021 Type *Ty = Src1Value->getType();
1022 EVT SrcEVT = TLI.getValueType(Ty, true);
1023 if (!SrcEVT.isSimple())
1025 MVT SrcVT = SrcEVT.getSimpleVT();
1027 // Check to see if the 2nd operand is a constant that we can encode directly
1030 bool UseImm = false;
1031 bool isNegativeImm = false;
1032 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
1033 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
1034 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1035 const APInt &CIVal = ConstInt->getValue();
1037 Imm = (isZExt) ? CIVal.getZExtValue() : CIVal.getSExtValue();
1038 if (CIVal.isNegative()) {
1039 isNegativeImm = true;
1042 // FIXME: We can handle more immediates using shifts.
1043 UseImm = ((Imm & 0xfff) == Imm);
1045 } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
1046 if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
1047 if (ConstFP->isZero() && !ConstFP->isNegative())
1054 bool needsExt = false;
1055 switch (SrcVT.SimpleTy) {
1062 // Intentional fall-through.
1064 ZReg = AArch64::WZR;
1066 CmpOpc = isNegativeImm ? AArch64::ADDSWri : AArch64::SUBSWri;
1068 CmpOpc = AArch64::SUBSWrr;
1071 ZReg = AArch64::XZR;
1073 CmpOpc = isNegativeImm ? AArch64::ADDSXri : AArch64::SUBSXri;
1075 CmpOpc = AArch64::SUBSXrr;
1079 CmpOpc = UseImm ? AArch64::FCMPSri : AArch64::FCMPSrr;
1083 CmpOpc = UseImm ? AArch64::FCMPDri : AArch64::FCMPDrr;
1087 unsigned SrcReg1 = getRegForValue(Src1Value);
1093 SrcReg2 = getRegForValue(Src2Value);
1098 // We have i1, i8, or i16, we need to either zero extend or sign extend.
1100 SrcReg1 = EmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
1104 SrcReg2 = EmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
1112 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), ZReg)
1117 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc), ZReg)
1122 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
1125 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
1132 bool AArch64FastISel::SelectCmp(const Instruction *I) {
1133 const CmpInst *CI = cast<CmpInst>(I);
1135 // We may not handle every CC for now.
1136 AArch64CC::CondCode CC = getCompareCC(CI->getPredicate());
1137 if (CC == AArch64CC::AL)
1141 if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1144 // Now set a register based on the comparison.
1145 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
1146 unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
1147 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
1149 .addReg(AArch64::WZR)
1150 .addReg(AArch64::WZR)
1151 .addImm(invertedCC);
1153 UpdateValueMap(I, ResultReg);
1157 bool AArch64FastISel::SelectSelect(const Instruction *I) {
1158 const SelectInst *SI = cast<SelectInst>(I);
1160 EVT DestEVT = TLI.getValueType(SI->getType(), true);
1161 if (!DestEVT.isSimple())
1164 MVT DestVT = DestEVT.getSimpleVT();
1165 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
1170 switch (DestVT.SimpleTy) {
1171 default: return false;
1172 case MVT::i32: SelectOpc = AArch64::CSELWr; break;
1173 case MVT::i64: SelectOpc = AArch64::CSELXr; break;
1174 case MVT::f32: SelectOpc = AArch64::FCSELSrrr; break;
1175 case MVT::f64: SelectOpc = AArch64::FCSELDrrr; break;
1178 const Value *Cond = SI->getCondition();
1179 bool NeedTest = true;
1180 AArch64CC::CondCode CC = AArch64CC::NE;
1181 if (foldXALUIntrinsic(CC, I, Cond))
1184 unsigned CondReg = getRegForValue(Cond);
1187 bool CondIsKill = hasTrivialKill(Cond);
1190 MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
1191 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
1192 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1194 .addReg(CondReg, getKillRegState(CondIsKill))
1195 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
1197 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri),
1204 unsigned TrueReg = getRegForValue(SI->getTrueValue());
1205 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
1207 unsigned FalseReg = getRegForValue(SI->getFalseValue());
1208 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
1210 if (!TrueReg || !FalseReg)
1213 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1214 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SelectOpc),
1216 .addReg(TrueReg, getKillRegState(TrueIsKill))
1217 .addReg(FalseReg, getKillRegState(FalseIsKill))
1220 UpdateValueMap(I, ResultReg);
1224 bool AArch64FastISel::SelectFPExt(const Instruction *I) {
1225 Value *V = I->getOperand(0);
1226 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
1229 unsigned Op = getRegForValue(V);
1233 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
1234 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
1235 ResultReg).addReg(Op);
1236 UpdateValueMap(I, ResultReg);
1240 bool AArch64FastISel::SelectFPTrunc(const Instruction *I) {
1241 Value *V = I->getOperand(0);
1242 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
1245 unsigned Op = getRegForValue(V);
1249 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
1250 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
1251 ResultReg).addReg(Op);
1252 UpdateValueMap(I, ResultReg);
1256 // FPToUI and FPToSI
1257 bool AArch64FastISel::SelectFPToInt(const Instruction *I, bool Signed) {
1259 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1262 unsigned SrcReg = getRegForValue(I->getOperand(0));
1266 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1267 if (SrcVT == MVT::f128)
1271 if (SrcVT == MVT::f64) {
1273 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
1275 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
1278 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
1280 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
1282 unsigned ResultReg = createResultReg(
1283 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
1284 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1286 UpdateValueMap(I, ResultReg);
1290 bool AArch64FastISel::SelectIntToFP(const Instruction *I, bool Signed) {
1292 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1294 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
1295 "Unexpected value type.");
1297 unsigned SrcReg = getRegForValue(I->getOperand(0));
1301 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1303 // Handle sign-extension.
1304 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1306 EmitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
1311 MRI.constrainRegClass(SrcReg, SrcVT == MVT::i64 ? &AArch64::GPR64RegClass
1312 : &AArch64::GPR32RegClass);
1315 if (SrcVT == MVT::i64) {
1317 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
1319 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
1322 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
1324 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
1327 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1328 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1330 UpdateValueMap(I, ResultReg);
1334 bool AArch64FastISel::FastLowerArguments() {
1335 if (!FuncInfo.CanLowerReturn)
1338 const Function *F = FuncInfo.Fn;
1342 CallingConv::ID CC = F->getCallingConv();
1343 if (CC != CallingConv::C)
1346 // Only handle simple cases like i1/i8/i16/i32/i64/f32/f64 of up to 8 GPR and
1348 unsigned GPRCnt = 0;
1349 unsigned FPRCnt = 0;
1351 for (auto const &Arg : F->args()) {
1352 // The first argument is at index 1.
1354 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1355 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1356 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1357 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1360 Type *ArgTy = Arg.getType();
1361 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1364 EVT ArgVT = TLI.getValueType(ArgTy);
1365 if (!ArgVT.isSimple()) return false;
1366 switch (ArgVT.getSimpleVT().SimpleTy) {
1367 default: return false;
1382 if (GPRCnt > 8 || FPRCnt > 8)
1386 static const MCPhysReg Registers[5][8] = {
1387 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
1388 AArch64::W5, AArch64::W6, AArch64::W7 },
1389 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
1390 AArch64::X5, AArch64::X6, AArch64::X7 },
1391 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
1392 AArch64::H5, AArch64::H6, AArch64::H7 },
1393 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
1394 AArch64::S5, AArch64::S6, AArch64::S7 },
1395 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
1396 AArch64::D5, AArch64::D6, AArch64::D7 }
1399 unsigned GPRIdx = 0;
1400 unsigned FPRIdx = 0;
1401 for (auto const &Arg : F->args()) {
1402 MVT VT = TLI.getSimpleValueType(Arg.getType());
1404 switch (VT.SimpleTy) {
1405 default: llvm_unreachable("Unexpected value type.");
1408 case MVT::i16: VT = MVT::i32; // fall-through
1409 case MVT::i32: SrcReg = Registers[0][GPRIdx++]; break;
1410 case MVT::i64: SrcReg = Registers[1][GPRIdx++]; break;
1411 case MVT::f16: SrcReg = Registers[2][FPRIdx++]; break;
1412 case MVT::f32: SrcReg = Registers[3][FPRIdx++]; break;
1413 case MVT::f64: SrcReg = Registers[4][FPRIdx++]; break;
1416 // Skip unused arguments.
1417 if (Arg.use_empty()) {
1418 UpdateValueMap(&Arg, 0);
1422 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1423 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1424 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1425 // Without this, EmitLiveInCopies may eliminate the livein if its only
1426 // use is a bitcast (which isn't turned into an instruction).
1427 unsigned ResultReg = createResultReg(RC);
1428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1429 TII.get(TargetOpcode::COPY), ResultReg)
1430 .addReg(DstReg, getKillRegState(true));
1431 UpdateValueMap(&Arg, ResultReg);
1436 bool AArch64FastISel::ProcessCallArgs(CallLoweringInfo &CLI,
1437 SmallVectorImpl<MVT> &OutVTs,
1438 unsigned &NumBytes) {
1439 CallingConv::ID CC = CLI.CallConv;
1440 SmallVector<CCValAssign, 16> ArgLocs;
1441 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
1442 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
1444 // Get a count of how many bytes are to be pushed on the stack.
1445 NumBytes = CCInfo.getNextStackOffset();
1447 // Issue CALLSEQ_START
1448 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1449 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
1452 // Process the args.
1453 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1454 CCValAssign &VA = ArgLocs[i];
1455 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
1456 MVT ArgVT = OutVTs[VA.getValNo()];
1458 unsigned ArgReg = getRegForValue(ArgVal);
1462 // Handle arg promotion: SExt, ZExt, AExt.
1463 switch (VA.getLocInfo()) {
1464 case CCValAssign::Full:
1466 case CCValAssign::SExt: {
1467 MVT DestVT = VA.getLocVT();
1469 ArgReg = EmitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
1474 case CCValAssign::AExt:
1475 // Intentional fall-through.
1476 case CCValAssign::ZExt: {
1477 MVT DestVT = VA.getLocVT();
1479 ArgReg = EmitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
1485 llvm_unreachable("Unknown arg promotion!");
1488 // Now copy/store arg to correct locations.
1489 if (VA.isRegLoc() && !VA.needsCustom()) {
1490 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1491 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
1492 CLI.OutRegs.push_back(VA.getLocReg());
1493 } else if (VA.needsCustom()) {
1494 // FIXME: Handle custom args.
1497 assert(VA.isMemLoc() && "Assuming store on stack.");
1499 // Don't emit stores for undef values.
1500 if (isa<UndefValue>(ArgVal))
1503 // Need to store on the stack.
1504 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
1506 unsigned BEAlign = 0;
1507 if (ArgSize < 8 && !Subtarget->isLittleEndian())
1508 BEAlign = 8 - ArgSize;
1511 Addr.setKind(Address::RegBase);
1512 Addr.setReg(AArch64::SP);
1513 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
1515 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
1516 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
1517 MachinePointerInfo::getStack(Addr.getOffset()),
1518 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
1520 if (!EmitStore(ArgVT, ArgReg, Addr, MMO))
1527 bool AArch64FastISel::FinishCall(CallLoweringInfo &CLI, MVT RetVT,
1528 unsigned NumBytes) {
1529 CallingConv::ID CC = CLI.CallConv;
1531 // Issue CALLSEQ_END
1532 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1533 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
1534 .addImm(NumBytes).addImm(0);
1536 // Now the return value.
1537 if (RetVT != MVT::isVoid) {
1538 SmallVector<CCValAssign, 16> RVLocs;
1539 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
1540 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
1542 // Only handle a single return value.
1543 if (RVLocs.size() != 1)
1546 // Copy all of the result registers out of their specified physreg.
1547 MVT CopyVT = RVLocs[0].getValVT();
1548 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
1549 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1550 TII.get(TargetOpcode::COPY), ResultReg)
1551 .addReg(RVLocs[0].getLocReg());
1552 CLI.InRegs.push_back(RVLocs[0].getLocReg());
1554 CLI.ResultReg = ResultReg;
1555 CLI.NumResultRegs = 1;
1561 bool AArch64FastISel::FastLowerCall(CallLoweringInfo &CLI) {
1562 CallingConv::ID CC = CLI.CallConv;
1563 bool IsTailCall = CLI.IsTailCall;
1564 bool IsVarArg = CLI.IsVarArg;
1565 const Value *Callee = CLI.Callee;
1566 const char *SymName = CLI.SymName;
1568 // Allow SelectionDAG isel to handle tail calls.
1572 CodeModel::Model CM = TM.getCodeModel();
1573 // Only support the small and large code model.
1574 if (CM != CodeModel::Small && CM != CodeModel::Large)
1577 // FIXME: Add large code model support for ELF.
1578 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
1581 // Let SDISel handle vararg functions.
1585 // FIXME: Only handle *simple* calls for now.
1587 if (CLI.RetTy->isVoidTy())
1588 RetVT = MVT::isVoid;
1589 else if (!isTypeLegal(CLI.RetTy, RetVT))
1592 for (auto Flag : CLI.OutFlags)
1593 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
1596 // Set up the argument vectors.
1597 SmallVector<MVT, 16> OutVTs;
1598 OutVTs.reserve(CLI.OutVals.size());
1600 for (auto *Val : CLI.OutVals) {
1602 if (!isTypeLegal(Val->getType(), VT) &&
1603 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
1606 // We don't handle vector parameters yet.
1607 if (VT.isVector() || VT.getSizeInBits() > 64)
1610 OutVTs.push_back(VT);
1614 if (!ComputeCallAddress(Callee, Addr))
1617 // Handle the arguments now that we've gotten them.
1619 if (!ProcessCallArgs(CLI, OutVTs, NumBytes))
1623 MachineInstrBuilder MIB;
1624 if (CM == CodeModel::Small) {
1625 unsigned CallOpc = Addr.getReg() ? AArch64::BLR : AArch64::BL;
1626 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
1628 MIB.addExternalSymbol(SymName, 0);
1629 else if (Addr.getGlobalValue())
1630 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
1631 else if (Addr.getReg())
1632 MIB.addReg(Addr.getReg());
1636 unsigned CallReg = 0;
1638 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
1639 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
1641 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
1643 CallReg = createResultReg(&AArch64::GPR64RegClass);
1644 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
1647 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
1649 } else if (Addr.getGlobalValue()) {
1650 CallReg = AArch64MaterializeGV(Addr.getGlobalValue());
1651 } else if (Addr.getReg())
1652 CallReg = Addr.getReg();
1657 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1658 TII.get(AArch64::BLR)).addReg(CallReg);
1661 // Add implicit physical register uses to the call.
1662 for (auto Reg : CLI.OutRegs)
1663 MIB.addReg(Reg, RegState::Implicit);
1665 // Add a register mask with the call-preserved registers.
1666 // Proper defs for return values will be added by setPhysRegsDeadExcept().
1667 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1671 // Finish off the call including any return values.
1672 return FinishCall(CLI, RetVT, NumBytes);
1675 bool AArch64FastISel::IsMemCpySmall(uint64_t Len, unsigned Alignment) {
1677 return Len / Alignment <= 4;
1682 bool AArch64FastISel::TryEmitSmallMemCpy(Address Dest, Address Src,
1683 uint64_t Len, unsigned Alignment) {
1684 // Make sure we don't bloat code by inlining very large memcpy's.
1685 if (!IsMemCpySmall(Len, Alignment))
1688 int64_t UnscaledOffset = 0;
1689 Address OrigDest = Dest;
1690 Address OrigSrc = Src;
1694 if (!Alignment || Alignment >= 8) {
1705 // Bound based on alignment.
1706 if (Len >= 4 && Alignment == 4)
1708 else if (Len >= 2 && Alignment == 2)
1717 RV = EmitLoad(VT, ResultReg, Src);
1721 RV = EmitStore(VT, ResultReg, Dest);
1725 int64_t Size = VT.getSizeInBits() / 8;
1727 UnscaledOffset += Size;
1729 // We need to recompute the unscaled offset for each iteration.
1730 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
1731 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
1737 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
1738 /// into the user. The condition code will only be updated on success.
1739 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
1740 const Instruction *I,
1741 const Value *Cond) {
1742 if (!isa<ExtractValueInst>(Cond))
1745 const auto *EV = cast<ExtractValueInst>(Cond);
1746 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
1749 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
1751 const Function *Callee = II->getCalledFunction();
1753 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
1754 if (!isTypeLegal(RetTy, RetVT))
1757 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1760 AArch64CC::CondCode TmpCC;
1761 switch (II->getIntrinsicID()) {
1762 default: return false;
1763 case Intrinsic::sadd_with_overflow:
1764 case Intrinsic::ssub_with_overflow: TmpCC = AArch64CC::VS; break;
1765 case Intrinsic::uadd_with_overflow: TmpCC = AArch64CC::HS; break;
1766 case Intrinsic::usub_with_overflow: TmpCC = AArch64CC::LO; break;
1767 case Intrinsic::smul_with_overflow:
1768 case Intrinsic::umul_with_overflow: TmpCC = AArch64CC::NE; break;
1771 // Check if both instructions are in the same basic block.
1772 if (II->getParent() != I->getParent())
1775 // Make sure nothing is in the way
1776 BasicBlock::const_iterator Start = I;
1777 BasicBlock::const_iterator End = II;
1778 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
1779 // We only expect extractvalue instructions between the intrinsic and the
1780 // instruction to be selected.
1781 if (!isa<ExtractValueInst>(Itr))
1784 // Check that the extractvalue operand comes from the intrinsic.
1785 const auto *EVI = cast<ExtractValueInst>(Itr);
1786 if (EVI->getAggregateOperand() != II)
1794 bool AArch64FastISel::FastLowerIntrinsicCall(const IntrinsicInst *II) {
1795 // FIXME: Handle more intrinsics.
1796 switch (II->getIntrinsicID()) {
1797 default: return false;
1798 case Intrinsic::frameaddress: {
1799 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
1800 MFI->setFrameAddressIsTaken(true);
1802 const AArch64RegisterInfo *RegInfo =
1803 static_cast<const AArch64RegisterInfo *>(
1804 TM.getSubtargetImpl()->getRegisterInfo());
1805 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
1806 unsigned SrcReg = FramePtr;
1808 // Recursively load frame address
1814 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
1816 DestReg = createResultReg(&AArch64::GPR64RegClass);
1817 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1818 TII.get(AArch64::LDRXui), DestReg)
1819 .addReg(SrcReg).addImm(0);
1823 UpdateValueMap(II, SrcReg);
1826 case Intrinsic::memcpy:
1827 case Intrinsic::memmove: {
1828 const auto *MTI = cast<MemTransferInst>(II);
1829 // Don't handle volatile.
1830 if (MTI->isVolatile())
1833 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
1834 // we would emit dead code because we don't currently handle memmoves.
1835 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
1836 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
1837 // Small memcpy's are common enough that we want to do them without a call
1839 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
1840 unsigned Alignment = MTI->getAlignment();
1841 if (IsMemCpySmall(Len, Alignment)) {
1843 if (!ComputeAddress(MTI->getRawDest(), Dest) ||
1844 !ComputeAddress(MTI->getRawSource(), Src))
1846 if (TryEmitSmallMemCpy(Dest, Src, Len, Alignment))
1851 if (!MTI->getLength()->getType()->isIntegerTy(64))
1854 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
1855 // Fast instruction selection doesn't support the special
1859 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
1860 return LowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
1862 case Intrinsic::memset: {
1863 const MemSetInst *MSI = cast<MemSetInst>(II);
1864 // Don't handle volatile.
1865 if (MSI->isVolatile())
1868 if (!MSI->getLength()->getType()->isIntegerTy(64))
1871 if (MSI->getDestAddressSpace() > 255)
1872 // Fast instruction selection doesn't support the special
1876 return LowerCallTo(II, "memset", II->getNumArgOperands() - 2);
1878 case Intrinsic::trap: {
1879 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
1883 case Intrinsic::sqrt: {
1884 Type *RetTy = II->getCalledFunction()->getReturnType();
1887 if (!isTypeLegal(RetTy, VT))
1890 unsigned Op0Reg = getRegForValue(II->getOperand(0));
1893 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
1895 unsigned ResultReg = FastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
1899 UpdateValueMap(II, ResultReg);
1902 case Intrinsic::sadd_with_overflow:
1903 case Intrinsic::uadd_with_overflow:
1904 case Intrinsic::ssub_with_overflow:
1905 case Intrinsic::usub_with_overflow:
1906 case Intrinsic::smul_with_overflow:
1907 case Intrinsic::umul_with_overflow: {
1908 // This implements the basic lowering of the xalu with overflow intrinsics.
1909 const Function *Callee = II->getCalledFunction();
1910 auto *Ty = cast<StructType>(Callee->getReturnType());
1911 Type *RetTy = Ty->getTypeAtIndex(0U);
1912 Type *CondTy = Ty->getTypeAtIndex(1);
1915 if (!isTypeLegal(RetTy, VT))
1918 if (VT != MVT::i32 && VT != MVT::i64)
1921 const Value *LHS = II->getArgOperand(0);
1922 const Value *RHS = II->getArgOperand(1);
1923 // Canonicalize immediate to the RHS.
1924 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
1925 isCommutativeIntrinsic(II))
1926 std::swap(LHS, RHS);
1928 unsigned LHSReg = getRegForValue(LHS);
1931 bool LHSIsKill = hasTrivialKill(LHS);
1933 // Check if the immediate can be encoded in the instruction and if we should
1934 // invert the instruction (adds -> subs) to handle negative immediates.
1935 bool UseImm = false;
1936 bool UseInverse = false;
1938 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1939 if (C->isNegative()) {
1941 Imm = -(C->getSExtValue());
1943 Imm = C->getZExtValue();
1945 if (isUInt<12>(Imm))
1948 UseInverse = UseImm && UseInverse;
1951 static const unsigned OpcTable[2][2][2] = {
1952 { {AArch64::ADDSWrr, AArch64::ADDSXrr},
1953 {AArch64::ADDSWri, AArch64::ADDSXri} },
1954 { {AArch64::SUBSWrr, AArch64::SUBSXrr},
1955 {AArch64::SUBSWri, AArch64::SUBSXri} }
1958 unsigned MulReg = 0;
1959 unsigned RHSReg = 0;
1960 bool RHSIsKill = false;
1961 AArch64CC::CondCode CC = AArch64CC::Invalid;
1962 bool Is64Bit = VT == MVT::i64;
1963 switch (II->getIntrinsicID()) {
1964 default: llvm_unreachable("Unexpected intrinsic!");
1965 case Intrinsic::sadd_with_overflow:
1966 Opc = OpcTable[UseInverse][UseImm][Is64Bit]; CC = AArch64CC::VS; break;
1967 case Intrinsic::uadd_with_overflow:
1968 Opc = OpcTable[UseInverse][UseImm][Is64Bit]; CC = AArch64CC::HS; break;
1969 case Intrinsic::ssub_with_overflow:
1970 Opc = OpcTable[!UseInverse][UseImm][Is64Bit]; CC = AArch64CC::VS; break;
1971 case Intrinsic::usub_with_overflow:
1972 Opc = OpcTable[!UseInverse][UseImm][Is64Bit]; CC = AArch64CC::LO; break;
1973 case Intrinsic::smul_with_overflow: {
1975 RHSReg = getRegForValue(RHS);
1978 RHSIsKill = hasTrivialKill(RHS);
1980 if (VT == MVT::i32) {
1981 MulReg = Emit_SMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1982 unsigned ShiftReg = Emit_LSR_ri(MVT::i64, MulReg, false, 32);
1983 MulReg = FastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
1985 ShiftReg = FastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
1987 unsigned CmpReg = createResultReg(TLI.getRegClassFor(VT));
1988 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1989 TII.get(AArch64::SUBSWrs), CmpReg)
1990 .addReg(ShiftReg, getKillRegState(true))
1991 .addReg(MulReg, getKillRegState(false))
1992 .addImm(159); // 159 <-> asr #31
1994 assert(VT == MVT::i64 && "Unexpected value type.");
1995 MulReg = Emit_MUL_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1996 unsigned SMULHReg = FastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
1998 unsigned CmpReg = createResultReg(TLI.getRegClassFor(VT));
1999 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2000 TII.get(AArch64::SUBSXrs), CmpReg)
2001 .addReg(SMULHReg, getKillRegState(true))
2002 .addReg(MulReg, getKillRegState(false))
2003 .addImm(191); // 191 <-> asr #63
2007 case Intrinsic::umul_with_overflow: {
2009 RHSReg = getRegForValue(RHS);
2012 RHSIsKill = hasTrivialKill(RHS);
2014 if (VT == MVT::i32) {
2015 MulReg = Emit_UMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2016 unsigned CmpReg = createResultReg(TLI.getRegClassFor(MVT::i64));
2017 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2018 TII.get(AArch64::SUBSXrs), CmpReg)
2019 .addReg(AArch64::XZR, getKillRegState(true))
2020 .addReg(MulReg, getKillRegState(false))
2021 .addImm(96); // 96 <-> lsr #32
2022 MulReg = FastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
2025 assert(VT == MVT::i64 && "Unexpected value type.");
2026 MulReg = Emit_MUL_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2027 unsigned UMULHReg = FastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
2029 unsigned CmpReg = createResultReg(TLI.getRegClassFor(VT));
2030 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2031 TII.get(AArch64::SUBSXrr), CmpReg)
2032 .addReg(AArch64::XZR, getKillRegState(true))
2033 .addReg(UMULHReg, getKillRegState(false));
2040 RHSReg = getRegForValue(RHS);
2043 RHSIsKill = hasTrivialKill(RHS);
2046 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2048 MachineInstrBuilder MIB;
2049 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2051 .addReg(LHSReg, getKillRegState(LHSIsKill));
2056 MIB.addReg(RHSReg, getKillRegState(RHSIsKill));
2059 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2060 TII.get(TargetOpcode::COPY), ResultReg)
2063 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2064 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2067 .addReg(AArch64::WZR, getKillRegState(true))
2068 .addReg(AArch64::WZR, getKillRegState(true))
2069 .addImm(getInvertedCondCode(CC));
2071 UpdateValueMap(II, ResultReg, 2);
2078 bool AArch64FastISel::SelectRet(const Instruction *I) {
2079 const ReturnInst *Ret = cast<ReturnInst>(I);
2080 const Function &F = *I->getParent()->getParent();
2082 if (!FuncInfo.CanLowerReturn)
2088 // Build a list of return value registers.
2089 SmallVector<unsigned, 4> RetRegs;
2091 if (Ret->getNumOperands() > 0) {
2092 CallingConv::ID CC = F.getCallingConv();
2093 SmallVector<ISD::OutputArg, 4> Outs;
2094 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
2096 // Analyze operands of the call, assigning locations to each operand.
2097 SmallVector<CCValAssign, 16> ValLocs;
2098 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
2099 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2100 : RetCC_AArch64_AAPCS;
2101 CCInfo.AnalyzeReturn(Outs, RetCC);
2103 // Only handle a single return value for now.
2104 if (ValLocs.size() != 1)
2107 CCValAssign &VA = ValLocs[0];
2108 const Value *RV = Ret->getOperand(0);
2110 // Don't bother handling odd stuff for now.
2111 if (VA.getLocInfo() != CCValAssign::Full)
2113 // Only handle register returns for now.
2116 unsigned Reg = getRegForValue(RV);
2120 unsigned SrcReg = Reg + VA.getValNo();
2121 unsigned DestReg = VA.getLocReg();
2122 // Avoid a cross-class copy. This is very unlikely.
2123 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
2126 EVT RVEVT = TLI.getValueType(RV->getType());
2127 if (!RVEVT.isSimple())
2130 // Vectors (of > 1 lane) in big endian need tricky handling.
2131 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1)
2134 MVT RVVT = RVEVT.getSimpleVT();
2135 if (RVVT == MVT::f128)
2137 MVT DestVT = VA.getValVT();
2138 // Special handling for extended integers.
2139 if (RVVT != DestVT) {
2140 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
2143 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
2146 bool isZExt = Outs[0].Flags.isZExt();
2147 SrcReg = EmitIntExt(RVVT, SrcReg, DestVT, isZExt);
2153 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2154 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
2156 // Add register to return instruction.
2157 RetRegs.push_back(VA.getLocReg());
2160 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2161 TII.get(AArch64::RET_ReallyLR));
2162 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
2163 MIB.addReg(RetRegs[i], RegState::Implicit);
2167 bool AArch64FastISel::SelectTrunc(const Instruction *I) {
2168 Type *DestTy = I->getType();
2169 Value *Op = I->getOperand(0);
2170 Type *SrcTy = Op->getType();
2172 EVT SrcEVT = TLI.getValueType(SrcTy, true);
2173 EVT DestEVT = TLI.getValueType(DestTy, true);
2174 if (!SrcEVT.isSimple())
2176 if (!DestEVT.isSimple())
2179 MVT SrcVT = SrcEVT.getSimpleVT();
2180 MVT DestVT = DestEVT.getSimpleVT();
2182 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
2185 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
2189 unsigned SrcReg = getRegForValue(Op);
2193 // If we're truncating from i64 to a smaller non-legal type then generate an
2194 // AND. Otherwise, we know the high bits are undefined and a truncate doesn't
2195 // generate any code.
2196 if (SrcVT == MVT::i64) {
2198 switch (DestVT.SimpleTy) {
2200 // Trunc i64 to i32 is handled by the target-independent fast-isel.
2212 // Issue an extract_subreg to get the lower 32-bits.
2213 unsigned Reg32 = FastEmitInst_extractsubreg(MVT::i32, SrcReg, /*Kill=*/true,
2215 MRI.constrainRegClass(Reg32, &AArch64::GPR32RegClass);
2216 // Create the AND instruction which performs the actual truncation.
2217 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
2218 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
2221 .addImm(AArch64_AM::encodeLogicalImmediate(Mask, 32));
2225 UpdateValueMap(I, SrcReg);
2229 unsigned AArch64FastISel::Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt) {
2230 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
2231 DestVT == MVT::i64) &&
2232 "Unexpected value type.");
2233 // Handle i8 and i16 as i32.
2234 if (DestVT == MVT::i8 || DestVT == MVT::i16)
2238 MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
2239 unsigned ResultReg = createResultReg(&AArch64::GPR32spRegClass);
2240 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
2243 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2245 if (DestVT == MVT::i64) {
2246 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
2247 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
2248 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2249 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2250 TII.get(AArch64::SUBREG_TO_REG), Reg64)
2253 .addImm(AArch64::sub_32);
2258 if (DestVT == MVT::i64) {
2259 // FIXME: We're SExt i1 to i64.
2262 unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
2263 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SBFMWri),
2272 unsigned AArch64FastISel::Emit_MUL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2273 unsigned Op1, bool Op1IsKill) {
2275 switch (RetVT.SimpleTy) {
2281 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
2283 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
2286 // Create the base instruction, then add the operands.
2287 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
2288 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2289 .addReg(Op0, getKillRegState(Op0IsKill))
2290 .addReg(Op1, getKillRegState(Op1IsKill))
2291 .addReg(ZReg, getKillRegState(true));
2296 unsigned AArch64FastISel::Emit_SMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2297 unsigned Op1, bool Op1IsKill) {
2298 if (RetVT != MVT::i64)
2301 // Create the base instruction, then add the operands.
2302 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
2303 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SMADDLrrr),
2305 .addReg(Op0, getKillRegState(Op0IsKill))
2306 .addReg(Op1, getKillRegState(Op1IsKill))
2307 .addReg(AArch64::XZR, getKillRegState(true));
2312 unsigned AArch64FastISel::Emit_UMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2313 unsigned Op1, bool Op1IsKill) {
2314 if (RetVT != MVT::i64)
2317 // Create the base instruction, then add the operands.
2318 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
2319 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::UMADDLrrr),
2321 .addReg(Op0, getKillRegState(Op0IsKill))
2322 .addReg(Op1, getKillRegState(Op1IsKill))
2323 .addReg(AArch64::XZR, getKillRegState(true));
2328 unsigned AArch64FastISel::Emit_LSL_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2330 unsigned Opc, ImmR, ImmS;
2331 switch (RetVT.SimpleTy) {
2334 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 7 - Shift; break;
2336 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 15 - Shift; break;
2338 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 31 - Shift; break;
2340 Opc = AArch64::UBFMXri; ImmR = -Shift % 64; ImmS = 63 - Shift; break;
2343 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2344 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, ImmR,
2348 unsigned AArch64FastISel::Emit_LSR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2351 switch (RetVT.SimpleTy) {
2353 case MVT::i8: Opc = AArch64::UBFMWri; ImmS = 7; break;
2354 case MVT::i16: Opc = AArch64::UBFMWri; ImmS = 15; break;
2355 case MVT::i32: Opc = AArch64::UBFMWri; ImmS = 31; break;
2356 case MVT::i64: Opc = AArch64::UBFMXri; ImmS = 63; break;
2359 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2360 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, Shift,
2364 unsigned AArch64FastISel::Emit_ASR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2367 switch (RetVT.SimpleTy) {
2369 case MVT::i8: Opc = AArch64::SBFMWri; ImmS = 7; break;
2370 case MVT::i16: Opc = AArch64::SBFMWri; ImmS = 15; break;
2371 case MVT::i32: Opc = AArch64::SBFMWri; ImmS = 31; break;
2372 case MVT::i64: Opc = AArch64::SBFMXri; ImmS = 63; break;
2375 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2376 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, Shift,
2380 unsigned AArch64FastISel::EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
2382 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
2384 // FastISel does not have plumbing to deal with extensions where the SrcVT or
2385 // DestVT are odd things, so test to make sure that they are both types we can
2386 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
2387 // bail out to SelectionDAG.
2388 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
2389 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
2390 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
2391 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
2397 switch (SrcVT.SimpleTy) {
2401 return Emiti1Ext(SrcReg, DestVT, isZExt);
2403 if (DestVT == MVT::i64)
2404 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2406 Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
2410 if (DestVT == MVT::i64)
2411 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2413 Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
2417 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
2418 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2423 // Handle i8 and i16 as i32.
2424 if (DestVT == MVT::i8 || DestVT == MVT::i16)
2426 else if (DestVT == MVT::i64) {
2427 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2429 TII.get(AArch64::SUBREG_TO_REG), Src64)
2432 .addImm(AArch64::sub_32);
2436 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2437 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2445 bool AArch64FastISel::SelectIntExt(const Instruction *I) {
2446 // On ARM, in general, integer casts don't involve legal types; this code
2447 // handles promotable integers. The high bits for a type smaller than
2448 // the register size are assumed to be undefined.
2449 Type *DestTy = I->getType();
2450 Value *Src = I->getOperand(0);
2451 Type *SrcTy = Src->getType();
2453 bool isZExt = isa<ZExtInst>(I);
2454 unsigned SrcReg = getRegForValue(Src);
2458 EVT SrcEVT = TLI.getValueType(SrcTy, true);
2459 EVT DestEVT = TLI.getValueType(DestTy, true);
2460 if (!SrcEVT.isSimple())
2462 if (!DestEVT.isSimple())
2465 MVT SrcVT = SrcEVT.getSimpleVT();
2466 MVT DestVT = DestEVT.getSimpleVT();
2467 unsigned ResultReg = 0;
2469 // Check if it is an argument and if it is already zero/sign-extended.
2470 if (const auto *Arg = dyn_cast<Argument>(Src)) {
2471 if ((isZExt && Arg->hasZExtAttr()) || (!isZExt && Arg->hasSExtAttr())) {
2472 if (DestVT == MVT::i64) {
2473 ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2474 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2475 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
2478 .addImm(AArch64::sub_32);
2485 ResultReg = EmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2490 UpdateValueMap(I, ResultReg);
2494 bool AArch64FastISel::SelectRem(const Instruction *I, unsigned ISDOpcode) {
2495 EVT DestEVT = TLI.getValueType(I->getType(), true);
2496 if (!DestEVT.isSimple())
2499 MVT DestVT = DestEVT.getSimpleVT();
2500 if (DestVT != MVT::i64 && DestVT != MVT::i32)
2504 bool is64bit = (DestVT == MVT::i64);
2505 switch (ISDOpcode) {
2509 DivOpc = is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
2512 DivOpc = is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
2515 unsigned MSubOpc = is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
2516 unsigned Src0Reg = getRegForValue(I->getOperand(0));
2520 unsigned Src1Reg = getRegForValue(I->getOperand(1));
2524 unsigned QuotReg = createResultReg(TLI.getRegClassFor(DestVT));
2525 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(DivOpc), QuotReg)
2528 // The remainder is computed as numerator - (quotient * denominator) using the
2529 // MSUB instruction.
2530 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2531 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MSubOpc), ResultReg)
2535 UpdateValueMap(I, ResultReg);
2539 bool AArch64FastISel::SelectMul(const Instruction *I) {
2540 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2541 if (!SrcEVT.isSimple())
2543 MVT SrcVT = SrcEVT.getSimpleVT();
2545 // Must be simple value type. Don't handle vectors.
2546 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
2550 unsigned Src0Reg = getRegForValue(I->getOperand(0));
2553 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
2555 unsigned Src1Reg = getRegForValue(I->getOperand(1));
2558 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
2560 unsigned ResultReg =
2561 Emit_MUL_rr(SrcVT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
2566 UpdateValueMap(I, ResultReg);
2570 bool AArch64FastISel::SelectShift(const Instruction *I, bool IsLeftShift,
2571 bool IsArithmetic) {
2572 EVT RetEVT = TLI.getValueType(I->getType(), true);
2573 if (!RetEVT.isSimple())
2575 MVT RetVT = RetEVT.getSimpleVT();
2577 if (!isa<ConstantInt>(I->getOperand(1)))
2580 unsigned Op0Reg = getRegForValue(I->getOperand(0));
2583 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
2585 uint64_t ShiftVal = cast<ConstantInt>(I->getOperand(1))->getZExtValue();
2589 ResultReg = Emit_LSL_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2592 ResultReg = Emit_ASR_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2594 ResultReg = Emit_LSR_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2600 UpdateValueMap(I, ResultReg);
2604 bool AArch64FastISel::SelectBitCast(const Instruction *I) {
2607 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
2609 if (!isTypeLegal(I->getType(), RetVT))
2613 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
2614 Opc = AArch64::FMOVWSr;
2615 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
2616 Opc = AArch64::FMOVXDr;
2617 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
2618 Opc = AArch64::FMOVSWr;
2619 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
2620 Opc = AArch64::FMOVDXr;
2624 unsigned Op0Reg = getRegForValue(I->getOperand(0));
2627 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
2628 unsigned ResultReg = FastEmitInst_r(Opc, TLI.getRegClassFor(RetVT),
2634 UpdateValueMap(I, ResultReg);
2638 bool AArch64FastISel::TargetSelectInstruction(const Instruction *I) {
2639 switch (I->getOpcode()) {
2642 case Instruction::Load:
2643 return SelectLoad(I);
2644 case Instruction::Store:
2645 return SelectStore(I);
2646 case Instruction::Br:
2647 return SelectBranch(I);
2648 case Instruction::IndirectBr:
2649 return SelectIndirectBr(I);
2650 case Instruction::FCmp:
2651 case Instruction::ICmp:
2652 return SelectCmp(I);
2653 case Instruction::Select:
2654 return SelectSelect(I);
2655 case Instruction::FPExt:
2656 return SelectFPExt(I);
2657 case Instruction::FPTrunc:
2658 return SelectFPTrunc(I);
2659 case Instruction::FPToSI:
2660 return SelectFPToInt(I, /*Signed=*/true);
2661 case Instruction::FPToUI:
2662 return SelectFPToInt(I, /*Signed=*/false);
2663 case Instruction::SIToFP:
2664 return SelectIntToFP(I, /*Signed=*/true);
2665 case Instruction::UIToFP:
2666 return SelectIntToFP(I, /*Signed=*/false);
2667 case Instruction::SRem:
2668 return SelectRem(I, ISD::SREM);
2669 case Instruction::URem:
2670 return SelectRem(I, ISD::UREM);
2671 case Instruction::Ret:
2672 return SelectRet(I);
2673 case Instruction::Trunc:
2674 return SelectTrunc(I);
2675 case Instruction::ZExt:
2676 case Instruction::SExt:
2677 return SelectIntExt(I);
2679 // FIXME: All of these should really be handled by the target-independent
2680 // selector -> improve FastISel tblgen.
2681 case Instruction::Mul:
2682 return SelectMul(I);
2683 case Instruction::Shl:
2684 return SelectShift(I, /*IsLeftShift=*/true, /*IsArithmetic=*/false);
2685 case Instruction::LShr:
2686 return SelectShift(I, /*IsLeftShift=*/false, /*IsArithmetic=*/false);
2687 case Instruction::AShr:
2688 return SelectShift(I, /*IsLeftShift=*/false, /*IsArithmetic=*/true);
2689 case Instruction::BitCast:
2690 return SelectBitCast(I);
2693 // Silence warnings.
2694 (void)&CC_AArch64_DarwinPCS_VarArg;
2698 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &funcInfo,
2699 const TargetLibraryInfo *libInfo) {
2700 return new AArch64FastISel(funcInfo, libInfo);