FastISelEmitter.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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 "CodeGenInstruction.h"
  20. #include "llvm/ADT/StringSwitch.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. std::set<std::tuple<OperandsSignature, std::string, MVT::SimpleValueType,
  329. MVT::SimpleValueType, std::string>>
  330. SimplePatternsCheck;
  331. std::map<OperandsSignature, std::vector<OperandsSignature> >
  332. SignaturesWithConstantForms;
  333. StringRef InstNS;
  334. ImmPredicateSet ImmediatePredicates;
  335. public:
  336. explicit FastISelMap(StringRef InstNS);
  337. void collectPatterns(CodeGenDAGPatterns &CGP);
  338. void printImmediatePredicates(raw_ostream &OS);
  339. void printFunctionDefinitions(raw_ostream &OS);
  340. private:
  341. void emitInstructionCode(raw_ostream &OS,
  342. const OperandsSignature &Operands,
  343. const PredMap &PM,
  344. const std::string &RetVTName);
  345. };
  346. } // End anonymous namespace
  347. static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
  348. return std::string(CGP.getSDNodeInfo(Op).getEnumName());
  349. }
  350. static std::string getLegalCName(std::string OpName) {
  351. std::string::size_type pos = OpName.find("::");
  352. if (pos != std::string::npos)
  353. OpName.replace(pos, 2, "_");
  354. return OpName;
  355. }
  356. FastISelMap::FastISelMap(StringRef instns) : InstNS(instns) {}
  357. static std::string PhyRegForNode(TreePatternNode *Op,
  358. const CodeGenTarget &Target) {
  359. std::string PhysReg;
  360. if (!Op->isLeaf())
  361. return PhysReg;
  362. Record *OpLeafRec = cast<DefInit>(Op->getLeafValue())->getDef();
  363. if (!OpLeafRec->isSubClassOf("Register"))
  364. return PhysReg;
  365. PhysReg += cast<StringInit>(OpLeafRec->getValue("Namespace")->getValue())
  366. ->getValue();
  367. PhysReg += "::";
  368. PhysReg += Target.getRegBank().getReg(OpLeafRec)->getName();
  369. return PhysReg;
  370. }
  371. void FastISelMap::collectPatterns(CodeGenDAGPatterns &CGP) {
  372. const CodeGenTarget &Target = CGP.getTargetInfo();
  373. // Scan through all the patterns and record the simple ones.
  374. for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
  375. E = CGP.ptm_end(); I != E; ++I) {
  376. const PatternToMatch &Pattern = *I;
  377. // For now, just look at Instructions, so that we don't have to worry
  378. // about emitting multiple instructions for a pattern.
  379. TreePatternNode *Dst = Pattern.getDstPattern();
  380. if (Dst->isLeaf()) continue;
  381. Record *Op = Dst->getOperator();
  382. if (!Op->isSubClassOf("Instruction"))
  383. continue;
  384. CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
  385. if (II.Operands.empty())
  386. continue;
  387. // Allow instructions to be marked as unavailable for FastISel for
  388. // certain cases, i.e. an ISA has two 'and' instruction which differ
  389. // by what registers they can use but are otherwise identical for
  390. // codegen purposes.
  391. if (II.FastISelShouldIgnore)
  392. continue;
  393. // For now, ignore multi-instruction patterns.
  394. bool MultiInsts = false;
  395. for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
  396. TreePatternNode *ChildOp = Dst->getChild(i);
  397. if (ChildOp->isLeaf())
  398. continue;
  399. if (ChildOp->getOperator()->isSubClassOf("Instruction")) {
  400. MultiInsts = true;
  401. break;
  402. }
  403. }
  404. if (MultiInsts)
  405. continue;
  406. // For now, ignore instructions where the first operand is not an
  407. // output register.
  408. const CodeGenRegisterClass *DstRC = nullptr;
  409. std::string SubRegNo;
  410. if (Op->getName() != "EXTRACT_SUBREG") {
  411. Record *Op0Rec = II.Operands[0].Rec;
  412. if (Op0Rec->isSubClassOf("RegisterOperand"))
  413. Op0Rec = Op0Rec->getValueAsDef("RegClass");
  414. if (!Op0Rec->isSubClassOf("RegisterClass"))
  415. continue;
  416. DstRC = &Target.getRegisterClass(Op0Rec);
  417. if (!DstRC)
  418. continue;
  419. } else {
  420. // If this isn't a leaf, then continue since the register classes are
  421. // a bit too complicated for now.
  422. if (!Dst->getChild(1)->isLeaf()) continue;
  423. DefInit *SR = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
  424. if (SR)
  425. SubRegNo = getQualifiedName(SR->getDef());
  426. else
  427. SubRegNo = Dst->getChild(1)->getLeafValue()->getAsString();
  428. }
  429. // Inspect the pattern.
  430. TreePatternNode *InstPatNode = Pattern.getSrcPattern();
  431. if (!InstPatNode) continue;
  432. if (InstPatNode->isLeaf()) continue;
  433. // Ignore multiple result nodes for now.
  434. if (InstPatNode->getNumTypes() > 1) continue;
  435. Record *InstPatOp = InstPatNode->getOperator();
  436. std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
  437. MVT::SimpleValueType RetVT = MVT::isVoid;
  438. if (InstPatNode->getNumTypes()) RetVT = InstPatNode->getSimpleType(0);
  439. MVT::SimpleValueType VT = RetVT;
  440. if (InstPatNode->getNumChildren()) {
  441. assert(InstPatNode->getChild(0)->getNumTypes() == 1);
  442. VT = InstPatNode->getChild(0)->getSimpleType(0);
  443. }
  444. // For now, filter out any instructions with predicates.
  445. if (!InstPatNode->getPredicateCalls().empty())
  446. continue;
  447. // Check all the operands.
  448. OperandsSignature Operands;
  449. if (!Operands.initialize(InstPatNode, Target, VT, ImmediatePredicates,
  450. DstRC))
  451. continue;
  452. std::vector<std::string> PhysRegInputs;
  453. if (InstPatNode->getOperator()->getName() == "imm" ||
  454. InstPatNode->getOperator()->getName() == "fpimm")
  455. PhysRegInputs.push_back("");
  456. else {
  457. // Compute the PhysRegs used by the given pattern, and check that
  458. // the mapping from the src to dst patterns is simple.
  459. bool FoundNonSimplePattern = false;
  460. unsigned DstIndex = 0;
  461. for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
  462. std::string PhysReg = PhyRegForNode(InstPatNode->getChild(i), Target);
  463. if (PhysReg.empty()) {
  464. if (DstIndex >= Dst->getNumChildren() ||
  465. Dst->getChild(DstIndex)->getName() !=
  466. InstPatNode->getChild(i)->getName()) {
  467. FoundNonSimplePattern = true;
  468. break;
  469. }
  470. ++DstIndex;
  471. }
  472. PhysRegInputs.push_back(PhysReg);
  473. }
  474. if (Op->getName() != "EXTRACT_SUBREG" && DstIndex < Dst->getNumChildren())
  475. FoundNonSimplePattern = true;
  476. if (FoundNonSimplePattern)
  477. continue;
  478. }
  479. // Check if the operands match one of the patterns handled by FastISel.
  480. std::string ManglingSuffix;
  481. raw_string_ostream SuffixOS(ManglingSuffix);
  482. Operands.PrintManglingSuffix(SuffixOS, ImmediatePredicates, true);
  483. if (!StringSwitch<bool>(ManglingSuffix)
  484. .Cases("", "r", "rr", "ri", "i", "f", true)
  485. .Default(false))
  486. continue;
  487. // Get the predicate that guards this pattern.
  488. std::string PredicateCheck = Pattern.getPredicateCheck();
  489. // Ok, we found a pattern that we can handle. Remember it.
  490. InstructionMemo Memo(
  491. Pattern.getDstPattern()->getOperator()->getName(),
  492. DstRC,
  493. SubRegNo,
  494. PhysRegInputs,
  495. PredicateCheck
  496. );
  497. int complexity = Pattern.getPatternComplexity(CGP);
  498. auto inserted_simple_pattern = SimplePatternsCheck.insert(
  499. std::make_tuple(Operands, OpcodeName, VT, RetVT, PredicateCheck));
  500. if (!inserted_simple_pattern.second) {
  501. PrintFatalError(Pattern.getSrcRecord()->getLoc(),
  502. "Duplicate predicate in FastISel table!");
  503. }
  504. // Note: Instructions with the same complexity will appear in the order
  505. // that they are encountered.
  506. SimplePatterns[Operands][OpcodeName][VT][RetVT].emplace(complexity,
  507. std::move(Memo));
  508. // If any of the operands were immediates with predicates on them, strip
  509. // them down to a signature that doesn't have predicates so that we can
  510. // associate them with the stripped predicate version.
  511. if (Operands.hasAnyImmediateCodes()) {
  512. SignaturesWithConstantForms[Operands.getWithoutImmCodes()]
  513. .push_back(Operands);
  514. }
  515. }
  516. }
  517. void FastISelMap::printImmediatePredicates(raw_ostream &OS) {
  518. if (ImmediatePredicates.begin() == ImmediatePredicates.end())
  519. return;
  520. OS << "\n// FastEmit Immediate Predicate functions.\n";
  521. for (auto ImmediatePredicate : ImmediatePredicates) {
  522. OS << "static bool " << ImmediatePredicate.getFnName()
  523. << "(int64_t Imm) {\n";
  524. OS << ImmediatePredicate.getImmediatePredicateCode() << "\n}\n";
  525. }
  526. OS << "\n\n";
  527. }
  528. void FastISelMap::emitInstructionCode(raw_ostream &OS,
  529. const OperandsSignature &Operands,
  530. const PredMap &PM,
  531. const std::string &RetVTName) {
  532. // Emit code for each possible instruction. There may be
  533. // multiple if there are subtarget concerns. A reverse iterator
  534. // is used to produce the ones with highest complexity first.
  535. bool OneHadNoPredicate = false;
  536. for (PredMap::const_reverse_iterator PI = PM.rbegin(), PE = PM.rend();
  537. PI != PE; ++PI) {
  538. const InstructionMemo &Memo = PI->second;
  539. std::string PredicateCheck = Memo.PredicateCheck;
  540. if (PredicateCheck.empty()) {
  541. assert(!OneHadNoPredicate &&
  542. "Multiple instructions match and more than one had "
  543. "no predicate!");
  544. OneHadNoPredicate = true;
  545. } else {
  546. if (OneHadNoPredicate) {
  547. PrintFatalError("Multiple instructions match and one with no "
  548. "predicate came before one with a predicate! "
  549. "name:" + Memo.Name + " predicate: " + PredicateCheck);
  550. }
  551. OS << " if (" + PredicateCheck + ") {\n";
  552. OS << " ";
  553. }
  554. for (unsigned i = 0; i < Memo.PhysRegs.size(); ++i) {
  555. if (Memo.PhysRegs[i] != "")
  556. OS << " BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, "
  557. << "TII.get(TargetOpcode::COPY), " << Memo.PhysRegs[i]
  558. << ").addReg(Op" << i << ");\n";
  559. }
  560. OS << " return fastEmitInst_";
  561. if (Memo.SubRegNo.empty()) {
  562. Operands.PrintManglingSuffix(OS, Memo.PhysRegs, ImmediatePredicates,
  563. true);
  564. OS << "(" << InstNS << "::" << Memo.Name << ", ";
  565. OS << "&" << InstNS << "::" << Memo.RC->getName() << "RegClass";
  566. if (!Operands.empty())
  567. OS << ", ";
  568. Operands.PrintArguments(OS, Memo.PhysRegs);
  569. OS << ");\n";
  570. } else {
  571. OS << "extractsubreg(" << RetVTName
  572. << ", Op0, " << Memo.SubRegNo << ");\n";
  573. }
  574. if (!PredicateCheck.empty()) {
  575. OS << " }\n";
  576. }
  577. }
  578. // Return 0 if all of the possibilities had predicates but none
  579. // were satisfied.
  580. if (!OneHadNoPredicate)
  581. OS << " return 0;\n";
  582. OS << "}\n";
  583. OS << "\n";
  584. }
  585. void FastISelMap::printFunctionDefinitions(raw_ostream &OS) {
  586. // Now emit code for all the patterns that we collected.
  587. for (const auto &SimplePattern : SimplePatterns) {
  588. const OperandsSignature &Operands = SimplePattern.first;
  589. const OpcodeTypeRetPredMap &OTM = SimplePattern.second;
  590. for (const auto &I : OTM) {
  591. const std::string &Opcode = I.first;
  592. const TypeRetPredMap &TM = I.second;
  593. OS << "// FastEmit functions for " << Opcode << ".\n";
  594. OS << "\n";
  595. // Emit one function for each opcode,type pair.
  596. for (const auto &TI : TM) {
  597. MVT::SimpleValueType VT = TI.first;
  598. const RetPredMap &RM = TI.second;
  599. if (RM.size() != 1) {
  600. for (const auto &RI : RM) {
  601. MVT::SimpleValueType RetVT = RI.first;
  602. const PredMap &PM = RI.second;
  603. OS << "unsigned fastEmit_" << getLegalCName(Opcode) << "_"
  604. << getLegalCName(std::string(getName(VT))) << "_"
  605. << getLegalCName(std::string(getName(RetVT))) << "_";
  606. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  607. OS << "(";
  608. Operands.PrintParameters(OS);
  609. OS << ") {\n";
  610. emitInstructionCode(OS, Operands, PM, std::string(getName(RetVT)));
  611. }
  612. // Emit one function for the type that demultiplexes on return type.
  613. OS << "unsigned fastEmit_" << getLegalCName(Opcode) << "_"
  614. << getLegalCName(std::string(getName(VT))) << "_";
  615. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  616. OS << "(MVT RetVT";
  617. if (!Operands.empty())
  618. OS << ", ";
  619. Operands.PrintParameters(OS);
  620. OS << ") {\nswitch (RetVT.SimpleTy) {\n";
  621. for (const auto &RI : RM) {
  622. MVT::SimpleValueType RetVT = RI.first;
  623. OS << " case " << getName(RetVT) << ": return fastEmit_"
  624. << getLegalCName(Opcode) << "_"
  625. << getLegalCName(std::string(getName(VT))) << "_"
  626. << getLegalCName(std::string(getName(RetVT))) << "_";
  627. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  628. OS << "(";
  629. Operands.PrintArguments(OS);
  630. OS << ");\n";
  631. }
  632. OS << " default: return 0;\n}\n}\n\n";
  633. } else {
  634. // Non-variadic return type.
  635. OS << "unsigned fastEmit_" << getLegalCName(Opcode) << "_"
  636. << getLegalCName(std::string(getName(VT))) << "_";
  637. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  638. OS << "(MVT RetVT";
  639. if (!Operands.empty())
  640. OS << ", ";
  641. Operands.PrintParameters(OS);
  642. OS << ") {\n";
  643. OS << " if (RetVT.SimpleTy != " << getName(RM.begin()->first)
  644. << ")\n return 0;\n";
  645. const PredMap &PM = RM.begin()->second;
  646. emitInstructionCode(OS, Operands, PM, "RetVT");
  647. }
  648. }
  649. // Emit one function for the opcode that demultiplexes based on the type.
  650. OS << "unsigned fastEmit_"
  651. << getLegalCName(Opcode) << "_";
  652. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  653. OS << "(MVT VT, MVT RetVT";
  654. if (!Operands.empty())
  655. OS << ", ";
  656. Operands.PrintParameters(OS);
  657. OS << ") {\n";
  658. OS << " switch (VT.SimpleTy) {\n";
  659. for (const auto &TI : TM) {
  660. MVT::SimpleValueType VT = TI.first;
  661. std::string TypeName = std::string(getName(VT));
  662. OS << " case " << TypeName << ": return fastEmit_"
  663. << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
  664. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  665. OS << "(RetVT";
  666. if (!Operands.empty())
  667. OS << ", ";
  668. Operands.PrintArguments(OS);
  669. OS << ");\n";
  670. }
  671. OS << " default: return 0;\n";
  672. OS << " }\n";
  673. OS << "}\n";
  674. OS << "\n";
  675. }
  676. OS << "// Top-level FastEmit function.\n";
  677. OS << "\n";
  678. // Emit one function for the operand signature that demultiplexes based
  679. // on opcode and type.
  680. OS << "unsigned fastEmit_";
  681. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  682. OS << "(MVT VT, MVT RetVT, unsigned Opcode";
  683. if (!Operands.empty())
  684. OS << ", ";
  685. Operands.PrintParameters(OS);
  686. OS << ") ";
  687. if (!Operands.hasAnyImmediateCodes())
  688. OS << "override ";
  689. OS << "{\n";
  690. // If there are any forms of this signature available that operate on
  691. // constrained forms of the immediate (e.g., 32-bit sext immediate in a
  692. // 64-bit operand), check them first.
  693. std::map<OperandsSignature, std::vector<OperandsSignature> >::iterator MI
  694. = SignaturesWithConstantForms.find(Operands);
  695. if (MI != SignaturesWithConstantForms.end()) {
  696. // Unique any duplicates out of the list.
  697. llvm::sort(MI->second);
  698. MI->second.erase(std::unique(MI->second.begin(), MI->second.end()),
  699. MI->second.end());
  700. // Check each in order it was seen. It would be nice to have a good
  701. // relative ordering between them, but we're not going for optimality
  702. // here.
  703. for (unsigned i = 0, e = MI->second.size(); i != e; ++i) {
  704. OS << " if (";
  705. MI->second[i].emitImmediatePredicate(OS, ImmediatePredicates);
  706. OS << ")\n if (unsigned Reg = fastEmit_";
  707. MI->second[i].PrintManglingSuffix(OS, ImmediatePredicates);
  708. OS << "(VT, RetVT, Opcode";
  709. if (!MI->second[i].empty())
  710. OS << ", ";
  711. MI->second[i].PrintArguments(OS);
  712. OS << "))\n return Reg;\n\n";
  713. }
  714. // Done with this, remove it.
  715. SignaturesWithConstantForms.erase(MI);
  716. }
  717. OS << " switch (Opcode) {\n";
  718. for (const auto &I : OTM) {
  719. const std::string &Opcode = I.first;
  720. OS << " case " << Opcode << ": return fastEmit_"
  721. << getLegalCName(Opcode) << "_";
  722. Operands.PrintManglingSuffix(OS, ImmediatePredicates);
  723. OS << "(VT, RetVT";
  724. if (!Operands.empty())
  725. OS << ", ";
  726. Operands.PrintArguments(OS);
  727. OS << ");\n";
  728. }
  729. OS << " default: return 0;\n";
  730. OS << " }\n";
  731. OS << "}\n";
  732. OS << "\n";
  733. }
  734. // TODO: SignaturesWithConstantForms should be empty here.
  735. }
  736. namespace llvm {
  737. void EmitFastISel(RecordKeeper &RK, raw_ostream &OS) {
  738. CodeGenDAGPatterns CGP(RK);
  739. const CodeGenTarget &Target = CGP.getTargetInfo();
  740. emitSourceFileHeader("\"Fast\" Instruction Selector for the " +
  741. Target.getName().str() + " target", OS);
  742. // Determine the target's namespace name.
  743. StringRef InstNS = Target.getInstNamespace();
  744. assert(!InstNS.empty() && "Can't determine target-specific namespace!");
  745. FastISelMap F(InstNS);
  746. F.collectPatterns(CGP);
  747. F.printImmediatePredicates(OS);
  748. F.printFunctionDefinitions(OS);
  749. }
  750. } // End llvm namespace