2
0

FastISelEmitter.cpp 30 KB

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