FastISelEmitter.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. ///===- FastISelEmitter.cpp - Generate an instruction selector -------------===//
  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. //
  9. // This tablegen backend emits code for use by the "fast" instruction
  10. // selection algorithm. See the comments at the top of
  11. // lib/CodeGen/SelectionDAG/FastISel.cpp for background.
  12. //
  13. // This file scans through the target's tablegen instruction-info files
  14. // and extracts instructions with obvious-looking patterns, and it emits
  15. // code to look up these instructions by type and operator.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "CodeGenDAGPatterns.h"
  19. #include "llvm/ADT/StringSwitch.h"
  20. #include "llvm/Support/Debug.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/TableGen/Error.h"
  23. #include "llvm/TableGen/Record.h"
  24. #include "llvm/TableGen/TableGenBackend.h"
  25. #include <utility>
  26. using namespace llvm;
  27. /// InstructionMemo - This class holds additional information about an
  28. /// instruction needed to emit code for it.
  29. ///
  30. namespace {
  31. struct InstructionMemo {
  32. std::string Name;
  33. const CodeGenRegisterClass *RC;
  34. std::string SubRegNo;
  35. std::vector<std::string> PhysRegs;
  36. std::string PredicateCheck;
  37. InstructionMemo(StringRef Name, const CodeGenRegisterClass *RC,
  38. std::string SubRegNo, std::vector<std::string> PhysRegs,
  39. std::string PredicateCheck)
  40. : Name(Name), RC(RC), SubRegNo(std::move(SubRegNo)),
  41. PhysRegs(std::move(PhysRegs)),
  42. PredicateCheck(std::move(PredicateCheck)) {}
  43. // Make sure we do not copy InstructionMemo.
  44. InstructionMemo(const InstructionMemo &Other) = delete;
  45. InstructionMemo(InstructionMemo &&Other) = default;
  46. };
  47. } // End anonymous namespace
  48. /// ImmPredicateSet - This uniques predicates (represented as a string) and
  49. /// gives them unique (small) integer ID's that start at 0.
  50. namespace {
  51. class ImmPredicateSet {
  52. DenseMap<TreePattern *, unsigned> ImmIDs;
  53. std::vector<TreePredicateFn> PredsByName;
  54. public:
  55. unsigned getIDFor(TreePredicateFn Pred) {
  56. unsigned &Entry = ImmIDs[Pred.getOrigPatFragRecord()];
  57. if (Entry == 0) {
  58. PredsByName.push_back(Pred);
  59. Entry = PredsByName.size();
  60. }
  61. return Entry-1;
  62. }
  63. const TreePredicateFn &getPredicate(unsigned i) {
  64. assert(i < PredsByName.size());
  65. return PredsByName[i];
  66. }
  67. typedef std::vector<TreePredicateFn>::const_iterator iterator;
  68. iterator begin() const { return PredsByName.begin(); }
  69. iterator end() const { return PredsByName.end(); }
  70. };
  71. } // End anonymous namespace
  72. /// OperandsSignature - This class holds a description of a list of operand
  73. /// types. It has utility methods for emitting text based on the operands.
  74. ///
  75. namespace {
  76. struct OperandsSignature {
  77. class OpKind {
  78. enum { OK_Reg, OK_FP, OK_Imm, OK_Invalid = -1 };
  79. char Repr;
  80. public:
  81. OpKind() : Repr(OK_Invalid) {}
  82. bool operator<(OpKind RHS) const { return Repr < RHS.Repr; }
  83. bool operator==(OpKind RHS) const { return Repr == RHS.Repr; }
  84. static OpKind getReg() { OpKind K; K.Repr = OK_Reg; return K; }
  85. static OpKind getFP() { OpKind K; K.Repr = OK_FP; return K; }
  86. static OpKind getImm(unsigned V) {
  87. assert((unsigned)OK_Imm+V < 128 &&
  88. "Too many integer predicates for the 'Repr' char");
  89. OpKind K; K.Repr = OK_Imm+V; return K;
  90. }
  91. bool isReg() const { return Repr == OK_Reg; }
  92. bool isFP() const { return Repr == OK_FP; }
  93. bool isImm() const { return Repr >= OK_Imm; }
  94. unsigned getImmCode() const { assert(isImm()); return Repr-OK_Imm; }
  95. void printManglingSuffix(raw_ostream &OS, ImmPredicateSet &ImmPredicates,
  96. bool StripImmCodes) const {
  97. if (isReg())
  98. OS << 'r';
  99. else if (isFP())
  100. OS << 'f';
  101. else {
  102. OS << 'i';
  103. if (!StripImmCodes)
  104. if (unsigned Code = getImmCode())
  105. OS << "_" << ImmPredicates.getPredicate(Code-1).getFnName();
  106. }
  107. }
  108. };
  109. SmallVector<OpKind, 3> Operands;
  110. bool operator<(const OperandsSignature &O) const {
  111. return Operands < O.Operands;
  112. }
  113. bool operator==(const OperandsSignature &O) const {
  114. return Operands == O.Operands;
  115. }
  116. bool empty() const { return Operands.empty(); }
  117. bool hasAnyImmediateCodes() const {
  118. for (unsigned i = 0, e = Operands.size(); i != e; ++i)
  119. if (Operands[i].isImm() && Operands[i].getImmCode() != 0)
  120. return true;
  121. return false;
  122. }
  123. /// getWithoutImmCodes - Return a copy of this with any immediate codes forced
  124. /// to zero.
  125. OperandsSignature getWithoutImmCodes() const {
  126. OperandsSignature Result;
  127. for (unsigned i = 0, e = Operands.size(); i != e; ++i)
  128. if (!Operands[i].isImm())
  129. Result.Operands.push_back(Operands[i]);
  130. else
  131. Result.Operands.push_back(OpKind::getImm(0));
  132. return Result;
  133. }
  134. void emitImmediatePredicate(raw_ostream &OS, ImmPredicateSet &ImmPredicates) {
  135. bool EmittedAnything = false;
  136. for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
  137. if (!Operands[i].isImm()) continue;
  138. unsigned Code = Operands[i].getImmCode();
  139. if (Code == 0) continue;
  140. if (EmittedAnything)
  141. OS << " &&\n ";
  142. TreePredicateFn PredFn = ImmPredicates.getPredicate(Code-1);
  143. // Emit the type check.
  144. TreePattern *TP = PredFn.getOrigPatFragRecord();
  145. ValueTypeByHwMode VVT = TP->getTree(0)->getType(0);
  146. assert(VVT.isSimple() &&
  147. "Cannot use variable value types with fast isel");
  148. OS << "VT == " << getEnumName(VVT.getSimple().SimpleTy) << " && ";
  149. OS << PredFn.getFnName() << "(imm" << i <<')';
  150. EmittedAnything = true;
  151. }
  152. }
  153. /// initialize - Examine the given pattern and initialize the contents
  154. /// of the Operands array accordingly. Return true if all the operands
  155. /// are supported, false otherwise.
  156. ///
  157. bool initialize(TreePatternNode *InstPatNode, const CodeGenTarget &Target,
  158. MVT::SimpleValueType VT,
  159. ImmPredicateSet &ImmediatePredicates,
  160. const CodeGenRegisterClass *OrigDstRC) {
  161. if (InstPatNode->isLeaf())
  162. return false;
  163. if (InstPatNode->getOperator()->getName() == "imm") {
  164. Operands.push_back(OpKind::getImm(0));
  165. return true;
  166. }
  167. if (InstPatNode->getOperator()->getName() == "fpimm") {
  168. Operands.push_back(OpKind::getFP());
  169. return true;
  170. }
  171. const CodeGenRegisterClass *DstRC = nullptr;
  172. for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
  173. TreePatternNode *Op = InstPatNode->getChild(i);
  174. // Handle imm operands specially.
  175. if (!Op->isLeaf() && Op->getOperator()->getName() == "imm") {
  176. unsigned PredNo = 0;
  177. if (!Op->getPredicateCalls().empty()) {
  178. TreePredicateFn PredFn = Op->getPredicateCalls()[0].Fn;
  179. // If there is more than one predicate weighing in on this operand
  180. // then we don't handle it. This doesn't typically happen for
  181. // immediates anyway.
  182. if (Op->getPredicateCalls().size() > 1 ||
  183. !PredFn.isImmediatePattern() || PredFn.usesOperands())
  184. return false;
  185. // Ignore any instruction with 'FastIselShouldIgnore', these are
  186. // not needed and just bloat the fast instruction selector. For
  187. // example, X86 doesn't need to generate code to match ADD16ri8 since
  188. // ADD16ri will do just fine.
  189. Record *Rec = PredFn.getOrigPatFragRecord()->getRecord();
  190. if (Rec->getValueAsBit("FastIselShouldIgnore"))
  191. return false;
  192. PredNo = ImmediatePredicates.getIDFor(PredFn)+1;
  193. }
  194. Operands.push_back(OpKind::getImm(PredNo));
  195. continue;
  196. }
  197. // For now, filter out any operand with a predicate.
  198. // For now, filter out any operand with multiple values.
  199. if (!Op->getPredicateCalls().empty() || Op->getNumTypes() != 1)
  200. return false;
  201. if (!Op->isLeaf()) {
  202. if (Op->getOperator()->getName() == "fpimm") {
  203. Operands.push_back(OpKind::getFP());
  204. continue;
  205. }
  206. // For now, ignore other non-leaf nodes.
  207. return false;
  208. }
  209. assert(Op->hasConcreteType(0) && "Type infererence not done?");
  210. // For now, all the operands must have the same type (if they aren't
  211. // immediates). Note that this causes us to reject variable sized shifts
  212. // on X86.
  213. if (Op->getSimpleType(0) != VT)
  214. return false;
  215. DefInit *OpDI = dyn_cast<DefInit>(Op->getLeafValue());
  216. if (!OpDI)
  217. return false;
  218. Record *OpLeafRec = OpDI->getDef();
  219. // For now, the only other thing we accept is register operands.
  220. const CodeGenRegisterClass *RC = nullptr;
  221. if (OpLeafRec->isSubClassOf("RegisterOperand"))
  222. OpLeafRec = OpLeafRec->getValueAsDef("RegClass");
  223. if (OpLeafRec->isSubClassOf("RegisterClass"))
  224. RC = &Target.getRegisterClass(OpLeafRec);
  225. else if (OpLeafRec->isSubClassOf("Register"))
  226. RC = Target.getRegBank().getRegClassForRegister(OpLeafRec);
  227. else if (OpLeafRec->isSubClassOf("ValueType")) {
  228. RC = OrigDstRC;
  229. } else
  230. return false;
  231. // For now, this needs to be a register class of some sort.
  232. if (!RC)
  233. return false;
  234. // For now, all the operands must have the same register class or be
  235. // a strict subclass of the destination.
  236. if (DstRC) {
  237. if (DstRC != RC && !DstRC->hasSubClass(RC))
  238. return false;
  239. } else
  240. DstRC = RC;
  241. Operands.push_back(OpKind::getReg());
  242. }
  243. return true;
  244. }
  245. void PrintParameters(raw_ostream &OS) const {
  246. ListSeparator LS;
  247. for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
  248. OS << LS;
  249. if (Operands[i].isReg()) {
  250. OS << "unsigned Op" << i;
  251. } else if (Operands[i].isImm()) {
  252. OS << "uint64_t imm" << i;
  253. } else if (Operands[i].isFP()) {
  254. OS << "const ConstantFP *f" << i;
  255. } else {
  256. llvm_unreachable("Unknown operand kind!");
  257. }
  258. }
  259. }
  260. void PrintArguments(raw_ostream &OS,
  261. const std::vector<std::string> &PR) const {
  262. assert(PR.size() == Operands.size());
  263. ListSeparator LS;
  264. for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
  265. if (PR[i] != "")
  266. // Implicit physical register operand.
  267. continue;
  268. OS << LS;
  269. if (Operands[i].isReg()) {
  270. OS << "Op" << i;
  271. } else if (Operands[i].isImm()) {
  272. OS << "imm" << i;
  273. } else if (Operands[i].isFP()) {
  274. OS << "f" << i;
  275. } else {
  276. llvm_unreachable("Unknown operand kind!");
  277. }
  278. }
  279. }
  280. void PrintArguments(raw_ostream &OS) const {
  281. ListSeparator LS;
  282. for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
  283. OS << LS;
  284. if (Operands[i].isReg()) {
  285. OS << "Op" << i;
  286. } else if (Operands[i].isImm()) {
  287. OS << "imm" << i;
  288. } else if (Operands[i].isFP()) {
  289. OS << "f" << i;
  290. } else {
  291. llvm_unreachable("Unknown operand kind!");
  292. }
  293. }
  294. }
  295. void PrintManglingSuffix(raw_ostream &OS, const std::vector<std::string> &PR,
  296. ImmPredicateSet &ImmPredicates,
  297. bool StripImmCodes = false) const {
  298. for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
  299. if (PR[i] != "")
  300. // Implicit physical register operand. e.g. Instruction::Mul expect to
  301. // select to a binary op. On x86, mul may take a single operand with
  302. // the other operand being implicit. We must emit something that looks
  303. // like a binary instruction except for the very inner fastEmitInst_*
  304. // call.
  305. continue;
  306. Operands[i].printManglingSuffix(OS, ImmPredicates, StripImmCodes);
  307. }
  308. }
  309. void PrintManglingSuffix(raw_ostream &OS, ImmPredicateSet &ImmPredicates,
  310. bool StripImmCodes = false) const {
  311. for (unsigned i = 0, e = Operands.size(); i != e; ++i)
  312. Operands[i].printManglingSuffix(OS, ImmPredicates, StripImmCodes);
  313. }
  314. };
  315. } // End anonymous namespace
  316. namespace {
  317. class FastISelMap {
  318. // A multimap is needed instead of a "plain" map because the key is
  319. // the instruction's complexity (an int) and they are not unique.
  320. typedef std::multimap<int, InstructionMemo> PredMap;
  321. typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
  322. typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
  323. typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
  324. typedef std::map<OperandsSignature, OpcodeTypeRetPredMap>
  325. OperandsOpcodeTypeRetPredMap;
  326. OperandsOpcodeTypeRetPredMap SimplePatterns;
  327. // This is used to check that there are no duplicate predicates
  328. typedef std::multimap<std::string, bool> PredCheckMap;
  329. typedef std::map<MVT::SimpleValueType, PredCheckMap> RetPredCheckMap;
  330. typedef std::map<MVT::SimpleValueType, RetPredCheckMap> TypeRetPredCheckMap;
  331. typedef std::map<std::string, TypeRetPredCheckMap> OpcodeTypeRetPredCheckMap;
  332. typedef std::map<OperandsSignature, OpcodeTypeRetPredCheckMap>
  333. OperandsOpcodeTypeRetPredCheckMap;
  334. OperandsOpcodeTypeRetPredCheckMap SimplePatternsCheck;
  335. std::map<OperandsSignature, std::vector<OperandsSignature> >
  336. SignaturesWithConstantForms;
  337. StringRef InstNS;
  338. ImmPredicateSet ImmediatePredicates;
  339. public:
  340. explicit FastISelMap(StringRef InstNS);
  341. void collectPatterns(CodeGenDAGPatterns &CGP);
  342. void printImmediatePredicates(raw_ostream &OS);
  343. void printFunctionDefinitions(raw_ostream &OS);
  344. private:
  345. void emitInstructionCode(raw_ostream &OS,
  346. const OperandsSignature &Operands,
  347. const PredMap &PM,
  348. const std::string &RetVTName);
  349. };
  350. } // End anonymous namespace
  351. static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
  352. return std::string(CGP.getSDNodeInfo(Op).getEnumName());
  353. }
  354. static std::string getLegalCName(std::string OpName) {
  355. std::string::size_type pos = OpName.find("::");
  356. if (pos != std::string::npos)
  357. OpName.replace(pos, 2, "_");
  358. return OpName;
  359. }
  360. FastISelMap::FastISelMap(StringRef instns) : InstNS(instns) {}
  361. static std::string PhyRegForNode(TreePatternNode *Op,
  362. const CodeGenTarget &Target) {
  363. std::string PhysReg;
  364. if (!Op->isLeaf())
  365. return PhysReg;
  366. Record *OpLeafRec = cast<DefInit>(Op->getLeafValue())->getDef();
  367. if (!OpLeafRec->isSubClassOf("Register"))
  368. return PhysReg;
  369. PhysReg += cast<StringInit>(OpLeafRec->getValue("Namespace")->getValue())
  370. ->getValue();
  371. PhysReg += "::";
  372. PhysReg += Target.getRegBank().getReg(OpLeafRec)->getName();
  373. return PhysReg;
  374. }
  375. void FastISelMap::collectPatterns(CodeGenDAGPatterns &CGP) {
  376. const CodeGenTarget &Target = CGP.getTargetInfo();
  377. // Scan through all the patterns and record the simple ones.
  378. for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
  379. E = CGP.ptm_end(); I != E; ++I) {
  380. const PatternToMatch &Pattern = *I;
  381. // For now, just look at Instructions, so that we don't have to worry
  382. // about emitting multiple instructions for a pattern.
  383. TreePatternNode *Dst = Pattern.getDstPattern();
  384. if (Dst->isLeaf()) continue;
  385. Record *Op = Dst->getOperator();
  386. if (!Op->isSubClassOf("Instruction"))
  387. continue;
  388. CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
  389. if (II.Operands.empty())
  390. continue;
  391. // Allow instructions to be marked as unavailable for FastISel for
  392. // certain cases, i.e. an ISA has two 'and' instruction which differ
  393. // by what registers they can use but are otherwise identical for
  394. // codegen purposes.
  395. if (II.FastISelShouldIgnore)
  396. continue;
  397. // For now, ignore multi-instruction patterns.
  398. bool MultiInsts = false;
  399. for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
  400. TreePatternNode *ChildOp = Dst->getChild(i);
  401. if (ChildOp->isLeaf())
  402. continue;
  403. if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
  404. MultiInsts = true;
  405. break;
  406. }
  407. }
  408. if (MultiInsts)
  409. continue;
  410. // For now, ignore instructions where the first operand is not an
  411. // output register.
  412. const CodeGenRegisterClass *DstRC = nullptr;
  413. std::string SubRegNo;
  414. if (Op->getName() != "EXTRACT_SUBREG") {
  415. Record *Op0Rec = II.Operands[0].Rec;
  416. if (Op0Rec->isSubClassOf("RegisterOperand"))
  417. Op0Rec = Op0Rec->getValueAsDef("RegClass");
  418. if (!Op0Rec->isSubClassOf("RegisterClass"))
  419. continue;
  420. DstRC = &Target.getRegisterClass(Op0Rec);
  421. if (!DstRC)
  422. continue;
  423. } else {
  424. // If this isn't a leaf, then continue since the register classes are
  425. // a bit too complicated for now.
  426. if (!Dst->getChild(1)->isLeaf()) continue;
  427. DefInit *SR = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
  428. if (SR)
  429. SubRegNo = getQualifiedName(SR->getDef());
  430. else
  431. SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString();
  432. }
  433. // Inspect the pattern.
  434. TreePatternNode *InstPatNode = Pattern.getSrcPattern();
  435. if (!InstPatNode) continue;
  436. if (InstPatNode->isLeaf()) continue;
  437. // Ignore multiple result nodes for now.
  438. if (InstPatNode->getNumTypes() > 1) continue;
  439. Record *InstPatOp = InstPatNode->getOperator();
  440. std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
  441. MVT::SimpleValueType RetVT = MVT::isVoid;
  442. if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getSimpleType(0);
  443. MVT::SimpleValueType VT = RetVT;
  444. if (InstPatNode->getNumChildren()) {
  445. assert(InstPatNode->getChild(0)->getNumTypes() == 1);
  446. VT = InstPatNode->getChild(0)->getSimpleType(0);
  447. }
  448. // For now, filter out any instructions with predicates.
  449. if (!InstPatNode->getPredicateCalls().empty())
  450. continue;
  451. // Check all the operands.
  452. OperandsSignature Operands;
  453. if (!Operands.initialize(InstPatNode, Target, VT, ImmediatePredicates,
  454. DstRC))
  455. continue;
  456. std::vector<std::string> PhysRegInputs;
  457. if (InstPatNode->getOperator()->getName() == "imm" ||
  458. InstPatNode->getOperator()->getName() == "fpimm")
  459. PhysRegInputs.push_back("");
  460. else {
  461. // Compute the PhysRegs used by the given pattern, and check that
  462. // the mapping from the src to dst patterns is simple.
  463. bool FoundNonSimplePattern = false;
  464. unsigned DstIndex = 0;
  465. for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
  466. std::string PhysReg = PhyRegForNode(InstPatNode->getChild(i), Target);
  467. if (PhysReg.empty()) {
  468. if (DstIndex >= Dst->getNumChildren() ||
  469. Dst->getChild(DstIndex)->getName() !=
  470. InstPatNode->getChild(i)->getName()) {
  471. FoundNonSimplePattern = true;
  472. break;
  473. }
  474. ++DstIndex;
  475. }
  476. PhysRegInputs.push_back(PhysReg);
  477. }
  478. if (Op->getName() != "EXTRACT_SUBREG" && DstIndex < Dst->getNumChildren())
  479. FoundNonSimplePattern = true;
  480. if (FoundNonSimplePattern)
  481. continue;
  482. }
  483. // Check if the operands match one of the patterns handled by FastISel.
  484. std::string ManglingSuffix;
  485. raw_string_ostream SuffixOS(ManglingSuffix);
  486. Operands.PrintManglingSuffix(SuffixOS, ImmediatePredicates, true);
  487. if (!StringSwitch<bool>(ManglingSuffix)
  488. .Cases("", "r", "rr", "ri", "i", "f", true)
  489. .Default(false))
  490. continue;
  491. // Get the predicate that guards this pattern.
  492. std::string PredicateCheck = Pattern.getPredicateCheck();
  493. // Ok, we found a pattern that we can handle. Remember it.
  494. InstructionMemo Memo(
  495. Pattern.getDstPattern()->getOperator()->getName(),
  496. DstRC,
  497. SubRegNo,
  498. PhysRegInputs,
  499. PredicateCheck
  500. );
  501. int complexity = Pattern.getPatternComplexity(CGP);
  502. if (SimplePatternsCheck[Operands][OpcodeName][VT]
  503. [RetVT].count(PredicateCheck)) {
  504. PrintFatalError(Pattern.getSrcRecord()->getLoc(),
  505. "Duplicate predicate in FastISel table!");
  506. }
  507. SimplePatternsCheck[Operands][OpcodeName][VT][RetVT].insert(
  508. std::make_pair(PredicateCheck, true));
  509. // Note: Instructions with the same complexity will appear in the order
  510. // that they are encountered.
  511. SimplePatterns[Operands][OpcodeName][VT][RetVT].emplace(complexity,
  512. std::move(Memo));
  513. // If any of the operands were immediates with predicates on them, strip
  514. // them down to a signature that doesn't have predicates so that we can
  515. // associate them with the stripped predicate version.
  516. if (Operands.hasAnyImmediateCodes()) {
  517. SignaturesWithConstantForms[Operands.getWithoutImmCodes()]
  518. .push_back(Operands);
  519. }
  520. }
  521. }
  522. void FastISelMap::printImmediatePredicates(raw_ostream &OS) {
  523. if (ImmediatePredicates.begin() == ImmediatePredicates.end())
  524. return;
  525. OS << "\n// FastEmit Immediate Predicate functions.\n";
  526. for (auto ImmediatePredicate : ImmediatePredicates) {
  527. OS << "static bool " << ImmediatePredicate.getFnName()
  528. << "(int64_t Imm) {\n";
  529. OS << ImmediatePredicate.getImmediatePredicateCode() << "\n}\n";
  530. }
  531. OS << "\n\n";
  532. }
  533. void FastISelMap::emitInstructionCode(raw_ostream &OS,
  534. const OperandsSignature &Operands,
  535. const PredMap &PM,
  536. const std::string &RetVTName) {
  537. // Emit code for each possible instruction. There may be
  538. // multiple if there are subtarget concerns. A reverse iterator
  539. // is used to produce the ones with highest complexity first.
  540. bool OneHadNoPredicate = false;
  541. for (PredMap::const_reverse_iterator PI = PM.rbegin(), PE = PM.rend();
  542. PI != PE; ++PI) {
  543. const InstructionMemo &Memo = PI->second;
  544. std::string PredicateCheck = Memo.PredicateCheck;
  545. if (PredicateCheck.empty()) {
  546. assert(!OneHadNoPredicate &&
  547. "Multiple instructions match and more than one had "
  548. "no predicate!");
  549. OneHadNoPredicate = true;
  550. } else {
  551. if (OneHadNoPredicate) {
  552. PrintFatalError("Multiple instructions match and one with no "
  553. "predicate came before one with a predicate! "
  554. "name:" + Memo.Name + " predicate: " + PredicateCheck);
  555. }
  556. OS << " if (" + PredicateCheck + ") {\n";
  557. OS << " ";
  558. }
  559. for (unsigned i = 0; i < Memo.PhysRegs.size(); ++i) {
  560. if (Memo.PhysRegs[i] != "")
  561. OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, "
  562. << "TII.get(TargetOpcode::COPY), " << Memo.PhysRegs[i]
  563. << ").addReg(Op" << i << ");\n";
  564. }
  565. OS << " return fastEmitInst_";
  566. if (Memo.SubRegNo.empty()) {
  567. Operands.PrintManglingSuffix(OS, Memo.PhysRegs, ImmediatePredicates,
  568. true);
  569. OS << "(" << InstNS << "::" << Memo.Name << ", ";
  570. OS << "&" << InstNS << "::" << Memo.RC->getName() << "RegClass";
  571. if (!Operands.empty())
  572. OS << ", ";
  573. Operands.PrintArguments(OS, Memo.PhysRegs);
  574. OS << ");\n";
  575. } else {
  576. OS << "extractsubreg(" << RetVTName
  577. << ", Op0, " << Memo.SubRegNo << ");\n";
  578. }
  579. if (!PredicateCheck.empty()) {
  580. OS << " }\n";
  581. }
  582. }
  583. // Return 0 if all of the possibilities had predicates but none
  584. // were satisfied.
  585. if (!OneHadNoPredicate)
  586. OS << " return 0;\n";
  587. OS << "}\n";
  588. OS << "\n";
  589. }
  590. void FastISelMap::printFunctionDefinitions(raw_ostream &OS) {
  591. // Now emit code for all the patterns that we collected.
  592. for (const auto &SimplePattern : SimplePatterns) {
  593. const OperandsSignature &Operands = SimplePattern.first;
  594. const OpcodeTypeRetPredMap &OTM = SimplePattern.second;
  595. for (const auto &I : OTM) {
  596. const std::string &Opcode = I.first;
  597. const TypeRetPredMap &TM = I.second;
  598. OS << "// FastEmit functions for " << Opcode << ".\n";
  599. OS << "\n";
  600. // Emit one function for each opcode,type pair.
  601. for (const auto &TI : TM) {
  602. MVT::SimpleValueType VT = TI.first;
  603. const RetPredMap &RM = TI.second;
  604. if (RM.size() != 1) {
  605. for (const auto &RI : RM) {
  606. MVT::SimpleValueType RetVT = RI.first;
  607. const PredMap &PM = RI.second;
  608. OS << "unsigned fastEmit_" << getLegalCName(Opcode) << "_"
  609. << getLegalCName(std::string(getName(VT))) << "_"
  610. << getLegalCName(std::string(getName(RetVT))) << "_";
  611. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  612. OS << "(";
  613. Operands.PrintParameters(OS);
  614. OS << ") {\n";
  615. emitInstructionCode(OS, Operands, PM, std::string(getName(RetVT)));
  616. }
  617. // Emit one function for the type that demultiplexes on return type.
  618. OS << "unsigned fastEmit_" << getLegalCName(Opcode) << "_"
  619. << getLegalCName(std::string(getName(VT))) << "_";
  620. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  621. OS << "(MVT RetVT";
  622. if (!Operands.empty())
  623. OS << ", ";
  624. Operands.PrintParameters(OS);
  625. OS << ") {\nswitch (RetVT.SimpleTy) {\n";
  626. for (const auto &RI : RM) {
  627. MVT::SimpleValueType RetVT = RI.first;
  628. OS << " case " << getName(RetVT) << ": return fastEmit_"
  629. << getLegalCName(Opcode) << "_"
  630. << getLegalCName(std::string(getName(VT))) << "_"
  631. << getLegalCName(std::string(getName(RetVT))) << "_";
  632. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  633. OS << "(";
  634. Operands.PrintArguments(OS);
  635. OS << ");\n";
  636. }
  637. OS << " default: return 0;\n}\n}\n\n";
  638. } else {
  639. // Non-variadic return type.
  640. OS << "unsigned fastEmit_" << getLegalCName(Opcode) << "_"
  641. << getLegalCName(std::string(getName(VT))) << "_";
  642. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  643. OS << "(MVT RetVT";
  644. if (!Operands.empty())
  645. OS << ", ";
  646. Operands.PrintParameters(OS);
  647. OS << ") {\n";
  648. OS << " if (RetVT.SimpleTy != " << getName(RM.begin()->first)
  649. << ")\n return 0;\n";
  650. const PredMap &PM = RM.begin()->second;
  651. emitInstructionCode(OS, Operands, PM, "RetVT");
  652. }
  653. }
  654. // Emit one function for the opcode that demultiplexes based on the type.
  655. OS << "unsigned fastEmit_"
  656. << getLegalCName(Opcode) << "_";
  657. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  658. OS << "(MVT VT, MVT RetVT";
  659. if (!Operands.empty())
  660. OS << ", ";
  661. Operands.PrintParameters(OS);
  662. OS << ") {\n";
  663. OS << " switch (VT.SimpleTy) {\n";
  664. for (const auto &TI : TM) {
  665. MVT::SimpleValueType VT = TI.first;
  666. std::string TypeName = std::string(getName(VT));
  667. OS << " case " << TypeName << ": return fastEmit_"
  668. << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
  669. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  670. OS << "(RetVT";
  671. if (!Operands.empty())
  672. OS << ", ";
  673. Operands.PrintArguments(OS);
  674. OS << ");\n";
  675. }
  676. OS << " default: return 0;\n";
  677. OS << " }\n";
  678. OS << "}\n";
  679. OS << "\n";
  680. }
  681. OS << "// Top-level FastEmit function.\n";
  682. OS << "\n";
  683. // Emit one function for the operand signature that demultiplexes based
  684. // on opcode and type.
  685. OS << "unsigned fastEmit_";
  686. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  687. OS << "(MVT VT, MVT RetVT, unsigned Opcode";
  688. if (!Operands.empty())
  689. OS << ", ";
  690. Operands.PrintParameters(OS);
  691. OS << ") ";
  692. if (!Operands.hasAnyImmediateCodes())
  693. OS << "override ";
  694. OS << "{\n";
  695. // If there are any forms of this signature available that operate on
  696. // constrained forms of the immediate (e.g., 32-bit sext immediate in a
  697. // 64-bit operand), check them first.
  698. std::map<OperandsSignature, std::vector<OperandsSignature> >::iterator MI
  699. = SignaturesWithConstantForms.find(Operands);
  700. if (MI != SignaturesWithConstantForms.end()) {
  701. // Unique any duplicates out of the list.
  702. llvm::sort(MI->second);
  703. MI->second.erase(std::unique(MI->second.begin(), MI->second.end()),
  704. MI->second.end());
  705. // Check each in order it was seen. It would be nice to have a good
  706. // relative ordering between them, but we're not going for optimality
  707. // here.
  708. for (unsigned i = 0, e = MI->second.size(); i != e; ++i) {
  709. OS << " if (";
  710. MI->second[i].emitImmediatePredicate(OS, ImmediatePredicates);
  711. OS << ")\n if (unsigned Reg = fastEmit_";
  712. MI->second[i].PrintManglingSuffix(OS, ImmediatePredicates);
  713. OS << "(VT, RetVT, Opcode";
  714. if (!MI->second[i].empty())
  715. OS << ", ";
  716. MI->second[i].PrintArguments(OS);
  717. OS << "))\n return Reg;\n\n";
  718. }
  719. // Done with this, remove it.
  720. SignaturesWithConstantForms.erase(MI);
  721. }
  722. OS << " switch (Opcode) {\n";
  723. for (const auto &I : OTM) {
  724. const std::string &Opcode = I.first;
  725. OS << " case " << Opcode << ": return fastEmit_"
  726. << getLegalCName(Opcode) << "_";
  727. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  728. OS << "(VT, RetVT";
  729. if (!Operands.empty())
  730. OS << ", ";
  731. Operands.PrintArguments(OS);
  732. OS << ");\n";
  733. }
  734. OS << " default: return 0;\n";
  735. OS << " }\n";
  736. OS << "}\n";
  737. OS << "\n";
  738. }
  739. // TODO: SignaturesWithConstantForms should be empty here.
  740. }
  741. namespace llvm {
  742. void EmitFastISel(RecordKeeper &RK, raw_ostream &OS) {
  743. CodeGenDAGPatterns CGP(RK);
  744. const CodeGenTarget &Target = CGP.getTargetInfo();
  745. emitSourceFileHeader("\"Fast\" Instruction Selector for the " +
  746. Target.getName().str() + " target", OS);
  747. // Determine the target's namespace name.
  748. StringRef InstNS = Target.getInstNamespace();
  749. assert(!InstNS.empty() && "Can't determine target-specific namespace!");
  750. FastISelMap F(InstNS);
  751. F.collectPatterns(CGP);
  752. F.printImmediatePredicates(OS);
  753. F.printFunctionDefinitions(OS);
  754. }
  755. } // End llvm namespace