FastISelEmitter.cpp 31 KB

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