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) {
222 return FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
224 // Create a copy from the zero register to materialize a "0" value.
225 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
226 : &AArch64::GPR32RegClass;
227 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
228 unsigned ResultReg = createResultReg(RC);
229 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
230 TII.get(TargetOpcode::COPY), ResultReg)
231 .addReg(ZeroReg, getKillRegState(true));
235 unsigned AArch64FastISel::AArch64MaterializeFP(const ConstantFP *CFP, MVT VT) {
236 if (VT != MVT::f32 && VT != MVT::f64)
239 const APFloat Val = CFP->getValueAPF();
240 bool Is64Bit = (VT == MVT::f64);
242 // This checks to see if we can use FMOV instructions to materialize
243 // a constant, otherwise we have to materialize via the constant pool.
244 if (TLI.isFPImmLegal(Val, VT)) {
245 int Imm = Is64Bit ? AArch64_AM::getFP64Imm(Val)
246 : AArch64_AM::getFP32Imm(Val);
247 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
248 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
249 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
254 // Materialize via constant pool. MachineConstantPool wants an explicit
256 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
258 Align = DL.getTypeAllocSize(CFP->getType());
260 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
261 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
262 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
264 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
266 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
267 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
268 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
270 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
274 unsigned AArch64FastISel::AArch64MaterializeGV(const GlobalValue *GV) {
275 // We can't handle thread-local variables quickly yet.
276 if (GV->isThreadLocal())
279 // MachO still uses GOT for large code-model accesses, but ELF requires
280 // movz/movk sequences, which FastISel doesn't handle yet.
281 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
284 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
286 EVT DestEVT = TLI.getValueType(GV->getType(), true);
287 if (!DestEVT.isSimple())
290 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
293 if (OpFlags & AArch64II::MO_GOT) {
295 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
297 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
299 ResultReg = createResultReg(&AArch64::GPR64RegClass);
300 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
303 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
307 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
309 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
311 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
312 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
315 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
321 unsigned AArch64FastISel::TargetMaterializeConstant(const Constant *C) {
322 EVT CEVT = TLI.getValueType(C->getType(), true);
324 // Only handle simple types.
325 if (!CEVT.isSimple())
327 MVT VT = CEVT.getSimpleVT();
329 if (const auto *CI = dyn_cast<ConstantInt>(C))
330 return AArch64MaterializeInt(CI, VT);
331 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
332 return AArch64MaterializeFP(CFP, VT);
333 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
334 return AArch64MaterializeGV(GV);
339 // Computes the address to get to an object.
340 bool AArch64FastISel::ComputeAddress(const Value *Obj, Address &Addr) {
341 const User *U = nullptr;
342 unsigned Opcode = Instruction::UserOp1;
343 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
344 // Don't walk into other basic blocks unless the object is an alloca from
345 // another block, otherwise it may not have a virtual register assigned.
346 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
347 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
348 Opcode = I->getOpcode();
351 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
352 Opcode = C->getOpcode();
356 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
357 if (Ty->getAddressSpace() > 255)
358 // Fast instruction selection doesn't support the special
365 case Instruction::BitCast: {
366 // Look through bitcasts.
367 return ComputeAddress(U->getOperand(0), Addr);
369 case Instruction::IntToPtr: {
370 // Look past no-op inttoptrs.
371 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
372 return ComputeAddress(U->getOperand(0), Addr);
375 case Instruction::PtrToInt: {
376 // Look past no-op ptrtoints.
377 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
378 return ComputeAddress(U->getOperand(0), Addr);
381 case Instruction::GetElementPtr: {
382 Address SavedAddr = Addr;
383 uint64_t TmpOffset = Addr.getOffset();
385 // Iterate through the GEP folding the constants into offsets where
387 gep_type_iterator GTI = gep_type_begin(U);
388 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
390 const Value *Op = *i;
391 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
392 const StructLayout *SL = DL.getStructLayout(STy);
393 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
394 TmpOffset += SL->getElementOffset(Idx);
396 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
398 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
399 // Constant-offset addressing.
400 TmpOffset += CI->getSExtValue() * S;
403 if (canFoldAddIntoGEP(U, Op)) {
404 // A compatible add with a constant operand. Fold the constant.
406 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
407 TmpOffset += CI->getSExtValue() * S;
408 // Iterate on the other operand.
409 Op = cast<AddOperator>(Op)->getOperand(0);
413 goto unsupported_gep;
418 // Try to grab the base operand now.
419 Addr.setOffset(TmpOffset);
420 if (ComputeAddress(U->getOperand(0), Addr))
423 // We failed, restore everything and try the other options.
429 case Instruction::Alloca: {
430 const AllocaInst *AI = cast<AllocaInst>(Obj);
431 DenseMap<const AllocaInst *, int>::iterator SI =
432 FuncInfo.StaticAllocaMap.find(AI);
433 if (SI != FuncInfo.StaticAllocaMap.end()) {
434 Addr.setKind(Address::FrameIndexBase);
435 Addr.setFI(SI->second);
440 case Instruction::Add:
441 // Adds of constants are common and easy enough.
442 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
443 Addr.setOffset(Addr.getOffset() + (uint64_t)CI->getSExtValue());
444 return ComputeAddress(U->getOperand(0), Addr);
449 // Try to get this in a register if nothing else has worked.
451 Addr.setReg(getRegForValue(Obj));
452 return Addr.isValid();
455 bool AArch64FastISel::ComputeCallAddress(const Value *V, Address &Addr) {
456 const User *U = nullptr;
457 unsigned Opcode = Instruction::UserOp1;
460 if (const auto *I = dyn_cast<Instruction>(V)) {
461 Opcode = I->getOpcode();
463 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
464 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
465 Opcode = C->getOpcode();
471 case Instruction::BitCast:
472 // Look past bitcasts if its operand is in the same BB.
474 return ComputeCallAddress(U->getOperand(0), Addr);
476 case Instruction::IntToPtr:
477 // Look past no-op inttoptrs if its operand is in the same BB.
479 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
480 return ComputeCallAddress(U->getOperand(0), Addr);
482 case Instruction::PtrToInt:
483 // Look past no-op ptrtoints if its operand is in the same BB.
485 TLI.getValueType(U->getType()) == TLI.getPointerTy())
486 return ComputeCallAddress(U->getOperand(0), Addr);
490 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
491 Addr.setGlobalValue(GV);
495 // If all else fails, try to materialize the value in a register.
496 if (!Addr.getGlobalValue()) {
497 Addr.setReg(getRegForValue(V));
498 return Addr.getReg() != 0;
505 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
506 EVT evt = TLI.getValueType(Ty, true);
508 // Only handle simple types.
509 if (evt == MVT::Other || !evt.isSimple())
511 VT = evt.getSimpleVT();
513 // This is a legal type, but it's not something we handle in fast-isel.
517 // Handle all other legal types, i.e. a register that will directly hold this
519 return TLI.isTypeLegal(VT);
522 bool AArch64FastISel::isLoadStoreTypeLegal(Type *Ty, MVT &VT) {
523 if (isTypeLegal(Ty, VT))
526 // If this is a type than can be sign or zero-extended to a basic operation
527 // go ahead and accept it now. For stores, this reflects truncation.
528 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
534 bool AArch64FastISel::SimplifyAddress(Address &Addr, MVT VT,
535 int64_t ScaleFactor, bool UseUnscaled) {
536 bool needsLowering = false;
537 int64_t Offset = Addr.getOffset();
538 switch (VT.SimpleTy) {
549 // Using scaled, 12-bit, unsigned immediate offsets.
550 needsLowering = ((Offset & 0xfff) != Offset);
552 // Using unscaled, 9-bit, signed immediate offsets.
553 needsLowering = (Offset > 256 || Offset < -256);
557 //If this is a stack pointer and the offset needs to be simplified then put
558 // the alloca address into a register, set the base type back to register and
559 // continue. This should almost never happen.
560 if (needsLowering && Addr.getKind() == Address::FrameIndexBase) {
561 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
564 .addFrameIndex(Addr.getFI())
567 Addr.setKind(Address::RegBase);
568 Addr.setReg(ResultReg);
571 // Since the offset is too large for the load/store instruction get the
572 // reg+offset into a register.
574 uint64_t UnscaledOffset = Addr.getOffset() * ScaleFactor;
575 unsigned ResultReg = FastEmit_ri_(MVT::i64, ISD::ADD, Addr.getReg(), false,
576 UnscaledOffset, MVT::i64);
579 Addr.setReg(ResultReg);
585 void AArch64FastISel::AddLoadStoreOperands(Address &Addr,
586 const MachineInstrBuilder &MIB,
588 MachineMemOperand *MMO,
590 int64_t Offset = Addr.getOffset();
591 // Frame base works a bit differently. Handle it separately.
592 if (Addr.getKind() == Address::FrameIndexBase) {
593 int FI = Addr.getFI();
594 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
595 // and alignment should be based on the VT.
596 MMO = FuncInfo.MF->getMachineMemOperand(
597 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
598 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
599 // Now add the rest of the operands.
600 MIB.addFrameIndex(FI).addImm(Offset);
602 // Now add the rest of the operands.
603 MIB.addReg(Addr.getReg());
608 MIB.addMemOperand(MMO);
611 bool AArch64FastISel::EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
612 MachineMemOperand *MMO, bool UseUnscaled) {
613 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
614 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
615 if (!UseUnscaled && Addr.getOffset() < 0)
619 const TargetRegisterClass *RC;
621 int64_t ScaleFactor = 0;
622 switch (VT.SimpleTy) {
627 // Intentional fall-through.
629 Opc = UseUnscaled ? AArch64::LDURBBi : AArch64::LDRBBui;
630 RC = &AArch64::GPR32RegClass;
634 Opc = UseUnscaled ? AArch64::LDURHHi : AArch64::LDRHHui;
635 RC = &AArch64::GPR32RegClass;
639 Opc = UseUnscaled ? AArch64::LDURWi : AArch64::LDRWui;
640 RC = &AArch64::GPR32RegClass;
644 Opc = UseUnscaled ? AArch64::LDURXi : AArch64::LDRXui;
645 RC = &AArch64::GPR64RegClass;
649 Opc = UseUnscaled ? AArch64::LDURSi : AArch64::LDRSui;
650 RC = TLI.getRegClassFor(VT);
654 Opc = UseUnscaled ? AArch64::LDURDi : AArch64::LDRDui;
655 RC = TLI.getRegClassFor(VT);
661 int64_t Offset = Addr.getOffset();
662 if (Offset & (ScaleFactor - 1))
663 // Retry using an unscaled, 9-bit, signed immediate offset.
664 return EmitLoad(VT, ResultReg, Addr, MMO, /*UseUnscaled*/ true);
666 Addr.setOffset(Offset / ScaleFactor);
669 // Simplify this down to something we can handle.
670 if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
673 // Create the base instruction, then add the operands.
674 ResultReg = createResultReg(RC);
675 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
676 TII.get(Opc), ResultReg);
677 AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, MMO, UseUnscaled);
679 // Loading an i1 requires special handling.
681 MRI.constrainRegClass(ResultReg, &AArch64::GPR32RegClass);
682 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
683 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
686 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
692 bool AArch64FastISel::SelectLoad(const Instruction *I) {
694 // Verify we have a legal type before going any further. Currently, we handle
695 // simple types that will directly fit in a register (i32/f32/i64/f64) or
696 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
697 if (!isLoadStoreTypeLegal(I->getType(), VT) || cast<LoadInst>(I)->isAtomic())
700 // See if we can handle this address.
702 if (!ComputeAddress(I->getOperand(0), Addr))
706 if (!EmitLoad(VT, ResultReg, Addr, createMachineMemOperandFor(I)))
709 UpdateValueMap(I, ResultReg);
713 bool AArch64FastISel::EmitStore(MVT VT, unsigned SrcReg, Address Addr,
714 MachineMemOperand *MMO, bool UseUnscaled) {
715 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
716 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
717 if (!UseUnscaled && Addr.getOffset() < 0)
722 int64_t ScaleFactor = 0;
723 // Using scaled, 12-bit, unsigned immediate offsets.
724 switch (VT.SimpleTy) {
730 StrOpc = UseUnscaled ? AArch64::STURBBi : AArch64::STRBBui;
734 StrOpc = UseUnscaled ? AArch64::STURHHi : AArch64::STRHHui;
738 StrOpc = UseUnscaled ? AArch64::STURWi : AArch64::STRWui;
742 StrOpc = UseUnscaled ? AArch64::STURXi : AArch64::STRXui;
746 StrOpc = UseUnscaled ? AArch64::STURSi : AArch64::STRSui;
750 StrOpc = UseUnscaled ? AArch64::STURDi : AArch64::STRDui;
756 int64_t Offset = Addr.getOffset();
757 if (Offset & (ScaleFactor - 1))
758 // Retry using an unscaled, 9-bit, signed immediate offset.
759 return EmitStore(VT, SrcReg, Addr, MMO, /*UseUnscaled*/ true);
761 Addr.setOffset(Offset / ScaleFactor);
764 // Simplify this down to something we can handle.
765 if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
768 // Storing an i1 requires special handling.
770 MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
771 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
772 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
775 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
778 // Create the base instruction, then add the operands.
779 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
780 TII.get(StrOpc)).addReg(SrcReg);
781 AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, MMO, UseUnscaled);
786 bool AArch64FastISel::SelectStore(const Instruction *I) {
788 Value *Op0 = I->getOperand(0);
789 // Verify we have a legal type before going any further. Currently, we handle
790 // simple types that will directly fit in a register (i32/f32/i64/f64) or
791 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
792 if (!isLoadStoreTypeLegal(Op0->getType(), VT) ||
793 cast<StoreInst>(I)->isAtomic())
796 // Get the value to be stored into a register.
797 unsigned SrcReg = getRegForValue(Op0);
801 // See if we can handle this address.
803 if (!ComputeAddress(I->getOperand(1), Addr))
806 if (!EmitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
811 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
813 case CmpInst::FCMP_ONE:
814 case CmpInst::FCMP_UEQ:
816 // AL is our "false" for now. The other two need more compares.
817 return AArch64CC::AL;
818 case CmpInst::ICMP_EQ:
819 case CmpInst::FCMP_OEQ:
820 return AArch64CC::EQ;
821 case CmpInst::ICMP_SGT:
822 case CmpInst::FCMP_OGT:
823 return AArch64CC::GT;
824 case CmpInst::ICMP_SGE:
825 case CmpInst::FCMP_OGE:
826 return AArch64CC::GE;
827 case CmpInst::ICMP_UGT:
828 case CmpInst::FCMP_UGT:
829 return AArch64CC::HI;
830 case CmpInst::FCMP_OLT:
831 return AArch64CC::MI;
832 case CmpInst::ICMP_ULE:
833 case CmpInst::FCMP_OLE:
834 return AArch64CC::LS;
835 case CmpInst::FCMP_ORD:
836 return AArch64CC::VC;
837 case CmpInst::FCMP_UNO:
838 return AArch64CC::VS;
839 case CmpInst::FCMP_UGE:
840 return AArch64CC::PL;
841 case CmpInst::ICMP_SLT:
842 case CmpInst::FCMP_ULT:
843 return AArch64CC::LT;
844 case CmpInst::ICMP_SLE:
845 case CmpInst::FCMP_ULE:
846 return AArch64CC::LE;
847 case CmpInst::FCMP_UNE:
848 case CmpInst::ICMP_NE:
849 return AArch64CC::NE;
850 case CmpInst::ICMP_UGE:
851 return AArch64CC::HS;
852 case CmpInst::ICMP_ULT:
853 return AArch64CC::LO;
857 bool AArch64FastISel::SelectBranch(const Instruction *I) {
858 const BranchInst *BI = cast<BranchInst>(I);
859 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
860 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
862 AArch64CC::CondCode CC = AArch64CC::NE;
863 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
864 if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
865 // We may not handle every CC for now.
866 CC = getCompareCC(CI->getPredicate());
867 if (CC == AArch64CC::AL)
871 if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
875 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
879 // Obtain the branch weight and add the TrueBB to the successor list.
880 uint32_t BranchWeight = 0;
882 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
883 TBB->getBasicBlock());
884 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
886 FastEmitBranch(FBB, DbgLoc);
889 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
891 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
892 (isLoadStoreTypeLegal(TI->getOperand(0)->getType(), SrcVT))) {
893 unsigned CondReg = getRegForValue(TI->getOperand(0));
897 // Issue an extract_subreg to get the lower 32-bits.
898 if (SrcVT == MVT::i64)
899 CondReg = FastEmitInst_extractsubreg(MVT::i32, CondReg, /*Kill=*/true,
902 MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
903 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
904 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
905 TII.get(AArch64::ANDWri), ANDReg)
907 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
908 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
909 TII.get(AArch64::SUBSWri))
915 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
919 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
923 // Obtain the branch weight and add the TrueBB to the successor list.
924 uint32_t BranchWeight = 0;
926 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
927 TBB->getBasicBlock());
928 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
930 FastEmitBranch(FBB, DbgLoc);
933 } else if (const ConstantInt *CI =
934 dyn_cast<ConstantInt>(BI->getCondition())) {
935 uint64_t Imm = CI->getZExtValue();
936 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
937 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
940 // Obtain the branch weight and add the target to the successor list.
941 uint32_t BranchWeight = 0;
943 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
944 Target->getBasicBlock());
945 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
947 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
948 // Fake request the condition, otherwise the intrinsic might be completely
950 unsigned CondReg = getRegForValue(BI->getCondition());
955 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
959 // Obtain the branch weight and add the TrueBB to the successor list.
960 uint32_t BranchWeight = 0;
962 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
963 TBB->getBasicBlock());
964 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
966 FastEmitBranch(FBB, DbgLoc);
970 unsigned CondReg = getRegForValue(BI->getCondition());
974 // We've been divorced from our compare! Our block was split, and
975 // now our compare lives in a predecessor block. We musn't
976 // re-compare here, as the children of the compare aren't guaranteed
977 // live across the block boundary (we *could* check for this).
978 // Regardless, the compare has been done in the predecessor block,
979 // and it left a value for us in a virtual register. Ergo, we test
980 // the one-bit value left in the virtual register.
981 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri),
987 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
992 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
996 // Obtain the branch weight and add the TrueBB to the successor list.
997 uint32_t BranchWeight = 0;
999 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1000 TBB->getBasicBlock());
1001 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1003 FastEmitBranch(FBB, DbgLoc);
1007 bool AArch64FastISel::SelectIndirectBr(const Instruction *I) {
1008 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
1009 unsigned AddrReg = getRegForValue(BI->getOperand(0));
1013 // Emit the indirect branch.
1014 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BR))
1017 // Make sure the CFG is up-to-date.
1018 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
1019 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
1024 bool AArch64FastISel::EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt) {
1025 Type *Ty = Src1Value->getType();
1026 EVT SrcEVT = TLI.getValueType(Ty, true);
1027 if (!SrcEVT.isSimple())
1029 MVT SrcVT = SrcEVT.getSimpleVT();
1031 // Check to see if the 2nd operand is a constant that we can encode directly
1034 bool UseImm = false;
1035 bool isNegativeImm = false;
1036 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
1037 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
1038 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1039 const APInt &CIVal = ConstInt->getValue();
1041 Imm = (isZExt) ? CIVal.getZExtValue() : CIVal.getSExtValue();
1042 if (CIVal.isNegative()) {
1043 isNegativeImm = true;
1046 // FIXME: We can handle more immediates using shifts.
1047 UseImm = ((Imm & 0xfff) == Imm);
1049 } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
1050 if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
1051 if (ConstFP->isZero() && !ConstFP->isNegative())
1058 bool needsExt = false;
1059 switch (SrcVT.SimpleTy) {
1066 // Intentional fall-through.
1068 ZReg = AArch64::WZR;
1070 CmpOpc = isNegativeImm ? AArch64::ADDSWri : AArch64::SUBSWri;
1072 CmpOpc = AArch64::SUBSWrr;
1075 ZReg = AArch64::XZR;
1077 CmpOpc = isNegativeImm ? AArch64::ADDSXri : AArch64::SUBSXri;
1079 CmpOpc = AArch64::SUBSXrr;
1083 CmpOpc = UseImm ? AArch64::FCMPSri : AArch64::FCMPSrr;
1087 CmpOpc = UseImm ? AArch64::FCMPDri : AArch64::FCMPDrr;
1091 unsigned SrcReg1 = getRegForValue(Src1Value);
1097 SrcReg2 = getRegForValue(Src2Value);
1102 // We have i1, i8, or i16, we need to either zero extend or sign extend.
1104 SrcReg1 = EmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
1108 SrcReg2 = EmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
1116 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
1122 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
1128 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
1131 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
1138 bool AArch64FastISel::SelectCmp(const Instruction *I) {
1139 const CmpInst *CI = cast<CmpInst>(I);
1141 // We may not handle every CC for now.
1142 AArch64CC::CondCode CC = getCompareCC(CI->getPredicate());
1143 if (CC == AArch64CC::AL)
1147 if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1150 // Now set a register based on the comparison.
1151 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
1152 unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
1153 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
1155 .addReg(AArch64::WZR)
1156 .addReg(AArch64::WZR)
1157 .addImm(invertedCC);
1159 UpdateValueMap(I, ResultReg);
1163 bool AArch64FastISel::SelectSelect(const Instruction *I) {
1164 const SelectInst *SI = cast<SelectInst>(I);
1166 EVT DestEVT = TLI.getValueType(SI->getType(), true);
1167 if (!DestEVT.isSimple())
1170 MVT DestVT = DestEVT.getSimpleVT();
1171 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
1176 switch (DestVT.SimpleTy) {
1177 default: return false;
1178 case MVT::i32: SelectOpc = AArch64::CSELWr; break;
1179 case MVT::i64: SelectOpc = AArch64::CSELXr; break;
1180 case MVT::f32: SelectOpc = AArch64::FCSELSrrr; break;
1181 case MVT::f64: SelectOpc = AArch64::FCSELDrrr; break;
1184 const Value *Cond = SI->getCondition();
1185 bool NeedTest = true;
1186 AArch64CC::CondCode CC = AArch64CC::NE;
1187 if (foldXALUIntrinsic(CC, I, Cond))
1190 unsigned CondReg = getRegForValue(Cond);
1193 bool CondIsKill = hasTrivialKill(Cond);
1196 MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
1197 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
1198 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1200 .addReg(CondReg, getKillRegState(CondIsKill))
1201 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
1203 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri))
1210 unsigned TrueReg = getRegForValue(SI->getTrueValue());
1211 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
1213 unsigned FalseReg = getRegForValue(SI->getFalseValue());
1214 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
1216 if (!TrueReg || !FalseReg)
1219 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1220 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SelectOpc),
1222 .addReg(TrueReg, getKillRegState(TrueIsKill))
1223 .addReg(FalseReg, getKillRegState(FalseIsKill))
1226 UpdateValueMap(I, ResultReg);
1230 bool AArch64FastISel::SelectFPExt(const Instruction *I) {
1231 Value *V = I->getOperand(0);
1232 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
1235 unsigned Op = getRegForValue(V);
1239 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
1240 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
1241 ResultReg).addReg(Op);
1242 UpdateValueMap(I, ResultReg);
1246 bool AArch64FastISel::SelectFPTrunc(const Instruction *I) {
1247 Value *V = I->getOperand(0);
1248 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
1251 unsigned Op = getRegForValue(V);
1255 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
1256 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
1257 ResultReg).addReg(Op);
1258 UpdateValueMap(I, ResultReg);
1262 // FPToUI and FPToSI
1263 bool AArch64FastISel::SelectFPToInt(const Instruction *I, bool Signed) {
1265 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1268 unsigned SrcReg = getRegForValue(I->getOperand(0));
1272 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1273 if (SrcVT == MVT::f128)
1277 if (SrcVT == MVT::f64) {
1279 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
1281 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
1284 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
1286 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
1288 unsigned ResultReg = createResultReg(
1289 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
1290 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1292 UpdateValueMap(I, ResultReg);
1296 bool AArch64FastISel::SelectIntToFP(const Instruction *I, bool Signed) {
1298 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1300 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
1301 "Unexpected value type.");
1303 unsigned SrcReg = getRegForValue(I->getOperand(0));
1307 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1309 // Handle sign-extension.
1310 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1312 EmitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
1317 MRI.constrainRegClass(SrcReg, SrcVT == MVT::i64 ? &AArch64::GPR64RegClass
1318 : &AArch64::GPR32RegClass);
1321 if (SrcVT == MVT::i64) {
1323 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
1325 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
1328 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
1330 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
1333 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1334 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1336 UpdateValueMap(I, ResultReg);
1340 bool AArch64FastISel::FastLowerArguments() {
1341 if (!FuncInfo.CanLowerReturn)
1344 const Function *F = FuncInfo.Fn;
1348 CallingConv::ID CC = F->getCallingConv();
1349 if (CC != CallingConv::C)
1352 // Only handle simple cases like i1/i8/i16/i32/i64/f32/f64 of up to 8 GPR and
1354 unsigned GPRCnt = 0;
1355 unsigned FPRCnt = 0;
1357 for (auto const &Arg : F->args()) {
1358 // The first argument is at index 1.
1360 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1361 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1362 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1363 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1366 Type *ArgTy = Arg.getType();
1367 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1370 EVT ArgVT = TLI.getValueType(ArgTy);
1371 if (!ArgVT.isSimple()) return false;
1372 switch (ArgVT.getSimpleVT().SimpleTy) {
1373 default: return false;
1388 if (GPRCnt > 8 || FPRCnt > 8)
1392 static const MCPhysReg Registers[5][8] = {
1393 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
1394 AArch64::W5, AArch64::W6, AArch64::W7 },
1395 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
1396 AArch64::X5, AArch64::X6, AArch64::X7 },
1397 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
1398 AArch64::H5, AArch64::H6, AArch64::H7 },
1399 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
1400 AArch64::S5, AArch64::S6, AArch64::S7 },
1401 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
1402 AArch64::D5, AArch64::D6, AArch64::D7 }
1405 unsigned GPRIdx = 0;
1406 unsigned FPRIdx = 0;
1407 for (auto const &Arg : F->args()) {
1408 MVT VT = TLI.getSimpleValueType(Arg.getType());
1410 switch (VT.SimpleTy) {
1411 default: llvm_unreachable("Unexpected value type.");
1414 case MVT::i16: VT = MVT::i32; // fall-through
1415 case MVT::i32: SrcReg = Registers[0][GPRIdx++]; break;
1416 case MVT::i64: SrcReg = Registers[1][GPRIdx++]; break;
1417 case MVT::f16: SrcReg = Registers[2][FPRIdx++]; break;
1418 case MVT::f32: SrcReg = Registers[3][FPRIdx++]; break;
1419 case MVT::f64: SrcReg = Registers[4][FPRIdx++]; break;
1422 // Skip unused arguments.
1423 if (Arg.use_empty()) {
1424 UpdateValueMap(&Arg, 0);
1428 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1429 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1430 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1431 // Without this, EmitLiveInCopies may eliminate the livein if its only
1432 // use is a bitcast (which isn't turned into an instruction).
1433 unsigned ResultReg = createResultReg(RC);
1434 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1435 TII.get(TargetOpcode::COPY), ResultReg)
1436 .addReg(DstReg, getKillRegState(true));
1437 UpdateValueMap(&Arg, ResultReg);
1442 bool AArch64FastISel::ProcessCallArgs(CallLoweringInfo &CLI,
1443 SmallVectorImpl<MVT> &OutVTs,
1444 unsigned &NumBytes) {
1445 CallingConv::ID CC = CLI.CallConv;
1446 SmallVector<CCValAssign, 16> ArgLocs;
1447 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
1448 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
1450 // Get a count of how many bytes are to be pushed on the stack.
1451 NumBytes = CCInfo.getNextStackOffset();
1453 // Issue CALLSEQ_START
1454 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1455 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
1458 // Process the args.
1459 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1460 CCValAssign &VA = ArgLocs[i];
1461 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
1462 MVT ArgVT = OutVTs[VA.getValNo()];
1464 unsigned ArgReg = getRegForValue(ArgVal);
1468 // Handle arg promotion: SExt, ZExt, AExt.
1469 switch (VA.getLocInfo()) {
1470 case CCValAssign::Full:
1472 case CCValAssign::SExt: {
1473 MVT DestVT = VA.getLocVT();
1475 ArgReg = EmitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
1480 case CCValAssign::AExt:
1481 // Intentional fall-through.
1482 case CCValAssign::ZExt: {
1483 MVT DestVT = VA.getLocVT();
1485 ArgReg = EmitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
1491 llvm_unreachable("Unknown arg promotion!");
1494 // Now copy/store arg to correct locations.
1495 if (VA.isRegLoc() && !VA.needsCustom()) {
1496 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1497 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
1498 CLI.OutRegs.push_back(VA.getLocReg());
1499 } else if (VA.needsCustom()) {
1500 // FIXME: Handle custom args.
1503 assert(VA.isMemLoc() && "Assuming store on stack.");
1505 // Don't emit stores for undef values.
1506 if (isa<UndefValue>(ArgVal))
1509 // Need to store on the stack.
1510 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
1512 unsigned BEAlign = 0;
1513 if (ArgSize < 8 && !Subtarget->isLittleEndian())
1514 BEAlign = 8 - ArgSize;
1517 Addr.setKind(Address::RegBase);
1518 Addr.setReg(AArch64::SP);
1519 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
1521 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
1522 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
1523 MachinePointerInfo::getStack(Addr.getOffset()),
1524 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
1526 if (!EmitStore(ArgVT, ArgReg, Addr, MMO))
1533 bool AArch64FastISel::FinishCall(CallLoweringInfo &CLI, MVT RetVT,
1534 unsigned NumBytes) {
1535 CallingConv::ID CC = CLI.CallConv;
1537 // Issue CALLSEQ_END
1538 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1539 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
1540 .addImm(NumBytes).addImm(0);
1542 // Now the return value.
1543 if (RetVT != MVT::isVoid) {
1544 SmallVector<CCValAssign, 16> RVLocs;
1545 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
1546 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
1548 // Only handle a single return value.
1549 if (RVLocs.size() != 1)
1552 // Copy all of the result registers out of their specified physreg.
1553 MVT CopyVT = RVLocs[0].getValVT();
1554 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
1555 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1556 TII.get(TargetOpcode::COPY), ResultReg)
1557 .addReg(RVLocs[0].getLocReg());
1558 CLI.InRegs.push_back(RVLocs[0].getLocReg());
1560 CLI.ResultReg = ResultReg;
1561 CLI.NumResultRegs = 1;
1567 bool AArch64FastISel::FastLowerCall(CallLoweringInfo &CLI) {
1568 CallingConv::ID CC = CLI.CallConv;
1569 bool IsTailCall = CLI.IsTailCall;
1570 bool IsVarArg = CLI.IsVarArg;
1571 const Value *Callee = CLI.Callee;
1572 const char *SymName = CLI.SymName;
1574 // Allow SelectionDAG isel to handle tail calls.
1578 CodeModel::Model CM = TM.getCodeModel();
1579 // Only support the small and large code model.
1580 if (CM != CodeModel::Small && CM != CodeModel::Large)
1583 // FIXME: Add large code model support for ELF.
1584 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
1587 // Let SDISel handle vararg functions.
1591 // FIXME: Only handle *simple* calls for now.
1593 if (CLI.RetTy->isVoidTy())
1594 RetVT = MVT::isVoid;
1595 else if (!isTypeLegal(CLI.RetTy, RetVT))
1598 for (auto Flag : CLI.OutFlags)
1599 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
1602 // Set up the argument vectors.
1603 SmallVector<MVT, 16> OutVTs;
1604 OutVTs.reserve(CLI.OutVals.size());
1606 for (auto *Val : CLI.OutVals) {
1608 if (!isTypeLegal(Val->getType(), VT) &&
1609 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
1612 // We don't handle vector parameters yet.
1613 if (VT.isVector() || VT.getSizeInBits() > 64)
1616 OutVTs.push_back(VT);
1620 if (!ComputeCallAddress(Callee, Addr))
1623 // Handle the arguments now that we've gotten them.
1625 if (!ProcessCallArgs(CLI, OutVTs, NumBytes))
1629 MachineInstrBuilder MIB;
1630 if (CM == CodeModel::Small) {
1631 unsigned CallOpc = Addr.getReg() ? AArch64::BLR : AArch64::BL;
1632 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
1634 MIB.addExternalSymbol(SymName, 0);
1635 else if (Addr.getGlobalValue())
1636 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
1637 else if (Addr.getReg())
1638 MIB.addReg(Addr.getReg());
1642 unsigned CallReg = 0;
1644 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
1645 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
1647 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
1649 CallReg = createResultReg(&AArch64::GPR64RegClass);
1650 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
1653 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
1655 } else if (Addr.getGlobalValue()) {
1656 CallReg = AArch64MaterializeGV(Addr.getGlobalValue());
1657 } else if (Addr.getReg())
1658 CallReg = Addr.getReg();
1663 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1664 TII.get(AArch64::BLR)).addReg(CallReg);
1667 // Add implicit physical register uses to the call.
1668 for (auto Reg : CLI.OutRegs)
1669 MIB.addReg(Reg, RegState::Implicit);
1671 // Add a register mask with the call-preserved registers.
1672 // Proper defs for return values will be added by setPhysRegsDeadExcept().
1673 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1677 // Finish off the call including any return values.
1678 return FinishCall(CLI, RetVT, NumBytes);
1681 bool AArch64FastISel::IsMemCpySmall(uint64_t Len, unsigned Alignment) {
1683 return Len / Alignment <= 4;
1688 bool AArch64FastISel::TryEmitSmallMemCpy(Address Dest, Address Src,
1689 uint64_t Len, unsigned Alignment) {
1690 // Make sure we don't bloat code by inlining very large memcpy's.
1691 if (!IsMemCpySmall(Len, Alignment))
1694 int64_t UnscaledOffset = 0;
1695 Address OrigDest = Dest;
1696 Address OrigSrc = Src;
1700 if (!Alignment || Alignment >= 8) {
1711 // Bound based on alignment.
1712 if (Len >= 4 && Alignment == 4)
1714 else if (Len >= 2 && Alignment == 2)
1723 RV = EmitLoad(VT, ResultReg, Src);
1727 RV = EmitStore(VT, ResultReg, Dest);
1731 int64_t Size = VT.getSizeInBits() / 8;
1733 UnscaledOffset += Size;
1735 // We need to recompute the unscaled offset for each iteration.
1736 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
1737 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
1743 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
1744 /// into the user. The condition code will only be updated on success.
1745 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
1746 const Instruction *I,
1747 const Value *Cond) {
1748 if (!isa<ExtractValueInst>(Cond))
1751 const auto *EV = cast<ExtractValueInst>(Cond);
1752 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
1755 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
1757 const Function *Callee = II->getCalledFunction();
1759 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
1760 if (!isTypeLegal(RetTy, RetVT))
1763 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1766 AArch64CC::CondCode TmpCC;
1767 switch (II->getIntrinsicID()) {
1768 default: return false;
1769 case Intrinsic::sadd_with_overflow:
1770 case Intrinsic::ssub_with_overflow: TmpCC = AArch64CC::VS; break;
1771 case Intrinsic::uadd_with_overflow: TmpCC = AArch64CC::HS; break;
1772 case Intrinsic::usub_with_overflow: TmpCC = AArch64CC::LO; break;
1773 case Intrinsic::smul_with_overflow:
1774 case Intrinsic::umul_with_overflow: TmpCC = AArch64CC::NE; break;
1777 // Check if both instructions are in the same basic block.
1778 if (II->getParent() != I->getParent())
1781 // Make sure nothing is in the way
1782 BasicBlock::const_iterator Start = I;
1783 BasicBlock::const_iterator End = II;
1784 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
1785 // We only expect extractvalue instructions between the intrinsic and the
1786 // instruction to be selected.
1787 if (!isa<ExtractValueInst>(Itr))
1790 // Check that the extractvalue operand comes from the intrinsic.
1791 const auto *EVI = cast<ExtractValueInst>(Itr);
1792 if (EVI->getAggregateOperand() != II)
1800 bool AArch64FastISel::FastLowerIntrinsicCall(const IntrinsicInst *II) {
1801 // FIXME: Handle more intrinsics.
1802 switch (II->getIntrinsicID()) {
1803 default: return false;
1804 case Intrinsic::frameaddress: {
1805 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
1806 MFI->setFrameAddressIsTaken(true);
1808 const AArch64RegisterInfo *RegInfo =
1809 static_cast<const AArch64RegisterInfo *>(
1810 TM.getSubtargetImpl()->getRegisterInfo());
1811 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
1812 unsigned SrcReg = FramePtr;
1814 // Recursively load frame address
1820 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
1822 DestReg = createResultReg(&AArch64::GPR64RegClass);
1823 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1824 TII.get(AArch64::LDRXui), DestReg)
1825 .addReg(SrcReg).addImm(0);
1829 UpdateValueMap(II, SrcReg);
1832 case Intrinsic::memcpy:
1833 case Intrinsic::memmove: {
1834 const auto *MTI = cast<MemTransferInst>(II);
1835 // Don't handle volatile.
1836 if (MTI->isVolatile())
1839 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
1840 // we would emit dead code because we don't currently handle memmoves.
1841 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
1842 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
1843 // Small memcpy's are common enough that we want to do them without a call
1845 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
1846 unsigned Alignment = MTI->getAlignment();
1847 if (IsMemCpySmall(Len, Alignment)) {
1849 if (!ComputeAddress(MTI->getRawDest(), Dest) ||
1850 !ComputeAddress(MTI->getRawSource(), Src))
1852 if (TryEmitSmallMemCpy(Dest, Src, Len, Alignment))
1857 if (!MTI->getLength()->getType()->isIntegerTy(64))
1860 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
1861 // Fast instruction selection doesn't support the special
1865 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
1866 return LowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
1868 case Intrinsic::memset: {
1869 const MemSetInst *MSI = cast<MemSetInst>(II);
1870 // Don't handle volatile.
1871 if (MSI->isVolatile())
1874 if (!MSI->getLength()->getType()->isIntegerTy(64))
1877 if (MSI->getDestAddressSpace() > 255)
1878 // Fast instruction selection doesn't support the special
1882 return LowerCallTo(II, "memset", II->getNumArgOperands() - 2);
1884 case Intrinsic::trap: {
1885 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
1889 case Intrinsic::sqrt: {
1890 Type *RetTy = II->getCalledFunction()->getReturnType();
1893 if (!isTypeLegal(RetTy, VT))
1896 unsigned Op0Reg = getRegForValue(II->getOperand(0));
1899 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
1901 unsigned ResultReg = FastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
1905 UpdateValueMap(II, ResultReg);
1908 case Intrinsic::sadd_with_overflow:
1909 case Intrinsic::uadd_with_overflow:
1910 case Intrinsic::ssub_with_overflow:
1911 case Intrinsic::usub_with_overflow:
1912 case Intrinsic::smul_with_overflow:
1913 case Intrinsic::umul_with_overflow: {
1914 // This implements the basic lowering of the xalu with overflow intrinsics.
1915 const Function *Callee = II->getCalledFunction();
1916 auto *Ty = cast<StructType>(Callee->getReturnType());
1917 Type *RetTy = Ty->getTypeAtIndex(0U);
1918 Type *CondTy = Ty->getTypeAtIndex(1);
1921 if (!isTypeLegal(RetTy, VT))
1924 if (VT != MVT::i32 && VT != MVT::i64)
1927 const Value *LHS = II->getArgOperand(0);
1928 const Value *RHS = II->getArgOperand(1);
1929 // Canonicalize immediate to the RHS.
1930 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
1931 isCommutativeIntrinsic(II))
1932 std::swap(LHS, RHS);
1934 unsigned LHSReg = getRegForValue(LHS);
1937 bool LHSIsKill = hasTrivialKill(LHS);
1939 // Check if the immediate can be encoded in the instruction and if we should
1940 // invert the instruction (adds -> subs) to handle negative immediates.
1941 bool UseImm = false;
1942 bool UseInverse = false;
1944 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1945 if (C->isNegative()) {
1947 Imm = -(C->getSExtValue());
1949 Imm = C->getZExtValue();
1951 if (isUInt<12>(Imm))
1954 UseInverse = UseImm && UseInverse;
1957 static const unsigned OpcTable[2][2][2] = {
1958 { {AArch64::ADDSWrr, AArch64::ADDSXrr},
1959 {AArch64::ADDSWri, AArch64::ADDSXri} },
1960 { {AArch64::SUBSWrr, AArch64::SUBSXrr},
1961 {AArch64::SUBSWri, AArch64::SUBSXri} }
1964 unsigned MulReg = 0;
1965 unsigned RHSReg = 0;
1966 bool RHSIsKill = false;
1967 AArch64CC::CondCode CC = AArch64CC::Invalid;
1968 bool Is64Bit = VT == MVT::i64;
1969 switch (II->getIntrinsicID()) {
1970 default: llvm_unreachable("Unexpected intrinsic!");
1971 case Intrinsic::sadd_with_overflow:
1972 Opc = OpcTable[UseInverse][UseImm][Is64Bit]; CC = AArch64CC::VS; break;
1973 case Intrinsic::uadd_with_overflow:
1974 Opc = OpcTable[UseInverse][UseImm][Is64Bit]; CC = AArch64CC::HS; break;
1975 case Intrinsic::ssub_with_overflow:
1976 Opc = OpcTable[!UseInverse][UseImm][Is64Bit]; CC = AArch64CC::VS; break;
1977 case Intrinsic::usub_with_overflow:
1978 Opc = OpcTable[!UseInverse][UseImm][Is64Bit]; CC = AArch64CC::LO; break;
1979 case Intrinsic::smul_with_overflow: {
1981 RHSReg = getRegForValue(RHS);
1984 RHSIsKill = hasTrivialKill(RHS);
1986 if (VT == MVT::i32) {
1987 MulReg = Emit_SMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1988 unsigned ShiftReg = Emit_LSR_ri(MVT::i64, MulReg, false, 32);
1989 MulReg = FastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
1991 ShiftReg = FastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
1993 unsigned CmpReg = createResultReg(TLI.getRegClassFor(VT));
1994 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1995 TII.get(AArch64::SUBSWrs), CmpReg)
1996 .addReg(ShiftReg, getKillRegState(true))
1997 .addReg(MulReg, getKillRegState(false))
1998 .addImm(159); // 159 <-> asr #31
2000 assert(VT == MVT::i64 && "Unexpected value type.");
2001 MulReg = Emit_MUL_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2002 unsigned SMULHReg = FastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
2004 unsigned CmpReg = createResultReg(TLI.getRegClassFor(VT));
2005 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2006 TII.get(AArch64::SUBSXrs), CmpReg)
2007 .addReg(SMULHReg, getKillRegState(true))
2008 .addReg(MulReg, getKillRegState(false))
2009 .addImm(191); // 191 <-> asr #63
2013 case Intrinsic::umul_with_overflow: {
2015 RHSReg = getRegForValue(RHS);
2018 RHSIsKill = hasTrivialKill(RHS);
2020 if (VT == MVT::i32) {
2021 MulReg = Emit_UMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2022 unsigned CmpReg = createResultReg(TLI.getRegClassFor(MVT::i64));
2023 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2024 TII.get(AArch64::SUBSXrs), CmpReg)
2025 .addReg(AArch64::XZR, getKillRegState(true))
2026 .addReg(MulReg, getKillRegState(false))
2027 .addImm(96); // 96 <-> lsr #32
2028 MulReg = FastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
2031 assert(VT == MVT::i64 && "Unexpected value type.");
2032 MulReg = Emit_MUL_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2033 unsigned UMULHReg = FastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
2035 unsigned CmpReg = createResultReg(TLI.getRegClassFor(VT));
2036 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2037 TII.get(AArch64::SUBSXrr), CmpReg)
2038 .addReg(AArch64::XZR, getKillRegState(true))
2039 .addReg(UMULHReg, getKillRegState(false));
2046 RHSReg = getRegForValue(RHS);
2049 RHSIsKill = hasTrivialKill(RHS);
2052 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2054 MachineInstrBuilder MIB;
2055 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2057 .addReg(LHSReg, getKillRegState(LHSIsKill));
2062 MIB.addReg(RHSReg, getKillRegState(RHSIsKill));
2065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2066 TII.get(TargetOpcode::COPY), ResultReg)
2069 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2070 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2071 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2073 .addReg(AArch64::WZR, getKillRegState(true))
2074 .addReg(AArch64::WZR, getKillRegState(true))
2075 .addImm(getInvertedCondCode(CC));
2077 UpdateValueMap(II, ResultReg, 2);
2084 bool AArch64FastISel::SelectRet(const Instruction *I) {
2085 const ReturnInst *Ret = cast<ReturnInst>(I);
2086 const Function &F = *I->getParent()->getParent();
2088 if (!FuncInfo.CanLowerReturn)
2094 // Build a list of return value registers.
2095 SmallVector<unsigned, 4> RetRegs;
2097 if (Ret->getNumOperands() > 0) {
2098 CallingConv::ID CC = F.getCallingConv();
2099 SmallVector<ISD::OutputArg, 4> Outs;
2100 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
2102 // Analyze operands of the call, assigning locations to each operand.
2103 SmallVector<CCValAssign, 16> ValLocs;
2104 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
2105 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2106 : RetCC_AArch64_AAPCS;
2107 CCInfo.AnalyzeReturn(Outs, RetCC);
2109 // Only handle a single return value for now.
2110 if (ValLocs.size() != 1)
2113 CCValAssign &VA = ValLocs[0];
2114 const Value *RV = Ret->getOperand(0);
2116 // Don't bother handling odd stuff for now.
2117 if (VA.getLocInfo() != CCValAssign::Full)
2119 // Only handle register returns for now.
2122 unsigned Reg = getRegForValue(RV);
2126 unsigned SrcReg = Reg + VA.getValNo();
2127 unsigned DestReg = VA.getLocReg();
2128 // Avoid a cross-class copy. This is very unlikely.
2129 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
2132 EVT RVEVT = TLI.getValueType(RV->getType());
2133 if (!RVEVT.isSimple())
2136 // Vectors (of > 1 lane) in big endian need tricky handling.
2137 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1)
2140 MVT RVVT = RVEVT.getSimpleVT();
2141 if (RVVT == MVT::f128)
2143 MVT DestVT = VA.getValVT();
2144 // Special handling for extended integers.
2145 if (RVVT != DestVT) {
2146 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
2149 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
2152 bool isZExt = Outs[0].Flags.isZExt();
2153 SrcReg = EmitIntExt(RVVT, SrcReg, DestVT, isZExt);
2159 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2160 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
2162 // Add register to return instruction.
2163 RetRegs.push_back(VA.getLocReg());
2166 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2167 TII.get(AArch64::RET_ReallyLR));
2168 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
2169 MIB.addReg(RetRegs[i], RegState::Implicit);
2173 bool AArch64FastISel::SelectTrunc(const Instruction *I) {
2174 Type *DestTy = I->getType();
2175 Value *Op = I->getOperand(0);
2176 Type *SrcTy = Op->getType();
2178 EVT SrcEVT = TLI.getValueType(SrcTy, true);
2179 EVT DestEVT = TLI.getValueType(DestTy, true);
2180 if (!SrcEVT.isSimple())
2182 if (!DestEVT.isSimple())
2185 MVT SrcVT = SrcEVT.getSimpleVT();
2186 MVT DestVT = DestEVT.getSimpleVT();
2188 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
2191 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
2195 unsigned SrcReg = getRegForValue(Op);
2199 // If we're truncating from i64 to a smaller non-legal type then generate an
2200 // AND. Otherwise, we know the high bits are undefined and a truncate doesn't
2201 // generate any code.
2202 if (SrcVT == MVT::i64) {
2204 switch (DestVT.SimpleTy) {
2206 // Trunc i64 to i32 is handled by the target-independent fast-isel.
2218 // Issue an extract_subreg to get the lower 32-bits.
2219 unsigned Reg32 = FastEmitInst_extractsubreg(MVT::i32, SrcReg, /*Kill=*/true,
2221 MRI.constrainRegClass(Reg32, &AArch64::GPR32RegClass);
2222 // Create the AND instruction which performs the actual truncation.
2223 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
2224 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
2227 .addImm(AArch64_AM::encodeLogicalImmediate(Mask, 32));
2231 UpdateValueMap(I, SrcReg);
2235 unsigned AArch64FastISel::Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt) {
2236 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
2237 DestVT == MVT::i64) &&
2238 "Unexpected value type.");
2239 // Handle i8 and i16 as i32.
2240 if (DestVT == MVT::i8 || DestVT == MVT::i16)
2244 MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
2245 unsigned ResultReg = createResultReg(&AArch64::GPR32spRegClass);
2246 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
2249 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2251 if (DestVT == MVT::i64) {
2252 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
2253 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
2254 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2255 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2256 TII.get(AArch64::SUBREG_TO_REG), Reg64)
2259 .addImm(AArch64::sub_32);
2264 if (DestVT == MVT::i64) {
2265 // FIXME: We're SExt i1 to i64.
2268 unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
2269 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SBFMWri),
2278 unsigned AArch64FastISel::Emit_MUL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2279 unsigned Op1, bool Op1IsKill) {
2281 switch (RetVT.SimpleTy) {
2287 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
2289 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
2292 // Create the base instruction, then add the operands.
2293 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
2294 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2295 .addReg(Op0, getKillRegState(Op0IsKill))
2296 .addReg(Op1, getKillRegState(Op1IsKill))
2297 .addReg(ZReg, getKillRegState(true));
2302 unsigned AArch64FastISel::Emit_SMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2303 unsigned Op1, bool Op1IsKill) {
2304 if (RetVT != MVT::i64)
2307 // Create the base instruction, then add the operands.
2308 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
2309 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SMADDLrrr),
2311 .addReg(Op0, getKillRegState(Op0IsKill))
2312 .addReg(Op1, getKillRegState(Op1IsKill))
2313 .addReg(AArch64::XZR, getKillRegState(true));
2318 unsigned AArch64FastISel::Emit_UMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2319 unsigned Op1, bool Op1IsKill) {
2320 if (RetVT != MVT::i64)
2323 // Create the base instruction, then add the operands.
2324 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
2325 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::UMADDLrrr),
2327 .addReg(Op0, getKillRegState(Op0IsKill))
2328 .addReg(Op1, getKillRegState(Op1IsKill))
2329 .addReg(AArch64::XZR, getKillRegState(true));
2334 unsigned AArch64FastISel::Emit_LSL_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2336 unsigned Opc, ImmR, ImmS;
2337 switch (RetVT.SimpleTy) {
2340 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 7 - Shift; break;
2342 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 15 - Shift; break;
2344 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 31 - Shift; break;
2346 Opc = AArch64::UBFMXri; ImmR = -Shift % 64; ImmS = 63 - Shift; break;
2349 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2350 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, ImmR,
2354 unsigned AArch64FastISel::Emit_LSR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2357 switch (RetVT.SimpleTy) {
2359 case MVT::i8: Opc = AArch64::UBFMWri; ImmS = 7; break;
2360 case MVT::i16: Opc = AArch64::UBFMWri; ImmS = 15; break;
2361 case MVT::i32: Opc = AArch64::UBFMWri; ImmS = 31; break;
2362 case MVT::i64: Opc = AArch64::UBFMXri; ImmS = 63; break;
2365 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2366 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, Shift,
2370 unsigned AArch64FastISel::Emit_ASR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2373 switch (RetVT.SimpleTy) {
2375 case MVT::i8: Opc = AArch64::SBFMWri; ImmS = 7; break;
2376 case MVT::i16: Opc = AArch64::SBFMWri; ImmS = 15; break;
2377 case MVT::i32: Opc = AArch64::SBFMWri; ImmS = 31; break;
2378 case MVT::i64: Opc = AArch64::SBFMXri; ImmS = 63; break;
2381 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2382 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, Shift,
2386 unsigned AArch64FastISel::EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
2388 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
2390 // FastISel does not have plumbing to deal with extensions where the SrcVT or
2391 // DestVT are odd things, so test to make sure that they are both types we can
2392 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
2393 // bail out to SelectionDAG.
2394 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
2395 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
2396 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
2397 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
2403 switch (SrcVT.SimpleTy) {
2407 return Emiti1Ext(SrcReg, DestVT, isZExt);
2409 if (DestVT == MVT::i64)
2410 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2412 Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
2416 if (DestVT == MVT::i64)
2417 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2419 Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
2423 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
2424 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2429 // Handle i8 and i16 as i32.
2430 if (DestVT == MVT::i8 || DestVT == MVT::i16)
2432 else if (DestVT == MVT::i64) {
2433 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2434 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2435 TII.get(AArch64::SUBREG_TO_REG), Src64)
2438 .addImm(AArch64::sub_32);
2442 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2443 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2451 bool AArch64FastISel::SelectIntExt(const Instruction *I) {
2452 // On ARM, in general, integer casts don't involve legal types; this code
2453 // handles promotable integers. The high bits for a type smaller than
2454 // the register size are assumed to be undefined.
2455 Type *DestTy = I->getType();
2456 Value *Src = I->getOperand(0);
2457 Type *SrcTy = Src->getType();
2459 bool isZExt = isa<ZExtInst>(I);
2460 unsigned SrcReg = getRegForValue(Src);
2464 EVT SrcEVT = TLI.getValueType(SrcTy, true);
2465 EVT DestEVT = TLI.getValueType(DestTy, true);
2466 if (!SrcEVT.isSimple())
2468 if (!DestEVT.isSimple())
2471 MVT SrcVT = SrcEVT.getSimpleVT();
2472 MVT DestVT = DestEVT.getSimpleVT();
2473 unsigned ResultReg = 0;
2475 // Check if it is an argument and if it is already zero/sign-extended.
2476 if (const auto *Arg = dyn_cast<Argument>(Src)) {
2477 if ((isZExt && Arg->hasZExtAttr()) || (!isZExt && Arg->hasSExtAttr())) {
2478 if (DestVT == MVT::i64) {
2479 ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2480 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2481 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
2484 .addImm(AArch64::sub_32);
2491 ResultReg = EmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2496 UpdateValueMap(I, ResultReg);
2500 bool AArch64FastISel::SelectRem(const Instruction *I, unsigned ISDOpcode) {
2501 EVT DestEVT = TLI.getValueType(I->getType(), true);
2502 if (!DestEVT.isSimple())
2505 MVT DestVT = DestEVT.getSimpleVT();
2506 if (DestVT != MVT::i64 && DestVT != MVT::i32)
2510 bool is64bit = (DestVT == MVT::i64);
2511 switch (ISDOpcode) {
2515 DivOpc = is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
2518 DivOpc = is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
2521 unsigned MSubOpc = is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
2522 unsigned Src0Reg = getRegForValue(I->getOperand(0));
2526 unsigned Src1Reg = getRegForValue(I->getOperand(1));
2530 unsigned QuotReg = createResultReg(TLI.getRegClassFor(DestVT));
2531 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(DivOpc), QuotReg)
2534 // The remainder is computed as numerator - (quotient * denominator) using the
2535 // MSUB instruction.
2536 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2537 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MSubOpc), ResultReg)
2541 UpdateValueMap(I, ResultReg);
2545 bool AArch64FastISel::SelectMul(const Instruction *I) {
2546 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2547 if (!SrcEVT.isSimple())
2549 MVT SrcVT = SrcEVT.getSimpleVT();
2551 // Must be simple value type. Don't handle vectors.
2552 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
2556 unsigned Src0Reg = getRegForValue(I->getOperand(0));
2559 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
2561 unsigned Src1Reg = getRegForValue(I->getOperand(1));
2564 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
2566 unsigned ResultReg =
2567 Emit_MUL_rr(SrcVT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
2572 UpdateValueMap(I, ResultReg);
2576 bool AArch64FastISel::SelectShift(const Instruction *I, bool IsLeftShift,
2577 bool IsArithmetic) {
2578 EVT RetEVT = TLI.getValueType(I->getType(), true);
2579 if (!RetEVT.isSimple())
2581 MVT RetVT = RetEVT.getSimpleVT();
2583 if (!isa<ConstantInt>(I->getOperand(1)))
2586 unsigned Op0Reg = getRegForValue(I->getOperand(0));
2589 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
2591 uint64_t ShiftVal = cast<ConstantInt>(I->getOperand(1))->getZExtValue();
2595 ResultReg = Emit_LSL_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2598 ResultReg = Emit_ASR_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2600 ResultReg = Emit_LSR_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2606 UpdateValueMap(I, ResultReg);
2610 bool AArch64FastISel::SelectBitCast(const Instruction *I) {
2613 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
2615 if (!isTypeLegal(I->getType(), RetVT))
2619 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
2620 Opc = AArch64::FMOVWSr;
2621 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
2622 Opc = AArch64::FMOVXDr;
2623 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
2624 Opc = AArch64::FMOVSWr;
2625 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
2626 Opc = AArch64::FMOVDXr;
2630 unsigned Op0Reg = getRegForValue(I->getOperand(0));
2633 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
2634 unsigned ResultReg = FastEmitInst_r(Opc, TLI.getRegClassFor(RetVT),
2640 UpdateValueMap(I, ResultReg);
2644 bool AArch64FastISel::TargetSelectInstruction(const Instruction *I) {
2645 switch (I->getOpcode()) {
2648 case Instruction::Load:
2649 return SelectLoad(I);
2650 case Instruction::Store:
2651 return SelectStore(I);
2652 case Instruction::Br:
2653 return SelectBranch(I);
2654 case Instruction::IndirectBr:
2655 return SelectIndirectBr(I);
2656 case Instruction::FCmp:
2657 case Instruction::ICmp:
2658 return SelectCmp(I);
2659 case Instruction::Select:
2660 return SelectSelect(I);
2661 case Instruction::FPExt:
2662 return SelectFPExt(I);
2663 case Instruction::FPTrunc:
2664 return SelectFPTrunc(I);
2665 case Instruction::FPToSI:
2666 return SelectFPToInt(I, /*Signed=*/true);
2667 case Instruction::FPToUI:
2668 return SelectFPToInt(I, /*Signed=*/false);
2669 case Instruction::SIToFP:
2670 return SelectIntToFP(I, /*Signed=*/true);
2671 case Instruction::UIToFP:
2672 return SelectIntToFP(I, /*Signed=*/false);
2673 case Instruction::SRem:
2674 return SelectRem(I, ISD::SREM);
2675 case Instruction::URem:
2676 return SelectRem(I, ISD::UREM);
2677 case Instruction::Ret:
2678 return SelectRet(I);
2679 case Instruction::Trunc:
2680 return SelectTrunc(I);
2681 case Instruction::ZExt:
2682 case Instruction::SExt:
2683 return SelectIntExt(I);
2685 // FIXME: All of these should really be handled by the target-independent
2686 // selector -> improve FastISel tblgen.
2687 case Instruction::Mul:
2688 return SelectMul(I);
2689 case Instruction::Shl:
2690 return SelectShift(I, /*IsLeftShift=*/true, /*IsArithmetic=*/false);
2691 case Instruction::LShr:
2692 return SelectShift(I, /*IsLeftShift=*/false, /*IsArithmetic=*/false);
2693 case Instruction::AShr:
2694 return SelectShift(I, /*IsLeftShift=*/false, /*IsArithmetic=*/true);
2695 case Instruction::BitCast:
2696 return SelectBitCast(I);
2699 // Silence warnings.
2700 (void)&CC_AArch64_DarwinPCS_VarArg;
2704 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &funcInfo,
2705 const TargetLibraryInfo *libInfo) {
2706 return new AArch64FastISel(funcInfo, libInfo);