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