1 //===- ARMInstructionSelector.cpp ----------------------------*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements the targeting of the InstructionSelector class for ARM.
10 /// \todo This should be generated by TableGen.
11 //===----------------------------------------------------------------------===//
12 
13 #include "ARMRegisterBankInfo.h"
14 #include "ARMSubtarget.h"
15 #include "ARMTargetMachine.h"
16 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
17 #include "llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/Support/Debug.h"
21 
22 #define DEBUG_TYPE "arm-isel"
23 
24 using namespace llvm;
25 
26 namespace {
27 
28 #define GET_GLOBALISEL_PREDICATE_BITSET
29 #include "ARMGenGlobalISel.inc"
30 #undef GET_GLOBALISEL_PREDICATE_BITSET
31 
32 class ARMInstructionSelector : public InstructionSelector {
33 public:
34   ARMInstructionSelector(const ARMBaseTargetMachine &TM, const ARMSubtarget &STI,
35                          const ARMRegisterBankInfo &RBI);
36 
37   bool select(MachineInstr &I, CodeGenCoverage &CoverageInfo) const override;
38   static const char *getName() { return DEBUG_TYPE; }
39 
40 private:
41   bool selectImpl(MachineInstr &I, CodeGenCoverage &CoverageInfo) const;
42 
43   struct CmpConstants;
44   struct InsertInfo;
45 
46   bool selectCmp(CmpConstants Helper, MachineInstrBuilder &MIB,
47                  MachineRegisterInfo &MRI) const;
48 
49   // Helper for inserting a comparison sequence that sets \p ResReg to either 1
50   // if \p LHSReg and \p RHSReg are in the relationship defined by \p Cond, or
51   // \p PrevRes otherwise. In essence, it computes PrevRes OR (LHS Cond RHS).
52   bool insertComparison(CmpConstants Helper, InsertInfo I, unsigned ResReg,
53                         ARMCC::CondCodes Cond, unsigned LHSReg, unsigned RHSReg,
54                         unsigned PrevRes) const;
55 
56   // Set \p DestReg to \p Constant.
57   void putConstant(InsertInfo I, unsigned DestReg, unsigned Constant) const;
58 
59   bool selectGlobal(MachineInstrBuilder &MIB, MachineRegisterInfo &MRI) const;
60   bool selectSelect(MachineInstrBuilder &MIB, MachineRegisterInfo &MRI) const;
61   bool selectShift(unsigned ShiftOpc, MachineInstrBuilder &MIB) const;
62 
63   // Check if the types match and both operands have the expected size and
64   // register bank.
65   bool validOpRegPair(MachineRegisterInfo &MRI, unsigned LHS, unsigned RHS,
66                       unsigned ExpectedSize, unsigned ExpectedRegBankID) const;
67 
68   // Check if the register has the expected size and register bank.
69   bool validReg(MachineRegisterInfo &MRI, unsigned Reg, unsigned ExpectedSize,
70                 unsigned ExpectedRegBankID) const;
71 
72   const ARMBaseInstrInfo &TII;
73   const ARMBaseRegisterInfo &TRI;
74   const ARMBaseTargetMachine &TM;
75   const ARMRegisterBankInfo &RBI;
76   const ARMSubtarget &STI;
77 
78   // Store the opcodes that we might need, so we don't have to check what kind
79   // of subtarget (ARM vs Thumb) we have all the time.
80   struct OpcodeCache {
81     unsigned ZEXT16;
82     unsigned SEXT16;
83 
84     unsigned ZEXT8;
85     unsigned SEXT8;
86 
87     // Used for implementing ZEXT/SEXT from i1
88     unsigned AND;
89     unsigned RSB;
90 
91     unsigned STORE32;
92     unsigned LOAD32;
93 
94     unsigned STORE16;
95     unsigned LOAD16;
96 
97     unsigned STORE8;
98     unsigned LOAD8;
99 
100     unsigned ADDrr;
101 
102     // Used for G_ICMP
103     unsigned CMPrr;
104     unsigned MOVi;
105     unsigned MOVCCi;
106 
107     // Used for G_SELECT
108     unsigned CMPri;
109     unsigned MOVCCr;
110 
111     unsigned TSTri;
112     unsigned Bcc;
113 
114     OpcodeCache(const ARMSubtarget &STI);
115   } const Opcodes;
116 
117   // Select the opcode for simple extensions (that translate to a single SXT/UXT
118   // instruction). Extension operations more complicated than that should not
119   // invoke this. Returns the original opcode if it doesn't know how to select a
120   // better one.
121   unsigned selectSimpleExtOpc(unsigned Opc, unsigned Size) const;
122 
123   // Select the opcode for simple loads and stores. Returns the original opcode
124   // if it doesn't know how to select a better one.
125   unsigned selectLoadStoreOpCode(unsigned Opc, unsigned RegBank,
126                                  unsigned Size) const;
127 
128 #define GET_GLOBALISEL_PREDICATES_DECL
129 #include "ARMGenGlobalISel.inc"
130 #undef GET_GLOBALISEL_PREDICATES_DECL
131 
132 // We declare the temporaries used by selectImpl() in the class to minimize the
133 // cost of constructing placeholder values.
134 #define GET_GLOBALISEL_TEMPORARIES_DECL
135 #include "ARMGenGlobalISel.inc"
136 #undef GET_GLOBALISEL_TEMPORARIES_DECL
137 };
138 } // end anonymous namespace
139 
140 namespace llvm {
141 InstructionSelector *
142 createARMInstructionSelector(const ARMBaseTargetMachine &TM,
143                              const ARMSubtarget &STI,
144                              const ARMRegisterBankInfo &RBI) {
145   return new ARMInstructionSelector(TM, STI, RBI);
146 }
147 }
148 
149 const unsigned zero_reg = 0;
150 
151 #define GET_GLOBALISEL_IMPL
152 #include "ARMGenGlobalISel.inc"
153 #undef GET_GLOBALISEL_IMPL
154 
155 ARMInstructionSelector::ARMInstructionSelector(const ARMBaseTargetMachine &TM,
156                                                const ARMSubtarget &STI,
157                                                const ARMRegisterBankInfo &RBI)
158     : InstructionSelector(), TII(*STI.getInstrInfo()),
159       TRI(*STI.getRegisterInfo()), TM(TM), RBI(RBI), STI(STI), Opcodes(STI),
160 #define GET_GLOBALISEL_PREDICATES_INIT
161 #include "ARMGenGlobalISel.inc"
162 #undef GET_GLOBALISEL_PREDICATES_INIT
163 #define GET_GLOBALISEL_TEMPORARIES_INIT
164 #include "ARMGenGlobalISel.inc"
165 #undef GET_GLOBALISEL_TEMPORARIES_INIT
166 {
167 }
168 
169 static const TargetRegisterClass *guessRegClass(unsigned Reg,
170                                                 MachineRegisterInfo &MRI,
171                                                 const TargetRegisterInfo &TRI,
172                                                 const RegisterBankInfo &RBI) {
173   const RegisterBank *RegBank = RBI.getRegBank(Reg, MRI, TRI);
174   assert(RegBank && "Can't get reg bank for virtual register");
175 
176   const unsigned Size = MRI.getType(Reg).getSizeInBits();
177   assert((RegBank->getID() == ARM::GPRRegBankID ||
178           RegBank->getID() == ARM::FPRRegBankID) &&
179          "Unsupported reg bank");
180 
181   if (RegBank->getID() == ARM::FPRRegBankID) {
182     if (Size == 32)
183       return &ARM::SPRRegClass;
184     else if (Size == 64)
185       return &ARM::DPRRegClass;
186     else if (Size == 128)
187       return &ARM::QPRRegClass;
188     else
189       llvm_unreachable("Unsupported destination size");
190   }
191 
192   return &ARM::GPRRegClass;
193 }
194 
195 static bool selectCopy(MachineInstr &I, const TargetInstrInfo &TII,
196                        MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
197                        const RegisterBankInfo &RBI) {
198   unsigned DstReg = I.getOperand(0).getReg();
199   if (TargetRegisterInfo::isPhysicalRegister(DstReg))
200     return true;
201 
202   const TargetRegisterClass *RC = guessRegClass(DstReg, MRI, TRI, RBI);
203 
204   // No need to constrain SrcReg. It will get constrained when
205   // we hit another of its uses or its defs.
206   // Copies do not have constraints.
207   if (!RBI.constrainGenericRegister(DstReg, *RC, MRI)) {
208     LLVM_DEBUG(dbgs() << "Failed to constrain " << TII.getName(I.getOpcode())
209                       << " operand\n");
210     return false;
211   }
212   return true;
213 }
214 
215 static bool selectMergeValues(MachineInstrBuilder &MIB,
216                               const ARMBaseInstrInfo &TII,
217                               MachineRegisterInfo &MRI,
218                               const TargetRegisterInfo &TRI,
219                               const RegisterBankInfo &RBI) {
220   assert(TII.getSubtarget().hasVFP2() && "Can't select merge without VFP");
221 
222   // We only support G_MERGE_VALUES as a way to stick together two scalar GPRs
223   // into one DPR.
224   unsigned VReg0 = MIB->getOperand(0).getReg();
225   (void)VReg0;
226   assert(MRI.getType(VReg0).getSizeInBits() == 64 &&
227          RBI.getRegBank(VReg0, MRI, TRI)->getID() == ARM::FPRRegBankID &&
228          "Unsupported operand for G_MERGE_VALUES");
229   unsigned VReg1 = MIB->getOperand(1).getReg();
230   (void)VReg1;
231   assert(MRI.getType(VReg1).getSizeInBits() == 32 &&
232          RBI.getRegBank(VReg1, MRI, TRI)->getID() == ARM::GPRRegBankID &&
233          "Unsupported operand for G_MERGE_VALUES");
234   unsigned VReg2 = MIB->getOperand(2).getReg();
235   (void)VReg2;
236   assert(MRI.getType(VReg2).getSizeInBits() == 32 &&
237          RBI.getRegBank(VReg2, MRI, TRI)->getID() == ARM::GPRRegBankID &&
238          "Unsupported operand for G_MERGE_VALUES");
239 
240   MIB->setDesc(TII.get(ARM::VMOVDRR));
241   MIB.add(predOps(ARMCC::AL));
242 
243   return true;
244 }
245 
246 static bool selectUnmergeValues(MachineInstrBuilder &MIB,
247                                 const ARMBaseInstrInfo &TII,
248                                 MachineRegisterInfo &MRI,
249                                 const TargetRegisterInfo &TRI,
250                                 const RegisterBankInfo &RBI) {
251   assert(TII.getSubtarget().hasVFP2() && "Can't select unmerge without VFP");
252 
253   // We only support G_UNMERGE_VALUES as a way to break up one DPR into two
254   // GPRs.
255   unsigned VReg0 = MIB->getOperand(0).getReg();
256   (void)VReg0;
257   assert(MRI.getType(VReg0).getSizeInBits() == 32 &&
258          RBI.getRegBank(VReg0, MRI, TRI)->getID() == ARM::GPRRegBankID &&
259          "Unsupported operand for G_UNMERGE_VALUES");
260   unsigned VReg1 = MIB->getOperand(1).getReg();
261   (void)VReg1;
262   assert(MRI.getType(VReg1).getSizeInBits() == 32 &&
263          RBI.getRegBank(VReg1, MRI, TRI)->getID() == ARM::GPRRegBankID &&
264          "Unsupported operand for G_UNMERGE_VALUES");
265   unsigned VReg2 = MIB->getOperand(2).getReg();
266   (void)VReg2;
267   assert(MRI.getType(VReg2).getSizeInBits() == 64 &&
268          RBI.getRegBank(VReg2, MRI, TRI)->getID() == ARM::FPRRegBankID &&
269          "Unsupported operand for G_UNMERGE_VALUES");
270 
271   MIB->setDesc(TII.get(ARM::VMOVRRD));
272   MIB.add(predOps(ARMCC::AL));
273 
274   return true;
275 }
276 
277 ARMInstructionSelector::OpcodeCache::OpcodeCache(const ARMSubtarget &STI) {
278   bool isThumb = STI.isThumb();
279 
280   using namespace TargetOpcode;
281 
282 #define STORE_OPCODE(VAR, OPC) VAR = isThumb ? ARM::t2##OPC : ARM::OPC
283   STORE_OPCODE(SEXT16, SXTH);
284   STORE_OPCODE(ZEXT16, UXTH);
285 
286   STORE_OPCODE(SEXT8, SXTB);
287   STORE_OPCODE(ZEXT8, UXTB);
288 
289   STORE_OPCODE(AND, ANDri);
290   STORE_OPCODE(RSB, RSBri);
291 
292   STORE_OPCODE(STORE32, STRi12);
293   STORE_OPCODE(LOAD32, LDRi12);
294 
295   // LDRH/STRH are special...
296   STORE16 = isThumb ? ARM::t2STRHi12 : ARM::STRH;
297   LOAD16 = isThumb ? ARM::t2LDRHi12 : ARM::LDRH;
298 
299   STORE_OPCODE(STORE8, STRBi12);
300   STORE_OPCODE(LOAD8, LDRBi12);
301 
302   STORE_OPCODE(ADDrr, ADDrr);
303 
304   STORE_OPCODE(CMPrr, CMPrr);
305   STORE_OPCODE(MOVi, MOVi);
306   STORE_OPCODE(MOVCCi, MOVCCi);
307 
308   STORE_OPCODE(CMPri, CMPri);
309   STORE_OPCODE(MOVCCr, MOVCCr);
310 
311   STORE_OPCODE(TSTri, TSTri);
312   STORE_OPCODE(Bcc, Bcc);
313 #undef MAP_OPCODE
314 }
315 
316 unsigned ARMInstructionSelector::selectSimpleExtOpc(unsigned Opc,
317                                                     unsigned Size) const {
318   using namespace TargetOpcode;
319 
320   if (Size != 8 && Size != 16)
321     return Opc;
322 
323   if (Opc == G_SEXT)
324     return Size == 8 ? Opcodes.SEXT8 : Opcodes.SEXT16;
325 
326   if (Opc == G_ZEXT)
327     return Size == 8 ? Opcodes.ZEXT8 : Opcodes.ZEXT16;
328 
329   return Opc;
330 }
331 
332 unsigned ARMInstructionSelector::selectLoadStoreOpCode(unsigned Opc,
333                                                        unsigned RegBank,
334                                                        unsigned Size) const {
335   bool isStore = Opc == TargetOpcode::G_STORE;
336 
337   if (RegBank == ARM::GPRRegBankID) {
338     switch (Size) {
339     case 1:
340     case 8:
341       return isStore ? Opcodes.STORE8 : Opcodes.LOAD8;
342     case 16:
343       return isStore ? Opcodes.STORE16 : Opcodes.LOAD16;
344     case 32:
345       return isStore ? Opcodes.STORE32 : Opcodes.LOAD32;
346     default:
347       return Opc;
348     }
349   }
350 
351   if (RegBank == ARM::FPRRegBankID) {
352     switch (Size) {
353     case 32:
354       return isStore ? ARM::VSTRS : ARM::VLDRS;
355     case 64:
356       return isStore ? ARM::VSTRD : ARM::VLDRD;
357     default:
358       return Opc;
359     }
360   }
361 
362   return Opc;
363 }
364 
365 // When lowering comparisons, we sometimes need to perform two compares instead
366 // of just one. Get the condition codes for both comparisons. If only one is
367 // needed, the second member of the pair is ARMCC::AL.
368 static std::pair<ARMCC::CondCodes, ARMCC::CondCodes>
369 getComparePreds(CmpInst::Predicate Pred) {
370   std::pair<ARMCC::CondCodes, ARMCC::CondCodes> Preds = {ARMCC::AL, ARMCC::AL};
371   switch (Pred) {
372   case CmpInst::FCMP_ONE:
373     Preds = {ARMCC::GT, ARMCC::MI};
374     break;
375   case CmpInst::FCMP_UEQ:
376     Preds = {ARMCC::EQ, ARMCC::VS};
377     break;
378   case CmpInst::ICMP_EQ:
379   case CmpInst::FCMP_OEQ:
380     Preds.first = ARMCC::EQ;
381     break;
382   case CmpInst::ICMP_SGT:
383   case CmpInst::FCMP_OGT:
384     Preds.first = ARMCC::GT;
385     break;
386   case CmpInst::ICMP_SGE:
387   case CmpInst::FCMP_OGE:
388     Preds.first = ARMCC::GE;
389     break;
390   case CmpInst::ICMP_UGT:
391   case CmpInst::FCMP_UGT:
392     Preds.first = ARMCC::HI;
393     break;
394   case CmpInst::FCMP_OLT:
395     Preds.first = ARMCC::MI;
396     break;
397   case CmpInst::ICMP_ULE:
398   case CmpInst::FCMP_OLE:
399     Preds.first = ARMCC::LS;
400     break;
401   case CmpInst::FCMP_ORD:
402     Preds.first = ARMCC::VC;
403     break;
404   case CmpInst::FCMP_UNO:
405     Preds.first = ARMCC::VS;
406     break;
407   case CmpInst::FCMP_UGE:
408     Preds.first = ARMCC::PL;
409     break;
410   case CmpInst::ICMP_SLT:
411   case CmpInst::FCMP_ULT:
412     Preds.first = ARMCC::LT;
413     break;
414   case CmpInst::ICMP_SLE:
415   case CmpInst::FCMP_ULE:
416     Preds.first = ARMCC::LE;
417     break;
418   case CmpInst::FCMP_UNE:
419   case CmpInst::ICMP_NE:
420     Preds.first = ARMCC::NE;
421     break;
422   case CmpInst::ICMP_UGE:
423     Preds.first = ARMCC::HS;
424     break;
425   case CmpInst::ICMP_ULT:
426     Preds.first = ARMCC::LO;
427     break;
428   default:
429     break;
430   }
431   assert(Preds.first != ARMCC::AL && "No comparisons needed?");
432   return Preds;
433 }
434 
435 struct ARMInstructionSelector::CmpConstants {
436   CmpConstants(unsigned CmpOpcode, unsigned FlagsOpcode, unsigned SelectOpcode,
437                unsigned OpRegBank, unsigned OpSize)
438       : ComparisonOpcode(CmpOpcode), ReadFlagsOpcode(FlagsOpcode),
439         SelectResultOpcode(SelectOpcode), OperandRegBankID(OpRegBank),
440         OperandSize(OpSize) {}
441 
442   // The opcode used for performing the comparison.
443   const unsigned ComparisonOpcode;
444 
445   // The opcode used for reading the flags set by the comparison. May be
446   // ARM::INSTRUCTION_LIST_END if we don't need to read the flags.
447   const unsigned ReadFlagsOpcode;
448 
449   // The opcode used for materializing the result of the comparison.
450   const unsigned SelectResultOpcode;
451 
452   // The assumed register bank ID for the operands.
453   const unsigned OperandRegBankID;
454 
455   // The assumed size in bits for the operands.
456   const unsigned OperandSize;
457 };
458 
459 struct ARMInstructionSelector::InsertInfo {
460   InsertInfo(MachineInstrBuilder &MIB)
461       : MBB(*MIB->getParent()), InsertBefore(std::next(MIB->getIterator())),
462         DbgLoc(MIB->getDebugLoc()) {}
463 
464   MachineBasicBlock &MBB;
465   const MachineBasicBlock::instr_iterator InsertBefore;
466   const DebugLoc &DbgLoc;
467 };
468 
469 void ARMInstructionSelector::putConstant(InsertInfo I, unsigned DestReg,
470                                          unsigned Constant) const {
471   (void)BuildMI(I.MBB, I.InsertBefore, I.DbgLoc, TII.get(Opcodes.MOVi))
472       .addDef(DestReg)
473       .addImm(Constant)
474       .add(predOps(ARMCC::AL))
475       .add(condCodeOp());
476 }
477 
478 bool ARMInstructionSelector::validOpRegPair(MachineRegisterInfo &MRI,
479                                             unsigned LHSReg, unsigned RHSReg,
480                                             unsigned ExpectedSize,
481                                             unsigned ExpectedRegBankID) const {
482   return MRI.getType(LHSReg) == MRI.getType(RHSReg) &&
483          validReg(MRI, LHSReg, ExpectedSize, ExpectedRegBankID) &&
484          validReg(MRI, RHSReg, ExpectedSize, ExpectedRegBankID);
485 }
486 
487 bool ARMInstructionSelector::validReg(MachineRegisterInfo &MRI, unsigned Reg,
488                                       unsigned ExpectedSize,
489                                       unsigned ExpectedRegBankID) const {
490   if (MRI.getType(Reg).getSizeInBits() != ExpectedSize) {
491     LLVM_DEBUG(dbgs() << "Unexpected size for register");
492     return false;
493   }
494 
495   if (RBI.getRegBank(Reg, MRI, TRI)->getID() != ExpectedRegBankID) {
496     LLVM_DEBUG(dbgs() << "Unexpected register bank for register");
497     return false;
498   }
499 
500   return true;
501 }
502 
503 bool ARMInstructionSelector::selectCmp(CmpConstants Helper,
504                                        MachineInstrBuilder &MIB,
505                                        MachineRegisterInfo &MRI) const {
506   const InsertInfo I(MIB);
507 
508   auto ResReg = MIB->getOperand(0).getReg();
509   if (!validReg(MRI, ResReg, 1, ARM::GPRRegBankID))
510     return false;
511 
512   auto Cond =
513       static_cast<CmpInst::Predicate>(MIB->getOperand(1).getPredicate());
514   if (Cond == CmpInst::FCMP_TRUE || Cond == CmpInst::FCMP_FALSE) {
515     putConstant(I, ResReg, Cond == CmpInst::FCMP_TRUE ? 1 : 0);
516     MIB->eraseFromParent();
517     return true;
518   }
519 
520   auto LHSReg = MIB->getOperand(2).getReg();
521   auto RHSReg = MIB->getOperand(3).getReg();
522   if (!validOpRegPair(MRI, LHSReg, RHSReg, Helper.OperandSize,
523                       Helper.OperandRegBankID))
524     return false;
525 
526   auto ARMConds = getComparePreds(Cond);
527   auto ZeroReg = MRI.createVirtualRegister(&ARM::GPRRegClass);
528   putConstant(I, ZeroReg, 0);
529 
530   if (ARMConds.second == ARMCC::AL) {
531     // Simple case, we only need one comparison and we're done.
532     if (!insertComparison(Helper, I, ResReg, ARMConds.first, LHSReg, RHSReg,
533                           ZeroReg))
534       return false;
535   } else {
536     // Not so simple, we need two successive comparisons.
537     auto IntermediateRes = MRI.createVirtualRegister(&ARM::GPRRegClass);
538     if (!insertComparison(Helper, I, IntermediateRes, ARMConds.first, LHSReg,
539                           RHSReg, ZeroReg))
540       return false;
541     if (!insertComparison(Helper, I, ResReg, ARMConds.second, LHSReg, RHSReg,
542                           IntermediateRes))
543       return false;
544   }
545 
546   MIB->eraseFromParent();
547   return true;
548 }
549 
550 bool ARMInstructionSelector::insertComparison(CmpConstants Helper, InsertInfo I,
551                                               unsigned ResReg,
552                                               ARMCC::CondCodes Cond,
553                                               unsigned LHSReg, unsigned RHSReg,
554                                               unsigned PrevRes) const {
555   // Perform the comparison.
556   auto CmpI =
557       BuildMI(I.MBB, I.InsertBefore, I.DbgLoc, TII.get(Helper.ComparisonOpcode))
558           .addUse(LHSReg)
559           .addUse(RHSReg)
560           .add(predOps(ARMCC::AL));
561   if (!constrainSelectedInstRegOperands(*CmpI, TII, TRI, RBI))
562     return false;
563 
564   // Read the comparison flags (if necessary).
565   if (Helper.ReadFlagsOpcode != ARM::INSTRUCTION_LIST_END) {
566     auto ReadI = BuildMI(I.MBB, I.InsertBefore, I.DbgLoc,
567                          TII.get(Helper.ReadFlagsOpcode))
568                      .add(predOps(ARMCC::AL));
569     if (!constrainSelectedInstRegOperands(*ReadI, TII, TRI, RBI))
570       return false;
571   }
572 
573   // Select either 1 or the previous result based on the value of the flags.
574   auto Mov1I = BuildMI(I.MBB, I.InsertBefore, I.DbgLoc,
575                        TII.get(Helper.SelectResultOpcode))
576                    .addDef(ResReg)
577                    .addUse(PrevRes)
578                    .addImm(1)
579                    .add(predOps(Cond, ARM::CPSR));
580   if (!constrainSelectedInstRegOperands(*Mov1I, TII, TRI, RBI))
581     return false;
582 
583   return true;
584 }
585 
586 bool ARMInstructionSelector::selectGlobal(MachineInstrBuilder &MIB,
587                                           MachineRegisterInfo &MRI) const {
588   if ((STI.isROPI() || STI.isRWPI()) && !STI.isTargetELF()) {
589     LLVM_DEBUG(dbgs() << "ROPI and RWPI only supported for ELF\n");
590     return false;
591   }
592 
593   auto GV = MIB->getOperand(1).getGlobal();
594   if (GV->isThreadLocal()) {
595     LLVM_DEBUG(dbgs() << "TLS variables not supported yet\n");
596     return false;
597   }
598 
599   auto &MBB = *MIB->getParent();
600   auto &MF = *MBB.getParent();
601 
602   bool UseMovt = STI.useMovt();
603 
604   unsigned Size = TM.getPointerSize(0);
605   unsigned Alignment = 4;
606 
607   auto addOpsForConstantPoolLoad = [&MF, Alignment,
608                                     Size](MachineInstrBuilder &MIB,
609                                           const GlobalValue *GV, bool IsSBREL) {
610     assert(MIB->getOpcode() == ARM::LDRi12 && "Unsupported instruction");
611     auto ConstPool = MF.getConstantPool();
612     auto CPIndex =
613         // For SB relative entries we need a target-specific constant pool.
614         // Otherwise, just use a regular constant pool entry.
615         IsSBREL
616             ? ConstPool->getConstantPoolIndex(
617                   ARMConstantPoolConstant::Create(GV, ARMCP::SBREL), Alignment)
618             : ConstPool->getConstantPoolIndex(GV, Alignment);
619     MIB.addConstantPoolIndex(CPIndex, /*Offset*/ 0, /*TargetFlags*/ 0)
620         .addMemOperand(
621             MF.getMachineMemOperand(MachinePointerInfo::getConstantPool(MF),
622                                     MachineMemOperand::MOLoad, Size, Alignment))
623         .addImm(0)
624         .add(predOps(ARMCC::AL));
625   };
626 
627   if (TM.isPositionIndependent()) {
628     bool Indirect = STI.isGVIndirectSymbol(GV);
629     // FIXME: Taking advantage of MOVT for ELF is pretty involved, so we don't
630     // support it yet. See PR28229.
631     unsigned Opc =
632         UseMovt && !STI.isTargetELF()
633             ? (Indirect ? ARM::MOV_ga_pcrel_ldr : ARM::MOV_ga_pcrel)
634             : (Indirect ? ARM::LDRLIT_ga_pcrel_ldr : ARM::LDRLIT_ga_pcrel);
635     MIB->setDesc(TII.get(Opc));
636 
637     int TargetFlags = ARMII::MO_NO_FLAG;
638     if (STI.isTargetDarwin())
639       TargetFlags |= ARMII::MO_NONLAZY;
640     if (STI.isGVInGOT(GV))
641       TargetFlags |= ARMII::MO_GOT;
642     MIB->getOperand(1).setTargetFlags(TargetFlags);
643 
644     if (Indirect)
645       MIB.addMemOperand(MF.getMachineMemOperand(
646           MachinePointerInfo::getGOT(MF), MachineMemOperand::MOLoad,
647           TM.getProgramPointerSize(), Alignment));
648 
649     return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
650   }
651 
652   bool isReadOnly = STI.getTargetLowering()->isReadOnly(GV);
653   if (STI.isROPI() && isReadOnly) {
654     unsigned Opc = UseMovt ? ARM::MOV_ga_pcrel : ARM::LDRLIT_ga_pcrel;
655     MIB->setDesc(TII.get(Opc));
656     return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
657   }
658   if (STI.isRWPI() && !isReadOnly) {
659     auto Offset = MRI.createVirtualRegister(&ARM::GPRRegClass);
660     MachineInstrBuilder OffsetMIB;
661     if (UseMovt) {
662       OffsetMIB = BuildMI(MBB, *MIB, MIB->getDebugLoc(),
663                           TII.get(ARM::MOVi32imm), Offset);
664       OffsetMIB.addGlobalAddress(GV, /*Offset*/ 0, ARMII::MO_SBREL);
665     } else {
666       // Load the offset from the constant pool.
667       OffsetMIB =
668           BuildMI(MBB, *MIB, MIB->getDebugLoc(), TII.get(ARM::LDRi12), Offset);
669       addOpsForConstantPoolLoad(OffsetMIB, GV, /*IsSBREL*/ true);
670     }
671     if (!constrainSelectedInstRegOperands(*OffsetMIB, TII, TRI, RBI))
672       return false;
673 
674     // Add the offset to the SB register.
675     MIB->setDesc(TII.get(ARM::ADDrr));
676     MIB->RemoveOperand(1);
677     MIB.addReg(ARM::R9) // FIXME: don't hardcode R9
678         .addReg(Offset)
679         .add(predOps(ARMCC::AL))
680         .add(condCodeOp());
681 
682     return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
683   }
684 
685   if (STI.isTargetELF()) {
686     if (UseMovt) {
687       MIB->setDesc(TII.get(ARM::MOVi32imm));
688     } else {
689       // Load the global's address from the constant pool.
690       MIB->setDesc(TII.get(ARM::LDRi12));
691       MIB->RemoveOperand(1);
692       addOpsForConstantPoolLoad(MIB, GV, /*IsSBREL*/ false);
693     }
694   } else if (STI.isTargetMachO()) {
695     if (UseMovt)
696       MIB->setDesc(TII.get(ARM::MOVi32imm));
697     else
698       MIB->setDesc(TII.get(ARM::LDRLIT_ga_abs));
699   } else {
700     LLVM_DEBUG(dbgs() << "Object format not supported yet\n");
701     return false;
702   }
703 
704   return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
705 }
706 
707 bool ARMInstructionSelector::selectSelect(MachineInstrBuilder &MIB,
708                                           MachineRegisterInfo &MRI) const {
709   auto &MBB = *MIB->getParent();
710   auto InsertBefore = std::next(MIB->getIterator());
711   auto &DbgLoc = MIB->getDebugLoc();
712 
713   // Compare the condition to 0.
714   auto CondReg = MIB->getOperand(1).getReg();
715   assert(validReg(MRI, CondReg, 1, ARM::GPRRegBankID) &&
716          "Unsupported types for select operation");
717   auto CmpI = BuildMI(MBB, InsertBefore, DbgLoc, TII.get(Opcodes.CMPri))
718                   .addUse(CondReg)
719                   .addImm(0)
720                   .add(predOps(ARMCC::AL));
721   if (!constrainSelectedInstRegOperands(*CmpI, TII, TRI, RBI))
722     return false;
723 
724   // Move a value into the result register based on the result of the
725   // comparison.
726   auto ResReg = MIB->getOperand(0).getReg();
727   auto TrueReg = MIB->getOperand(2).getReg();
728   auto FalseReg = MIB->getOperand(3).getReg();
729   assert(validOpRegPair(MRI, ResReg, TrueReg, 32, ARM::GPRRegBankID) &&
730          validOpRegPair(MRI, TrueReg, FalseReg, 32, ARM::GPRRegBankID) &&
731          "Unsupported types for select operation");
732   auto Mov1I = BuildMI(MBB, InsertBefore, DbgLoc, TII.get(Opcodes.MOVCCr))
733                    .addDef(ResReg)
734                    .addUse(TrueReg)
735                    .addUse(FalseReg)
736                    .add(predOps(ARMCC::EQ, ARM::CPSR));
737   if (!constrainSelectedInstRegOperands(*Mov1I, TII, TRI, RBI))
738     return false;
739 
740   MIB->eraseFromParent();
741   return true;
742 }
743 
744 bool ARMInstructionSelector::selectShift(unsigned ShiftOpc,
745                                          MachineInstrBuilder &MIB) const {
746   MIB->setDesc(TII.get(ARM::MOVsr));
747   MIB.addImm(ShiftOpc);
748   MIB.add(predOps(ARMCC::AL)).add(condCodeOp());
749   return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
750 }
751 
752 bool ARMInstructionSelector::select(MachineInstr &I,
753                                     CodeGenCoverage &CoverageInfo) const {
754   assert(I.getParent() && "Instruction should be in a basic block!");
755   assert(I.getParent()->getParent() && "Instruction should be in a function!");
756 
757   auto &MBB = *I.getParent();
758   auto &MF = *MBB.getParent();
759   auto &MRI = MF.getRegInfo();
760 
761   if (!isPreISelGenericOpcode(I.getOpcode())) {
762     if (I.isCopy())
763       return selectCopy(I, TII, MRI, TRI, RBI);
764 
765     return true;
766   }
767 
768   using namespace TargetOpcode;
769 
770   if (selectImpl(I, CoverageInfo))
771     return true;
772 
773   MachineInstrBuilder MIB{MF, I};
774   bool isSExt = false;
775 
776   switch (I.getOpcode()) {
777   case G_SEXT:
778     isSExt = true;
779     LLVM_FALLTHROUGH;
780   case G_ZEXT: {
781     LLT DstTy = MRI.getType(I.getOperand(0).getReg());
782     // FIXME: Smaller destination sizes coming soon!
783     if (DstTy.getSizeInBits() != 32) {
784       LLVM_DEBUG(dbgs() << "Unsupported destination size for extension");
785       return false;
786     }
787 
788     LLT SrcTy = MRI.getType(I.getOperand(1).getReg());
789     unsigned SrcSize = SrcTy.getSizeInBits();
790     switch (SrcSize) {
791     case 1: {
792       // ZExt boils down to & 0x1; for SExt we also subtract that from 0
793       I.setDesc(TII.get(Opcodes.AND));
794       MIB.addImm(1).add(predOps(ARMCC::AL)).add(condCodeOp());
795 
796       if (isSExt) {
797         unsigned SExtResult = I.getOperand(0).getReg();
798 
799         // Use a new virtual register for the result of the AND
800         unsigned AndResult = MRI.createVirtualRegister(&ARM::GPRRegClass);
801         I.getOperand(0).setReg(AndResult);
802 
803         auto InsertBefore = std::next(I.getIterator());
804         auto SubI =
805             BuildMI(MBB, InsertBefore, I.getDebugLoc(), TII.get(Opcodes.RSB))
806                 .addDef(SExtResult)
807                 .addUse(AndResult)
808                 .addImm(0)
809                 .add(predOps(ARMCC::AL))
810                 .add(condCodeOp());
811         if (!constrainSelectedInstRegOperands(*SubI, TII, TRI, RBI))
812           return false;
813       }
814       break;
815     }
816     case 8:
817     case 16: {
818       unsigned NewOpc = selectSimpleExtOpc(I.getOpcode(), SrcSize);
819       if (NewOpc == I.getOpcode())
820         return false;
821       I.setDesc(TII.get(NewOpc));
822       MIB.addImm(0).add(predOps(ARMCC::AL));
823       break;
824     }
825     default:
826       LLVM_DEBUG(dbgs() << "Unsupported source size for extension");
827       return false;
828     }
829     break;
830   }
831   case G_ANYEXT:
832   case G_TRUNC: {
833     // The high bits are undefined, so there's nothing special to do, just
834     // treat it as a copy.
835     auto SrcReg = I.getOperand(1).getReg();
836     auto DstReg = I.getOperand(0).getReg();
837 
838     const auto &SrcRegBank = *RBI.getRegBank(SrcReg, MRI, TRI);
839     const auto &DstRegBank = *RBI.getRegBank(DstReg, MRI, TRI);
840 
841     if (SrcRegBank.getID() == ARM::FPRRegBankID) {
842       // This should only happen in the obscure case where we have put a 64-bit
843       // integer into a D register. Get it out of there and keep only the
844       // interesting part.
845       assert(I.getOpcode() == G_TRUNC && "Unsupported operand for G_ANYEXT");
846       assert(DstRegBank.getID() == ARM::GPRRegBankID &&
847              "Unsupported combination of register banks");
848       assert(MRI.getType(SrcReg).getSizeInBits() == 64 && "Unsupported size");
849       assert(MRI.getType(DstReg).getSizeInBits() <= 32 && "Unsupported size");
850 
851       unsigned IgnoredBits = MRI.createVirtualRegister(&ARM::GPRRegClass);
852       auto InsertBefore = std::next(I.getIterator());
853       auto MovI =
854           BuildMI(MBB, InsertBefore, I.getDebugLoc(), TII.get(ARM::VMOVRRD))
855               .addDef(DstReg)
856               .addDef(IgnoredBits)
857               .addUse(SrcReg)
858               .add(predOps(ARMCC::AL));
859       if (!constrainSelectedInstRegOperands(*MovI, TII, TRI, RBI))
860         return false;
861 
862       MIB->eraseFromParent();
863       return true;
864     }
865 
866     if (SrcRegBank.getID() != DstRegBank.getID()) {
867       LLVM_DEBUG(
868           dbgs() << "G_TRUNC/G_ANYEXT operands on different register banks\n");
869       return false;
870     }
871 
872     if (SrcRegBank.getID() != ARM::GPRRegBankID) {
873       LLVM_DEBUG(dbgs() << "G_TRUNC/G_ANYEXT on non-GPR not supported yet\n");
874       return false;
875     }
876 
877     I.setDesc(TII.get(COPY));
878     return selectCopy(I, TII, MRI, TRI, RBI);
879   }
880   case G_CONSTANT: {
881     if (!MRI.getType(I.getOperand(0).getReg()).isPointer()) {
882       // Non-pointer constants should be handled by TableGen.
883       LLVM_DEBUG(dbgs() << "Unsupported constant type\n");
884       return false;
885     }
886 
887     auto &Val = I.getOperand(1);
888     if (Val.isCImm()) {
889       if (!Val.getCImm()->isZero()) {
890         LLVM_DEBUG(dbgs() << "Unsupported pointer constant value\n");
891         return false;
892       }
893       Val.ChangeToImmediate(0);
894     } else {
895       assert(Val.isImm() && "Unexpected operand for G_CONSTANT");
896       if (Val.getImm() != 0) {
897         LLVM_DEBUG(dbgs() << "Unsupported pointer constant value\n");
898         return false;
899       }
900     }
901 
902     I.setDesc(TII.get(ARM::MOVi));
903     MIB.add(predOps(ARMCC::AL)).add(condCodeOp());
904     break;
905   }
906   case G_INTTOPTR:
907   case G_PTRTOINT: {
908     auto SrcReg = I.getOperand(1).getReg();
909     auto DstReg = I.getOperand(0).getReg();
910 
911     const auto &SrcRegBank = *RBI.getRegBank(SrcReg, MRI, TRI);
912     const auto &DstRegBank = *RBI.getRegBank(DstReg, MRI, TRI);
913 
914     if (SrcRegBank.getID() != DstRegBank.getID()) {
915       LLVM_DEBUG(
916           dbgs()
917           << "G_INTTOPTR/G_PTRTOINT operands on different register banks\n");
918       return false;
919     }
920 
921     if (SrcRegBank.getID() != ARM::GPRRegBankID) {
922       LLVM_DEBUG(
923           dbgs() << "G_INTTOPTR/G_PTRTOINT on non-GPR not supported yet\n");
924       return false;
925     }
926 
927     I.setDesc(TII.get(COPY));
928     return selectCopy(I, TII, MRI, TRI, RBI);
929   }
930   case G_SELECT:
931     return selectSelect(MIB, MRI);
932   case G_ICMP: {
933     CmpConstants Helper(Opcodes.CMPrr, ARM::INSTRUCTION_LIST_END,
934                         Opcodes.MOVCCi, ARM::GPRRegBankID, 32);
935     return selectCmp(Helper, MIB, MRI);
936   }
937   case G_FCMP: {
938     assert(STI.hasVFP2() && "Can't select fcmp without VFP");
939 
940     unsigned OpReg = I.getOperand(2).getReg();
941     unsigned Size = MRI.getType(OpReg).getSizeInBits();
942 
943     if (Size == 64 && STI.isFPOnlySP()) {
944       LLVM_DEBUG(dbgs() << "Subtarget only supports single precision");
945       return false;
946     }
947     if (Size != 32 && Size != 64) {
948       LLVM_DEBUG(dbgs() << "Unsupported size for G_FCMP operand");
949       return false;
950     }
951 
952     CmpConstants Helper(Size == 32 ? ARM::VCMPS : ARM::VCMPD, ARM::FMSTAT,
953                         Opcodes.MOVCCi, ARM::FPRRegBankID, Size);
954     return selectCmp(Helper, MIB, MRI);
955   }
956   case G_LSHR:
957     return selectShift(ARM_AM::ShiftOpc::lsr, MIB);
958   case G_ASHR:
959     return selectShift(ARM_AM::ShiftOpc::asr, MIB);
960   case G_SHL: {
961     return selectShift(ARM_AM::ShiftOpc::lsl, MIB);
962   }
963   case G_GEP:
964     I.setDesc(TII.get(Opcodes.ADDrr));
965     MIB.add(predOps(ARMCC::AL)).add(condCodeOp());
966     break;
967   case G_FRAME_INDEX:
968     // Add 0 to the given frame index and hope it will eventually be folded into
969     // the user(s).
970     I.setDesc(TII.get(ARM::ADDri));
971     MIB.addImm(0).add(predOps(ARMCC::AL)).add(condCodeOp());
972     break;
973   case G_GLOBAL_VALUE:
974     return selectGlobal(MIB, MRI);
975   case G_STORE:
976   case G_LOAD: {
977     const auto &MemOp = **I.memoperands_begin();
978     if (MemOp.getOrdering() != AtomicOrdering::NotAtomic) {
979       LLVM_DEBUG(dbgs() << "Atomic load/store not supported yet\n");
980       return false;
981     }
982 
983     unsigned Reg = I.getOperand(0).getReg();
984     unsigned RegBank = RBI.getRegBank(Reg, MRI, TRI)->getID();
985 
986     LLT ValTy = MRI.getType(Reg);
987     const auto ValSize = ValTy.getSizeInBits();
988 
989     assert((ValSize != 64 || STI.hasVFP2()) &&
990            "Don't know how to load/store 64-bit value without VFP");
991 
992     const auto NewOpc = selectLoadStoreOpCode(I.getOpcode(), RegBank, ValSize);
993     if (NewOpc == G_LOAD || NewOpc == G_STORE)
994       return false;
995 
996     I.setDesc(TII.get(NewOpc));
997 
998     if (NewOpc == ARM::LDRH || NewOpc == ARM::STRH)
999       // LDRH has a funny addressing mode (there's already a FIXME for it).
1000       MIB.addReg(0);
1001     MIB.addImm(0).add(predOps(ARMCC::AL));
1002     break;
1003   }
1004   case G_MERGE_VALUES: {
1005     if (!selectMergeValues(MIB, TII, MRI, TRI, RBI))
1006       return false;
1007     break;
1008   }
1009   case G_UNMERGE_VALUES: {
1010     if (!selectUnmergeValues(MIB, TII, MRI, TRI, RBI))
1011       return false;
1012     break;
1013   }
1014   case G_BRCOND: {
1015     if (!validReg(MRI, I.getOperand(0).getReg(), 1, ARM::GPRRegBankID)) {
1016       LLVM_DEBUG(dbgs() << "Unsupported condition register for G_BRCOND");
1017       return false;
1018     }
1019 
1020     // Set the flags.
1021     auto Test =
1022         BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcodes.TSTri))
1023             .addReg(I.getOperand(0).getReg())
1024             .addImm(1)
1025             .add(predOps(ARMCC::AL));
1026     if (!constrainSelectedInstRegOperands(*Test, TII, TRI, RBI))
1027       return false;
1028 
1029     // Branch conditionally.
1030     auto Branch =
1031         BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(Opcodes.Bcc))
1032             .add(I.getOperand(1))
1033             .add(predOps(ARMCC::NE, ARM::CPSR));
1034     if (!constrainSelectedInstRegOperands(*Branch, TII, TRI, RBI))
1035       return false;
1036     I.eraseFromParent();
1037     return true;
1038   }
1039   case G_PHI: {
1040     I.setDesc(TII.get(PHI));
1041 
1042     unsigned DstReg = I.getOperand(0).getReg();
1043     const TargetRegisterClass *RC = guessRegClass(DstReg, MRI, TRI, RBI);
1044     if (!RBI.constrainGenericRegister(DstReg, *RC, MRI)) {
1045       break;
1046     }
1047 
1048     return true;
1049   }
1050   default:
1051     return false;
1052   }
1053 
1054   return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
1055 }
1056